Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

refactor(ai): Remove over-engineered URL discovery service

rcourtmanae7b66ecffae
diff --git a/cmd/pulse/main.go b/cmd/pulse/main.go
index ef3cb0c379..45a950e07b 100644
--- a/cmd/pulse/main.go
+++ b/cmd/pulse/main.go
@@ -184,6 +184,9 @@ func runServer() {
// This must be done after router creation since resourceHandlers is created in NewRouter
router.SetMonitor(reloadableMonitor.GetMonitor())
+ // Start AI patrol service for background infrastructure monitoring
+ router.StartPatrol(ctx)
+
// Create HTTP server with unified configuration
// In production, serve everything (frontend + API) on the frontend port
// NOTE: We use ReadHeaderTimeout instead of ReadTimeout to avoid affecting
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index ce3f104ccb..71862d4e76 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -46,6 +46,7 @@ import { useAlertsActivation } from './stores/alertsActivation';
import { UpdateProgressModal } from './components/UpdateProgressModal';
import type { UpdateStatus } from './api/updates';
import { AIChat } from './components/AI/AIChat';
+import { AIStatusIndicator } from './components/AI/AIStatusIndicator';
import { aiChatStore } from './stores/aiChat';
import { useResourcesAsLegacy } from './hooks/useResources';
@@ -1167,6 +1168,8 @@ function AppLayout(props: {
<div class="header-controls flex items-center gap-2 justify-end sm:col-start-3 sm:col-end-4 sm:w-auto sm:justify-end sm:justify-self-end">
<Show when={props.hasAuth() && !props.needsAuth()}>
<div class="flex items-center gap-2">
+ {/* AI Patrol Status Indicator */}
+ <AIStatusIndicator />
<Show when={props.proxyAuthInfo()?.username}>
<span class="text-xs px-2 py-1 text-gray-600 dark:text-gray-400">
{props.proxyAuthInfo()?.username}
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
new file mode 100644
index 0000000000..8671cb4e72
--- /dev/null
+++ b/frontend-modern/src/api/patrol.ts
@@ -0,0 +1,191 @@
+/**
+ * AI Patrol API client
+ * Provides access to background AI monitoring findings and status
+ */
+
+export type FindingSeverity = 'info' | 'watch' | 'warning' | 'critical';
+export type FindingCategory = 'performance' | 'capacity' | 'reliability' | 'backup' | 'security' | 'general';
+
+export interface Finding {
+ id: string;
+ severity: FindingSeverity;
+ category: FindingCategory;
+ resource_id: string;
+ resource_name: string;
+ resource_type: string; // node, vm, container, docker_host, docker_container, storage, pbs, host_raid
+ node?: string;
+ title: string;
+ description: string;
+ recommendation?: string;
+ evidence?: string;
+ detected_at: string;
+ last_seen_at: string;
+ resolved_at?: string;
+ auto_resolved: boolean;
+ acknowledged_at?: string;
+ snoozed_until?: string; // Finding hidden until this time
+ alert_id?: string;
+}
+
+export interface FindingsSummary {
+ critical: number;
+ warning: number;
+ watch: number;
+ info: number;
+}
+
+export interface PatrolStatus {
+ running: boolean;
+ enabled: boolean;
+ last_patrol_at?: string;
+ last_deep_analysis_at?: string;
+ next_patrol_at?: string;
+ last_duration_ms: number;
+ resources_checked: number;
+ findings_count: number;
+ healthy: boolean;
+ summary: FindingsSummary;
+}
+
+/**
+ * Get the current AI patrol status
+ */
+export async function getPatrolStatus(): Promise<PatrolStatus> {
+ const resp = await fetch('/api/ai/patrol/status', {
+ credentials: 'include',
+ });
+ if (!resp.ok) {
+ throw new Error(`Failed to get patrol status: ${resp.status}`);
+ }
+ return resp.json();
+}
+
+/**
+ * Get all active findings from the patrol service
+ * Optionally filter by resource ID
+ */
+export async function getFindings(resourceId?: string): Promise<Finding[]> {
+ const url = resourceId
+ ? `/api/ai/patrol/findings?resource_id=${encodeURIComponent(resourceId)}`
+ : '/api/ai/patrol/findings';
+
+ const resp = await fetch(url, {
+ credentials: 'include',
+ });
+ if (!resp.ok) {
+ throw new Error(`Failed to get findings: ${resp.status}`);
+ }
+ return resp.json();
+}
+
+/**
+ * Trigger an immediate patrol run
+ */
+export async function forcePatrol(deep: boolean = false): Promise<{ success: boolean; message: string }> {
+ const url = deep ? '/api/ai/patrol/run?deep=true' : '/api/ai/patrol/run';
+ const resp = await fetch(url, {
+ method: 'POST',
+ credentials: 'include',
+ });
+ if (!resp.ok) {
+ throw new Error(`Failed to trigger patrol: ${resp.status}`);
+ }
+ return resp.json();
+}
+
+/**
+ * Get AI findings history including resolved findings
+ * @param startTime Optional ISO timestamp to filter findings from
+ */
+export async function getFindingsHistory(startTime?: string): Promise<Finding[]> {
+ const url = startTime
+ ? `/api/ai/patrol/history?start_time=${encodeURIComponent(startTime)}`
+ : '/api/ai/patrol/history';
+ const resp = await fetch(url, {
+ method: 'GET',
+ credentials: 'include',
+ });
+ if (!resp.ok) {
+ throw new Error(`Failed to get findings history: ${resp.status}`);
+ }
+ return resp.json();
+}
+
+/**
+ * Acknowledge a finding (marks as seen but keeps visible, like alert acknowledgement)
+ * Finding will auto-resolve when the underlying condition clears.
+ */
+export async function acknowledgeFinding(findingId: string): Promise<{ success: boolean; message: string }> {
+ const resp = await fetch('/api/ai/patrol/acknowledge', {
+ method: 'POST',
+ credentials: 'include',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ finding_id: findingId }),
+ });
+ if (!resp.ok) {
+ throw new Error(`Failed to acknowledge finding: ${resp.status}`);
+ }
+ return resp.json();
+}
+
+/**
+ * Snooze a finding for a specified duration
+ * @param findingId The ID of the finding to snooze
+ * @param durationHours Duration in hours (e.g., 1, 24, 168 for 7 days)
+ */
+export async function snoozeFinding(findingId: string, durationHours: number): Promise<{ success: boolean; message: string }> {
+ const resp = await fetch('/api/ai/patrol/snooze', {
+ method: 'POST',
+ credentials: 'include',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ finding_id: findingId, duration_hours: durationHours }),
+ });
+ if (!resp.ok) {
+ throw new Error(`Failed to snooze finding: ${resp.status}`);
+ }
+ return resp.json();
+}
+
+/**
+ * Severity color mapping for UI
+ */
+export const severityColors: Record<FindingSeverity, { bg: string; text: string; border: string }> = {
+ critical: { bg: 'rgba(220, 38, 38, 0.15)', text: '#ef4444', border: 'rgba(220, 38, 38, 0.3)' },
+ warning: { bg: 'rgba(234, 179, 8, 0.15)', text: '#eab308', border: 'rgba(234, 179, 8, 0.3)' },
+ watch: { bg: 'rgba(59, 130, 246, 0.15)', text: '#3b82f6', border: 'rgba(59, 130, 246, 0.3)' },
+ info: { bg: 'rgba(107, 114, 128, 0.15)', text: '#9ca3af', border: 'rgba(107, 114, 128, 0.3)' },
+};
+
+/**
+ * Category labels for UI
+ */
+export const categoryLabels: Record<FindingCategory, string> = {
+ performance: 'Performance',
+ capacity: 'Capacity',
+ reliability: 'Reliability',
+ backup: 'Backup',
+ security: 'Security',
+ general: 'General',
+};
+
+/**
+ * Format a timestamp for display
+ */
+export function formatTimestamp(ts: string): string {
+ const date = new Date(ts);
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+ const diffDays = Math.floor(diffMs / 86400000);
+
+ if (diffMins < 1) return 'just now';
+ if (diffMins < 60) return `${diffMins}m ago`;
+ if (diffHours < 24) return `${diffHours}h ago`;
+ if (diffDays < 7) return `${diffDays}d ago`;
+ return date.toLocaleDateString();
+}
diff --git a/frontend-modern/src/components/AI/AIChat.tsx b/frontend-modern/src/components/AI/AIChat.tsx
index 2ac837f9f7..2371e63d72 100644
--- a/frontend-modern/src/components/AI/AIChat.tsx
+++ b/frontend-modern/src/components/AI/AIChat.tsx
@@ -30,6 +30,31 @@ const renderMarkdown = (content: string): string => {
}
};
+// Helper to sanitize thinking/reasoning content for display
+// Removes raw network errors with IP addresses that are not user-friendly
+const sanitizeThinking = (content: string): string => {
+ // Replace raw TCP connection details like "write tcp 192.168.0.123:7655->192.168.0.134:58004: i/o timeout"
+ // with friendlier messages
+ let sanitized = content.replace(
+ /write tcp [\d.:]+->[\d.:]+: i\/o timeout/g,
+ 'connection timed out'
+ );
+ sanitized = sanitized.replace(
+ /read tcp [\d.:]+: i\/o timeout/g,
+ 'connection timed out'
+ );
+ sanitized = sanitized.replace(
+ /dial tcp [\d.:]+: connection refused/g,
+ 'connection refused'
+ );
+ // Replace "failed to send command: <raw error>" patterns
+ sanitized = sanitized.replace(
+ /failed to send command: write tcp [\d.:->\s]+/g,
+ 'failed to send command: connection error'
+ );
+ return sanitized;
+};
+
// In-progress tool execution (before completion)
interface PendingTool {
name: string;
@@ -47,11 +72,20 @@ interface PendingApproval {
}
+// Unified event type for chronological display
+interface StreamDisplayEvent {
+ type: 'thinking' | 'tool';
+ thinking?: string;
+ tool?: AIToolExecution;
+}
+
interface Message {
id: string;
role: 'user' | 'assistant';
content: string;
- thinking?: string; // DeepSeek reasoning/thinking content
+ thinking?: string; // DeepSeek reasoning/thinking content (accumulated)
+ thinkingChunks?: string[]; // Thinking split into sequential blocks for display
+ streamEvents?: StreamDisplayEvent[]; // All events in chronological order
timestamp: Date;
model?: string;
tokens?: { input: number; output: number };
@@ -326,6 +360,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
pendingTools: [],
pendingApprovals: [],
toolCalls: [],
+ thinkingChunks: [],
+ streamEvents: [],
};
setMessages((prev) => [...prev, streamingMessage]);
@@ -394,24 +430,37 @@ export const AIChat: Component<AIChatProps> = (props) => {
output: data.output,
success: data.success,
};
+ // Add to both toolCalls and streamEvents for chronological display
+ const events = msg.streamEvents || [];
return {
...msg,
pendingTools: updatedPending,
toolCalls: [...(msg.toolCalls || []), newToolCall],
+ streamEvents: [...events, { type: 'tool' as const, tool: newToolCall }],
};
}
case 'thinking': {
- const thinking = event.data as string;
+ const chunk = event.data as string;
+ if (!chunk.trim()) return msg; // Skip empty chunks
+ // Each thinking event is a new chunk - add to both arrays
+ const chunks = msg.thinkingChunks || [];
+ const events = msg.streamEvents || [];
return {
...msg,
- thinking: (msg.thinking || '') + thinking,
+ thinking: (msg.thinking || '') + chunk,
+ thinkingChunks: [...chunks, chunk.trim()],
+ streamEvents: [...events, { type: 'thinking' as const, thinking: chunk.trim() }],
};
}
case 'content': {
const content = event.data as string;
+ // Append content rather than replace - this allows intermediate AI responses
+ // during tool execution to accumulate, showing the user the full conversation flow
+ const existingContent = msg.content || '';
+ const separator = existingContent && !existingContent.endsWith('\n') ? '\n\n' : '';
return {
...msg,
- content: content,
+ content: existingContent + separator + content,
};
}
case 'complete': {
@@ -653,8 +702,13 @@ export const AIChat: Component<AIChatProps> = (props) => {
prev.map((msg) => {
if (msg.id !== assistantId) return msg;
switch (event.type) {
- case 'content':
- return { ...msg, content: event.data as string, isStreaming: false };
+ case 'content': {
+ // Append content, but filter out the initial placeholder
+ const content = event.data as string;
+ const existingContent = msg.content === '*Analyzing results...*' ? '' : (msg.content || '');
+ const separator = existingContent && !existingContent.endsWith('\n') ? '\n\n' : '';
+ return { ...msg, content: existingContent + separator + content, isStreaming: false };
+ }
case 'done':
return { ...msg, isStreaming: false };
case 'error':
@@ -889,45 +943,57 @@ export const AIChat: Component<AIChatProps> = (props) => {
: 'bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100'
}`}
>
- {/* Show thinking/reasoning content (DeepSeek) */}
- <Show when={message.role === 'assistant' && message.thinking}>
- <details class="mb-3 rounded border border-blue-300 dark:border-blue-700 overflow-hidden group">
- <summary class="px-2 py-1.5 text-xs font-medium flex items-center gap-2 bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-200 cursor-pointer hover:bg-blue-200 dark:hover:bg-blue-900/50 transition-colors">
- <svg class="w-3.5 h-3.5 transition-transform group-open:rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
- </svg>
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
- </svg>
- <span>Thinking...</span>
- <span class="text-blue-600 dark:text-blue-400 text-[10px]">({message.thinking!.length} chars)</span>
- </summary>
- <div class="px-2 py-2 text-xs bg-blue-50 dark:bg-blue-900/20 text-gray-700 dark:text-gray-300 max-h-48 overflow-y-auto whitespace-pre-wrap break-words font-mono">
- {message.thinking!.length > 2000 ? message.thinking!.substring(0, 2000) + '...' : message.thinking}
- </div>
- </details>
+ {/* Render all events in chronological order - thinking and tools interleaved */}
+ <Show when={message.role === 'assistant' && message.streamEvents && message.streamEvents.length > 0}>
+ <div class="mb-3 space-y-2">
+ <For each={message.streamEvents}>
+ {(evt) => (
+ <Show
+ when={evt.type === 'tool' && evt.tool}
+ fallback={
+ // Thinking chunk
+ <div class="px-2 py-1.5 text-xs bg-blue-50 dark:bg-blue-900/20 text-gray-700 dark:text-gray-300 rounded border-l-2 border-blue-400 whitespace-pre-wrap">
+ {sanitizeThinking(evt.thinking && evt.thinking.length > 500 ? evt.thinking.substring(0, 500) + '...' : evt.thinking || '')}
+ </div>
+ }
+ >
+ {/* Tool call */}
+ <div class="rounded border border-gray-300 dark:border-gray-600 overflow-hidden">
+ <div class={`px-2 py-1 text-xs font-medium flex items-center gap-2 ${evt.tool!.success
+ ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-200'
+ : 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-200'
+ }`}>
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
+ </svg>
+ <code class="font-mono">{evt.tool!.input}</code>
+ </div>
+ <Show when={evt.tool!.output}>
+ <pre class="px-2 py-1 text-xs font-mono bg-gray-50 dark:bg-gray-900 text-gray-700 dark:text-gray-300 overflow-x-auto max-h-32 overflow-y-auto whitespace-pre-wrap break-words">
+ {evt.tool!.output.length > 500 ? evt.tool!.output.substring(0, 500) + '...' : evt.tool!.output}
+ </pre>
+ </Show>
+ </div>
+ </Show>
+ )}
+ </For>
+ </div>
</Show>
- {/* Show completed tool calls FIRST - chronological order */}
- <Show when={message.role === 'assistant' && message.toolCalls && message.toolCalls.length > 0}>
+ {/* Show in-progress tool executions - at the bottom */}
+ <Show when={message.role === 'assistant' && message.pendingTools && message.pendingTools.length > 0}>
<div class="mb-3 space-y-2">
- <For each={message.toolCalls}>
+ <For each={message.pendingTools}>
{(tool) => (
- <div class="rounded border border-gray-300 dark:border-gray-600 overflow-hidden">
- <div class={`px-2 py-1 text-xs font-medium flex items-center gap-2 ${tool.success
- ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-200'
- : 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-200'
- }`}>
- <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
+ <div class="rounded border border-purple-400 dark:border-purple-600 overflow-hidden">
+ <div class="px-2 py-1 text-xs font-medium flex items-center gap-2 bg-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-200">
+ <svg class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
<code class="font-mono">{tool.input}</code>
+ <span class="text-[10px] text-purple-600 dark:text-purple-400">Running...</span>
</div>
- <Show when={tool.output}>
- <pre class="px-2 py-1 text-xs font-mono bg-gray-50 dark:bg-gray-900 text-gray-700 dark:text-gray-300 overflow-x-auto max-h-32 overflow-y-auto whitespace-pre-wrap break-words">
- {tool.output.length > 500 ? tool.output.substring(0, 500) + '...' : tool.output}
- </pre>
- </Show>
</div>
)}
</For>
diff --git a/frontend-modern/src/components/AI/AIStatusIndicator.css b/frontend-modern/src/components/AI/AIStatusIndicator.css
new file mode 100644
index 0000000000..fa27869483
--- /dev/null
+++ b/frontend-modern/src/components/AI/AIStatusIndicator.css
@@ -0,0 +1,74 @@
+/**
+ * AIStatusIndicator styles
+ * Designed to be minimal and blend with Pulse's header
+ */
+
+.ai-status-indicator {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 8px;
+ border-radius: 4px;
+ border: 1px solid transparent;
+ background: transparent;
+ cursor: pointer;
+ font-size: 12px;
+ font-weight: 500;
+ transition: all 0.15s ease;
+ color: var(--text-secondary, #9ca3af);
+}
+
+.ai-status-indicator:hover {
+ background: rgba(255, 255, 255, 0.05);
+}
+
+/* Healthy state - very subtle */
+.ai-status--healthy {
+ color: var(--success-color, #22c55e);
+ opacity: 0.7;
+}
+
+.ai-status--healthy:hover {
+ opacity: 1;
+}
+
+/* Watch state - noticeable but not alarming */
+.ai-status--watch {
+ color: var(--info-color, #3b82f6);
+ background: rgba(59, 130, 246, 0.1);
+ border-color: rgba(59, 130, 246, 0.2);
+}
+
+.ai-status--watch:hover {
+ background: rgba(59, 130, 246, 0.15);
+}
+
+/* Issues state - draws attention */
+.ai-status--issues {
+ color: var(--warning-color, #eab308);
+ background: rgba(234, 179, 8, 0.1);
+ border-color: rgba(234, 179, 8, 0.25);
+}
+
+.ai-status--issues:hover {
+ background: rgba(234, 179, 8, 0.15);
+}
+
+/* Icon */
+.ai-status-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.ai-status-icon svg {
+ display: block;
+}
+
+/* Count badge */
+.ai-status-count {
+ font-size: 11px;
+ font-weight: 600;
+ min-width: 16px;
+ text-align: center;
+}
diff --git a/frontend-modern/src/components/AI/AIStatusIndicator.tsx b/frontend-modern/src/components/AI/AIStatusIndicator.tsx
new file mode 100644
index 0000000000..61484d40be
--- /dev/null
+++ b/frontend-modern/src/components/AI/AIStatusIndicator.tsx
@@ -0,0 +1,113 @@
+/**
+ * AIStatusIndicator - Subtle header component showing AI patrol health
+ *
+ * Design: Minimal presence when healthy, highlighted when issues detected.
+ * Clicking navigates to the Alerts page where AI Insights are displayed.
+ */
+
+import { createResource, Show, createMemo, onCleanup } from 'solid-js';
+import { useNavigate } from '@solidjs/router';
+import { getPatrolStatus, type PatrolStatus } from '../../api/patrol';
+import './AIStatusIndicator.css';
+
+export function AIStatusIndicator() {
+ const navigate = useNavigate();
+
+ // Poll patrol status every 30 seconds
+ const [status, { refetch }] = createResource<PatrolStatus>(
+ async () => {
+ try {
+ return await getPatrolStatus();
+ } catch {
+ return null as unknown as PatrolStatus;
+ }
+ },
+ { initialValue: undefined }
+ );
+
+ // Refetch every 30 seconds with proper cleanup
+ const intervalId = setInterval(() => refetch(), 30000);
+ onCleanup(() => clearInterval(intervalId));
+
+ const hasIssues = createMemo(() => {
+ const s = status();
+ if (!s) return false;
+ return s.summary.critical > 0 || s.summary.warning > 0;
+ });
+
+ const hasWatch = createMemo(() => {
+ const s = status();
+ if (!s) return false;
+ return s.summary.watch > 0 && !hasIssues();
+ });
+
+ const totalFindings = createMemo(() => {
+ const s = status();
+ if (!s) return 0;
+ return s.summary.critical + s.summary.warning + s.summary.watch;
+ });
+
+ const tooltipText = createMemo(() => {
+ const s = status();
+ if (!s || !s.enabled) return 'AI Patrol disabled';
+ if (!s.running) return 'AI Patrol not running';
+
+ const parts: string[] = [];
+ if (s.summary.critical > 0) parts.push(`${s.summary.critical} critical`);
+ if (s.summary.warning > 0) parts.push(`${s.summary.warning} warning`);
+ if (s.summary.watch > 0) parts.push(`${s.summary.watch} watch`);
+
+ if (parts.length === 0) return 'AI: All systems healthy';
+ return `AI: ${parts.join(', ')}`;
+ });
+
+ const statusClass = createMemo(() => {
+ if (hasIssues()) return 'ai-status--issues';
+ if (hasWatch()) return 'ai-status--watch';
+ return 'ai-status--healthy';
+ });
+
+ const handleClick = () => {
+ // Navigate to Alerts page with AI Insights subtab selected
+ navigate('/alerts?subtab=ai-insights');
+ };
+
+ return (
+ <Show when={status()?.enabled}>
+ <button
+ class={`ai-status-indicator ${statusClass()}`}
+ onClick={handleClick}
+ title={tooltipText()}
+ >
+ <span class="ai-status-icon">
+ <Show when={hasIssues()} fallback={
+ <Show when={hasWatch()} fallback={
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
+ <path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z" />
+ <path d="M9 12l2 2 4-4" />
+ </svg>
+ }>
+ {/* Watch icon - eye */}
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
+ <circle cx="12" cy="12" r="3" />
+ </svg>
+ </Show>
+ }>
+ {/* Issues icon - alert */}
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <line x1="12" y1="9" x2="12" y2="13" />
+ <line x1="12" y1="17" x2="12.01" y2="17" />
+ </svg>
+ </Show>
+ </span>
+ <Show when={totalFindings() > 0}>
+ <span class="ai-status-count">{totalFindings()}</span>
+ </Show>
+ </button>
+ </Show>
+ );
+}
+
+export default AIStatusIndicator;
diff --git a/frontend-modern/src/components/Dashboard/Dashboard.tsx b/frontend-modern/src/components/Dashboard/Dashboard.tsx
index 3f56ecdc47..d4c60edb4b 100644
--- a/frontend-modern/src/components/Dashboard/Dashboard.tsx
+++ b/frontend-modern/src/components/Dashboard/Dashboard.tsx
@@ -1171,7 +1171,7 @@ export function Dashboard(props: DashboardProps) {
visibleColumnIds={visibleColumnIds()}
aboveGuestId={prevGuestId}
belowGuestId={nextGuestId}
- onRowClick={aiChatStore.isOpen ? handleGuestRowClick : undefined}
+ onRowClick={aiChatStore.enabled ? handleGuestRowClick : undefined}
/>
</ComponentErrorBoundary>
);
diff --git a/frontend-modern/src/components/Dashboard/GuestRow.tsx b/frontend-modern/src/components/Dashboard/GuestRow.tsx
index cdf00a2ceb..adf4bdd437 100644
--- a/frontend-modern/src/components/Dashboard/GuestRow.tsx
+++ b/frontend-modern/src/components/Dashboard/GuestRow.tsx
@@ -701,8 +701,8 @@ export function GuestRow(props: GuestRowProps) {
? ''
: 'hover:bg-gray-50 dark:hover:bg-gray-700/30';
const stoppedDimming = !isRunning() ? 'opacity-60' : '';
- // Make row clickable if click handler provided
- const clickable = props.onRowClick ? 'cursor-pointer' : '';
+ // Make row clickable if AI is enabled (for context selection)
+ const clickable = aiChatStore.enabled ? 'cursor-pointer' : '';
// AI context highlight with merged borders for adjacent rows
let aiContext = '';
if (isInAIContext()) {
diff --git a/frontend-modern/src/components/Settings/APITokenManager.tsx b/frontend-modern/src/components/Settings/APITokenManager.tsx
index c0b81c430e..dba976cc4e 100644
--- a/frontend-modern/src/components/Settings/APITokenManager.tsx
+++ b/frontend-modern/src/components/Settings/APITokenManager.tsx
@@ -802,7 +802,7 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
</Show>
<Card tone="muted" padding="sm" class="text-xs text-gray-600 dark:text-gray-400">
- 💡 Separate tokens per integration • Rotate regularly •{' '}
+ Separate tokens per integration • Rotate regularly •{' '}
<a
class="font-medium text-blue-600 underline-offset-2 hover:underline dark:text-blue-400"
href={SCOPES_DOC_URL}
diff --git a/frontend-modern/src/components/Settings/Settings.tsx b/frontend-modern/src/components/Settings/Settings.tsx
index 22f186a762..316c98dbe9 100644
--- a/frontend-modern/src/components/Settings/Settings.tsx
+++ b/frontend-modern/src/components/Settings/Settings.tsx
@@ -5359,7 +5359,7 @@ const Settings: Component<SettingsProps> = (props) => {
<div class="mt-3 p-2 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded">
<p class="text-xs text-green-700 dark:text-green-300">
- 💡 <strong>Tip:</strong> Make sure you've saved your credentials
+ <strong>Tip:</strong> Make sure you've saved your credentials
before restarting!
</p>
</div>
@@ -7425,7 +7425,7 @@ const Settings: Component<SettingsProps> = (props) => {
<div class="space-y-3">
<Show when={!diagnosticsData()}>
<div class="text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded p-2">
- 💡 Run diagnostics first for more comprehensive export data
+ Run diagnostics first for more comprehensive export data
</div>
</Show>
<div class="flex gap-2">
diff --git a/frontend-modern/src/components/shared/NodeSummaryTable.tsx b/frontend-modern/src/components/shared/NodeSummaryTable.tsx
index 6b6febe678..82dd883388 100644
--- a/frontend-modern/src/components/shared/NodeSummaryTable.tsx
+++ b/frontend-modern/src/components/shared/NodeSummaryTable.tsx
@@ -337,11 +337,11 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
return sortDirection() === 'asc' ? '▲' : '▼';
};
- const thClassBase = "px-2 py-1.5 text-[11px] sm:text-xs font-medium uppercase tracking-wider cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 whitespace-nowrap";
+ const thClassBase = "px-2 py-1 text-[11px] sm:text-xs font-medium uppercase tracking-wider cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 whitespace-nowrap";
const thClass = `${thClassBase} text-center`;
// Cell class constants for consistency
- const tdClass = "px-2 py-1.5 align-middle";
+ const tdClass = "px-2 py-1 align-middle";
const metricColumnStyle = { width: "200px", "min-width": "200px", "max-width": "200px" } as const;
return (
@@ -482,11 +482,11 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
return (
<tr
class={rowClass()}
- style={rowStyle()}
+ style={{ ...rowStyle(), height: '29px', 'max-height': '29px' }}
onClick={() => props.onNodeClick(nodeId, isPVEItem ? 'pve' : 'pbs')}
>
{/* Name */}
- <td class={`pr-2 py-1.5 align-middle ${showAlertHighlight() ? 'pl-4' : 'pl-3'}`}>
+ <td class={`pr-2 py-1 align-middle ${showAlertHighlight() ? 'pl-4' : 'pl-3'}`}>
<div class="flex items-center gap-1.5">
<StatusDot
variant={statusIndicator().variant}
@@ -568,11 +568,11 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
{/* CPU */}
<td class={tdClass} style={metricColumnStyle}>
<Show when={isMobile()}>
- <div class="md:hidden flex justify-center">
+ <div class="md:hidden h-4 flex items-center justify-center">
<MetricText value={cpuPercentValue} type="cpu" />
</div>
</Show>
- <div class="hidden md:block">
+ <div class="hidden md:block h-4">
<Show when={isPVEItem} fallback={
<ResponsiveMetricCell
value={cpuPercentValue}
@@ -596,11 +596,11 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
{/* Memory */}
<td class={tdClass} style={metricColumnStyle}>
<Show when={isMobile()}>
- <div class="md:hidden flex justify-center">
+ <div class="md:hidden h-4 flex items-center justify-center">
<MetricText value={memoryPercentValue} type="memory" />
</div>
</Show>
- <div class="hidden md:block">
+ <div class="hidden md:block h-4">
<Show when={isPVEItem} fallback={
<ResponsiveMetricCell
value={memoryPercentValue}
diff --git a/frontend-modern/src/components/shared/responsive/ResponsiveMetricCell.tsx b/frontend-modern/src/components/shared/responsive/ResponsiveMetricCell.tsx
index b9adb76905..c5f65c6e23 100644
--- a/frontend-modern/src/components/shared/responsive/ResponsiveMetricCell.tsx
+++ b/frontend-modern/src/components/shared/responsive/ResponsiveMetricCell.tsx
@@ -78,7 +78,9 @@ export const ResponsiveMetricCell: Component<ResponsiveMetricCellProps> = (props
const isRunning = () => props.isRunning !== false; // Default to true if not specified
const defaultFallback = (
- <span class="text-xs text-gray-400 dark:text-gray-500">—</span>
+ <div class="h-4 flex items-center justify-center">
+ <span class="text-xs text-gray-400 dark:text-gray-500">—</span>
+ </div>
);
return (
@@ -148,7 +150,9 @@ export const DualMetricCell: Component<{
const isRunning = () => props.isRunning !== false;
const defaultFallback = (
- <span class="text-xs text-gray-400 dark:text-gray-500">—</span>
+ <div class="h-4 flex items-center justify-center">
+ <span class="text-xs text-gray-400 dark:text-gray-500">—</span>
+ </div>
);
const defaultMobileContent = (
diff --git a/frontend-modern/src/pages/Alerts.tsx b/frontend-modern/src/pages/Alerts.tsx
index a5ecbae982..a322047545 100644
--- a/frontend-modern/src/pages/Alerts.tsx
+++ b/frontend-modern/src/pages/Alerts.tsx
@@ -28,6 +28,8 @@ import History from 'lucide-solid/icons/history';
import Gauge from 'lucide-solid/icons/gauge';
import Send from 'lucide-solid/icons/send';
import Calendar from 'lucide-solid/icons/calendar';
+import { getPatrolStatus, getFindings, getFindingsHistory, acknowledgeFinding, snoozeFinding, type Finding, type PatrolStatus, severityColors, formatTimestamp } from '@/api/patrol';
+import { aiChatStore } from '@/stores/aiChat';
type AlertTab = 'overview' | 'thresholds' | 'destinations' | 'schedule' | 'history';
@@ -1453,7 +1455,9 @@ export function Alerts() {
];
const flatTabs = tabGroups.flatMap((group) => group.items);
- const [sidebarCollapsed, setSidebarCollapsed] = createSignal(true);
+ // Sidebar always starts expanded for discoverability (consistent with Settings)
+ // Users can collapse during session but it resets on page reload
+ const [sidebarCollapsed, setSidebarCollapsed] = createSignal(false);
return (
<div class="space-y-4">
@@ -1746,16 +1750,58 @@ export function Alerts() {
<div class={`transition-opacity ${isAlertsActive() ? 'opacity-100' : 'opacity-50 pointer-events-none'
}`}>
- <Card padding="none" class="relative lg:flex">
+ <Card padding="none" class="relative lg:flex overflow-hidden">
<div
- class={`hidden lg:flex lg:flex-col ${sidebarCollapsed() ? 'w-16' : 'w-72'} ${sidebarCollapsed() ? 'lg:min-w-[4rem] lg:max-w-[4rem] lg:basis-[4rem]' : 'lg:min-w-[18rem] lg:max-w-[18rem] lg:basis-[18rem]'} relative border-b border-gray-200 dark:border-gray-700 lg:border-b-0 lg:border-r lg:border-gray-200 dark:lg:border-gray-700 lg:align-top flex-shrink-0 transition-all duration-300`}
- onMouseEnter={() => setSidebarCollapsed(false)}
- onMouseLeave={() => setSidebarCollapsed(true)}
+ class={`hidden lg:flex lg:flex-col ${sidebarCollapsed() ? 'w-16' : 'w-72'} ${sidebarCollapsed() ? 'lg:min-w-[4rem] lg:max-w-[4rem] lg:basis-[4rem]' : 'lg:min-w-[18rem] lg:max-w-[18rem] lg:basis-[18rem]'} relative border-b border-gray-200 dark:border-gray-700 lg:border-b-0 lg:border-r lg:border-gray-200 dark:lg:border-gray-700 lg:align-top flex-shrink-0 transition-all duration-200`}
aria-label="Alerts navigation"
aria-expanded={!sidebarCollapsed()}
>
- <div class={`sticky top-24 ${sidebarCollapsed() ? 'px-2' : 'px-5'} py-6 space-y-6 transition-all duration-300`}>
- <div id="alerts-sidebar-menu" class="space-y-6">
+ <div
+ class={`sticky top-0 ${sidebarCollapsed() ? 'px-2' : 'px-4'} py-5 space-y-5 transition-all duration-200`}
+ >
+ <Show when={!sidebarCollapsed()}>
+ <div class="flex items-center justify-between pb-2 border-b border-gray-200 dark:border-gray-700">
+ <h2 class="text-sm font-semibold text-gray-900 dark:text-gray-100">Alerts</h2>
+ <button
+ type="button"
+ onClick={() => setSidebarCollapsed(true)}
+ class="p-1 rounded-md text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
+ aria-label="Collapse sidebar"
+ >
+ <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
+ />
+ </svg>
+ </button>
+ </div>
+ </Show>
+ <Show when={sidebarCollapsed()}>
+ <button
+ type="button"
+ onClick={() => setSidebarCollapsed(false)}
+ class="w-full p-2 rounded-md text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
+ aria-label="Expand sidebar"
+ >
+ <svg
+ class="w-5 h-5 mx-auto"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M13 5l7 7-7 7M5 5l7 7-7 7"
+ />
+ </svg>
+ </button>
+ </Show>
+ <div id="alerts-sidebar-menu" class="space-y-5">
<For each={tabGroups}>
{(group) => (
<div class="space-y-2">
@@ -1772,24 +1818,18 @@ export function Alerts() {
<button
type="button"
aria-current={activeTab() === item.id ? 'page' : undefined}
- class={`flex w-full items-center ${sidebarCollapsed() ? 'justify-center' : 'gap-2.5'} rounded-md ${sidebarCollapsed() ? 'px-2 py-2.5' : 'px-3 py-2'} text-sm font-medium transition-colors ${activeTab() === item.id
- ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-200'
- : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-700/60 dark:hover:text-gray-100'
- } ${disabled() ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''}`}
disabled={disabled()}
+ class={`flex w-full items-center ${sidebarCollapsed() ? 'justify-center' : 'gap-2.5'} rounded-md ${sidebarCollapsed() ? 'px-2 py-2.5' : 'px-3 py-2'} text-sm font-medium transition-colors ${disabled()
+ ? 'opacity-60 cursor-not-allowed text-gray-400 dark:text-gray-600'
+ : activeTab() === item.id
+ ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-200'
+ : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-700/60 dark:hover:text-gray-100'
+ }`}
onClick={() => {
if (disabled()) return;
handleTabChange(item.id);
}}
- title={
- sidebarCollapsed()
- ? disabled()
- ? 'Activate alerts to configure'
- : item.label
- : disabled()
- ? 'Activate alerts to configure'
- : undefined
- }
+ title={sidebarCollapsed() ? item.label : undefined}
>
{item.icon}
<Show when={!sidebarCollapsed()}>
@@ -1807,7 +1847,7 @@ export function Alerts() {
</div>
</div>
- <div class="flex-1 min-w-0">
+ <div class="flex-1 overflow-hidden">
<Show when={flatTabs.length > 0}>
<div class="lg:hidden border-b border-gray-200 dark:border-gray-700">
<div class="p-1">
@@ -1999,6 +2039,30 @@ function OverviewTab(props: {
// Loading states for buttons
const [processingAlerts, setProcessingAlerts] = createSignal<Set<string>>(new Set());
+ // AI Patrol findings state
+ const [aiFindings, setAiFindings] = createSignal<Finding[]>([]);
+ const [patrolStatus, setPatrolStatus] = createSignal<PatrolStatus | null>(null);
+ const [processingFindings, setProcessingFindings] = createSignal<Set<string>>(new Set());
+
+ // Fetch AI findings on mount and every 30 seconds
+ onMount(() => {
+ const fetchAiData = async () => {
+ try {
+ const [status, findings] = await Promise.all([
+ getPatrolStatus(),
+ getFindings()
+ ]);
+ setPatrolStatus(status);
+ setAiFindings(findings);
+ } catch (e) {
+ // AI patrol may not be enabled - silently fail
+ }
+ };
+ fetchAiData();
+ const interval = setInterval(fetchAiData, 30000);
+ onCleanup(() => clearInterval(interval));
+ });
+
// Get alert stats from actual active alerts
const alertStats = createMemo(() => {
// Access the store properly for reactivity
@@ -2012,6 +2076,7 @@ function OverviewTab(props: {
};
});
+
const filteredAlerts = createMemo(() => {
const alerts = Object.values(props.activeAlerts);
// Sort: unacknowledged first, then by start time (newest first)
@@ -2033,34 +2098,23 @@ function OverviewTab(props: {
const [bulkAckProcessing, setBulkAckProcessing] = createSignal(false);
+ // Sub-tab for switching between AI Insights and Active Alerts
+ type OverviewSubTab = 'ai-insights' | 'active-alerts';
+
+ // Read subtab from URL query parameter to allow deep linking
+ const location = useLocation();
+ const getInitialSubTab = (): OverviewSubTab => {
+ const params = new URLSearchParams(location.search);
+ const subtab = params.get('subtab');
+ if (subtab === 'ai-insights') return 'ai-insights';
+ return 'active-alerts';
+ };
+ const [overviewSubTab, setOverviewSubTab] = createSignal<OverviewSubTab>(getInitialSubTab());
+
return (
<div class="space-y-6">
- {/* Stats Cards */}
- <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-4">
- <Card padding="sm" class="sm:p-4">
- <div class="flex items-center justify-between">
- <div>
- <p class="text-xs sm:text-sm text-gray-600 dark:text-gray-400">Active Alerts</p>
- <p class="text-xl sm:text-2xl font-semibold text-gray-600 dark:text-gray-300">
- {alertStats().active}
- </p>
- </div>
- <div class="w-8 h-8 sm:w-10 sm:h-10 bg-red-100 dark:bg-red-900/50 rounded-full flex items-center justify-center">
- <svg
- width="16"
- height="16"
- class="sm:w-5 sm:h-5 text-red-600 dark:text-red-400"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- >
- <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
- <path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
- </svg>
- </div>
- </div>
- </Card>
+ {/* Stats Cards - only show cards not duplicated in sub-tabs */}
+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3">
<Card padding="sm" class="sm:p-4">
<div class="flex items-center justify-between">
@@ -2138,256 +2192,483 @@ function OverviewTab(props: {
</Card>
</div>
- {/* Recent Alerts */}
- <div>
- <SectionHeader title="Active Alerts" size="md" class="mb-3" />
- <Show
- when={Object.keys(props.activeAlerts).length > 0}
- fallback={
- <div class="text-center py-8 text-gray-500 dark:text-gray-400">
- <div class="flex justify-center mb-3">
- <svg class="w-12 h-12 text-green-500 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" />
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4" />
- </svg>
- </div>
- <p class="text-sm">No active alerts</p>
- <p class="text-xs mt-1">Alerts will appear here when thresholds are exceeded</p>
- </div>
- }
- >
- <Show when={alertStats().acknowledged > 0 || alertStats().active > 0}>
- <div class="flex flex-wrap items-center justify-between gap-2 p-2 bg-gray-50 dark:bg-gray-800 rounded-t-lg border border-gray-200 dark:border-gray-700">
- <Show when={alertStats().acknowledged > 0}>
- <button
- onClick={() => props.setShowAcknowledged(!props.showAcknowledged())}
- class="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
- >
- {props.showAcknowledged() ? 'Hide' : 'Show'} acknowledged
- </button>
- </Show>
- <Show when={alertStats().active > 0}>
- <button
- type="button"
- class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium rounded-lg border border-blue-200 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-200 transition-colors hover:bg-blue-100 dark:hover:bg-blue-900/60 disabled:opacity-60 disabled:cursor-not-allowed"
- disabled={bulkAckProcessing()}
- onClick={async () => {
- if (bulkAckProcessing()) return;
- const pending = unacknowledgedAlerts();
- if (pending.length === 0) {
- return;
- }
- setBulkAckProcessing(true);
- try {
- const result = await AlertsAPI.bulkAcknowledge(pending.map((alert) => alert.id));
- const successes = result.results.filter((r) => r.success);
- const failures = result.results.filter((r) => !r.success);
-
- successes.forEach((res) => {
- props.updateAlert(res.alertId, {
- acknowledged: true,
- ackTime: new Date().toISOString(),
- });
- });
-
- if (successes.length > 0) {
- showSuccess(
- `Acknowledged ${successes.length} ${successes.length === 1 ? 'alert' : 'alerts'}.`,
- );
- }
+ {/* Sub-tabs for AI Insights vs Active Alerts */}
+ <Show when={patrolStatus()?.enabled}>
+ <div class="flex items-center gap-1 border-b border-gray-200 dark:border-gray-700/50 pb-1">
+ <button
+ class={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${overviewSubTab() === 'active-alerts'
+ ? 'bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 border border-b-0 border-gray-200 dark:border-gray-700'
+ : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
+ }`}
+ onClick={() => setOverviewSubTab('active-alerts')}
+ >
+ Active Alerts
+ <Show when={alertStats().active > 0}>
+ <span class="ml-2 px-1.5 py-0.5 text-xs font-medium rounded bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">
+ {alertStats().active}
+ </span>
+ </Show>
+ </button>
+ <button
+ class={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${overviewSubTab() === 'ai-insights'
+ ? 'bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 border border-b-0 border-gray-200 dark:border-gray-700'
+ : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
+ }`}
+ onClick={() => setOverviewSubTab('ai-insights')}
+ >
+ AI Insights
+ <Show when={aiFindings().length > 0}>
+ <span class="ml-2 px-1.5 py-0.5 text-xs font-medium rounded bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300">
+ {aiFindings().length}
+ </span>
+ </Show>
+ </button>
+ </div>
+ </Show>
- if (failures.length > 0) {
- showError(
- `Failed to acknowledge ${failures.length} ${failures.length === 1 ? 'alert' : 'alerts'}.`,
- );
- }
- } catch (error) {
- logger.error('Bulk acknowledge failed', error);
- showError('Failed to acknowledge alerts');
- } finally {
- setBulkAckProcessing(false);
- }
- }}
- >
- {bulkAckProcessing()
- ? 'Acknowledging…'
- : `Acknowledge all (${alertStats().active})`}
- </button>
- </Show>
- </div>
- </Show>
+ {/* AI Insights Section - show when AI tab selected and there are findings */}
+ <Show when={overviewSubTab() === 'ai-insights' && patrolStatus()?.enabled}>
+ <div>
+ <SectionHeader
+ title="AI Insights"
+ size="md"
+ class="mb-3"
+ />
+ <div class="text-xs text-gray-500 dark:text-gray-400 mb-3 flex items-center gap-2">
+ <svg class="w-4 h-4 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+ <span>Proactively detected by AI patrol • Last check: {patrolStatus()?.last_patrol_at ? formatTimestamp(patrolStatus()!.last_patrol_at!) : 'never'}</span>
+ </div>
<div class="space-y-2">
- <Show when={filteredAlerts().length === 0}>
- <div class="text-center py-8 text-gray-500 dark:text-gray-400">
- {props.showAcknowledged() ? 'No active alerts' : 'No unacknowledged alerts'}
- </div>
- </Show>
- <For each={filteredAlerts()}>
- {(alert) => (
- <div
- class={`border rounded-lg p-4 transition-all ${processingAlerts().has(alert.id) ? 'opacity-50' : ''
- } ${alert.acknowledged
- ? 'opacity-60 border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/20'
- : alert.level === 'critical'
- ? 'border-red-300 dark:border-red-800 bg-red-50 dark:bg-red-900/20'
- : 'border-yellow-300 dark:border-yellow-800 bg-yellow-50 dark:bg-yellow-900/20'
- }`}
- >
- <div class="flex flex-col sm:flex-row sm:items-start">
- <div class="flex items-start flex-1">
- {/* Status icon */}
- <div
- class={`mr-3 mt-0.5 transition-all ${alert.acknowledged
- ? 'text-green-600 dark:text-green-400'
- : alert.level === 'critical'
- ? 'text-red-600 dark:text-red-400'
- : 'text-yellow-600 dark:text-yellow-400'
- }`}
- >
- {alert.acknowledged ? (
- // Checkmark for acknowledged
- <svg
- class="w-5 h-5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
- />
- </svg>
- ) : (
- // Warning/Alert icon
- <svg
- class="w-5 h-5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
- />
- </svg>
- )}
- </div>
- <div class="flex-1 min-w-0">
- <div class="flex flex-wrap items-center gap-2">
+ <For each={aiFindings()}>
+ {(finding) => {
+ const colors = severityColors[finding.severity];
+ return (
+ <div
+ class={`border rounded-lg p-4 transition-all ${finding.acknowledged_at ? 'opacity-60' : ''}`}
+ style={{
+ 'background-color': colors.bg,
+ 'border-color': colors.border,
+ }}
+ >
+ <div class="flex flex-col sm:flex-row sm:items-start">
+ <div class="flex items-start flex-1">
+ {/* AI badge */}
+ <div class="mr-3 mt-0.5">
<span
- class={`text-sm font-medium truncate ${alert.level === 'critical'
- ? 'text-red-700 dark:text-red-400'
- : 'text-yellow-700 dark:text-yellow-400'
- }`}
+ class="inline-flex items-center justify-center w-5 h-5 rounded text-xs font-bold"
+ style={{ 'background-color': colors.border, color: colors.text }}
>
- {alert.resourceName}
+ AI
</span>
- <span class="text-xs text-gray-600 dark:text-gray-400">
- ({alert.type})
- </span>
- <Show when={alert.node}>
- <span class="text-xs text-gray-500 dark:text-gray-500">
- on {alert.node}
+ </div>
+ <div class="flex-1 min-w-0">
+ <div class="flex flex-wrap items-center gap-2">
+ <span
+ class="text-sm font-medium truncate"
+ style={{ color: colors.text }}
+ >
+ {finding.resource_name}
</span>
- </Show>
- <Show when={alert.acknowledged}>
- <span class="px-2 py-0.5 text-xs bg-yellow-200 dark:bg-yellow-800 text-yellow-800 dark:text-yellow-200 rounded">
- Acknowledged
+ <span class="text-xs text-gray-600 dark:text-gray-400">
+ ({finding.category})
</span>
+ <Show when={finding.node}>
+ <span class="text-xs text-gray-500 dark:text-gray-500">
+ on {finding.node}
+ </span>
+ </Show>
+ <span
+ class="px-2 py-0.5 text-xs rounded capitalize"
+ style={{ 'background-color': colors.border, color: colors.text }}
+ >
+ {finding.severity}
+ </span>
+ </div>
+ <p class="text-sm text-gray-700 dark:text-gray-300 mt-1 font-medium">
+ {finding.title}
+ </p>
+ <p class="text-sm text-gray-600 dark:text-gray-400 mt-0.5">
+ {finding.description}
+ </p>
+ <Show when={finding.recommendation}>
+ <p class="text-xs text-gray-500 dark:text-gray-500 mt-1 italic">
+ {finding.recommendation}
+ </p>
</Show>
+ <p class="text-xs text-gray-500 dark:text-gray-500 mt-1">
+ Detected: {formatTimestamp(finding.detected_at)}
+ </p>
</div>
- <p class="text-sm text-gray-700 dark:text-gray-300 mt-1 break-words">
- {alert.message}
- </p>
- <p class="text-xs text-gray-600 dark:text-gray-400 mt-1">
- Started: {new Date(alert.startTime).toLocaleString()}
- </p>
</div>
- </div>
- <div class="flex gap-2 mt-3 sm:mt-0 sm:ml-4 self-end sm:self-start">
- <button
- class={`px-3 py-1.5 text-xs font-medium border rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${alert.acknowledged
- ? 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600'
- : 'bg-white dark:bg-gray-700 text-yellow-700 dark:text-yellow-300 border-yellow-300 dark:border-yellow-700 hover:bg-yellow-50 dark:hover:bg-yellow-900/20'
- }`}
- disabled={processingAlerts().has(alert.id)}
- onClick={async (e) => {
- e.preventDefault();
- e.stopPropagation();
-
- // Prevent double-clicks
- if (processingAlerts().has(alert.id)) return;
-
- setProcessingAlerts((prev) => new Set(prev).add(alert.id));
-
- // Store current state to avoid race conditions
- const wasAcknowledged = alert.acknowledged;
-
- try {
- if (wasAcknowledged) {
- // Call API first, only update local state if successful
- await AlertsAPI.unacknowledge(alert.id);
- // Only update local state after successful API call
- props.updateAlert(alert.id, {
- acknowledged: false,
- ackTime: undefined,
- ackUser: undefined,
- });
- showSuccess('Alert restored');
- } else {
- // Call API first, only update local state if successful
- await AlertsAPI.acknowledge(alert.id);
- // Only update local state after successful API call
- props.updateAlert(alert.id, {
- acknowledged: true,
- ackTime: new Date().toISOString(),
- });
- showSuccess('Alert acknowledged');
- }
- } catch (err) {
- logger.error(
- `Failed to ${wasAcknowledged ? 'unacknowledge' : 'acknowledge'} alert:`,
- err,
- );
- showError(
- `Failed to ${wasAcknowledged ? 'restore' : 'acknowledge'} alert`,
- );
- // Don't update local state on error - let WebSocket keep the correct state
- } finally {
- // Keep button disabled for longer to prevent race conditions with WebSocket updates
- setTimeout(() => {
- setProcessingAlerts((prev) => {
+ <div class="flex gap-2 mt-3 sm:mt-0 sm:ml-4 self-end sm:self-start">
+ <button
+ class={`px-3 py-1.5 text-xs font-medium border rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${finding.acknowledged_at
+ ? 'bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-300 border-green-300 dark:border-green-700'
+ : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600'
+ }`}
+ disabled={processingFindings().has(finding.id) || !!finding.acknowledged_at}
+ onClick={async () => {
+ if (processingFindings().has(finding.id)) return;
+ setProcessingFindings((prev) => new Set(prev).add(finding.id));
+ try {
+ await acknowledgeFinding(finding.id);
+ // Update local state to mark as acknowledged (keep visible but dimmed)
+ setAiFindings((prev) => prev.map(f =>
+ f.id === finding.id
+ ? { ...f, acknowledged_at: new Date().toISOString() }
+ : f
+ ));
+ showSuccess('Finding acknowledged');
+ } catch (err) {
+ logger.error('Failed to acknowledge finding:', err);
+ showError('Failed to acknowledge finding');
+ } finally {
+ setProcessingFindings((prev) => {
const next = new Set(prev);
- next.delete(alert.id);
+ next.delete(finding.id);
return next;
});
- }, 1500); // 1.5 seconds to allow server to process and WebSocket to sync
- }
- }}
- >
- {processingAlerts().has(alert.id)
- ? 'Processing...'
- : alert.acknowledged
- ? 'Unacknowledge'
- : 'Acknowledge'}
- </button>
- <InvestigateAlertButton
- alert={alert}
- variant="text"
- size="sm"
- />
+ }
+ }}
+ >
+ {processingFindings().has(finding.id) ? 'Acknowledging...' : finding.acknowledged_at ? '✓ Acknowledged' : 'Acknowledge'}
+ </button>
+ {/* Snooze dropdown */}
+ <div class="relative group">
+ <button
+ class="px-3 py-1.5 text-xs font-medium border rounded-lg transition-all bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50"
+ disabled={processingFindings().has(finding.id)}
+ >
+ Snooze ▾
+ </button>
+ <div class="absolute right-0 mt-1 w-28 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-50">
+ <button
+ class="w-full px-3 py-2 text-left text-xs hover:bg-gray-100 dark:hover:bg-gray-700 rounded-t-lg"
+ onClick={async () => {
+ setProcessingFindings((prev) => new Set(prev).add(finding.id));
+ try {
+ await snoozeFinding(finding.id, 1);
+ setAiFindings((prev) => prev.filter(f => f.id !== finding.id));
+ showSuccess('Snoozed for 1 hour');
+ } catch (err) {
+ showError('Failed to snooze');
+ } finally {
+ setProcessingFindings((prev) => { const n = new Set(prev); n.delete(finding.id); return n; });
+ }
+ }}
+ >
+ 1 hour
+ </button>
+ <button
+ class="w-full px-3 py-2 text-left text-xs hover:bg-gray-100 dark:hover:bg-gray-700"
+ onClick={async () => {
+ setProcessingFindings((prev) => new Set(prev).add(finding.id));
+ try {
+ await snoozeFinding(finding.id, 24);
+ setAiFindings((prev) => prev.filter(f => f.id !== finding.id));
+ showSuccess('Snoozed for 24 hours');
+ } catch (err) {
+ showError('Failed to snooze');
+ } finally {
+ setProcessingFindings((prev) => { const n = new Set(prev); n.delete(finding.id); return n; });
+ }
+ }}
+ >
+ 24 hours
+ </button>
+ <button
+ class="w-full px-3 py-2 text-left text-xs hover:bg-gray-100 dark:hover:bg-gray-700 rounded-b-lg"
+ onClick={async () => {
+ setProcessingFindings((prev) => new Set(prev).add(finding.id));
+ try {
+ await snoozeFinding(finding.id, 168);
+ setAiFindings((prev) => prev.filter(f => f.id !== finding.id));
+ showSuccess('Snoozed for 7 days');
+ } catch (err) {
+ showError('Failed to snooze');
+ } finally {
+ setProcessingFindings((prev) => { const n = new Set(prev); n.delete(finding.id); return n; });
+ }
+ }}
+ >
+ 7 days
+ </button>
+ </div>
+ </div>
+ <button
+ class="px-3 py-1.5 text-xs font-medium border rounded-lg transition-all bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 border-purple-300 dark:border-purple-700 hover:bg-purple-100 dark:hover:bg-purple-900/50"
+ onClick={() => {
+ aiChatStore.openWithPrompt(
+ `Tell me more about this issue: ${finding.title} on ${finding.resource_name}. ${finding.description}`
+ );
+ }}
+ >
+ Investigate
+ </button>
+ </div>
</div>
</div>
- </div>
- )}
+ );
+ }}
</For>
</div>
- </Show>
- </div>
+ </div>
+ </Show>
+
+ {/* Active Alerts - show when alerts tab selected OR when patrol is disabled (no sub-tabs) */}
+ <Show when={overviewSubTab() === 'active-alerts' || !patrolStatus()?.enabled}>
+ <div>
+ <SectionHeader title="Active Alerts" size="md" class="mb-3" />
+ <Show
+ when={Object.keys(props.activeAlerts).length > 0}
+ fallback={
+ <div class="text-center py-8 text-gray-500 dark:text-gray-400">
+ <div class="flex justify-center mb-3">
+ <svg class="w-12 h-12 text-green-500 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" />
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4" />
+ </svg>
+ </div>
+ <p class="text-sm">No active alerts</p>
+ <p class="text-xs mt-1">Alerts will appear here when thresholds are exceeded</p>
+ </div>
+ }
+ >
+ <Show when={alertStats().acknowledged > 0 || alertStats().active > 0}>
+ <div class="flex flex-wrap items-center justify-between gap-2 p-2 bg-gray-50 dark:bg-gray-800 rounded-t-lg border border-gray-200 dark:border-gray-700">
+ <Show when={alertStats().acknowledged > 0}>
+ <button
+ onClick={() => props.setShowAcknowledged(!props.showAcknowledged())}
+ class="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
+ >
+ {props.showAcknowledged() ? 'Hide' : 'Show'} acknowledged
+ </button>
+ </Show>
+ <Show when={alertStats().active > 0}>
+ <button
+ type="button"
+ class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium rounded-lg border border-blue-200 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-200 transition-colors hover:bg-blue-100 dark:hover:bg-blue-900/60 disabled:opacity-60 disabled:cursor-not-allowed"
+ disabled={bulkAckProcessing()}
+ onClick={async () => {
+ if (bulkAckProcessing()) return;
+ const pending = unacknowledgedAlerts();
+ if (pending.length === 0) {
+ return;
+ }
+ setBulkAckProcessing(true);
+ try {
+ const result = await AlertsAPI.bulkAcknowledge(pending.map((alert) => alert.id));
+ const successes = result.results.filter((r) => r.success);
+ const failures = result.results.filter((r) => !r.success);
+
+ successes.forEach((res) => {
+ props.updateAlert(res.alertId, {
+ acknowledged: true,
+ ackTime: new Date().toISOString(),
+ });
+ });
+
+ if (successes.length > 0) {
+ showSuccess(
+ `Acknowledged ${successes.length} ${successes.length === 1 ? 'alert' : 'alerts'}.`,
+ );
+ }
+
+ if (failures.length > 0) {
+ showError(
+ `Failed to acknowledge ${failures.length} ${failures.length === 1 ? 'alert' : 'alerts'}.`,
+ );
+ }
+ } catch (error) {
+ logger.error('Bulk acknowledge failed', error);
+ showError('Failed to acknowledge alerts');
+ } finally {
+ setBulkAckProcessing(false);
+ }
+ }}
+ >
+ {bulkAckProcessing()
+ ? 'Acknowledging…'
+ : `Acknowledge all (${alertStats().active})`}
+ </button>
+ </Show>
+ </div>
+ </Show>
+ <div class="space-y-2">
+ <Show when={filteredAlerts().length === 0}>
+ <div class="text-center py-8 text-gray-500 dark:text-gray-400">
+ {props.showAcknowledged() ? 'No active alerts' : 'No unacknowledged alerts'}
+ </div>
+ </Show>
+ <For each={filteredAlerts()}>
+ {(alert) => (
+ <div
+ class={`border rounded-lg p-4 transition-all ${processingAlerts().has(alert.id) ? 'opacity-50' : ''
+ } ${alert.acknowledged
+ ? 'opacity-60 border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/20'
+ : alert.level === 'critical'
+ ? 'border-red-300 dark:border-red-800 bg-red-50 dark:bg-red-900/20'
+ : 'border-yellow-300 dark:border-yellow-800 bg-yellow-50 dark:bg-yellow-900/20'
+ }`}
+ >
+ <div class="flex flex-col sm:flex-row sm:items-start">
+ <div class="flex items-start flex-1">
+ {/* Status icon */}
+ <div
+ class={`mr-3 mt-0.5 transition-all ${alert.acknowledged
+ ? 'text-green-600 dark:text-green-400'
+ : alert.level === 'critical'
+ ? 'text-red-600 dark:text-red-400'
+ : 'text-yellow-600 dark:text-yellow-400'
+ }`}
+ >
+ {alert.acknowledged ? (
+ // Checkmark for acknowledged
+ <svg
+ class="w-5 h-5"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
+ </svg>
+ ) : (
+ // Warning/Alert icon
+ <svg
+ class="w-5 h-5"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
+ />
+ </svg>
+ )}
+ </div>
+ <div class="flex-1 min-w-0">
+ <div class="flex flex-wrap items-center gap-2">
+ <span
+ class={`text-sm font-medium truncate ${alert.level === 'critical'
+ ? 'text-red-700 dark:text-red-400'
+ : 'text-yellow-700 dark:text-yellow-400'
+ }`}
+ >
+ {alert.resourceName}
+ </span>
+ <span class="text-xs text-gray-600 dark:text-gray-400">
+ ({alert.type})
+ </span>
+ <Show when={alert.node}>
+ <span class="text-xs text-gray-500 dark:text-gray-500">
+ on {alert.node}
+ </span>
+ </Show>
+ <Show when={alert.acknowledged}>
+ <span class="px-2 py-0.5 text-xs bg-yellow-200 dark:bg-yellow-800 text-yellow-800 dark:text-yellow-200 rounded">
+ Acknowledged
+ </span>
+ </Show>
+ </div>
+ <p class="text-sm text-gray-700 dark:text-gray-300 mt-1 break-words">
+ {alert.message}
+ </p>
+ <p class="text-xs text-gray-600 dark:text-gray-400 mt-1">
+ Started: {new Date(alert.startTime).toLocaleString()}
+ </p>
+ </div>
+ </div>
+ <div class="flex gap-2 mt-3 sm:mt-0 sm:ml-4 self-end sm:self-start">
+ <button
+ class={`px-3 py-1.5 text-xs font-medium border rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${alert.acknowledged
+ ? 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600'
+ : 'bg-white dark:bg-gray-700 text-yellow-700 dark:text-yellow-300 border-yellow-300 dark:border-yellow-700 hover:bg-yellow-50 dark:hover:bg-yellow-900/20'
+ }`}
+ disabled={processingAlerts().has(alert.id)}
+ onClick={async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Prevent double-clicks
+ if (processingAlerts().has(alert.id)) return;
+
+ setProcessingAlerts((prev) => new Set(prev).add(alert.id));
+
+ // Store current state to avoid race conditions
+ const wasAcknowledged = alert.acknowledged;
+
+ try {
+ if (wasAcknowledged) {
+ // Call API first, only update local state if successful
+ await AlertsAPI.unacknowledge(alert.id);
+ // Only update local state after successful API call
+ props.updateAlert(alert.id, {
+ acknowledged: false,
+ ackTime: undefined,
+ ackUser: undefined,
+ });
+ showSuccess('Alert restored');
+ } else {
+ // Call API first, only update local state if successful
+ await AlertsAPI.acknowledge(alert.id);
+ // Only update local state after successful API call
+ props.updateAlert(alert.id, {
+ acknowledged: true,
+ ackTime: new Date().toISOString(),
+ });
+ showSuccess('Alert acknowledged');
+ }
+ } catch (err) {
+ logger.error(
+ `Failed to ${wasAcknowledged ? 'unacknowledge' : 'acknowledge'} alert:`,
+ err,
+ );
+ showError(
+ `Failed to ${wasAcknowledged ? 'restore' : 'acknowledge'} alert`,
+ );
+ // Don't update local state on error - let WebSocket keep the correct state
+ } finally {
+ // Keep button disabled for longer to prevent race conditions with WebSocket updates
+ setTimeout(() => {
+ setProcessingAlerts((prev) => {
+ const next = new Set(prev);
+ next.delete(alert.id);
+ return next;
+ });
+ }, 1500); // 1.5 seconds to allow server to process and WebSocket to sync
+ }
+ }}
+ >
+ {processingAlerts().has(alert.id)
+ ? 'Processing...'
+ : alert.acknowledged
+ ? 'Unacknowledge'
+ : 'Acknowledge'}
+ </button>
+ <InvestigateAlertButton
+ alert={alert}
+ variant="text"
+ size="sm"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ </Show>
</div>
);
}
@@ -3897,8 +4178,16 @@ function HistoryTab() {
deserialize: (raw) => (raw === 'warning' || raw === 'critical' ? raw : 'all'),
},
);
+ const [sourceFilter, setSourceFilter] = usePersistentSignal<'all' | 'alerts' | 'ai'>(
+ 'alertHistorySourceFilter',
+ 'all',
+ {
+ deserialize: (raw) => (raw === 'alerts' || raw === 'ai' ? raw : 'all'),
+ },
+ );
const [searchTerm, setSearchTerm] = createSignal('');
const [alertHistory, setAlertHistory] = createSignal<Alert[]>([]);
+ const [aiFindingsHistory, setAiFindingsHistory] = createSignal<Finding[]>([]);
const [loading, setLoading] = createSignal(true);
const [selectedBarIndex, setSelectedBarIndex] = createSignal<number | null>(null);
const MS_PER_HOUR = 60 * 60 * 1000;
@@ -3935,18 +4224,27 @@ function HistoryTab() {
};
let fetchRequestId = 0;
- const fetchAlertHistory = async (range: string) => {
+ const fetchHistory = async (range: string) => {
const requestId = ++fetchRequestId;
setLoading(true);
try {
- const history = await AlertsAPI.getHistory(buildHistoryParams(range));
+ // Fetch both alert history and AI findings history in parallel
+ const params = buildHistoryParams(range);
+ const startTimeStr = params.startTime;
+
+ const [alertHistoryData, aiFindingsData] = await Promise.all([
+ AlertsAPI.getHistory(params),
+ getFindingsHistory(startTimeStr),
+ ]);
+
if (requestId === fetchRequestId) {
- setAlertHistory(history);
+ setAlertHistory(alertHistoryData);
+ setAiFindingsHistory(aiFindingsData);
}
} catch (err) {
if (requestId === fetchRequestId) {
- logger.error('Failed to load alert history:', err);
+ logger.error('Failed to load history:', err);
}
} finally {
if (requestId === fetchRequestId) {
@@ -3981,7 +4279,7 @@ function HistoryTab() {
// Load alert history on mount
onMount(() => {
- fetchAlertHistory(timeFilter());
+ fetchHistory(timeFilter());
// Add keyboard event listeners
const handleKeydown = (e: KeyboardEvent) => {
@@ -4023,7 +4321,7 @@ function HistoryTab() {
skipInitialFetchEffect = false;
return;
}
- fetchAlertHistory(range);
+ fetchHistory(range);
});
// Format duration for display
@@ -4140,66 +4438,155 @@ function HistoryTab() {
return 'Unknown';
};
- // Extended alert type for display
- interface ExtendedAlert extends Alert {
- status?: string;
- duration?: string;
- resourceType?: string;
+ // Unified history item type that can be either an alert or an AI finding
+ type HistoryItemSource = 'alert' | 'ai';
+ interface HistoryItem {
+ id: string;
+ source: HistoryItemSource;
+ status: string;
+ startTime: string;
+ endTime?: string;
+ duration: string;
+ resourceName: string;
+ resourceType: string;
+ resourceId?: string;
+ node?: string;
+ severity: string; // warning, critical for alerts; severity for findings
+ // Aliases for backward compat with existing rendering code
+ level: string; // same as severity
+ type: string; // same as title
+ message?: string; // same as description
+ title: string;
+ description?: string;
+ acknowledged?: boolean;
+ autoResolved?: boolean;
}
- // Prepare all alerts without filtering
- const allAlertsData = createMemo(() => {
- // Combine active and historical alerts
- const allAlerts: ExtendedAlert[] = [];
-
- // Add active alerts
- Object.values(activeAlerts || {}).forEach((alert) => {
- allAlerts.push({
- ...alert,
- status: 'active',
- duration: formatDuration(alert.startTime),
- resourceType: getResourceType(alert.resourceName, alert.metadata),
+ // Prepare all history items (alerts + AI findings) based on source filter
+ const allHistoryData = createMemo(() => {
+ const items: HistoryItem[] = [];
+ const currentSource = sourceFilter();
+
+ // Add alerts if not filtering to AI only
+ if (currentSource === 'all' || currentSource === 'alerts') {
+ // Add active alerts
+ Object.values(activeAlerts || {}).forEach((alert) => {
+ items.push({
+ id: alert.id,
+ source: 'alert',
+ status: 'active',
+ startTime: alert.startTime,
+ duration: formatDuration(alert.startTime),
+ resourceName: alert.resourceName,
+ resourceType: getResourceType(alert.resourceName, alert.metadata),
+ resourceId: alert.resourceId,
+ node: alert.node,
+ severity: alert.level,
+ level: alert.level,
+ type: alert.type,
+ message: alert.message,
+ title: alert.type,
+ description: alert.message,
+ acknowledged: false,
+ });
});
- });
- // Create a set of active alert IDs for quick lookup
- const activeAlertIds = new Set(Object.keys(activeAlerts || {}));
+ // Create a set of active alert IDs for quick lookup
+ const activeAlertIds = new Set(Object.keys(activeAlerts || {}));
+
+ // Add historical alerts
+ alertHistory().forEach((alert) => {
+ if (activeAlertIds.has(alert.id)) return;
+
+ items.push({
+ id: alert.id,
+ source: 'alert',
+ status: alert.acknowledged ? 'acknowledged' : 'resolved',
+ startTime: alert.startTime,
+ endTime: alert.lastSeen,
+ duration: formatDuration(alert.startTime, alert.lastSeen),
+ resourceName: alert.resourceName,
+ resourceType: getResourceType(alert.resourceName, alert.metadata),
+ resourceId: alert.resourceId,
+ node: alert.node,
+ severity: alert.level,
+ level: alert.level,
+ type: alert.type,
+ message: alert.message,
+ title: alert.type,
+ description: alert.message,
+ acknowledged: alert.acknowledged,
+ });
+ });
+ }
- // Add historical alerts
- alertHistory().forEach((alert) => {
- // Skip if this alert is already in active alerts (avoid duplicates)
- if (activeAlertIds.has(alert.id)) {
- return;
- }
+ // Add AI findings if not filtering to alerts only
+ if (currentSource === 'all' || currentSource === 'ai') {
+ aiFindingsHistory().forEach((finding) => {
+ const isSnoozed = finding.snoozed_until && new Date(finding.snoozed_until) > new Date();
+
+ let status = 'active';
+ if (finding.resolved_at) {
+ status = finding.auto_resolved ? 'auto-resolved' : 'resolved';
+ } else if (isSnoozed) {
+ status = 'snoozed';
+ } else if (finding.acknowledged_at) {
+ status = 'acknowledged';
+ }
- allAlerts.push({
- ...alert,
- status: alert.acknowledged ? 'acknowledged' : 'resolved',
- duration: formatDuration(alert.startTime, alert.lastSeen),
- resourceType: getResourceType(alert.resourceName, alert.metadata),
+ items.push({
+ id: finding.id,
+ source: 'ai',
+ status,
+ startTime: finding.detected_at,
+ endTime: finding.resolved_at,
+ duration: formatDuration(finding.detected_at, finding.resolved_at),
+ resourceName: finding.resource_name,
+ resourceType: finding.resource_type,
+ resourceId: finding.resource_id,
+ node: finding.node,
+ severity: finding.severity,
+ level: finding.severity, // Map severity to level for compatibility
+ type: `AI: ${finding.title}`, // Prefix with AI to distinguish
+ message: finding.description,
+ title: finding.title,
+ description: finding.description,
+ acknowledged: !!finding.acknowledged_at,
+ autoResolved: finding.auto_resolved,
+ });
});
- });
+ }
- return allAlerts;
+ return items;
});
// Apply severity & search filters (time filtering is layered separately)
- const severityAndSearchFilteredAlerts = createMemo(() => {
- let filtered = allAlertsData();
+ const severityAndSearchFilteredItems = createMemo(() => {
+ let filtered = allHistoryData();
+ // Filter by severity (map AI severity to alert levels for consistent filtering)
if (severityFilter() !== 'all') {
- filtered = filtered.filter((a) => a.level === severityFilter());
+ const sevFilter = severityFilter();
+ filtered = filtered.filter((item) => {
+ // For alerts, use level; for AI findings, map severity
+ if (item.source === 'alert') {
+ return item.severity === sevFilter;
+ } else {
+ // AI findings: map warning->warning, critical->critical
+ return item.severity === sevFilter;
+ }
+ });
}
if (searchTerm()) {
const term = searchTerm().toLowerCase();
- filtered = filtered.filter((alert) => {
- const name = alert.resourceName?.toLowerCase() ?? '';
- const message = alert.message?.toLowerCase() ?? '';
- const type = alert.type?.toLowerCase() ?? '';
- const nodeName = alert.node?.toLowerCase() ?? '';
+ filtered = filtered.filter((item) => {
+ const name = item.resourceName?.toLowerCase() ?? '';
+ const title = item.title?.toLowerCase() ?? '';
+ const description = item.description?.toLowerCase() ?? '';
+ const nodeName = item.node?.toLowerCase() ?? '';
return (
- name.includes(term) || message.includes(term) || type.includes(term) || nodeName.includes(term)
+ name.includes(term) || title.includes(term) || description.includes(term) || nodeName.includes(term)
);
});
}
@@ -4209,7 +4596,7 @@ function HistoryTab() {
// Apply filters to get the final alert data
const alertData = createMemo(() => {
- let filtered = severityAndSearchFilteredAlerts();
+ let filtered = severityAndSearchFilteredItems();
const currentTimeFilter = timeFilter();
// Selected bar filter (takes precedence over time filter)
@@ -4343,7 +4730,7 @@ function HistoryTab() {
const alertTrends = createMemo(() => {
const now = Date.now();
const msPerHour = MS_PER_HOUR;
- const filteredAlerts = severityAndSearchFilteredAlerts();
+ const filteredAlerts = severityAndSearchFilteredItems();
const niceBucketSizes = [1, 2, 3, 6, 12, 24, 48, 72, 168, 336, 720, 1440]; // hours
const maxBuckets = 30;
@@ -4760,6 +5147,16 @@ function HistoryTab() {
<option value="warning">Warning Only</option>
</select>
+ <select
+ value={sourceFilter()}
+ onChange={(e) => setSourceFilter(e.currentTarget.value as 'all' | 'alerts' | 'ai')}
+ class="w-full sm:w-auto px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600"
+ >
+ <option value="all">All Sources</option>
+ <option value="alerts">Alerts Only</option>
+ <option value="ai">AI Insights Only</option>
+ </select>
+
<div class="w-full sm:flex-1 sm:max-w-xs">
<input
ref={searchInputRef}
@@ -4794,13 +5191,16 @@ function HistoryTab() {
>
{/* Table */}
<div class="mb-2 border border-gray-200 dark:border-gray-700 rounded overflow-hidden">
- <ScrollableTable minWidth="900px">
- <table class="w-full min-w-[900px] text-xs sm:text-sm">
+ <ScrollableTable minWidth="1000px">
+ <table class="w-full min-w-[1000px] text-xs sm:text-sm">
<thead>
<tr class="bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 border-b border-gray-300 dark:border-gray-600">
<th class="p-1 px-2 text-left text-[10px] sm:text-xs font-medium uppercase tracking-wider">
Timestamp
</th>
+ <th class="p-1 px-2 text-center text-[10px] sm:text-xs font-medium uppercase tracking-wider">
+ Source
+ </th>
<th class="p-1 px-2 text-left text-[10px] sm:text-xs font-medium uppercase tracking-wider">
Resource
</th>
@@ -4834,7 +5234,7 @@ function HistoryTab() {
{/* Date divider */}
<tr class="bg-gray-50 dark:bg-gray-900/40">
<td
- colspan="9"
+ colspan="10"
class="py-1.5 pr-3 pl-4 text-[12px] sm:text-sm font-semibold text-slate-700 dark:text-slate-100"
>
<div class="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
@@ -4842,8 +5242,14 @@ function HistoryTab() {
{group.label}
</span>
<span class="text-[10px] font-medium text-slate-500 dark:text-slate-400">
- {group.alerts.length}{' '}
- {group.alerts.length === 1 ? 'alert' : 'alerts'}
+ {(() => {
+ const alertCount = group.alerts.filter(a => a.source === 'alert').length;
+ const aiCount = group.alerts.filter(a => a.source === 'ai').length;
+ const parts = [];
+ if (alertCount > 0) parts.push(`${alertCount} alert${alertCount === 1 ? '' : 's'}`);
+ if (aiCount > 0) parts.push(`${aiCount} AI insight${aiCount === 1 ? '' : 's'}`);
+ return parts.join(', ') || `${group.alerts.length} item${group.alerts.length === 1 ? '' : 's'}`;
+ })()}
</span>
</div>
</td>
@@ -4864,6 +5270,18 @@ function HistoryTab() {
})}
</td>
+ {/* Source */}
+ <td class="p-1 px-2 text-center">
+ <span
+ class={`text-[10px] px-1.5 py-0.5 rounded font-medium ${alert.source === 'ai'
+ ? 'bg-violet-100 dark:bg-violet-900/50 text-violet-700 dark:text-violet-300'
+ : 'bg-sky-100 dark:bg-sky-900/50 text-sky-700 dark:text-sky-300'
+ }`}
+ >
+ {alert.source === 'ai' ? 'AI' : 'Alert'}
+ </span>
+ </td>
+
{/* Resource */}
<td class="p-1 px-2 font-medium text-gray-900 dark:text-gray-100 truncate max-w-[150px]">
{alert.resourceName}
@@ -4939,11 +5357,11 @@ function HistoryTab() {
id: alert.id,
type: alert.type,
level: alert.level as 'warning' | 'critical',
- resourceId: alert.resourceId,
+ resourceId: alert.resourceId || '',
resourceName: alert.resourceName,
- node: alert.node,
+ node: alert.node || '',
instance: '',
- message: alert.message,
+ message: alert.message || '',
value: 0,
threshold: 0,
startTime: alert.startTime,
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index 05d288c372..57fd5542da 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -256,6 +256,10 @@ func (s *Server) pingLoop(ac *agentConn, done chan struct{}) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
+ // Track consecutive ping failures to detect dead connections faster
+ consecutiveFailures := 0
+ const maxConsecutiveFailures = 3
+
for {
select {
case <-done:
@@ -267,8 +271,28 @@ func (s *Server) pingLoop(ac *agentConn, done chan struct{}) {
err := ac.conn.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(5*time.Second))
ac.writeMu.Unlock()
if err != nil {
- log.Debug().Err(err).Str("agent_id", ac.agent.AgentID).Msg("Failed to send ping to agent")
- return
+ consecutiveFailures++
+ log.Warn().
+ Err(err).
+ Str("agent_id", ac.agent.AgentID).
+ Str("hostname", ac.agent.Hostname).
+ Int("consecutive_failures", consecutiveFailures).
+ Msg("Failed to send ping to agent")
+
+ if consecutiveFailures >= maxConsecutiveFailures {
+ log.Error().
+ Str("agent_id", ac.agent.AgentID).
+ Str("hostname", ac.agent.Hostname).
+ Int("failures", consecutiveFailures).
+ Msg("Agent connection appears dead after multiple ping failures, closing connection")
+
+ // Close the connection - this will cause readLoop to exit and clean up
+ ac.conn.Close()
+ return
+ }
+ } else {
+ // Reset failure counter on successful ping
+ consecutiveFailures = 0
}
}
}
diff --git a/internal/ai/alert_threshold_adapter.go b/internal/ai/alert_threshold_adapter.go
new file mode 100644
index 0000000000..64e81f48f6
--- /dev/null
+++ b/internal/ai/alert_threshold_adapter.go
@@ -0,0 +1,76 @@
+package ai
+
+import (
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+// AlertThresholdAdapter adapts alerts.Manager to the ThresholdProvider interface
+// This allows the patrol service to use user-configured alert thresholds
+type AlertThresholdAdapter struct {
+ manager *alerts.Manager
+}
+
+// NewAlertThresholdAdapter creates a new adapter for the alerts manager
+func NewAlertThresholdAdapter(manager *alerts.Manager) *AlertThresholdAdapter {
+ return &AlertThresholdAdapter{manager: manager}
+}
+
+// GetNodeCPUThreshold returns the CPU alert trigger threshold for nodes (0-100%)
+func (a *AlertThresholdAdapter) GetNodeCPUThreshold() float64 {
+ if a.manager == nil {
+ return 80 // default
+ }
+ cfg := a.manager.GetConfig()
+ if cfg.NodeDefaults.CPU != nil && cfg.NodeDefaults.CPU.Trigger > 0 {
+ return cfg.NodeDefaults.CPU.Trigger
+ }
+ return 80 // default
+}
+
+// GetNodeMemoryThreshold returns the memory alert trigger threshold for nodes (0-100%)
+func (a *AlertThresholdAdapter) GetNodeMemoryThreshold() float64 {
+ if a.manager == nil {
+ return 85 // default
+ }
+ cfg := a.manager.GetConfig()
+ if cfg.NodeDefaults.Memory != nil && cfg.NodeDefaults.Memory.Trigger > 0 {
+ return cfg.NodeDefaults.Memory.Trigger
+ }
+ return 85 // default
+}
+
+// GetGuestMemoryThreshold returns the memory alert trigger threshold for guests (0-100%)
+func (a *AlertThresholdAdapter) GetGuestMemoryThreshold() float64 {
+ if a.manager == nil {
+ return 85 // default
+ }
+ cfg := a.manager.GetConfig()
+ if cfg.GuestDefaults.Memory != nil && cfg.GuestDefaults.Memory.Trigger > 0 {
+ return cfg.GuestDefaults.Memory.Trigger
+ }
+ return 85 // default
+}
+
+// GetGuestDiskThreshold returns the disk alert trigger threshold for guests (0-100%)
+func (a *AlertThresholdAdapter) GetGuestDiskThreshold() float64 {
+ if a.manager == nil {
+ return 90 // default
+ }
+ cfg := a.manager.GetConfig()
+ if cfg.GuestDefaults.Disk != nil && cfg.GuestDefaults.Disk.Trigger > 0 {
+ return cfg.GuestDefaults.Disk.Trigger
+ }
+ return 90 // default
+}
+
+// GetStorageThreshold returns the usage alert trigger threshold for storage (0-100%)
+func (a *AlertThresholdAdapter) GetStorageThreshold() float64 {
+ if a.manager == nil {
+ return 85 // default
+ }
+ cfg := a.manager.GetConfig()
+ if cfg.StorageDefault.Trigger > 0 {
+ return cfg.StorageDefault.Trigger
+ }
+ return 85 // default
+}
diff --git a/internal/ai/findings.go b/internal/ai/findings.go
new file mode 100644
index 0000000000..1f32b0ebbf
--- /dev/null
+++ b/internal/ai/findings.go
@@ -0,0 +1,444 @@
+// Package ai provides AI-powered infrastructure monitoring and investigation.
+package ai
+
+import (
+ "sync"
+ "time"
+)
+
+// FindingSeverity represents how urgent a finding is
+type FindingSeverity string
+
+const (
+ // FindingSeverityInfo is informational - user may want to know
+ FindingSeverityInfo FindingSeverity = "info"
+ // FindingSeverityWatch means something to keep an eye on
+ FindingSeverityWatch FindingSeverity = "watch"
+ // FindingSeverityWarning means action should be taken soon
+ FindingSeverityWarning FindingSeverity = "warning"
+ // FindingSeverityCritical means immediate action needed
+ FindingSeverityCritical FindingSeverity = "critical"
+)
+
+// FindingCategory groups findings by type
+type FindingCategory string
+
+const (
+ FindingCategoryPerformance FindingCategory = "performance"
+ FindingCategoryCapacity FindingCategory = "capacity"
+ FindingCategoryReliability FindingCategory = "reliability"
+ FindingCategoryBackup FindingCategory = "backup"
+ FindingCategorySecurity FindingCategory = "security"
+ FindingCategoryGeneral FindingCategory = "general"
+)
+
+// Finding represents an AI-discovered insight about infrastructure
+type Finding struct {
+ ID string `json:"id"`
+ Severity FindingSeverity `json:"severity"`
+ Category FindingCategory `json:"category"`
+ ResourceID string `json:"resource_id"`
+ ResourceName string `json:"resource_name"`
+ ResourceType string `json:"resource_type"` // node, vm, container, docker, storage, host, pbs, host_raid
+ Node string `json:"node,omitempty"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Recommendation string `json:"recommendation,omitempty"`
+ Evidence string `json:"evidence,omitempty"` // data/commands that led to this finding
+ DetectedAt time.Time `json:"detected_at"`
+ LastSeenAt time.Time `json:"last_seen_at"`
+ ResolvedAt *time.Time `json:"resolved_at,omitempty"`
+ AutoResolved bool `json:"auto_resolved"`
+ AcknowledgedAt *time.Time `json:"acknowledged_at,omitempty"`
+ SnoozedUntil *time.Time `json:"snoozed_until,omitempty"` // Finding hidden until this time
+ // Link to alert if this finding was triggered by or attached to an alert
+ AlertID string `json:"alert_id,omitempty"`
+}
+
+// IsActive returns true if the finding is still active (not resolved and not snoozed)
+func (f *Finding) IsActive() bool {
+ return f.ResolvedAt == nil && !f.IsSnoozed()
+}
+
+// IsSnoozed returns true if the finding is currently snoozed
+func (f *Finding) IsSnoozed() bool {
+ return f.SnoozedUntil != nil && time.Now().Before(*f.SnoozedUntil)
+}
+
+// IsResolved returns true if the finding has been resolved (ignores snooze)
+func (f *Finding) IsResolved() bool {
+ return f.ResolvedAt != nil
+}
+
+// FindingsPersistence interface for saving/loading findings (avoids circular imports)
+type FindingsPersistence interface {
+ SaveFindings(findings map[string]*Finding) error
+ LoadFindings() (map[string]*Finding, error)
+}
+
+// FindingsStore provides thread-safe storage for AI findings with optional persistence
+type FindingsStore struct {
+ mu sync.RWMutex
+ findings map[string]*Finding // keyed by ID
+ // Index by resource for quick lookups
+ byResource map[string][]string // resource_id -> []finding_id
+ // Keep track of active findings count by severity (cached, but GetSummary calculates dynamically)
+ activeCounts map[FindingSeverity]int
+ // Persistence layer (optional)
+ persistence FindingsPersistence
+ // Debounce save operations
+ saveTimer *time.Timer
+ savePending bool
+ saveDebounce time.Duration
+}
+
+// NewFindingsStore creates a new findings store
+func NewFindingsStore() *FindingsStore {
+ return &FindingsStore{
+ findings: make(map[string]*Finding),
+ byResource: make(map[string][]string),
+ activeCounts: make(map[FindingSeverity]int),
+ saveDebounce: 5 * time.Second, // Debounce saves by 5 seconds
+ }
+}
+
+// SetPersistence sets the persistence layer and loads existing findings
+func (s *FindingsStore) SetPersistence(p FindingsPersistence) error {
+ s.mu.Lock()
+ s.persistence = p
+ s.mu.Unlock()
+
+ // Load existing findings from disk
+ if p != nil {
+ findings, err := p.LoadFindings()
+ if err != nil {
+ return err
+ }
+ if len(findings) > 0 {
+ s.mu.Lock()
+ for id, f := range findings {
+ s.findings[id] = f
+ s.byResource[f.ResourceID] = append(s.byResource[f.ResourceID], id)
+ if f.IsActive() {
+ s.activeCounts[f.Severity]++
+ }
+ }
+ s.mu.Unlock()
+ }
+ }
+ return nil
+}
+
+// scheduleSave schedules a debounced save operation
+func (s *FindingsStore) scheduleSave() {
+ if s.persistence == nil {
+ return
+ }
+
+ // Already have a save pending
+ if s.savePending {
+ return
+ }
+
+ s.savePending = true
+ s.saveTimer = time.AfterFunc(s.saveDebounce, func() {
+ s.mu.Lock()
+ s.savePending = false
+ // Make a copy for saving
+ findingsCopy := make(map[string]*Finding, len(s.findings))
+ for id, f := range s.findings {
+ copy := *f
+ findingsCopy[id] = &copy
+ }
+ persistence := s.persistence
+ s.mu.Unlock()
+
+ if persistence != nil {
+ if err := persistence.SaveFindings(findingsCopy); err != nil {
+ // Log error but don't fail - persistence is best-effort
+ // (log import would create circular dep, so we silently fail)
+ }
+ }
+ })
+}
+
+// ForceSave immediately saves findings (useful for shutdown)
+func (s *FindingsStore) ForceSave() error {
+ s.mu.Lock()
+ if s.saveTimer != nil {
+ s.saveTimer.Stop()
+ }
+ s.savePending = false
+
+ findingsCopy := make(map[string]*Finding, len(s.findings))
+ for id, f := range s.findings {
+ copy := *f
+ findingsCopy[id] = &copy
+ }
+ persistence := s.persistence
+ s.mu.Unlock()
+
+ if persistence != nil {
+ return persistence.SaveFindings(findingsCopy)
+ }
+ return nil
+}
+
+// Add adds or updates a finding
+// If a finding with the same ID exists, it updates LastSeenAt
+// Returns true if this is a new finding
+func (s *FindingsStore) Add(f *Finding) bool {
+ s.mu.Lock()
+
+ existing, exists := s.findings[f.ID]
+ if exists {
+ // Update existing finding
+ existing.LastSeenAt = time.Now()
+ existing.Description = f.Description
+ existing.Recommendation = f.Recommendation
+ existing.Evidence = f.Evidence
+ existing.Severity = f.Severity
+ s.mu.Unlock()
+ s.scheduleSave()
+ return false
+ }
+
+ // New finding
+ if f.DetectedAt.IsZero() {
+ f.DetectedAt = time.Now()
+ }
+ f.LastSeenAt = time.Now()
+
+ s.findings[f.ID] = f
+ s.byResource[f.ResourceID] = append(s.byResource[f.ResourceID], f.ID)
+ if f.IsActive() {
+ s.activeCounts[f.Severity]++
+ }
+ s.mu.Unlock()
+ s.scheduleSave()
+
+ return true
+}
+
+// Resolve marks a finding as resolved
+func (s *FindingsStore) Resolve(id string, auto bool) bool {
+ s.mu.Lock()
+
+ f, exists := s.findings[id]
+ if !exists || !f.IsActive() {
+ s.mu.Unlock()
+ return false
+ }
+
+ now := time.Now()
+ f.ResolvedAt = &now
+ f.AutoResolved = auto
+ s.activeCounts[f.Severity]--
+ s.mu.Unlock()
+ s.scheduleSave()
+
+ return true
+}
+
+// Acknowledge marks a finding as acknowledged
+func (s *FindingsStore) Acknowledge(id string) bool {
+ s.mu.Lock()
+
+ f, exists := s.findings[id]
+ if !exists {
+ s.mu.Unlock()
+ return false
+ }
+
+ now := time.Now()
+ f.AcknowledgedAt = &now
+ s.mu.Unlock()
+ s.scheduleSave()
+ return true
+}
+
+// Snooze hides a finding for the specified duration
+// Common durations: 1h, 24h, 7d (168h)
+func (s *FindingsStore) Snooze(id string, duration time.Duration) bool {
+ s.mu.Lock()
+
+ f, exists := s.findings[id]
+ if !exists || f.IsResolved() {
+ s.mu.Unlock()
+ return false
+ }
+
+ // If was previously active (not snoozed), decrement count
+ if f.SnoozedUntil == nil || time.Now().After(*f.SnoozedUntil) {
+ s.activeCounts[f.Severity]--
+ }
+
+ until := time.Now().Add(duration)
+ f.SnoozedUntil = &until
+ s.mu.Unlock()
+ s.scheduleSave()
+ return true
+}
+
+// Unsnooze removes the snooze from a finding, making it active again
+func (s *FindingsStore) Unsnooze(id string) bool {
+ s.mu.Lock()
+
+ f, exists := s.findings[id]
+ if !exists || f.IsResolved() {
+ s.mu.Unlock()
+ return false
+ }
+
+ if f.SnoozedUntil != nil {
+ f.SnoozedUntil = nil
+ s.activeCounts[f.Severity]++
+ }
+ s.mu.Unlock()
+ s.scheduleSave()
+ return true
+}
+
+// Get returns a finding by ID
+func (s *FindingsStore) Get(id string) *Finding {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if f, exists := s.findings[id]; exists {
+ // Return a copy to prevent mutations
+ copy := *f
+ return &copy
+ }
+ return nil
+}
+
+// GetByResource returns all active findings for a resource
+func (s *FindingsStore) GetByResource(resourceID string) []*Finding {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ ids := s.byResource[resourceID]
+ result := make([]*Finding, 0, len(ids))
+ for _, id := range ids {
+ if f, exists := s.findings[id]; exists && f.IsActive() {
+ copy := *f
+ result = append(result, &copy)
+ }
+ }
+ return result
+}
+
+// GetActive returns all active findings, optionally filtered by severity
+func (s *FindingsStore) GetActive(minSeverity FindingSeverity) []*Finding {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ severityOrder := map[FindingSeverity]int{
+ FindingSeverityInfo: 0,
+ FindingSeverityWatch: 1,
+ FindingSeverityWarning: 2,
+ FindingSeverityCritical: 3,
+ }
+ minOrder := severityOrder[minSeverity]
+
+ result := make([]*Finding, 0)
+ for _, f := range s.findings {
+ if f.IsActive() && severityOrder[f.Severity] >= minOrder {
+ copy := *f
+ result = append(result, &copy)
+ }
+ }
+ return result
+}
+
+// GetSummary returns a summary of active findings
+// Note: This calculates counts dynamically to handle time-based snooze expiration
+func (s *FindingsStore) GetSummary() FindingsSummary {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ summary := FindingsSummary{
+ Total: len(s.findings),
+ }
+
+ // Calculate active counts dynamically since IsActive() checks time-based snooze
+ for _, f := range s.findings {
+ if f.IsActive() {
+ switch f.Severity {
+ case FindingSeverityCritical:
+ summary.Critical++
+ case FindingSeverityWarning:
+ summary.Warning++
+ case FindingSeverityWatch:
+ summary.Watch++
+ case FindingSeverityInfo:
+ summary.Info++
+ }
+ }
+ }
+
+ return summary
+}
+
+// GetAll returns all findings including resolved ones (for history)
+// Results can be filtered by time range using startTime parameter
+func (s *FindingsStore) GetAll(startTime *time.Time) []*Finding {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ result := make([]*Finding, 0, len(s.findings))
+ for _, f := range s.findings {
+ // If startTime specified, only include findings detected after it
+ if startTime != nil && f.DetectedAt.Before(*startTime) {
+ continue
+ }
+ copy := *f
+ result = append(result, &copy)
+ }
+ return result
+}
+
+// Cleanup removes old resolved findings
+func (s *FindingsStore) Cleanup(maxAge time.Duration) int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ cutoff := time.Now().Add(-maxAge)
+ removed := 0
+
+ for id, f := range s.findings {
+ if f.ResolvedAt != nil && f.ResolvedAt.Before(cutoff) {
+ delete(s.findings, id)
+ // Clean up resource index
+ ids := s.byResource[f.ResourceID]
+ for i, fid := range ids {
+ if fid == id {
+ s.byResource[f.ResourceID] = append(ids[:i], ids[i+1:]...)
+ break
+ }
+ }
+ removed++
+ }
+ }
+
+ return removed
+}
+
+// FindingsSummary provides a quick count of findings by severity
+type FindingsSummary struct {
+ Critical int `json:"critical"`
+ Warning int `json:"warning"`
+ Watch int `json:"watch"`
+ Info int `json:"info"`
+ Total int `json:"total"`
+}
+
+// HasIssues returns true if there are any warning or critical findings
+func (s FindingsSummary) HasIssues() bool {
+ return s.Critical > 0 || s.Warning > 0
+}
+
+// IsHealthy returns true if there are no watch, warning, or critical findings
+func (s FindingsSummary) IsHealthy() bool {
+ return s.Critical == 0 && s.Warning == 0 && s.Watch == 0
+}
diff --git a/internal/ai/findings_persistence.go b/internal/ai/findings_persistence.go
new file mode 100644
index 0000000000..92f9712104
--- /dev/null
+++ b/internal/ai/findings_persistence.go
@@ -0,0 +1,79 @@
+// Package ai provides AI-powered infrastructure monitoring and investigation.
+package ai
+
+import (
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// FindingsPersistenceAdapter bridges ConfigPersistence to FindingsPersistence interface
+type FindingsPersistenceAdapter struct {
+ config *config.ConfigPersistence
+}
+
+// NewFindingsPersistenceAdapter creates a new adapter
+func NewFindingsPersistenceAdapter(cfg *config.ConfigPersistence) *FindingsPersistenceAdapter {
+ return &FindingsPersistenceAdapter{config: cfg}
+}
+
+// SaveFindings saves findings to disk via ConfigPersistence
+func (a *FindingsPersistenceAdapter) SaveFindings(findings map[string]*Finding) error {
+ // Convert from Finding to AIFindingRecord
+ records := make(map[string]*config.AIFindingRecord, len(findings))
+ for id, f := range findings {
+ records[id] = &config.AIFindingRecord{
+ ID: f.ID,
+ Severity: string(f.Severity),
+ Category: string(f.Category),
+ ResourceID: f.ResourceID,
+ ResourceName: f.ResourceName,
+ ResourceType: f.ResourceType,
+ Node: f.Node,
+ Title: f.Title,
+ Description: f.Description,
+ Recommendation: f.Recommendation,
+ Evidence: f.Evidence,
+ DetectedAt: f.DetectedAt,
+ LastSeenAt: f.LastSeenAt,
+ ResolvedAt: f.ResolvedAt,
+ AutoResolved: f.AutoResolved,
+ AcknowledgedAt: f.AcknowledgedAt,
+ SnoozedUntil: f.SnoozedUntil,
+ AlertID: f.AlertID,
+ }
+ }
+ return a.config.SaveAIFindings(records)
+}
+
+// LoadFindings loads findings from disk via ConfigPersistence
+func (a *FindingsPersistenceAdapter) LoadFindings() (map[string]*Finding, error) {
+ data, err := a.config.LoadAIFindings()
+ if err != nil {
+ return nil, err
+ }
+
+ // Convert from AIFindingRecord to Finding
+ findings := make(map[string]*Finding, len(data.Findings))
+ for id, r := range data.Findings {
+ findings[id] = &Finding{
+ ID: r.ID,
+ Severity: FindingSeverity(r.Severity),
+ Category: FindingCategory(r.Category),
+ ResourceID: r.ResourceID,
+ ResourceName: r.ResourceName,
+ ResourceType: r.ResourceType,
+ Node: r.Node,
+ Title: r.Title,
+ Description: r.Description,
+ Recommendation: r.Recommendation,
+ Evidence: r.Evidence,
+ DetectedAt: r.DetectedAt,
+ LastSeenAt: r.LastSeenAt,
+ ResolvedAt: r.ResolvedAt,
+ AutoResolved: r.AutoResolved,
+ AcknowledgedAt: r.AcknowledgedAt,
+ SnoozedUntil: r.SnoozedUntil,
+ AlertID: r.AlertID,
+ }
+ }
+ return findings, nil
+}
diff --git a/internal/ai/findings_test.go b/internal/ai/findings_test.go
new file mode 100644
index 0000000000..c82b480b89
--- /dev/null
+++ b/internal/ai/findings_test.go
@@ -0,0 +1,252 @@
+package ai
+
+import (
+ "testing"
+ "time"
+)
+
+func TestFinding_IsActive(t *testing.T) {
+ tests := []struct {
+ name string
+ finding Finding
+ expected bool
+ }{
+ {
+ name: "active finding",
+ finding: Finding{ID: "test-1"},
+ expected: true,
+ },
+ {
+ name: "resolved finding",
+ finding: Finding{
+ ID: "test-2",
+ ResolvedAt: timePtr(time.Now()),
+ },
+ expected: false,
+ },
+ {
+ name: "snoozed finding",
+ finding: Finding{
+ ID: "test-3",
+ SnoozedUntil: timePtr(time.Now().Add(1 * time.Hour)),
+ },
+ expected: false,
+ },
+ {
+ name: "expired snooze finding",
+ finding: Finding{
+ ID: "test-4",
+ SnoozedUntil: timePtr(time.Now().Add(-1 * time.Hour)),
+ },
+ expected: true, // Snooze expired, should be active again
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tt.finding.IsActive(); got != tt.expected {
+ t.Errorf("IsActive() = %v, want %v", got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestFinding_IsSnoozed(t *testing.T) {
+ tests := []struct {
+ name string
+ finding Finding
+ expected bool
+ }{
+ {
+ name: "not snoozed",
+ finding: Finding{ID: "test-1"},
+ expected: false,
+ },
+ {
+ name: "actively snoozed",
+ finding: Finding{
+ ID: "test-2",
+ SnoozedUntil: timePtr(time.Now().Add(1 * time.Hour)),
+ },
+ expected: true,
+ },
+ {
+ name: "snooze expired",
+ finding: Finding{
+ ID: "test-3",
+ SnoozedUntil: timePtr(time.Now().Add(-1 * time.Hour)),
+ },
+ expected: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tt.finding.IsSnoozed(); got != tt.expected {
+ t.Errorf("IsSnoozed() = %v, want %v", got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestFindingsStore_Snooze(t *testing.T) {
+ store := NewFindingsStore()
+
+ // Add a finding
+ finding := &Finding{
+ ID: "finding-1",
+ Severity: FindingSeverityWarning,
+ ResourceID: "res-1",
+ ResourceName: "test-resource",
+ Title: "Test Finding",
+ }
+ store.Add(finding)
+
+ // Verify it's active
+ activeFindings := store.GetActive(FindingSeverityInfo)
+ if len(activeFindings) != 1 {
+ t.Fatalf("Expected 1 active finding, got %d", len(activeFindings))
+ }
+
+ // Snooze the finding for 1 hour
+ if !store.Snooze("finding-1", 1*time.Hour) {
+ t.Fatal("Snooze should return true for existing finding")
+ }
+
+ // Verify it's no longer in active list
+ activeFindings = store.GetActive(FindingSeverityInfo)
+ if len(activeFindings) != 0 {
+ t.Fatalf("Expected 0 active findings after snooze, got %d", len(activeFindings))
+ }
+
+ // Verify summary counts decreased
+ summary := store.GetSummary()
+ if summary.Warning != 0 {
+ t.Errorf("Expected 0 warning count, got %d", summary.Warning)
+ }
+
+ // Snooze non-existent finding
+ if store.Snooze("non-existent", 1*time.Hour) {
+ t.Error("Snooze should return false for non-existent finding")
+ }
+}
+
+func TestFindingsStore_Unsnooze(t *testing.T) {
+ store := NewFindingsStore()
+
+ // Add and snooze a finding
+ finding := &Finding{
+ ID: "finding-1",
+ Severity: FindingSeverityCritical,
+ ResourceID: "res-1",
+ ResourceName: "test-resource",
+ Title: "Test Finding",
+ }
+ store.Add(finding)
+ store.Snooze("finding-1", 1*time.Hour)
+
+ // Verify it's snoozed
+ activeFindings := store.GetActive(FindingSeverityInfo)
+ if len(activeFindings) != 0 {
+ t.Fatalf("Expected 0 active findings when snoozed, got %d", len(activeFindings))
+ }
+
+ // Unsnooze
+ if !store.Unsnooze("finding-1") {
+ t.Fatal("Unsnooze should return true for snoozed finding")
+ }
+
+ // Verify it's active again
+ activeFindings = store.GetActive(FindingSeverityInfo)
+ if len(activeFindings) != 1 {
+ t.Fatalf("Expected 1 active finding after unsnooze, got %d", len(activeFindings))
+ }
+
+ // Verify summary counts increased
+ summary := store.GetSummary()
+ if summary.Critical != 1 {
+ t.Errorf("Expected 1 critical count, got %d", summary.Critical)
+ }
+
+ // Unsnooze non-existent finding
+ if store.Unsnooze("non-existent") {
+ t.Error("Unsnooze should return false for non-existent finding")
+ }
+}
+
+func TestFindingsStore_SnoozeResolvedFinding(t *testing.T) {
+ store := NewFindingsStore()
+
+ // Add a finding
+ finding := &Finding{
+ ID: "finding-1",
+ Severity: FindingSeverityWarning,
+ ResourceID: "res-1",
+ ResourceName: "test-resource",
+ Title: "Test Finding",
+ }
+ store.Add(finding)
+
+ // Resolve it
+ store.Resolve("finding-1", false)
+
+ // Try to snooze a resolved finding - should fail
+ if store.Snooze("finding-1", 1*time.Hour) {
+ t.Error("Should not be able to snooze a resolved finding")
+ }
+}
+
+func TestFindingsStore_SummaryConsistentWithActive(t *testing.T) {
+ store := NewFindingsStore()
+
+ // Add mixed severity findings
+ store.Add(&Finding{ID: "f1", Severity: FindingSeverityCritical, ResourceID: "r1", ResourceName: "res1", Title: "Critical"})
+ store.Add(&Finding{ID: "f2", Severity: FindingSeverityWarning, ResourceID: "r2", ResourceName: "res2", Title: "Warning"})
+ store.Add(&Finding{ID: "f3", Severity: FindingSeverityWatch, ResourceID: "r3", ResourceName: "res3", Title: "Watch"})
+
+ // Verify initial consistency
+ active := store.GetActive(FindingSeverityInfo)
+ summary := store.GetSummary()
+
+ if len(active) != summary.Critical+summary.Warning+summary.Watch+summary.Info {
+ t.Errorf("Mismatch: %d active findings, summary totals %d", len(active), summary.Critical+summary.Warning+summary.Watch+summary.Info)
+ }
+
+ // Resolve the warning finding
+ store.Resolve("f2", false)
+
+ // Verify consistency after resolution
+ active = store.GetActive(FindingSeverityInfo)
+ summary = store.GetSummary()
+
+ if len(active) != 2 {
+ t.Fatalf("Expected 2 active findings after resolution, got %d", len(active))
+ }
+
+ if summary.Warning != 0 {
+ t.Errorf("Summary shows %d warnings but should be 0 after resolution", summary.Warning)
+ }
+
+ if summary.Critical != 1 {
+ t.Errorf("Summary shows %d critical but should be 1", summary.Critical)
+ }
+
+ // Snooze the critical finding
+ store.Snooze("f1", 1*time.Hour)
+
+ // Verify consistency after snooze
+ active = store.GetActive(FindingSeverityInfo)
+ summary = store.GetSummary()
+
+ if len(active) != 1 {
+ t.Errorf("Expected 1 active finding after snooze, got %d", len(active))
+ }
+
+ if summary.Critical != 0 {
+ t.Errorf("Summary shows %d critical but should be 0 after snooze", summary.Critical)
+ }
+}
+
+func timePtr(t time.Time) *time.Time {
+ return &t
+}
diff --git a/internal/ai/knowledge/store.go b/internal/ai/knowledge/store.go
index c72379b81e..d422456e85 100644
--- a/internal/ai/knowledge/store.go
+++ b/internal/ai/knowledge/store.go
@@ -357,27 +357,69 @@ func (s *Store) ListGuests() ([]string, error) {
// FormatAllForContext returns a summary of all saved knowledge across all guests
// This is used when no specific target is selected to give the AI full context
+// To prevent context bloat, it limits output to maxGuests and maxBytes
func (s *Store) FormatAllForContext() string {
+ const maxGuests = 10 // Only include the 10 most recently updated guests
+ const maxBytes = 8000 // Cap total output at ~8KB to leave room for other context
+
guests, err := s.ListGuests()
if err != nil || len(guests) == 0 {
return ""
}
- var sections []string
- totalNotes := 0
+ // Load all guests with notes and sort by most recently updated
+ type guestWithTime struct {
+ id string
+ knowledge *GuestKnowledge
+ }
+ var guestsWithNotes []guestWithTime
for _, guestID := range guests {
knowledge, err := s.GetKnowledge(guestID)
if err != nil || len(knowledge.Notes) == 0 {
continue
}
+ guestsWithNotes = append(guestsWithNotes, guestWithTime{id: guestID, knowledge: knowledge})
+ }
- totalNotes += len(knowledge.Notes)
+ if len(guestsWithNotes) == 0 {
+ return ""
+ }
+
+ // Sort by UpdatedAt descending (most recent first)
+ for i := 0; i < len(guestsWithNotes)-1; i++ {
+ for j := i + 1; j < len(guestsWithNotes); j++ {
+ if guestsWithNotes[j].knowledge.UpdatedAt.After(guestsWithNotes[i].knowledge.UpdatedAt) {
+ guestsWithNotes[i], guestsWithNotes[j] = guestsWithNotes[j], guestsWithNotes[i]
+ }
+ }
+ }
+
+ // Track how many guests and notes we're including vs total
+ totalGuests := len(guestsWithNotes)
+ totalNotes := 0
+ for _, g := range guestsWithNotes {
+ totalNotes += len(g.knowledge.Notes)
+ }
+
+ // Limit to maxGuests
+ truncatedGuests := false
+ if len(guestsWithNotes) > maxGuests {
+ guestsWithNotes = guestsWithNotes[:maxGuests]
+ truncatedGuests = true
+ }
+
+ var sections []string
+ includedNotes := 0
+ currentBytes := 0
+
+ for _, g := range guestsWithNotes {
+ knowledge := g.knowledge
// Build a summary for this guest
guestName := knowledge.GuestName
if guestName == "" {
- guestName = guestID
+ guestName = g.id
}
// Group notes by category
@@ -401,18 +443,44 @@ func (s *Store) FormatAllForContext() string {
if cat == "credential" && len(content) > 6 {
content = content[:2] + "****" + content[len(content)-2:]
}
- guestSection += fmt.Sprintf("\n- **%s**: %s", note.Title, content)
+ noteLine := fmt.Sprintf("\n- **%s**: %s", note.Title, content)
+
+ // Check if adding this note would exceed our byte limit
+ if currentBytes+len(guestSection)+len(noteLine) > maxBytes {
+ // Stop adding notes, we've hit the limit
+ if includedNotes > 0 {
+ log.Warn().
+ Int("total_notes", totalNotes).
+ Int("included_notes", includedNotes).
+ Int("total_guests", totalGuests).
+ Int("max_bytes", maxBytes).
+ Msg("Knowledge context truncated to prevent bloat - consider cleaning up old notes")
+ }
+ goto finalize
+ }
+ guestSection += noteLine
+ includedNotes++
}
}
+ currentBytes += len(guestSection)
sections = append(sections, guestSection)
}
+finalize:
if len(sections) == 0 {
return ""
}
- result := fmt.Sprintf("\n\n## Saved Knowledge (%d notes across %d guests)\n", totalNotes, len(sections))
+ // Build result with info about truncation if applicable
+ var header string
+ if truncatedGuests || includedNotes < totalNotes {
+ header = fmt.Sprintf("\n\n## Saved Knowledge (%d/%d notes from %d/%d guests, most recent)\n",
+ includedNotes, totalNotes, len(sections), totalGuests)
+ } else {
+ header = fmt.Sprintf("\n\n## Saved Knowledge (%d notes across %d guests)\n", totalNotes, len(sections))
+ }
+ result := header
result += "This is information learned from previous sessions. Use it to avoid rediscovery.\n"
result += strings.Join(sections, "\n")
diff --git a/internal/ai/knowledge/store_test.go b/internal/ai/knowledge/store_test.go
new file mode 100644
index 0000000000..86ba101ff9
--- /dev/null
+++ b/internal/ai/knowledge/store_test.go
@@ -0,0 +1,155 @@
+package knowledge
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestFormatAllForContext_LimitsOutput(t *testing.T) {
+ // Create a temp directory for the test
+ tmpDir, err := os.MkdirTemp("", "knowledge-test")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ // Create store without encryption for simplicity
+ store, err := NewStore(tmpDir)
+ if err != nil {
+ t.Fatalf("Failed to create store: %v", err)
+ }
+
+ // Add more than maxGuests (10) guests with notes
+ for i := 0; i < 15; i++ {
+ guestID := filepath.Base(tmpDir) + "-guest-" + string(rune('A'+i))
+ err := store.SaveNote(guestID, "Guest-"+string(rune('A'+i)), "vm", "service", "Web Server", "http://example.com:8080")
+ if err != nil {
+ t.Fatalf("Failed to save note: %v", err)
+ }
+ // Small delay to ensure different UpdatedAt times
+ time.Sleep(10 * time.Millisecond)
+ }
+
+ // Get the formatted context
+ result := store.FormatAllForContext()
+
+ if result == "" {
+ t.Fatal("Expected non-empty result")
+ }
+
+ // Should mention it's truncated (15 guests but only 10 included)
+ if !contains(result, "/") {
+ t.Error("Expected truncation indicator (e.g., '10/15 notes') in output")
+ }
+
+ // Count how many guest sections we have (look for "### Guest-")
+ guestCount := countOccurrences(result, "### Guest-")
+ if guestCount > 10 {
+ t.Errorf("Expected at most 10 guests, got %d", guestCount)
+ }
+
+ // Should be under 8KB
+ if len(result) > 8500 {
+ t.Errorf("Result too large: %d bytes (expected < 8500)", len(result))
+ }
+}
+
+func TestFormatAllForContext_PrioritizesRecent(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "knowledge-test")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, err := NewStore(tmpDir)
+ if err != nil {
+ t.Fatalf("Failed to create store: %v", err)
+ }
+
+ // Create an old guest first
+ err = store.SaveNote("old-guest", "OldGuest", "vm", "config", "Setting", "old value")
+ if err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(50 * time.Millisecond)
+
+ // Create a newer guest
+ err = store.SaveNote("new-guest", "NewGuest", "vm", "config", "Setting", "new value")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ result := store.FormatAllForContext()
+
+ // NewGuest should appear before OldGuest (more recently updated)
+ newIdx := indexOf(result, "NewGuest")
+ oldIdx := indexOf(result, "OldGuest")
+
+ if newIdx == -1 || oldIdx == -1 {
+ t.Fatalf("Both guests should be in result. newIdx=%d, oldIdx=%d", newIdx, oldIdx)
+ }
+
+ if newIdx > oldIdx {
+ t.Error("Expected NewGuest to appear before OldGuest (more recent)")
+ }
+}
+
+func TestFormatAllForContext_ByteLimit(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "knowledge-test")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, err := NewStore(tmpDir)
+ if err != nil {
+ t.Fatalf("Failed to create store: %v", err)
+ }
+
+ // Create notes with very large content to trigger byte limit
+ largeContent := make([]byte, 2000)
+ for i := range largeContent {
+ largeContent[i] = 'x'
+ }
+
+ for i := 0; i < 10; i++ {
+ guestID := "large-guest-" + string(rune('A'+i))
+ err := store.SaveNote(guestID, "LargeGuest-"+string(rune('A'+i)), "vm", "learning", "Big Note", string(largeContent))
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ result := store.FormatAllForContext()
+
+ // Should be capped at ~8KB (with some tolerance for headers)
+ if len(result) > 9000 {
+ t.Errorf("Result should be capped at ~8KB, got %d bytes", len(result))
+ }
+}
+
+// Helper functions
+func contains(s, substr string) bool {
+ return indexOf(s, substr) != -1
+}
+
+func indexOf(s, substr string) int {
+ for i := 0; i <= len(s)-len(substr); i++ {
+ if s[i:i+len(substr)] == substr {
+ return i
+ }
+ }
+ return -1
+}
+
+func countOccurrences(s, substr string) int {
+ count := 0
+ for i := 0; i <= len(s)-len(substr); i++ {
+ if s[i:i+len(substr)] == substr {
+ count++
+ }
+ }
+ return count
+}
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
new file mode 100644
index 0000000000..b9c54778c1
--- /dev/null
+++ b/internal/ai/patrol.go
@@ -0,0 +1,1243 @@
+package ai
+
+import (
+ "context"
+ "crypto/sha256"
+ "fmt"
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rs/zerolog/log"
+)
+
+// ThresholdProvider provides user-configured alert thresholds for patrol to use
+type ThresholdProvider interface {
+ // GetNodeCPUThreshold returns the CPU alert trigger threshold for nodes (0-100%)
+ GetNodeCPUThreshold() float64
+ // GetNodeMemoryThreshold returns the memory alert trigger threshold for nodes (0-100%)
+ GetNodeMemoryThreshold() float64
+ // GetGuestMemoryThreshold returns the memory alert trigger threshold for guests (0-100%)
+ GetGuestMemoryThreshold() float64
+ // GetGuestDiskThreshold returns the disk alert trigger threshold for guests (0-100%)
+ GetGuestDiskThreshold() float64
+ // GetStorageThreshold returns the usage alert trigger threshold for storage (0-100%)
+ GetStorageThreshold() float64
+}
+
+// PatrolThresholds holds calculated thresholds for patrol (derived from alert thresholds)
+type PatrolThresholds struct {
+ // Node thresholds
+ NodeCPUWatch float64 // CPU % to flag as "watch" (typically alertThreshold - 15)
+ NodeCPUWarning float64 // CPU % to flag as "warning" (typically alertThreshold - 5)
+ NodeMemWatch float64
+ NodeMemWarning float64
+ // Guest thresholds (VMs/containers)
+ GuestMemWatch float64
+ GuestMemWarning float64
+ GuestDiskWatch float64
+ GuestDiskWarn float64
+ GuestDiskCrit float64
+ // Storage thresholds
+ StorageWatch float64
+ StorageWarning float64
+ StorageCritical float64
+}
+
+// DefaultPatrolThresholds returns fallback thresholds when no provider is set
+func DefaultPatrolThresholds() PatrolThresholds {
+ return PatrolThresholds{
+ NodeCPUWatch: 75, NodeCPUWarning: 85,
+ NodeMemWatch: 75, NodeMemWarning: 85,
+ GuestMemWatch: 80, GuestMemWarning: 88,
+ GuestDiskWatch: 75, GuestDiskWarn: 85, GuestDiskCrit: 92,
+ StorageWatch: 70, StorageWarning: 80, StorageCritical: 90,
+ }
+}
+
+// CalculatePatrolThresholds derives patrol thresholds from alert thresholds
+// Patrol warns ~10% BEFORE the alert fires so users can take action early
+func CalculatePatrolThresholds(provider ThresholdProvider) PatrolThresholds {
+ if provider == nil {
+ return DefaultPatrolThresholds()
+ }
+
+ // Get user's alert thresholds
+ nodeCPU := provider.GetNodeCPUThreshold()
+ nodeMem := provider.GetNodeMemoryThreshold()
+ guestMem := provider.GetGuestMemoryThreshold()
+ guestDisk := provider.GetGuestDiskThreshold()
+ storage := provider.GetStorageThreshold()
+
+ // Calculate patrol thresholds (watch = alert-15%, warning = alert-5%)
+ return PatrolThresholds{
+ NodeCPUWatch: clampThreshold(nodeCPU - 15),
+ NodeCPUWarning: clampThreshold(nodeCPU - 5),
+ NodeMemWatch: clampThreshold(nodeMem - 15),
+ NodeMemWarning: clampThreshold(nodeMem - 5),
+ GuestMemWatch: clampThreshold(guestMem - 12),
+ GuestMemWarning: clampThreshold(guestMem - 5),
+ GuestDiskWatch: clampThreshold(guestDisk - 15),
+ GuestDiskWarn: clampThreshold(guestDisk - 8),
+ GuestDiskCrit: clampThreshold(guestDisk - 3),
+ StorageWatch: clampThreshold(storage - 15),
+ StorageWarning: clampThreshold(storage - 8),
+ StorageCritical: clampThreshold(storage - 3),
+ }
+}
+
+// clampThreshold ensures a threshold is within valid range
+func clampThreshold(v float64) float64 {
+ if v < 10 {
+ return 10 // Never go below 10%
+ }
+ if v > 99 {
+ return 99
+ }
+ return v
+}
+
+// PatrolConfig holds configuration for the AI patrol service
+type PatrolConfig struct {
+ // Enabled controls whether background patrol runs
+ Enabled bool `json:"enabled"`
+ // QuickCheckInterval is how often to do quick health checks
+ QuickCheckInterval time.Duration `json:"quick_check_interval"`
+ // DeepAnalysisInterval is how often to do thorough analysis
+ DeepAnalysisInterval time.Duration `json:"deep_analysis_interval"`
+ // AnalyzeNodes controls whether to analyze Proxmox nodes
+ AnalyzeNodes bool `json:"analyze_nodes"`
+ // AnalyzeGuests controls whether to analyze VMs/containers
+ AnalyzeGuests bool `json:"analyze_guests"`
+ // AnalyzeDocker controls whether to analyze Docker hosts
+ AnalyzeDocker bool `json:"analyze_docker"`
+ // AnalyzeStorage controls whether to analyze storage
+ AnalyzeStorage bool `json:"analyze_storage"`
+ // AnalyzePBS controls whether to analyze PBS backup servers
+ AnalyzePBS bool `json:"analyze_pbs"`
+ // AnalyzeHosts controls whether to analyze agent hosts (RAID, sensors)
+ AnalyzeHosts bool `json:"analyze_hosts"`
+}
+
+// DefaultPatrolConfig returns sensible defaults
+func DefaultPatrolConfig() PatrolConfig {
+ return PatrolConfig{
+ Enabled: true,
+ QuickCheckInterval: 15 * time.Minute,
+ DeepAnalysisInterval: 6 * time.Hour,
+ AnalyzeNodes: true,
+ AnalyzeGuests: true,
+ AnalyzeDocker: true,
+ AnalyzeStorage: true,
+ AnalyzePBS: true,
+ AnalyzeHosts: true,
+ }
+}
+
+// PatrolStatus represents the current state of the patrol service
+type PatrolStatus struct {
+ Running bool `json:"running"`
+ LastPatrolAt *time.Time `json:"last_patrol_at,omitempty"`
+ LastDeepAnalysis *time.Time `json:"last_deep_analysis_at,omitempty"`
+ NextPatrolAt *time.Time `json:"next_patrol_at,omitempty"`
+ LastDuration time.Duration `json:"last_duration_ms"`
+ ResourcesChecked int `json:"resources_checked"`
+ FindingsCount int `json:"findings_count"`
+ ErrorCount int `json:"error_count"`
+ Healthy bool `json:"healthy"`
+}
+
+// PatrolService runs background AI analysis of infrastructure
+type PatrolService struct {
+ mu sync.RWMutex
+
+ aiService *Service
+ stateProvider StateProvider
+ thresholdProvider ThresholdProvider
+ config PatrolConfig
+ findings *FindingsStore
+
+ // Cached thresholds (recalculated when thresholdProvider changes)
+ thresholds PatrolThresholds
+
+ // Runtime state
+ running bool
+ stopCh chan struct{}
+ lastPatrol time.Time
+ lastDeepAnalysis time.Time
+ lastDuration time.Duration
+ resourcesChecked int
+ errorCount int
+}
+
+// NewPatrolService creates a new patrol service
+func NewPatrolService(aiService *Service, stateProvider StateProvider) *PatrolService {
+ return &PatrolService{
+ aiService: aiService,
+ stateProvider: stateProvider,
+ config: DefaultPatrolConfig(),
+ findings: NewFindingsStore(),
+ thresholds: DefaultPatrolThresholds(),
+ stopCh: make(chan struct{}),
+ }
+}
+
+// SetConfig updates the patrol configuration
+func (p *PatrolService) SetConfig(cfg PatrolConfig) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.config = cfg
+}
+
+// SetThresholdProvider sets the provider for user-configured alert thresholds
+// This allows patrol to warn BEFORE alerts fire
+func (p *PatrolService) SetThresholdProvider(provider ThresholdProvider) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.thresholdProvider = provider
+ p.thresholds = CalculatePatrolThresholds(provider)
+ log.Debug().
+ Float64("storageWatch", p.thresholds.StorageWatch).
+ Float64("storageWarning", p.thresholds.StorageWarning).
+ Float64("storageCritical", p.thresholds.StorageCritical).
+ Msg("Patrol thresholds updated from alert config")
+}
+
+// SetFindingsPersistence enables findings persistence (load from and save to disk)
+// This should be called before Start() to load any existing findings
+func (p *PatrolService) SetFindingsPersistence(persistence FindingsPersistence) error {
+ p.mu.Lock()
+ findings := p.findings
+ p.mu.Unlock()
+
+ if findings != nil && persistence != nil {
+ if err := findings.SetPersistence(persistence); err != nil {
+ return err
+ }
+ log.Info().Msg("AI Patrol findings persistence enabled")
+ }
+ return nil
+}
+
+// GetConfig returns the current patrol configuration
+func (p *PatrolService) GetConfig() PatrolConfig {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.config
+}
+
+// GetFindings returns the findings store
+func (p *PatrolService) GetFindings() *FindingsStore {
+ return p.findings
+}
+
+// GetStatus returns the current patrol status
+func (p *PatrolService) GetStatus() PatrolStatus {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+
+ status := PatrolStatus{
+ Running: p.running,
+ LastDuration: p.lastDuration,
+ ResourcesChecked: p.resourcesChecked,
+ FindingsCount: len(p.findings.GetActive(FindingSeverityInfo)),
+ ErrorCount: p.errorCount,
+ }
+
+ if !p.lastPatrol.IsZero() {
+ status.LastPatrolAt = &p.lastPatrol
+ }
+ if !p.lastDeepAnalysis.IsZero() {
+ status.LastDeepAnalysis = &p.lastDeepAnalysis
+ }
+
+ if p.running && p.config.QuickCheckInterval > 0 {
+ next := p.lastPatrol.Add(p.config.QuickCheckInterval)
+ status.NextPatrolAt = &next
+ }
+
+ summary := p.findings.GetSummary()
+ status.Healthy = summary.IsHealthy()
+
+ return status
+}
+
+// Start begins the background patrol loop
+func (p *PatrolService) Start(ctx context.Context) {
+ p.mu.Lock()
+ if p.running {
+ p.mu.Unlock()
+ return
+ }
+ p.running = true
+ p.stopCh = make(chan struct{})
+ p.mu.Unlock()
+
+ log.Info().
+ Dur("quick_interval", p.config.QuickCheckInterval).
+ Dur("deep_interval", p.config.DeepAnalysisInterval).
+ Msg("Starting AI Patrol Service")
+
+ go p.patrolLoop(ctx)
+}
+
+// Stop stops the patrol service
+func (p *PatrolService) Stop() {
+ p.mu.Lock()
+ if !p.running {
+ p.mu.Unlock()
+ return
+ }
+ p.running = false
+ close(p.stopCh)
+ p.mu.Unlock()
+
+ log.Info().Msg("Stopping AI Patrol Service")
+}
+
+// patrolLoop is the main background loop
+func (p *PatrolService) patrolLoop(ctx context.Context) {
+ // Run initial quick patrol shortly after startup
+ initialDelay := 30 * time.Second
+ select {
+ case <-time.After(initialDelay):
+ p.runPatrol(ctx, false)
+ case <-p.stopCh:
+ return
+ case <-ctx.Done():
+ return
+ }
+
+ quickTicker := time.NewTicker(p.config.QuickCheckInterval)
+ defer quickTicker.Stop()
+
+ // Deep analysis ticker (if configured)
+ var deepTicker *time.Ticker
+ if p.config.DeepAnalysisInterval > 0 {
+ deepTicker = time.NewTicker(p.config.DeepAnalysisInterval)
+ defer deepTicker.Stop()
+ }
+
+ for {
+ select {
+ case <-quickTicker.C:
+ p.runPatrol(ctx, false)
+
+ case <-func() <-chan time.Time {
+ if deepTicker != nil {
+ return deepTicker.C
+ }
+ return make(chan time.Time) // never fires
+ }():
+ p.runPatrol(ctx, true)
+
+ case <-p.stopCh:
+ return
+
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+// runPatrol executes a patrol run
+func (p *PatrolService) runPatrol(ctx context.Context, deep bool) {
+ p.mu.RLock()
+ cfg := p.config
+ p.mu.RUnlock()
+
+ if !cfg.Enabled {
+ return
+ }
+
+ // Check if AI service is enabled
+ if p.aiService == nil || !p.aiService.IsEnabled() {
+ log.Debug().Msg("AI Patrol: AI service not enabled, skipping patrol")
+ return
+ }
+
+ start := time.Now()
+ patrolType := "quick"
+ if deep {
+ patrolType = "deep"
+ }
+
+ log.Debug().Str("type", patrolType).Msg("AI Patrol: Starting patrol run")
+
+ var resourceCount int
+ var errors int
+
+ // Get current state
+ if p.stateProvider == nil {
+ log.Warn().Msg("AI Patrol: No state provider available")
+ return
+ }
+
+ state := p.stateProvider.GetState()
+
+ // Analyze nodes
+ if cfg.AnalyzeNodes {
+ for _, node := range state.Nodes {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ resourceCount++
+ findings := p.analyzeNode(node, deep)
+ for _, f := range findings {
+ if p.findings.Add(f) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("severity", string(f.Severity)).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: New finding")
+ }
+ }
+ }
+ }
+
+ // Analyze VMs and containers
+ if cfg.AnalyzeGuests {
+ for _, vm := range state.VMs {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ resourceCount++
+ // Calculate usage percentages from Memory/Disk structs
+ var memUsage, diskUsage float64
+ if vm.Memory.Total > 0 {
+ memUsage = float64(vm.Memory.Used) / float64(vm.Memory.Total)
+ }
+ if vm.Disk.Total > 0 {
+ diskUsage = float64(vm.Disk.Used) / float64(vm.Disk.Total)
+ }
+ // Handle LastBackup - pass nil if zero time
+ var lastBackup *time.Time
+ if !vm.LastBackup.IsZero() {
+ t := vm.LastBackup
+ lastBackup = &t
+ }
+ findings := p.analyzeGuest(vm.ID, vm.Name, "vm", vm.Node, vm.Status,
+ vm.CPU, memUsage, diskUsage, lastBackup, vm.Template, deep)
+ for _, f := range findings {
+ if p.findings.Add(f) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("severity", string(f.Severity)).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: New finding")
+ }
+ }
+ }
+
+ for _, ct := range state.Containers {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ resourceCount++
+ // Calculate usage percentages from Memory/Disk structs
+ var memUsage, diskUsage float64
+ if ct.Memory.Total > 0 {
+ memUsage = float64(ct.Memory.Used) / float64(ct.Memory.Total)
+ }
+ if ct.Disk.Total > 0 {
+ diskUsage = float64(ct.Disk.Used) / float64(ct.Disk.Total)
+ }
+ // Handle LastBackup - pass nil if zero time
+ var lastBackup *time.Time
+ if !ct.LastBackup.IsZero() {
+ t := ct.LastBackup
+ lastBackup = &t
+ }
+ findings := p.analyzeGuest(ct.ID, ct.Name, "container", ct.Node, ct.Status,
+ ct.CPU, memUsage, diskUsage, lastBackup, ct.Template, deep)
+ for _, f := range findings {
+ if p.findings.Add(f) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("severity", string(f.Severity)).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: New finding")
+ }
+ }
+ }
+ }
+
+ // Analyze Docker hosts
+ if cfg.AnalyzeDocker {
+ for _, dh := range state.DockerHosts {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ resourceCount++
+ findings := p.analyzeDockerHost(dh, deep)
+ for _, f := range findings {
+ if p.findings.Add(f) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("severity", string(f.Severity)).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: New finding")
+ }
+ }
+ }
+ }
+
+ // Analyze storage
+ if cfg.AnalyzeStorage {
+ for _, st := range state.Storage {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ resourceCount++
+ findings := p.analyzeStorage(st, deep)
+ for _, f := range findings {
+ if p.findings.Add(f) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("severity", string(f.Severity)).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: New finding")
+ }
+ }
+ }
+ }
+
+ // Analyze PBS instances (backup servers)
+ if cfg.AnalyzePBS {
+ for _, pbs := range state.PBSInstances {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ resourceCount++
+ findings := p.analyzePBSInstance(pbs, state.PBSBackups, deep)
+ for _, f := range findings {
+ if p.findings.Add(f) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("severity", string(f.Severity)).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: New finding")
+ }
+ }
+ }
+ }
+
+ // Analyze agent hosts (RAID, sensors)
+ if cfg.AnalyzeHosts {
+ for _, host := range state.Hosts {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ resourceCount++
+ findings := p.analyzeHost(host, deep)
+ for _, f := range findings {
+ if p.findings.Add(f) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("severity", string(f.Severity)).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: New finding")
+ }
+ }
+ }
+ }
+
+ // Auto-resolve findings that weren't seen in this patrol run
+ p.autoResolveStaleFindings(start)
+
+ // Cleanup old resolved findings
+ cleaned := p.findings.Cleanup(24 * time.Hour)
+ if cleaned > 0 {
+ log.Debug().Int("cleaned", cleaned).Msg("AI Patrol: Cleaned up old findings")
+ }
+
+ duration := time.Since(start)
+
+ p.mu.Lock()
+ p.lastPatrol = time.Now()
+ p.lastDuration = duration
+ p.resourcesChecked = resourceCount
+ p.errorCount = errors
+ if deep {
+ p.lastDeepAnalysis = time.Now()
+ }
+ p.mu.Unlock()
+
+ summary := p.findings.GetSummary()
+ log.Info().
+ Str("type", patrolType).
+ Dur("duration", duration).
+ Int("resources", resourceCount).
+ Int("critical", summary.Critical).
+ Int("warning", summary.Warning).
+ Int("watch", summary.Watch).
+ Msg("AI Patrol: Completed patrol run")
+}
+
+// generateFindingID creates a stable ID for a finding based on resource and issue
+func generateFindingID(resourceID, category, issue string) string {
+ hash := sha256.Sum256([]byte(fmt.Sprintf("%s:%s:%s", resourceID, category, issue)))
+ return fmt.Sprintf("%x", hash[:8])
+}
+
+// analyzeNode checks a Proxmox node for issues
+func (p *PatrolService) analyzeNode(node models.Node, deep bool) []*Finding {
+ var findings []*Finding
+
+ // Calculate memory usage from Memory struct (as percentage 0-100)
+ var memUsagePct float64
+ if node.Memory.Total > 0 {
+ memUsagePct = float64(node.Memory.Used) / float64(node.Memory.Total) * 100
+ }
+
+ // CPU as percentage (node.CPU is 0-1 ratio from Proxmox)
+ cpuPct := node.CPU * 100
+
+ // Check for offline nodes
+ if node.Status == "offline" || node.Status == "unknown" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(node.ID, "reliability", "offline"),
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryReliability,
+ ResourceID: node.ID,
+ ResourceName: node.Name,
+ ResourceType: "node",
+ Title: "Node offline",
+ Description: fmt.Sprintf("Node '%s' is not responding", node.Name),
+ Recommendation: "Check network connectivity, SSH access, and Proxmox services on the node",
+ })
+ }
+
+ // High CPU - use dynamic thresholds from user's alert config
+ if cpuPct > p.thresholds.NodeCPUWatch {
+ severity := FindingSeverityWatch
+ if cpuPct > p.thresholds.NodeCPUWarning {
+ severity = FindingSeverityWarning
+ }
+ findings = append(findings, &Finding{
+ ID: generateFindingID(node.ID, "performance", "high-cpu"),
+ Severity: severity,
+ Category: FindingCategoryPerformance,
+ ResourceID: node.ID,
+ ResourceName: node.Name,
+ ResourceType: "node",
+ Title: "High CPU usage",
+ Description: fmt.Sprintf("Node '%s' CPU at %.0f%%", node.Name, cpuPct),
+ Recommendation: "Check which VMs/containers are consuming CPU. Consider load balancing.",
+ Evidence: fmt.Sprintf("CPU: %.1f%%", cpuPct),
+ })
+ }
+
+ // High memory - use dynamic thresholds
+ if memUsagePct > p.thresholds.NodeMemWatch {
+ severity := FindingSeverityWatch
+ if memUsagePct > p.thresholds.NodeMemWarning {
+ severity = FindingSeverityWarning
+ }
+ findings = append(findings, &Finding{
+ ID: generateFindingID(node.ID, "performance", "high-memory"),
+ Severity: severity,
+ Category: FindingCategoryPerformance,
+ ResourceID: node.ID,
+ ResourceName: node.Name,
+ ResourceType: "node",
+ Title: "High memory usage",
+ Description: fmt.Sprintf("Node '%s' memory at %.0f%%", node.Name, memUsagePct),
+ Recommendation: "Consider migrating some VMs to other nodes or increasing node RAM",
+ Evidence: fmt.Sprintf("Memory: %.1f%%", memUsagePct),
+ })
+ }
+
+ return findings
+}
+
+// analyzeGuest checks a VM or container for issues
+func (p *PatrolService) analyzeGuest(id, name, guestType, node, status string,
+ cpu, memUsage, diskUsage float64, lastBackup *time.Time, template, deep bool) []*Finding {
+ var findings []*Finding
+
+ // Skip templates
+ if template {
+ return findings
+ }
+
+ // Convert ratios to percentages for comparison with thresholds
+ memPct := memUsage * 100
+ diskPct := diskUsage * 100
+
+ // High memory (sustained) - use dynamic thresholds
+ if memPct > p.thresholds.GuestMemWatch {
+ severity := FindingSeverityWatch
+ if memPct > p.thresholds.GuestMemWarning {
+ severity = FindingSeverityWarning
+ }
+ findings = append(findings, &Finding{
+ ID: generateFindingID(id, "performance", "high-memory"),
+ Severity: severity,
+ Category: FindingCategoryPerformance,
+ ResourceID: id,
+ ResourceName: name,
+ ResourceType: guestType,
+ Node: node,
+ Title: "High memory usage",
+ Description: fmt.Sprintf("'%s' memory at %.0f%% - risk of OOM", name, memPct),
+ Recommendation: "Consider increasing allocated RAM or investigating memory-hungry processes",
+ Evidence: fmt.Sprintf("Memory: %.1f%%", memPct),
+ })
+ }
+
+ // High disk usage - use dynamic thresholds
+ if diskPct > p.thresholds.GuestDiskWatch {
+ severity := FindingSeverityWatch
+ if diskPct > p.thresholds.GuestDiskWarn {
+ severity = FindingSeverityWarning
+ }
+ if diskPct > p.thresholds.GuestDiskCrit {
+ severity = FindingSeverityCritical
+ }
+ findings = append(findings, &Finding{
+ ID: generateFindingID(id, "capacity", "high-disk"),
+ Severity: severity,
+ Category: FindingCategoryCapacity,
+ ResourceID: id,
+ ResourceName: name,
+ ResourceType: guestType,
+ Node: node,
+ Title: "High disk usage",
+ Description: fmt.Sprintf("'%s' disk at %.0f%%", name, diskPct),
+ Recommendation: "Clean up old files, logs, or docker images. Consider expanding disk.",
+ Evidence: fmt.Sprintf("Disk: %.1f%%", diskPct),
+ })
+ }
+
+ // Backup check (only for running guests)
+ if status == "running" && lastBackup != nil {
+ daysSinceBackup := time.Since(*lastBackup).Hours() / 24
+ if daysSinceBackup > 14 {
+ severity := FindingSeverityWatch
+ if daysSinceBackup > 30 {
+ severity = FindingSeverityWarning
+ }
+ findings = append(findings, &Finding{
+ ID: generateFindingID(id, "backup", "stale"),
+ Severity: severity,
+ Category: FindingCategoryBackup,
+ ResourceID: id,
+ ResourceName: name,
+ ResourceType: guestType,
+ Node: node,
+ Title: "Backup overdue",
+ Description: fmt.Sprintf("'%s' hasn't been backed up in %.0f days", name, daysSinceBackup),
+ Recommendation: "Check backup job configuration or run a manual backup",
+ Evidence: fmt.Sprintf("Last backup: %s", lastBackup.Format("2006-01-02")),
+ })
+ }
+ } else if status == "running" && lastBackup == nil {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(id, "backup", "never"),
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryBackup,
+ ResourceID: id,
+ ResourceName: name,
+ ResourceType: guestType,
+ Node: node,
+ Title: "Never backed up",
+ Description: fmt.Sprintf("'%s' has no backup history", name),
+ Recommendation: "Configure backup job for this guest",
+ })
+ }
+
+ return findings
+}
+
+// analyzeDockerHost checks a Docker host for issues
+func (p *PatrolService) analyzeDockerHost(host models.DockerHost, deep bool) []*Finding {
+ var findings []*Finding
+
+ hostName := host.Hostname
+ if host.DisplayName != "" {
+ hostName = host.DisplayName
+ }
+
+ // Host offline
+ if host.Status != "online" && host.Status != "connected" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(host.ID, "reliability", "offline"),
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryReliability,
+ ResourceID: host.ID,
+ ResourceName: hostName,
+ ResourceType: "docker_host",
+ Title: "Docker host offline",
+ Description: fmt.Sprintf("Docker host '%s' is not responding", hostName),
+ Recommendation: "Check network connectivity and docker-agent service",
+ })
+ }
+
+ // Check individual containers
+ for _, c := range host.Containers {
+ // Restarting containers
+ if c.State == "restarting" || c.RestartCount > 3 {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(c.ID, "reliability", "restart-loop"),
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryReliability,
+ ResourceID: c.ID,
+ ResourceName: c.Name,
+ ResourceType: "docker_container",
+ Node: hostName,
+ Title: "Container restart loop",
+ Description: fmt.Sprintf("Container '%s' has restarted %d times", c.Name, c.RestartCount),
+ Recommendation: "Check container logs: docker logs " + c.Name,
+ Evidence: fmt.Sprintf("State: %s, Restarts: %d", c.State, c.RestartCount),
+ })
+ }
+
+ // High memory containers
+ if c.MemoryPercent > 90 {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(c.ID, "performance", "high-memory"),
+ Severity: FindingSeverityWatch,
+ Category: FindingCategoryPerformance,
+ ResourceID: c.ID,
+ ResourceName: c.Name,
+ ResourceType: "docker_container",
+ Node: hostName,
+ Title: "High memory usage",
+ Description: fmt.Sprintf("Container '%s' using %.0f%% of allocated memory", c.Name, c.MemoryPercent),
+ Recommendation: "Consider increasing container memory limit",
+ Evidence: fmt.Sprintf("Memory: %.1f%%", c.MemoryPercent),
+ })
+ }
+ }
+
+ return findings
+}
+
+// analyzeStorage checks storage for issues
+func (p *PatrolService) analyzeStorage(storage models.Storage, deep bool) []*Finding {
+ var findings []*Finding
+
+ // Note: storage.Usage is already a percentage (0-100, e.g. 85.5 means 85.5%)
+ // If Usage is 0 but we have bytes data, calculate it as percentage
+ usage := storage.Usage
+ if usage == 0 && storage.Total > 0 {
+ usage = float64(storage.Used) / float64(storage.Total) * 100
+ }
+
+ // High storage usage - use dynamic thresholds from user's alert config
+ if usage > p.thresholds.StorageWatch {
+ severity := FindingSeverityWatch
+ if usage > p.thresholds.StorageWarning {
+ severity = FindingSeverityWarning
+ }
+ if usage > p.thresholds.StorageCritical {
+ severity = FindingSeverityCritical
+ }
+
+ findings = append(findings, &Finding{
+ ID: generateFindingID(storage.ID, "capacity", "high-usage"),
+ Severity: severity,
+ Category: FindingCategoryCapacity,
+ ResourceID: storage.ID,
+ ResourceName: storage.Name,
+ ResourceType: "storage",
+ Title: "Storage filling up",
+ Description: fmt.Sprintf("Storage '%s' at %.0f%% capacity", storage.Name, usage),
+ Recommendation: "Clean up old backups, snapshots, or unused disk images",
+ Evidence: fmt.Sprintf("Usage: %.1f%%", usage),
+ })
+ }
+
+ return findings
+}
+
+// autoResolveHealthyResources marks findings as resolved when they weren't seen in the current patrol
+// patrolStartTime is used to determine which findings are stale (LastSeenAt < patrolStartTime)
+func (p *PatrolService) autoResolveStaleFindings(patrolStartTime time.Time) {
+ // Get all active findings and check if they're stale
+ activeFindings := p.findings.GetActive(FindingSeverityInfo)
+
+ for _, f := range activeFindings {
+ // If the finding wasn't updated during this patrol (LastSeenAt is before patrol started),
+ // it means the condition that caused it has been resolved
+ if f.LastSeenAt.Before(patrolStartTime) {
+ if p.findings.Resolve(f.ID, true) {
+ log.Info().
+ Str("finding_id", f.ID).
+ Str("resource", f.ResourceName).
+ Str("title", f.Title).
+ Msg("AI Patrol: Auto-resolved finding")
+ }
+ }
+ }
+}
+
+// GetFindingsForResource returns active findings for a specific resource
+func (p *PatrolService) GetFindingsForResource(resourceID string) []*Finding {
+ return p.findings.GetByResource(resourceID)
+}
+
+// GetFindingsSummary returns a summary of all findings
+func (p *PatrolService) GetFindingsSummary() FindingsSummary {
+ return p.findings.GetSummary()
+}
+
+// GetAllFindings returns all active findings sorted by severity
+func (p *PatrolService) GetAllFindings() []*Finding {
+ findings := p.findings.GetActive(FindingSeverityInfo)
+
+ // Sort by severity (critical first) then by time
+ severityOrder := map[FindingSeverity]int{
+ FindingSeverityCritical: 0,
+ FindingSeverityWarning: 1,
+ FindingSeverityWatch: 2,
+ FindingSeverityInfo: 3,
+ }
+
+ sort.Slice(findings, func(i, j int) bool {
+ if severityOrder[findings[i].Severity] != severityOrder[findings[j].Severity] {
+ return severityOrder[findings[i].Severity] < severityOrder[findings[j].Severity]
+ }
+ return findings[i].DetectedAt.After(findings[j].DetectedAt)
+ })
+
+ return findings
+}
+
+// GetFindingsHistory returns all findings including resolved ones for history display
+// Optionally filter by startTime
+func (p *PatrolService) GetFindingsHistory(startTime *time.Time) []*Finding {
+ findings := p.findings.GetAll(startTime)
+
+ // Sort by detected time (newest first)
+ sort.Slice(findings, func(i, j int) bool {
+ return findings[i].DetectedAt.After(findings[j].DetectedAt)
+ })
+
+ return findings
+}
+
+// ForcePatrol triggers an immediate patrol run
+func (p *PatrolService) ForcePatrol(ctx context.Context, deep bool) {
+ go p.runPatrol(ctx, deep)
+}
+
+// analyzePBSInstance checks a PBS backup server for issues
+func (p *PatrolService) analyzePBSInstance(pbs models.PBSInstance, allBackups []models.PBSBackup, deep bool) []*Finding {
+ var findings []*Finding
+
+ pbsName := pbs.Name
+ if pbsName == "" {
+ pbsName = pbs.Host
+ }
+
+ // Check PBS connectivity
+ if pbs.Status != "online" && pbs.Status != "connected" && pbs.Status != "" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(pbs.ID, "reliability", "offline"),
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryReliability,
+ ResourceID: pbs.ID,
+ ResourceName: pbsName,
+ ResourceType: "pbs",
+ Title: "PBS server offline",
+ Description: fmt.Sprintf("Proxmox Backup Server '%s' is not responding", pbsName),
+ Recommendation: "Check network connectivity and PBS service status",
+ })
+ }
+
+ // Check each datastore capacity
+ for _, ds := range pbs.Datastores {
+ usage := ds.Usage
+ if usage == 0 && ds.Total > 0 {
+ usage = float64(ds.Used) / float64(ds.Total) * 100
+ }
+
+ // PBS datastores should trigger earlier than regular storage
+ // since running out of backup space is critical
+ if usage > p.thresholds.StorageWatch {
+ severity := FindingSeverityWatch
+ if usage > p.thresholds.StorageWarning {
+ severity = FindingSeverityWarning
+ }
+ if usage > p.thresholds.StorageCritical {
+ severity = FindingSeverityCritical
+ }
+
+ findings = append(findings, &Finding{
+ ID: generateFindingID(pbs.ID+":"+ds.Name, "capacity", "high-usage"),
+ Severity: severity,
+ Category: FindingCategoryCapacity,
+ ResourceID: pbs.ID + ":" + ds.Name,
+ ResourceName: fmt.Sprintf("%s/%s", pbsName, ds.Name),
+ ResourceType: "pbs_datastore",
+ Title: "PBS datastore filling up",
+ Description: fmt.Sprintf("Datastore '%s' on PBS '%s' at %.0f%% capacity", ds.Name, pbsName, usage),
+ Recommendation: "Run garbage collection, prune old backups, or expand storage",
+ Evidence: fmt.Sprintf("Usage: %.1f%%", usage),
+ })
+ }
+
+ // Check for datastore errors
+ if ds.Error != "" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(pbs.ID+":"+ds.Name, "reliability", "error"),
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryReliability,
+ ResourceID: pbs.ID + ":" + ds.Name,
+ ResourceName: fmt.Sprintf("%s/%s", pbsName, ds.Name),
+ ResourceType: "pbs_datastore",
+ Title: "PBS datastore error",
+ Description: fmt.Sprintf("Datastore '%s' has an error: %s", ds.Name, ds.Error),
+ Recommendation: "Check PBS server logs and datastore configuration",
+ Evidence: ds.Error,
+ })
+ }
+ }
+
+ // Check for backup staleness per datastore
+ // Build a map of latest backup time per datastore
+ datastoreLastBackup := make(map[string]time.Time)
+ for _, backup := range allBackups {
+ if backup.Instance != pbs.ID && backup.Instance != pbs.Name {
+ continue
+ }
+ dsKey := backup.Datastore
+ if backup.BackupTime.After(datastoreLastBackup[dsKey]) {
+ datastoreLastBackup[dsKey] = backup.BackupTime
+ }
+ }
+
+ for _, ds := range pbs.Datastores {
+ lastBackup, hasBackups := datastoreLastBackup[ds.Name]
+
+ if !hasBackups {
+ // No backups found for this datastore - might be intentional (empty datastore)
+ // Only warn if datastore has actual content
+ if ds.Used > 0 {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(pbs.ID+":"+ds.Name, "backup", "no-recent"),
+ Severity: FindingSeverityWatch,
+ Category: FindingCategoryBackup,
+ ResourceID: pbs.ID + ":" + ds.Name,
+ ResourceName: fmt.Sprintf("%s/%s", pbsName, ds.Name),
+ ResourceType: "pbs_datastore",
+ Title: "No recent backup metadata",
+ Description: fmt.Sprintf("Datastore '%s' has content but no recent backup entries visible", ds.Name),
+ Recommendation: "Verify backup jobs are configured and running",
+ })
+ }
+ continue
+ }
+
+ hoursSinceBackup := time.Since(lastBackup).Hours()
+ if hoursSinceBackup > 48 {
+ severity := FindingSeverityWatch
+ if hoursSinceBackup > 72 {
+ severity = FindingSeverityWarning
+ }
+ if hoursSinceBackup > 168 { // 7 days
+ severity = FindingSeverityCritical
+ }
+
+ findings = append(findings, &Finding{
+ ID: generateFindingID(pbs.ID+":"+ds.Name, "backup", "stale"),
+ Severity: severity,
+ Category: FindingCategoryBackup,
+ ResourceID: pbs.ID + ":" + ds.Name,
+ ResourceName: fmt.Sprintf("%s/%s", pbsName, ds.Name),
+ ResourceType: "pbs_datastore",
+ Title: "Stale backups",
+ Description: fmt.Sprintf("No backups to '%s/%s' in %.0f hours", pbsName, ds.Name, hoursSinceBackup),
+ Recommendation: "Check backup job schedule and logs for failures",
+ Evidence: fmt.Sprintf("Last backup: %s", lastBackup.Format("2006-01-02 15:04")),
+ })
+ }
+ }
+
+ // Check backup jobs for failures (only during deep analysis)
+ if deep {
+ for _, job := range pbs.BackupJobs {
+ if job.Status == "error" || job.Error != "" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(pbs.ID+":job:"+job.ID, "backup", "job-failed"),
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryBackup,
+ ResourceID: pbs.ID + ":job:" + job.ID,
+ ResourceName: fmt.Sprintf("%s/job/%s", pbsName, job.ID),
+ ResourceType: "pbs_job",
+ Title: "Backup job failed",
+ Description: fmt.Sprintf("Backup job '%s' on PBS '%s' is failing", job.ID, pbsName),
+ Recommendation: "Check PBS task logs for error details",
+ Evidence: job.Error,
+ })
+ }
+ }
+
+ for _, job := range pbs.VerifyJobs {
+ if job.Status == "error" || job.Error != "" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(pbs.ID+":verify:"+job.ID, "backup", "verify-failed"),
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryBackup,
+ ResourceID: pbs.ID + ":verify:" + job.ID,
+ ResourceName: fmt.Sprintf("%s/verify/%s", pbsName, job.ID),
+ ResourceType: "pbs_job",
+ Title: "Verify job failed",
+ Description: fmt.Sprintf("Verify job '%s' on PBS '%s' is failing", job.ID, pbsName),
+ Recommendation: "Check PBS task logs - verify failures may indicate backup corruption",
+ Evidence: job.Error,
+ })
+ }
+ }
+ }
+
+ return findings
+}
+
+// analyzeHost checks an agent host for issues (RAID, sensors, connectivity)
+func (p *PatrolService) analyzeHost(host models.Host, deep bool) []*Finding {
+ var findings []*Finding
+
+ hostName := host.DisplayName
+ if hostName == "" {
+ hostName = host.Hostname
+ }
+
+ // Check host connectivity
+ if host.Status != "online" && host.Status != "connected" && host.Status != "" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(host.ID, "reliability", "offline"),
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryReliability,
+ ResourceID: host.ID,
+ ResourceName: hostName,
+ ResourceType: "host",
+ Title: "Host agent offline",
+ Description: fmt.Sprintf("Host '%s' agent is not reporting", hostName),
+ Recommendation: "Check network connectivity and pulse-agent service status",
+ })
+ }
+
+ // Check RAID arrays
+ for _, raid := range host.RAID {
+ raidName := raid.Device
+ if raid.Name != "" {
+ raidName = raid.Name
+ }
+
+ // Check for degraded/failed state
+ switch raid.State {
+ case "degraded", "DEGRADED":
+ findings = append(findings, &Finding{
+ ID: generateFindingID(host.ID+":"+raid.Device, "reliability", "raid-degraded"),
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryReliability,
+ ResourceID: host.ID + ":" + raid.Device,
+ ResourceName: fmt.Sprintf("%s/%s", hostName, raidName),
+ ResourceType: "host_raid",
+ Title: "RAID array degraded",
+ Description: fmt.Sprintf("RAID array '%s' on '%s' is degraded (%d/%d devices active)", raidName, hostName, raid.ActiveDevices, raid.TotalDevices),
+ Recommendation: "Replace failed drive and initiate rebuild. Check dmesg for drive errors.",
+ Evidence: fmt.Sprintf("State: %s, Active: %d/%d, Failed: %d", raid.State, raid.ActiveDevices, raid.TotalDevices, raid.FailedDevices),
+ })
+
+ case "recovering", "rebuilding", "resyncing", "RECOVERING":
+ severity := FindingSeverityWarning
+ if raid.RebuildPercent < 50 {
+ severity = FindingSeverityWatch // Early in rebuild, less urgent
+ }
+ findings = append(findings, &Finding{
+ ID: generateFindingID(host.ID+":"+raid.Device, "reliability", "raid-rebuilding"),
+ Severity: severity,
+ Category: FindingCategoryReliability,
+ ResourceID: host.ID + ":" + raid.Device,
+ ResourceName: fmt.Sprintf("%s/%s", hostName, raidName),
+ ResourceType: "host_raid",
+ Title: "RAID array rebuilding",
+ Description: fmt.Sprintf("RAID array '%s' on '%s' is rebuilding (%.1f%% complete)", raidName, hostName, raid.RebuildPercent),
+ Recommendation: "Monitor rebuild progress. Avoid heavy I/O if possible. Array is vulnerable until rebuild completes.",
+ Evidence: fmt.Sprintf("State: %s, Progress: %.1f%%, Speed: %s", raid.State, raid.RebuildPercent, raid.RebuildSpeed),
+ })
+
+ case "inactive", "INACTIVE":
+ findings = append(findings, &Finding{
+ ID: generateFindingID(host.ID+":"+raid.Device, "reliability", "raid-inactive"),
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryReliability,
+ ResourceID: host.ID + ":" + raid.Device,
+ ResourceName: fmt.Sprintf("%s/%s", hostName, raidName),
+ ResourceType: "host_raid",
+ Title: "RAID array inactive",
+ Description: fmt.Sprintf("RAID array '%s' on '%s' is inactive", raidName, hostName),
+ Recommendation: "RAID array is not running. Check mdadm status and system logs.",
+ Evidence: fmt.Sprintf("State: %s", raid.State),
+ })
+ }
+
+ // Check for failed devices even if array state is "clean"
+ if raid.FailedDevices > 0 && raid.State != "degraded" {
+ findings = append(findings, &Finding{
+ ID: generateFindingID(host.ID+":"+raid.Device, "reliability", "raid-failed-devices"),
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryReliability,
+ ResourceID: host.ID + ":" + raid.Device,
+ ResourceName: fmt.Sprintf("%s/%s", hostName, raidName),
+ ResourceType: "host_raid",
+ Title: "RAID has failed devices",
+ Description: fmt.Sprintf("RAID array '%s' on '%s' has %d failed device(s)", raidName, hostName, raid.FailedDevices),
+ Recommendation: "Replace failed drives. Array may still be operational due to spares.",
+ Evidence: fmt.Sprintf("Failed: %d, Spare: %d", raid.FailedDevices, raid.SpareDevices),
+ })
+ }
+ }
+
+ // Check high temperature (during deep analysis)
+ if deep && len(host.Sensors.TemperatureCelsius) > 0 {
+ for sensorName, temp := range host.Sensors.TemperatureCelsius {
+ if temp > 85 {
+ severity := FindingSeverityWarning
+ if temp > 95 {
+ severity = FindingSeverityCritical
+ }
+ findings = append(findings, &Finding{
+ ID: generateFindingID(host.ID+":temp:"+sensorName, "reliability", "high-temp"),
+ Severity: severity,
+ Category: FindingCategoryReliability,
+ ResourceID: host.ID + ":temp:" + sensorName,
+ ResourceName: fmt.Sprintf("%s/%s", hostName, sensorName),
+ ResourceType: "host_sensor",
+ Title: "High temperature",
+ Description: fmt.Sprintf("Sensor '%s' on '%s' reading %.0f°C", sensorName, hostName, temp),
+ Recommendation: "Check cooling, fans, and airflow. High temps can cause hardware damage.",
+ Evidence: fmt.Sprintf("Temperature: %.1f°C", temp),
+ })
+ }
+ }
+ }
+
+ return findings
+}
diff --git a/internal/ai/sanitize_test.go b/internal/ai/sanitize_test.go
new file mode 100644
index 0000000000..bcb8a28fae
--- /dev/null
+++ b/internal/ai/sanitize_test.go
@@ -0,0 +1,70 @@
+package ai
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestSanitizeError(t *testing.T) {
+ tests := []struct {
+ name string
+ input error
+ expected string
+ }{
+ {
+ name: "nil error",
+ input: nil,
+ expected: "",
+ },
+ {
+ name: "i/o timeout with TCP details",
+ input: errors.New("failed to send command: write tcp 192.168.0.123:7655->192.168.0.134:58004: i/o timeout"),
+ expected: "connection to agent timed out - the agent may be disconnected or unreachable",
+ },
+ {
+ name: "read tcp i/o timeout",
+ input: errors.New("read tcp 192.168.1.100:8006: i/o timeout"),
+ expected: "network timeout - the target may be unreachable",
+ },
+ {
+ name: "connection refused with TCP details",
+ input: errors.New("dial tcp 192.168.1.50:9090: connection refused"),
+ expected: "connection refused - the agent may not be running on the target host",
+ },
+ {
+ name: "no such host",
+ input: errors.New("dial tcp: lookup unknown-host: no such host"),
+ expected: "host not found - verify the hostname is correct and DNS is working",
+ },
+ {
+ name: "context deadline exceeded",
+ input: errors.New("context deadline exceeded"),
+ expected: "operation timed out - the command may have taken too long",
+ },
+ {
+ name: "regular error passes through",
+ input: errors.New("invalid command"),
+ expected: "invalid command",
+ },
+ {
+ name: "agent not connected error passes through",
+ input: errors.New("agent delly not connected"),
+ expected: "agent delly not connected",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sanitizeError(tt.input)
+ if tt.input == nil {
+ if result != nil {
+ t.Errorf("expected nil, got %v", result)
+ }
+ return
+ }
+ if result.Error() != tt.expected {
+ t.Errorf("expected %q, got %q", tt.expected, result.Error())
+ }
+ })
+ }
+}
diff --git a/internal/ai/service.go b/internal/ai/service.go
index ba08370870..dd02745325 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -29,19 +29,18 @@ type StateProvider interface {
// Service orchestrates AI interactions
type Service struct {
- mu sync.RWMutex
- persistence *config.ConfigPersistence
- provider providers.Provider
- cfg *config.AIConfig
- agentServer *agentexec.Server
- policy *agentexec.CommandPolicy
- stateProvider StateProvider
- alertProvider AlertProvider
- knowledgeStore *knowledge.Store
- resourceProvider ResourceProvider // Unified resource model provider (Phase 2)
- patrolService *PatrolService // Background AI monitoring service
- metadataProvider MetadataProvider // Enables AI to update resource URLs
- urlDiscoveryService *URLDiscoveryService // Bulk URL discovery service
+ mu sync.RWMutex
+ persistence *config.ConfigPersistence
+ provider providers.Provider
+ cfg *config.AIConfig
+ agentServer *agentexec.Server
+ policy *agentexec.CommandPolicy
+ stateProvider StateProvider
+ alertProvider AlertProvider
+ knowledgeStore *knowledge.Store
+ resourceProvider ResourceProvider // Unified resource model provider (Phase 2)
+ patrolService *PatrolService // Background AI monitoring service
+ metadataProvider MetadataProvider // Enables AI to update resource URLs
}
// NewService creates a new AI service
@@ -83,16 +82,7 @@ func (s *Service) GetPatrolService() *PatrolService {
return s.patrolService
}
-// GetURLDiscoveryService returns the URL discovery service for bulk discovery
-func (s *Service) GetURLDiscoveryService() *URLDiscoveryService {
- s.mu.Lock()
- defer s.mu.Unlock()
- // Lazy initialization
- if s.urlDiscoveryService == nil {
- s.urlDiscoveryService = NewURLDiscoveryService(s)
- }
- return s.urlDiscoveryService
-}
+
// SetPatrolThresholdProvider sets the threshold provider for patrol
// This should be called with an AlertThresholdAdapter to connect patrol to user-configured thresholds
diff --git a/internal/ai/url_discovery.go b/internal/ai/url_discovery.go
deleted file mode 100644
index fc9a164935..0000000000
--- a/internal/ai/url_discovery.go
+++ /dev/null
@@ -1,290 +0,0 @@
-package ai
-
-import (
- "context"
- "fmt"
- "strings"
- "sync"
- "time"
-
- "github.com/rs/zerolog/log"
-)
-
-// URLDiscoveryResult represents the result of URL discovery for a single resource
-type URLDiscoveryResult struct {
- ResourceType string `json:"resource_type"` // "guest", "docker", "host"
- ResourceID string `json:"resource_id"`
- ResourceName string `json:"resource_name,omitempty"`
- Status string `json:"status"` // "found", "not_found", "skipped", "error"
- URL string `json:"url,omitempty"`
- Error string `json:"error,omitempty"`
-}
-
-// URLDiscoveryProgress represents progress of bulk discovery
-type URLDiscoveryProgress struct {
- Total int `json:"total"`
- Completed int `json:"completed"`
- Found int `json:"found"`
- Errors int `json:"errors"`
- Results []URLDiscoveryResult `json:"results"`
- Running bool `json:"running"`
- StartedAt time.Time `json:"started_at,omitempty"`
-}
-
-// URLDiscoveryService handles bulk URL discovery operations
-type URLDiscoveryService struct {
- mu sync.RWMutex
- aiService *Service
- progress *URLDiscoveryProgress
- cancelFunc context.CancelFunc
-}
-
-// NewURLDiscoveryService creates a new URL discovery service
-func NewURLDiscoveryService(aiService *Service) *URLDiscoveryService {
- return &URLDiscoveryService{
- aiService: aiService,
- }
-}
-
-// GetProgress returns the current discovery progress
-func (s *URLDiscoveryService) GetProgress() *URLDiscoveryProgress {
- s.mu.RLock()
- defer s.mu.RUnlock()
- if s.progress == nil {
- return &URLDiscoveryProgress{Running: false}
- }
- // Return a copy
- copy := *s.progress
- return &copy
-}
-
-// IsRunning returns true if discovery is in progress
-func (s *URLDiscoveryService) IsRunning() bool {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.progress != nil && s.progress.Running
-}
-
-// Cancel stops the current discovery operation
-func (s *URLDiscoveryService) Cancel() {
- s.mu.Lock()
- defer s.mu.Unlock()
- if s.cancelFunc != nil {
- s.cancelFunc()
- s.cancelFunc = nil
- }
- if s.progress != nil {
- s.progress.Running = false
- }
-}
-
-// DiscoverURLs starts bulk URL discovery for resources without URLs
-func (s *URLDiscoveryService) DiscoverURLs(ctx context.Context, resourceType string, skipExisting bool) error {
- s.mu.Lock()
- if s.progress != nil && s.progress.Running {
- s.mu.Unlock()
- return fmt.Errorf("discovery already in progress")
- }
-
- // Create cancellable context
- ctx, cancel := context.WithCancel(ctx)
- s.cancelFunc = cancel
-
- s.progress = &URLDiscoveryProgress{
- Running: true,
- StartedAt: time.Now(),
- Results: []URLDiscoveryResult{},
- }
- s.mu.Unlock()
-
- // Run discovery in background
- go s.runDiscovery(ctx, resourceType, skipExisting)
- return nil
-}
-
-// runDiscovery performs the actual discovery work
-func (s *URLDiscoveryService) runDiscovery(ctx context.Context, resourceType string, skipExisting bool) {
- defer func() {
- s.mu.Lock()
- s.progress.Running = false
- s.cancelFunc = nil
- s.mu.Unlock()
- }()
-
- // Get resources to scan from the resource provider
- s.aiService.mu.RLock()
- rp := s.aiService.resourceProvider
- mp := s.aiService.metadataProvider
- s.aiService.mu.RUnlock()
-
- if rp == nil {
- log.Error().Msg("URL discovery: resource provider not available")
- return
- }
- if mp == nil {
- log.Error().Msg("URL discovery: metadata provider not available")
- return
- }
-
- resources := rp.GetAll()
- if resources == nil {
- log.Error().Msg("URL discovery: no resources available")
- return
- }
-
- // Filter resources
- var toScan []struct {
- Type string
- ID string
- Name string
- IP string
- }
-
- for _, r := range resources {
- // Only scan workloads (VMs, containers) and hosts
- if !r.IsWorkload() && !r.IsInfrastructure() {
- continue
- }
-
- // Filter by type if specified
- if resourceType != "" && resourceType != "all" {
- typeMatches := false
- switch strings.ToLower(resourceType) {
- case "guest":
- typeMatches = r.Type == "vm" || r.Type == "container"
- case "docker":
- typeMatches = r.Type == "docker-container" || r.Type == "docker-service"
- case "host":
- typeMatches = r.Type == "host" || r.Type == "node" || r.Type == "docker-host"
- default:
- typeMatches = strings.EqualFold(string(r.Type), resourceType)
- }
- if !typeMatches {
- continue
- }
- }
-
- // Need an IP to scan
- ip := ""
- if r.Identity != nil && len(r.Identity.IPs) > 0 {
- ip = r.Identity.IPs[0]
- }
-
- toScan = append(toScan, struct {
- Type string
- ID string
- Name string
- IP string
- }{
- Type: string(r.Type),
- ID: r.ID,
- Name: r.Name,
- IP: ip,
- })
- }
-
- // Update total
- s.mu.Lock()
- s.progress.Total = len(toScan)
- s.mu.Unlock()
-
- log.Info().
- Int("total", len(toScan)).
- Str("resourceType", resourceType).
- Bool("skipExisting", skipExisting).
- Msg("Starting bulk URL discovery")
-
- // Process each resource
- for _, res := range toScan {
- select {
- case <-ctx.Done():
- log.Info().Msg("URL discovery cancelled")
- return
- default:
- }
-
- result := s.discoverSingleResource(ctx, res.Type, res.ID, res.Name, res.IP)
-
- s.mu.Lock()
- s.progress.Completed++
- s.progress.Results = append(s.progress.Results, result)
- if result.Status == "found" {
- s.progress.Found++
- } else if result.Status == "error" {
- s.progress.Errors++
- }
- s.mu.Unlock()
- }
-
- log.Info().
- Int("total", len(toScan)).
- Int("found", s.progress.Found).
- Int("errors", s.progress.Errors).
- Msg("Bulk URL discovery completed")
-}
-
-// discoverSingleResource attempts to discover URL for a single resource
-func (s *URLDiscoveryService) discoverSingleResource(ctx context.Context, resType, resID, resName, ip string) URLDiscoveryResult {
- result := URLDiscoveryResult{
- ResourceType: resType,
- ResourceID: resID,
- ResourceName: resName,
- Status: "not_found",
- }
-
- if ip == "" {
- result.Status = "skipped"
- result.Error = "no IP address"
- return result
- }
-
- // Common web ports to check
- ports := []int{80, 443, 8080, 8443, 8096, 8920, 3000, 5000, 9000, 8081, 8000, 7878, 8989, 9117}
-
- for _, port := range ports {
- select {
- case <-ctx.Done():
- result.Status = "error"
- result.Error = "cancelled"
- return result
- default:
- }
-
- scheme := "http"
- if port == 443 || port == 8443 {
- scheme = "https"
- }
-
- url := fmt.Sprintf("%s://%s:%d/", scheme, ip, port)
-
- // Try to fetch the URL using the AI service's fetch method
- checkCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
- _, err := s.aiService.fetchURL(checkCtx, url)
- cancel()
-
- if err == nil {
- // Found a responding service!
- result.Status = "found"
- result.URL = url
-
- // Save it to metadata
- if err := s.aiService.SetResourceURL(resType, resID, url); err != nil {
- log.Warn().
- Err(err).
- Str("resourceID", resID).
- Str("url", url).
- Msg("Failed to save discovered URL")
- } else {
- log.Info().
- Str("resourceType", resType).
- Str("resourceID", resID).
- Str("resourceName", resName).
- Str("url", url).
- Msg("Discovered and saved URL")
- }
- return result
- }
- }
-
- return result
-}
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 6c8d2ff58f..0acca416ad 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -1844,104 +1844,3 @@ func (h *AISettingsHandler) HandleGetFindingsHistory(w http.ResponseWriter, r *h
log.Error().Err(err).Msg("Failed to write findings history response")
}
}
-
-// HandleStartURLDiscovery starts bulk URL discovery (POST /api/ai/discover-urls/start)
-func (h *AISettingsHandler) HandleStartURLDiscovery(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- // Require authentication
- if !CheckAuth(h.config, w, r) {
- return
- }
-
- // Parse request
- var req struct {
- ResourceType string `json:"resource_type"` // "guest", "docker", "host", or "all"
- SkipExisting bool `json:"skip_existing"` // Skip resources that already have URLs
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- // Default values
- req.ResourceType = "all"
- req.SkipExisting = true
- }
-
- discoveryService := h.aiService.GetURLDiscoveryService()
- if discoveryService == nil {
- http.Error(w, "URL discovery service not available", http.StatusServiceUnavailable)
- return
- }
-
- if err := discoveryService.DiscoverURLs(r.Context(), req.ResourceType, req.SkipExisting); err != nil {
- http.Error(w, err.Error(), http.StatusConflict)
- return
- }
-
- log.Info().
- Str("resourceType", req.ResourceType).
- Bool("skipExisting", req.SkipExisting).
- Msg("Started bulk URL discovery")
-
- if err := utils.WriteJSONResponse(w, map[string]interface{}{
- "success": true,
- "message": "URL discovery started",
- }); err != nil {
- log.Error().Err(err).Msg("Failed to write URL discovery start response")
- }
-}
-
-// HandleURLDiscoveryStatus returns the current discovery status (GET /api/ai/discover-urls/status)
-func (h *AISettingsHandler) HandleURLDiscoveryStatus(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- // Require authentication
- if !CheckAuth(h.config, w, r) {
- return
- }
-
- discoveryService := h.aiService.GetURLDiscoveryService()
- if discoveryService == nil {
- http.Error(w, "URL discovery service not available", http.StatusServiceUnavailable)
- return
- }
-
- progress := discoveryService.GetProgress()
- if err := utils.WriteJSONResponse(w, progress); err != nil {
- log.Error().Err(err).Msg("Failed to write URL discovery status response")
- }
-}
-
-// HandleCancelURLDiscovery cancels the current discovery operation (POST /api/ai/discover-urls/cancel)
-func (h *AISettingsHandler) HandleCancelURLDiscovery(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- // Require authentication
- if !CheckAuth(h.config, w, r) {
- return
- }
-
- discoveryService := h.aiService.GetURLDiscoveryService()
- if discoveryService == nil {
- http.Error(w, "URL discovery service not available", http.StatusServiceUnavailable)
- return
- }
-
- discoveryService.Cancel()
-
- log.Info().Msg("Cancelled bulk URL discovery")
-
- if err := utils.WriteJSONResponse(w, map[string]interface{}{
- "success": true,
- "message": "URL discovery cancelled",
- }); err != nil {
- log.Error().Err(err).Msg("Failed to write URL discovery cancel response")
- }
-}
diff --git a/internal/api/router.go b/internal/api/router.go
index 998039beee..2eb4ae65cf 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -1103,11 +1103,6 @@ func (r *Router) setupRoutes() {
r.mux.HandleFunc("/api/ai/patrol/dismiss", RequireAuth(r.config, r.aiSettingsHandler.HandleAcknowledgeFinding)) // Backward compat
r.mux.HandleFunc("/api/ai/patrol/snooze", RequireAuth(r.config, r.aiSettingsHandler.HandleSnoozeFinding))
- // AI URL Discovery routes for bulk scanning
- r.mux.HandleFunc("/api/ai/discover-urls/start", RequireAdmin(r.config, r.aiSettingsHandler.HandleStartURLDiscovery))
- r.mux.HandleFunc("/api/ai/discover-urls/status", RequireAuth(r.config, r.aiSettingsHandler.HandleURLDiscoveryStatus))
- r.mux.HandleFunc("/api/ai/discover-urls/cancel", RequireAdmin(r.config, r.aiSettingsHandler.HandleCancelURLDiscovery))
-
// Agent WebSocket for AI command execution
r.mux.HandleFunc("/api/agent/ws", r.handleAgentWebSocket)
diff --git a/internal/config/ai.go b/internal/config/ai.go
index 28e1073e5c..30b1edfd15 100644
--- a/internal/config/ai.go
+++ b/internal/config/ai.go
@@ -24,10 +24,18 @@ type AIConfig struct {
CustomContext string `json:"custom_context"` // user-provided context about their infrastructure
// OAuth fields for Claude Pro/Max subscription authentication
- AuthMethod AuthMethod `json:"auth_method,omitempty"` // "api_key" or "oauth" (for anthropic only)
- OAuthAccessToken string `json:"oauth_access_token,omitempty"` // OAuth access token (encrypted at rest)
- OAuthRefreshToken string `json:"oauth_refresh_token,omitempty"` // OAuth refresh token (encrypted at rest)
- OAuthExpiresAt time.Time `json:"oauth_expires_at,omitempty"` // Token expiration time
+ AuthMethod AuthMethod `json:"auth_method,omitempty"` // "api_key" or "oauth" (for anthropic only)
+ OAuthAccessToken string `json:"oauth_access_token,omitempty"` // OAuth access token (encrypted at rest)
+ OAuthRefreshToken string `json:"oauth_refresh_token,omitempty"` // OAuth refresh token (encrypted at rest)
+ OAuthExpiresAt time.Time `json:"oauth_expires_at,omitempty"` // Token expiration time
+
+ // Patrol settings for background AI monitoring
+ PatrolEnabled bool `json:"patrol_enabled"` // Enable background AI health patrol
+ PatrolIntervalMinutes int `json:"patrol_interval_minutes,omitempty"` // How often to run quick patrols (default: 15)
+ PatrolAnalyzeNodes bool `json:"patrol_analyze_nodes,omitempty"` // Include Proxmox nodes in patrol
+ PatrolAnalyzeGuests bool `json:"patrol_analyze_guests,omitempty"` // Include VMs/containers in patrol
+ PatrolAnalyzeDocker bool `json:"patrol_analyze_docker,omitempty"` // Include Docker hosts in patrol
+ PatrolAnalyzeStorage bool `json:"patrol_analyze_storage,omitempty"` // Include storage in patrol
}
// AIProvider constants
@@ -55,6 +63,13 @@ func NewDefaultAIConfig() *AIConfig {
Provider: AIProviderAnthropic,
Model: DefaultAIModelAnthropic,
AuthMethod: AuthMethodAPIKey,
+ // Patrol defaults - enabled when AI is enabled, check every 15 minutes
+ PatrolEnabled: true,
+ PatrolIntervalMinutes: 15,
+ PatrolAnalyzeNodes: true,
+ PatrolAnalyzeGuests: true,
+ PatrolAnalyzeDocker: true,
+ PatrolAnalyzeStorage: true,
}
}
@@ -130,3 +145,17 @@ func (c *AIConfig) ClearOAuthTokens() {
func (c *AIConfig) ClearAPIKey() {
c.APIKey = ""
}
+
+// GetPatrolInterval returns the patrol interval as a duration
+func (c *AIConfig) GetPatrolInterval() time.Duration {
+ if c.PatrolIntervalMinutes <= 0 {
+ return 15 * time.Minute // default
+ }
+ return time.Duration(c.PatrolIntervalMinutes) * time.Minute
+}
+
+// IsPatrolEnabled returns true if patrol should run
+// Note: Patrol uses local heuristics and doesn't require an AI API key
+func (c *AIConfig) IsPatrolEnabled() bool {
+ return c.PatrolEnabled
+}
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 1389439b68..195c4c3c89 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -20,19 +20,20 @@ import (
// ConfigPersistence handles saving and loading configuration
type ConfigPersistence struct {
- mu sync.RWMutex
- tx *importTransaction
- configDir string
- alertFile string
- emailFile string
- webhookFile string
- appriseFile string
- nodesFile string
- systemFile string
- oidcFile string
- apiTokensFile string
- aiFile string
- crypto *crypto.CryptoManager
+ mu sync.RWMutex
+ tx *importTransaction
+ configDir string
+ alertFile string
+ emailFile string
+ webhookFile string
+ appriseFile string
+ nodesFile string
+ systemFile string
+ oidcFile string
+ apiTokensFile string
+ aiFile string
+ aiFindingsFile string
+ crypto *crypto.CryptoManager
}
// NewConfigPersistence creates a new config persistence manager.
@@ -65,17 +66,18 @@ func newConfigPersistence(configDir string) (*ConfigPersistence, error) {
}
cp := &ConfigPersistence{
- configDir: configDir,
- alertFile: filepath.Join(configDir, "alerts.json"),
- emailFile: filepath.Join(configDir, "email.enc"),
- webhookFile: filepath.Join(configDir, "webhooks.enc"),
- appriseFile: filepath.Join(configDir, "apprise.enc"),
- nodesFile: filepath.Join(configDir, "nodes.enc"),
- systemFile: filepath.Join(configDir, "system.json"),
- oidcFile: filepath.Join(configDir, "oidc.enc"),
- apiTokensFile: filepath.Join(configDir, "api_tokens.json"),
- aiFile: filepath.Join(configDir, "ai.enc"),
- crypto: cryptoMgr,
+ configDir: configDir,
+ alertFile: filepath.Join(configDir, "alerts.json"),
+ emailFile: filepath.Join(configDir, "email.enc"),
+ webhookFile: filepath.Join(configDir, "webhooks.enc"),
+ appriseFile: filepath.Join(configDir, "apprise.enc"),
+ nodesFile: filepath.Join(configDir, "nodes.enc"),
+ systemFile: filepath.Join(configDir, "system.json"),
+ oidcFile: filepath.Join(configDir, "oidc.enc"),
+ apiTokensFile: filepath.Join(configDir, "api_tokens.json"),
+ aiFile: filepath.Join(configDir, "ai.enc"),
+ aiFindingsFile: filepath.Join(configDir, "ai_findings.json"),
+ crypto: cryptoMgr,
}
log.Debug().
@@ -1350,13 +1352,122 @@ func (c *ConfigPersistence) LoadAIConfig() (*AIConfig, error) {
data = decrypted
}
- var settings AIConfig
- if err := json.Unmarshal(data, &settings); err != nil {
+ // Start with defaults so new fields get proper values
+ settings := NewDefaultAIConfig()
+ if err := json.Unmarshal(data, settings); err != nil {
return nil, err
}
- log.Info().Str("file", c.aiFile).Bool("enabled", settings.Enabled).Msg("AI configuration loaded")
- return &settings, nil
+ // Migration: Ensure patrol settings have sensible defaults for existing configs
+ // PatrolIntervalMinutes=0 means it was never set - use default
+ if settings.PatrolIntervalMinutes <= 0 {
+ settings.PatrolIntervalMinutes = 15
+ }
+
+ log.Info().Str("file", c.aiFile).Bool("enabled", settings.Enabled).Bool("patrol_enabled", settings.PatrolEnabled).Msg("AI configuration loaded")
+ return settings, nil
+}
+
+// AIFindingsData represents persisted AI findings with metadata
+type AIFindingsData struct {
+ // Version for future migrations
+ Version int `json:"version"`
+ // LastSaved for debugging/diagnostics
+ LastSaved time.Time `json:"last_saved"`
+ // Findings is a map of finding ID to finding data
+ Findings map[string]*AIFindingRecord `json:"findings"`
+}
+
+// AIFindingRecord is a persisted finding with full history
+type AIFindingRecord struct {
+ ID string `json:"id"`
+ Severity string `json:"severity"`
+ Category string `json:"category"`
+ ResourceID string `json:"resource_id"`
+ ResourceName string `json:"resource_name"`
+ ResourceType string `json:"resource_type"`
+ Node string `json:"node,omitempty"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Recommendation string `json:"recommendation,omitempty"`
+ Evidence string `json:"evidence,omitempty"`
+ DetectedAt time.Time `json:"detected_at"`
+ LastSeenAt time.Time `json:"last_seen_at"`
+ ResolvedAt *time.Time `json:"resolved_at,omitempty"`
+ AutoResolved bool `json:"auto_resolved"`
+ AcknowledgedAt *time.Time `json:"acknowledged_at,omitempty"`
+ SnoozedUntil *time.Time `json:"snoozed_until,omitempty"`
+ AlertID string `json:"alert_id,omitempty"`
+}
+
+// SaveAIFindings persists AI findings to disk
+func (c *ConfigPersistence) SaveAIFindings(findings map[string]*AIFindingRecord) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if err := c.EnsureConfigDir(); err != nil {
+ return err
+ }
+
+ data := AIFindingsData{
+ Version: 1,
+ LastSaved: time.Now(),
+ Findings: findings,
+ }
+
+ jsonData, err := json.Marshal(data)
+ if err != nil {
+ return err
+ }
+
+ if err := c.writeConfigFileLocked(c.aiFindingsFile, jsonData, 0600); err != nil {
+ return err
+ }
+
+ log.Debug().
+ Str("file", c.aiFindingsFile).
+ Int("count", len(findings)).
+ Msg("AI findings saved")
+ return nil
+}
+
+// LoadAIFindings loads AI findings from disk
+func (c *ConfigPersistence) LoadAIFindings() (*AIFindingsData, error) {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+
+ data, err := os.ReadFile(c.aiFindingsFile)
+ if err != nil {
+ if os.IsNotExist(err) {
+ // Return empty data if file doesn't exist
+ return &AIFindingsData{
+ Version: 1,
+ Findings: make(map[string]*AIFindingRecord),
+ }, nil
+ }
+ return nil, err
+ }
+
+ var findingsData AIFindingsData
+ if err := json.Unmarshal(data, &findingsData); err != nil {
+ log.Error().Err(err).Str("file", c.aiFindingsFile).Msg("Failed to parse AI findings file")
+ // Return empty data on parse error rather than failing
+ return &AIFindingsData{
+ Version: 1,
+ Findings: make(map[string]*AIFindingRecord),
+ }, nil
+ }
+
+ if findingsData.Findings == nil {
+ findingsData.Findings = make(map[string]*AIFindingRecord)
+ }
+
+ log.Info().
+ Str("file", c.aiFindingsFile).
+ Int("count", len(findingsData.Findings)).
+ Time("last_saved", findingsData.LastSaved).
+ Msg("AI findings loaded")
+ return &findingsData, nil
}
// LoadSystemSettings loads system settings from file