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.

test(ai): add patrol AI analysis and intelligence tests

rcourtman4f866c411ca3
diff --git a/internal/ai/patrol_ai_intelligence_test.go b/internal/ai/patrol_ai_intelligence_test.go
new file mode 100644
index 0000000000..5eba51d196
--- /dev/null
+++ b/internal/ai/patrol_ai_intelligence_test.go
@@ -0,0 +1,279 @@
+package ai
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/knowledge"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/types"
+)
+
+type precomputeMetricsHistoryProvider struct {
+ metrics map[string][]types.MetricPoint
+ storage map[string][]types.MetricPoint
+}
+
+func (p *precomputeMetricsHistoryProvider) GetNodeMetrics(nodeID string, metricType string, duration time.Duration) []types.MetricPoint {
+ return p.metrics[nodeID+":"+metricType]
+}
+
+func (p *precomputeMetricsHistoryProvider) GetGuestMetrics(guestID string, metricType string, duration time.Duration) []types.MetricPoint {
+ return p.metrics[guestID+":"+metricType]
+}
+
+func (p *precomputeMetricsHistoryProvider) GetAllGuestMetrics(guestID string, duration time.Duration) map[string][]types.MetricPoint {
+ return nil
+}
+
+func (p *precomputeMetricsHistoryProvider) GetAllStorageMetrics(storageID string, duration time.Duration) map[string][]types.MetricPoint {
+ if p.storage == nil {
+ return nil
+ }
+ points := p.storage[storageID+":usage"]
+ if len(points) == 0 {
+ return nil
+ }
+ return map[string][]types.MetricPoint{"usage": points}
+}
+
+func TestSeedPrecomputeIntelligence_PopulatesSignals(t *testing.T) {
+ now := time.Now()
+ ps := NewPatrolService(nil, nil)
+
+ bs := baseline.NewStore(baseline.StoreConfig{MinSamples: 1})
+ baselinePoints := []baseline.MetricPoint{
+ {Value: 10, Timestamp: now.Add(-5 * time.Hour)},
+ {Value: 10, Timestamp: now.Add(-4 * time.Hour)},
+ {Value: 10, Timestamp: now.Add(-3 * time.Hour)},
+ {Value: 10, Timestamp: now.Add(-2 * time.Hour)},
+ {Value: 10, Timestamp: now.Add(-1 * time.Hour)},
+ }
+ _ = bs.Learn("node-1", "node", "cpu", baselinePoints)
+ _ = bs.Learn("node-1", "node", "memory", baselinePoints)
+ _ = bs.Learn("vm-1", "vm", "memory", baselinePoints)
+ _ = bs.Learn("vm-1", "vm", "disk", baselinePoints)
+ _ = bs.Learn("ct-1", "container", "memory", baselinePoints)
+ _ = bs.Learn("ct-1", "container", "disk", baselinePoints)
+ _ = bs.Learn("storage-1", "storage", "usage", baselinePoints)
+ ps.SetBaselineStore(bs)
+
+ series := func(start float64) []types.MetricPoint {
+ return []types.MetricPoint{
+ {Value: start, Timestamp: now.Add(-5 * time.Hour)},
+ {Value: start + 2, Timestamp: now.Add(-4 * time.Hour)},
+ {Value: start + 4, Timestamp: now.Add(-3 * time.Hour)},
+ {Value: start + 6, Timestamp: now.Add(-2 * time.Hour)},
+ {Value: start + 8, Timestamp: now.Add(-1 * time.Hour)},
+ }
+ }
+ mh := &precomputeMetricsHistoryProvider{
+ metrics: map[string][]types.MetricPoint{
+ "node-1:memory": series(70),
+ "vm-1:memory": series(60),
+ "vm-1:disk": series(50),
+ "ct-1:memory": series(55),
+ "ct-1:disk": series(45),
+ },
+ storage: map[string][]types.MetricPoint{
+ "storage-1:usage": series(65),
+ },
+ }
+ ps.SetMetricsHistoryProvider(mh)
+
+ patternCfg := DefaultPatternConfig()
+ patternCfg.MinOccurrences = 2
+ patternCfg.PredictionLimit = 72 * time.Hour
+ pd := NewPatternDetector(patternCfg)
+ pd.RecordEvent(HistoricalEvent{ResourceID: "vm-1", EventType: EventHighCPU, Timestamp: now.Add(-36 * time.Hour)})
+ pd.RecordEvent(HistoricalEvent{ResourceID: "vm-1", EventType: EventHighCPU, Timestamp: now.Add(-12 * time.Hour)})
+ ps.SetPatternDetector(pd)
+
+ cd := NewChangeDetector(ChangeDetectorConfig{MaxChanges: 10})
+ cd.DetectChanges([]ResourceSnapshot{{ID: "vm-1", Name: "vm-1", Type: "vm", Status: "running", SnapshotTime: now.Add(-2 * time.Hour)}})
+ cd.DetectChanges([]ResourceSnapshot{{ID: "vm-1", Name: "vm-1", Type: "vm", Status: "stopped", SnapshotTime: now.Add(-1 * time.Hour)}})
+ ps.SetChangeDetector(cd)
+
+ corrCfg := DefaultCorrelationConfig()
+ corrCfg.MinOccurrences = 1
+ corrCfg.CorrelationWindow = time.Hour
+ corr := NewCorrelationDetector(corrCfg)
+ for i := 0; i < 3; i++ {
+ base := now.Add(time.Duration(-30+i*5) * time.Minute)
+ corr.RecordEvent(CorrelationEvent{ResourceID: "node-1", ResourceName: "node-1", ResourceType: "node", EventType: CorrelationEventHighCPU, Timestamp: base})
+ corr.RecordEvent(CorrelationEvent{ResourceID: "vm-1", ResourceName: "vm-1", ResourceType: "vm", EventType: CorrelationEventRestart, Timestamp: base.Add(2 * time.Minute)})
+ }
+ ps.SetCorrelationDetector(corr)
+
+ state := models.StateSnapshot{
+ Nodes: []models.Node{
+ {ID: "node-1", Name: "node-1", CPU: 80, Memory: models.Memory{Usage: 80}},
+ },
+ VMs: []models.VM{
+ {ID: "vm-1", Name: "vm-1", Status: "running", CPU: 20, Memory: models.Memory{Usage: 70}, Disk: models.Disk{Usage: 60}},
+ },
+ Containers: []models.Container{
+ {ID: "ct-1", Name: "ct-1", Status: "running", CPU: 10, Memory: models.Memory{Usage: 65}, Disk: models.Disk{Usage: 55}},
+ },
+ Storage: []models.Storage{
+ {ID: "storage-1", Name: "local", Usage: 85},
+ },
+ ActiveAlerts: []models.Alert{{ID: "alert-1"}},
+ }
+
+ scoped := map[string]bool{"node-1": true, "vm-1": true, "ct-1": true, "storage-1": true}
+ intel := ps.seedPrecomputeIntelligence(state, scoped, now)
+
+ if !intel.hasBaselineStore {
+ t.Fatalf("expected baseline store flag to be true")
+ }
+ if len(intel.anomalies) == 0 {
+ t.Fatalf("expected anomalies to be populated")
+ }
+ nameSet := false
+ for _, a := range intel.anomalies {
+ if a.ResourceName != "" {
+ nameSet = true
+ break
+ }
+ }
+ if !nameSet {
+ t.Fatalf("expected anomaly resource names to be set")
+ }
+ if len(intel.forecasts) == 0 {
+ t.Fatalf("expected capacity forecasts")
+ }
+ if len(intel.predictions) == 0 {
+ t.Fatalf("expected failure predictions")
+ }
+ if len(intel.recentChanges) == 0 {
+ t.Fatalf("expected recent changes")
+ }
+ if len(intel.correlations) == 0 {
+ t.Fatalf("expected correlations")
+ }
+ if intel.isQuiet {
+ t.Fatalf("expected infrastructure to be non-quiet")
+ }
+}
+
+func TestSeedBackupAnalysis_StaleAndRecent(t *testing.T) {
+ now := time.Now()
+ ps := NewPatrolService(nil, nil)
+
+ state := models.StateSnapshot{
+ VMs: []models.VM{
+ {ID: "vm-1", VMID: 101, Name: "vm-1", Template: false, LastBackup: now.Add(-24 * time.Hour)},
+ {ID: "vm-2", VMID: 102, Name: "vm-2", Template: false},
+ },
+ Containers: []models.Container{{ID: "ct-1", VMID: 201, Name: "ct-1", Template: false}},
+ PVEBackups: models.PVEBackups{
+ BackupTasks: []models.BackupTask{{VMID: 102, Status: "OK", EndTime: now.Add(-72 * time.Hour)}},
+ StorageBackups: []models.StorageBackup{{VMID: 101, Time: now.Add(-36 * time.Hour)}},
+ },
+ PBSBackups: []models.PBSBackup{{VMID: "102", BackupTime: now.Add(-72 * time.Hour)}},
+ }
+
+ output := ps.seedBackupAnalysis(state, now)
+ if output == "" {
+ t.Fatalf("expected backup analysis output")
+ }
+ if !strings.Contains(output, "Guests with no backup in >48h") {
+ t.Fatalf("expected stale backup section, got: %s", output)
+ }
+ if !strings.Contains(output, "ct-1 (never)") {
+ t.Fatalf("expected never-backed guest, got: %s", output)
+ }
+ if !strings.Contains(output, "vm-2 (last:") {
+ t.Fatalf("expected stale vm entry, got: %s", output)
+ }
+ if !strings.Contains(output, "Guests with recent backups: 1/3") {
+ t.Fatalf("expected recent backup count, got: %s", output)
+ }
+}
+
+func TestSeedFindingsAndContext_ResolvesMissingAndAddsNotes(t *testing.T) {
+ now := time.Now()
+ ps := NewPatrolService(nil, nil)
+
+ missing := &Finding{
+ ID: "find-missing",
+ Severity: FindingSeverityInfo,
+ Category: FindingCategoryPerformance,
+ ResourceID: "vm-missing",
+ ResourceName: "vm-missing",
+ Title: "Missing VM",
+ Description: "no longer exists",
+ DetectedAt: now.Add(-2 * time.Hour),
+ LastSeenAt: now.Add(-2 * time.Hour),
+ }
+ active := &Finding{
+ ID: "find-active",
+ Severity: FindingSeverityInfo,
+ Category: FindingCategoryPerformance,
+ ResourceID: "node-1",
+ ResourceName: "node-1",
+ Title: "High CPU",
+ Description: "cpu high",
+ UserNote: "keep an eye",
+ DetectedAt: now.Add(-1 * time.Hour),
+ LastSeenAt: now.Add(-1 * time.Hour),
+ }
+ dismissed := &Finding{
+ ID: "find-dismissed",
+ Severity: FindingSeverityInfo,
+ Category: FindingCategoryPerformance,
+ ResourceID: "node-1",
+ ResourceName: "node-1",
+ Title: "Noisy alerts",
+ Description: "expected",
+ DetectedAt: now.Add(-30 * time.Minute),
+ LastSeenAt: now.Add(-30 * time.Minute),
+ }
+
+ ps.findings.Add(missing)
+ ps.findings.Add(active)
+ ps.findings.Add(dismissed)
+ ps.findings.Dismiss(dismissed.ID, "expected_behavior", "known workload")
+
+ resolvedID := ""
+ ps.unifiedFindingResolver = func(findingID string) {
+ resolvedID = findingID
+ }
+
+ knowledgeStore, err := knowledge.NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create knowledge store: %v", err)
+ }
+ if err := knowledgeStore.SaveNote("node-1", "node-1", "node", "config", "Pinned", "keep settings"); err != nil {
+ t.Fatalf("failed to save knowledge note: %v", err)
+ }
+ ps.knowledgeStore = knowledgeStore
+
+ state := models.StateSnapshot{Nodes: []models.Node{{ID: "node-1", Name: "node-1"}}}
+ output, seeded := ps.seedFindingsAndContext(&PatrolScope{ResourceIDs: []string{"node-1"}}, state)
+
+ if resolvedID != missing.ID {
+ t.Fatalf("expected unified resolver to be called for missing finding")
+ }
+ if missing.ResolvedAt == nil {
+ t.Fatalf("expected missing finding to be resolved")
+ }
+ if len(seeded) != 1 || seeded[0] != active.ID {
+ t.Fatalf("expected active finding to be seeded")
+ }
+ if !strings.Contains(output, "Active Findings to Re-check") {
+ t.Fatalf("expected active findings section, got: %s", output)
+ }
+ if !strings.Contains(output, "User note: \"keep an eye\"") {
+ t.Fatalf("expected user note in output, got: %s", output)
+ }
+ if !strings.Contains(output, "User Feedback on Previous Findings") {
+ t.Fatalf("expected dismissed findings context, got: %s", output)
+ }
+ if !strings.Contains(output, "# User Notes") || !strings.Contains(output, "Saved Knowledge") {
+ t.Fatalf("expected knowledge context, got: %s", output)
+ }
+}
diff --git a/internal/ai/patrol_ai_more_test.go b/internal/ai/patrol_ai_more_test.go
index a030937f89..314ff29a89 100644
--- a/internal/ai/patrol_ai_more_test.go
+++ b/internal/ai/patrol_ai_more_test.go
@@ -2,12 +2,15 @@ package ai
import (
"context"
+ "encoding/json"
"strings"
"sync"
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
@@ -39,6 +42,97 @@ func (n *noExecutorChatService) ReloadConfig(ctx context.Context, cfg *config.AI
return nil
}
+type streamChatService struct {
+ executor *tools.PulseToolExecutor
+}
+
+func (s *streamChatService) CreateSession(ctx context.Context) (*ChatSession, error) {
+ return &ChatSession{ID: "stream"}, nil
+}
+
+func (s *streamChatService) ExecuteStream(ctx context.Context, req ChatExecuteRequest, callback ChatStreamCallback) error {
+ return nil
+}
+
+func (s *streamChatService) ExecutePatrolStream(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {
+ contentData, _ := json.Marshal(struct {
+ Text string `json:"text"`
+ }{Text: "hello"})
+ callback(ChatStreamEvent{Type: "content", Data: contentData})
+
+ thinkingData, _ := json.Marshal(struct {
+ Text string `json:"text"`
+ }{Text: "thinking"})
+ callback(ChatStreamEvent{Type: "thinking", Data: thinkingData})
+
+ toolStartData, _ := json.Marshal(struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input string `json:"input"`
+ RawInput string `json:"raw_input"`
+ }{
+ ID: "",
+ Name: "pulse_query",
+ Input: `{"action":"health"}`,
+ RawInput: `{"action":"health"}`,
+ })
+ callback(ChatStreamEvent{Type: "tool_start", Data: toolStartData})
+
+ toolEndData, _ := json.Marshal(struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input string `json:"input"`
+ RawInput string `json:"raw_input"`
+ Output string `json:"output"`
+ Success bool `json:"success"`
+ }{
+ ID: "",
+ Name: "pulse_query",
+ Input: `{"action":"health"}`,
+ RawInput: `{"action":"health"}`,
+ Output: `{"status":"ok"}`,
+ Success: true,
+ })
+ callback(ChatStreamEvent{Type: "tool_end", Data: toolEndData})
+
+ toolEndMissingData, _ := json.Marshal(struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input string `json:"input"`
+ RawInput string `json:"raw_input"`
+ Output string `json:"output"`
+ Success bool `json:"success"`
+ }{
+ ID: "missing",
+ Name: "pulse_metrics",
+ Output: `{"status":"ok"}`,
+ Success: true,
+ })
+ callback(ChatStreamEvent{Type: "tool_end", Data: toolEndMissingData})
+
+ return &PatrolStreamResponse{
+ Content: "analysis complete",
+ InputTokens: 5,
+ OutputTokens: 7,
+ }, nil
+}
+
+func (s *streamChatService) GetMessages(ctx context.Context, sessionID string) ([]ChatMessage, error) {
+ return nil, nil
+}
+
+func (s *streamChatService) DeleteSession(ctx context.Context, sessionID string) error {
+ return nil
+}
+
+func (s *streamChatService) ReloadConfig(ctx context.Context, cfg *config.AIConfig) error {
+ return nil
+}
+
+func (s *streamChatService) GetExecutor() *tools.PulseToolExecutor {
+ return s.executor
+}
+
func samplePatrolState() models.StateSnapshot {
return models.StateSnapshot{
Nodes: []models.Node{
@@ -196,3 +290,271 @@ func TestSeedResourceInventory_QuietSummary(t *testing.T) {
t.Fatalf("expected quiet node summary, got: %s", out)
}
}
+
+func TestRunAIAnalysis_StreamEvents(t *testing.T) {
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ svc := &Service{}
+ svc.SetChatService(&streamChatService{executor: executor})
+
+ ps := NewPatrolService(svc, nil)
+ scope := &PatrolScope{NoStream: true}
+
+ res, err := ps.runAIAnalysis(context.Background(), samplePatrolState(), scope)
+ if err != nil {
+ t.Fatalf("runAIAnalysis failed: %v", err)
+ }
+ if res == nil || res.Response == "" {
+ t.Fatalf("expected analysis response, got %+v", res)
+ }
+ if len(res.ToolCalls) == 0 {
+ t.Fatalf("expected tool calls to be recorded")
+ }
+}
+
+func TestSeedResourceInventory_DetailedSections(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ cfg := DefaultPatrolConfig()
+ now := time.Now()
+
+ state := models.StateSnapshot{
+ Nodes: []models.Node{
+ {
+ ID: "node-1",
+ Name: "node-1",
+ Status: "online",
+ CPU: 0.55,
+ Memory: models.Memory{Usage: 65.0},
+ Disk: models.Disk{Usage: 40.0},
+ LoadAverage: []float64{1.2, 0.9, 0.7},
+ Uptime: int64(3600),
+ PendingUpdates: 5,
+ },
+ },
+ VMs: []models.VM{
+ {
+ ID: "vm-1",
+ VMID: 101,
+ Name: "vm-1",
+ Node: "node-1",
+ Status: "running",
+ CPU: 0.10,
+ Memory: models.Memory{Usage: 30.0},
+ Disk: models.Disk{Usage: 20.0},
+ LastBackup: now.Add(-2 * time.Hour),
+ },
+ },
+ Containers: []models.Container{
+ {
+ ID: "ct-1",
+ VMID: 200,
+ Name: "ct-1",
+ Node: "node-1",
+ Status: "stopped",
+ CPU: 0.05,
+ Memory: models.Memory{Usage: 15.0},
+ Disk: models.Disk{Usage: 10.0},
+ },
+ },
+ DockerHosts: []models.DockerHost{
+ {
+ ID: "docker-1",
+ Hostname: "docker-1",
+ Containers: []models.DockerContainer{
+ {Name: "web", State: "running", Health: "unhealthy"},
+ {Name: "db", State: "exited"},
+ },
+ },
+ },
+ Storage: []models.Storage{
+ {
+ ID: "store-1",
+ Name: "store-1",
+ Type: "zfs",
+ Usage: 70.0,
+ Used: 700 * 1024 * 1024,
+ Total: 1000 * 1024 * 1024,
+ Shared: true,
+ Active: true,
+ ZFSPool: &models.ZFSPool{
+ State: "DEGRADED",
+ ReadErrors: 1,
+ WriteErrors: 2,
+ ChecksumErrors: 3,
+ },
+ },
+ },
+ CephClusters: []models.CephCluster{
+ {
+ Name: "ceph-1",
+ Health: "HEALTH_WARN",
+ HealthMessage: "OSD down",
+ UsagePercent: 45.0,
+ UsedBytes: 450 * 1024 * 1024,
+ TotalBytes: 1000 * 1024 * 1024,
+ NumOSDs: 3,
+ NumOSDsUp: 2,
+ NumOSDsIn: 3,
+ },
+ },
+ PBSInstances: []models.PBSInstance{
+ {
+ Name: "pbs-1",
+ Datastores: []models.PBSDatastore{
+ {Name: "store", Usage: 55.0, Used: 550 * 1024 * 1024, Total: 1000 * 1024 * 1024},
+ },
+ },
+ },
+ }
+
+ out := ps.seedResourceInventory(state, nil, cfg, now, false)
+ for _, part := range []string{
+ "# Node Metrics",
+ "# Guest Metrics",
+ "# Docker",
+ "health=unhealthy",
+ "# Storage",
+ "ZFS errors",
+ "# Ceph",
+ "Message: OSD down",
+ "# PBS Datastores",
+ } {
+ if !strings.Contains(out, part) {
+ t.Fatalf("expected output to contain %q, got: %s", part, out)
+ }
+ }
+}
+
+func TestSeedHealthAndAlerts_NoIssues(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ cfg := DefaultPatrolConfig()
+ now := time.Now()
+
+ state := models.StateSnapshot{
+ PhysicalDisks: []models.PhysicalDisk{
+ {
+ Node: "node-1",
+ DevPath: "/dev/sda",
+ Model: "disk",
+ Health: "PASSED",
+ Wearout: 100,
+ Temperature: 40,
+ },
+ },
+ ConnectionHealth: map[string]bool{
+ "node-1": true,
+ "node-2": true,
+ },
+ }
+
+ out := ps.seedHealthAndAlerts(state, nil, cfg, now)
+ if !strings.Contains(out, "All 1 disks healthy") {
+ t.Fatalf("expected healthy disk summary, got: %s", out)
+ }
+ if !strings.Contains(out, "All 2 instances connected") {
+ t.Fatalf("expected all connections summary, got: %s", out)
+ }
+}
+
+func TestSeedHealthAndAlerts_WithIssues(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ cfg := DefaultPatrolConfig()
+ now := time.Now()
+
+ state := models.StateSnapshot{
+ PhysicalDisks: []models.PhysicalDisk{
+ {
+ Node: "node-1",
+ DevPath: "/dev/sda",
+ Model: "disk",
+ Health: "FAILED",
+ Wearout: 10,
+ Temperature: 60,
+ },
+ },
+ ActiveAlerts: []models.Alert{
+ {Level: "warning", Message: "CPU high", StartTime: now.Add(-time.Hour)},
+ },
+ RecentlyResolved: []models.ResolvedAlert{
+ {Alert: models.Alert{Message: "Disk alert"}, ResolvedTime: now.Add(-2 * time.Hour)},
+ },
+ ConnectionHealth: map[string]bool{
+ "node-1": true,
+ "node-2": false,
+ },
+ KubernetesClusters: []models.KubernetesCluster{
+ {Name: "k1", Nodes: []models.KubernetesNode{{Name: "n1"}}},
+ },
+ Hosts: []models.Host{
+ {ID: "host-1", Hostname: "host-1"},
+ },
+ }
+
+ out := ps.seedHealthAndAlerts(state, nil, cfg, now)
+ for _, part := range []string{
+ "# Disk Health",
+ "/dev/sda",
+ "# Active Alerts",
+ "# Recently Resolved Alerts",
+ "# Connections",
+ "Disconnected: node-2",
+ "# Kubernetes Clusters",
+ "# Hosts",
+ } {
+ if !strings.Contains(out, part) {
+ t.Fatalf("expected output to contain %q, got: %s", part, out)
+ }
+ }
+}
+
+func TestSeedIntelligenceContext_EmptyAnomalies(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ out := ps.seedIntelligenceContext(seedIntelligence{hasBaselineStore: true}, time.Now())
+ if !strings.Contains(out, "No anomalies detected") {
+ t.Fatalf("expected no anomalies message, got: %s", out)
+ }
+}
+
+func TestSeedIntelligenceContext_WithData(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ now := time.Now()
+
+ intel := seedIntelligence{
+ hasBaselineStore: true,
+ anomalies: []baseline.AnomalyReport{
+ {
+ ResourceID: "node-1",
+ ResourceName: "node-1",
+ Metric: "cpu",
+ CurrentValue: 0.9,
+ BaselineMean: 0.4,
+ ZScore: 2.5,
+ Severity: baseline.AnomalyHigh,
+ },
+ },
+ forecasts: []seedForecast{
+ {name: "node-1", metric: "memory", severity: "warning", daysToFull: 10, dailyChange: 2.5, current: 75.0},
+ },
+ predictions: []FailurePrediction{
+ {ResourceID: "node-1", EventType: "restart", DaysUntil: 3, Confidence: 0.9, Basis: "pattern"},
+ },
+ recentChanges: []memory.Change{
+ {ResourceID: "vm-1", ResourceType: "vm", Description: "config changed", DetectedAt: now.Add(-time.Hour)},
+ },
+ correlations: []*Correlation{
+ {SourceID: "node-1", TargetID: "vm-1", EventPattern: "cpu_high -> restart", AvgDelay: 10 * time.Minute, Confidence: 0.8, Occurrences: 4},
+ },
+ }
+
+ out := ps.seedIntelligenceContext(intel, now)
+ for _, part := range []string{
+ "# Anomalies",
+ "# Capacity Forecasts",
+ "# Failure Predictions",
+ "# Recent Infrastructure Changes",
+ "# Known Resource Correlations",
+ } {
+ if !strings.Contains(out, part) {
+ t.Fatalf("expected output to contain %q, got: %s", part, out)
+ }
+ }
+}