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.

10.0 KB
Raw Blame
package ai

import (
	"encoding/json"
	"strings"
	"testing"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/ai/correlation"
	"github.com/rcourtman/pulse-go-rewrite/internal/models"
	ur "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)

func TestPersistedPatrolToolInputKeepsExpectedFindingJSONComplete(t *testing.T) {
	payload, err := json.Marshal(map[string]string{
		"description":    strings.Repeat("d", 4*1024),
		"evidence":       strings.Repeat("e", 4*1024),
		"recommendation": strings.Repeat("r", 2*1024),
	})
	if err != nil {
		t.Fatal(err)
	}
	persisted := truncateString(string(payload), MaxToolInputSize)
	if persisted != string(payload) || !json.Valid([]byte(persisted)) {
		t.Fatalf("expected finding input (%d bytes) was not preserved as complete JSON", len(payload))
	}
}

func TestSeedFormattingHelpers(t *testing.T) {
	t.Run("formatBytes", func(t *testing.T) {
		cases := []struct {
			value int64
			want  string
		}{
			{value: 512, want: "512 B"},
			{value: 2 * 1024, want: "2 KB"},
			{value: 5 * 1024 * 1024, want: "5 MB"},
			{value: 3 * 1024 * 1024 * 1024, want: "3.0 GB"},
			{value: 2 * 1024 * 1024 * 1024 * 1024, want: "2.0 TB"},
		}
		for _, c := range cases {
			if got := seedFormatBytes(c.value); got != c.want {
				t.Fatalf("seedFormatBytes(%d) = %q, want %q", c.value, got, c.want)
			}
		}
	})

	t.Run("formatDuration", func(t *testing.T) {
		cases := []struct {
			value time.Duration
			want  string
		}{
			{value: 30 * time.Second, want: "30s"},
			{value: 5 * time.Minute, want: "5m"},
			{value: 3 * time.Hour, want: "3h"},
			{value: 48 * time.Hour, want: "2d"},
		}
		for _, c := range cases {
			if got := seedFormatDuration(c.value); got != c.want {
				t.Fatalf("seedFormatDuration(%s) = %q, want %q", c.value, got, c.want)
			}
		}
	})

	t.Run("formatTimeAgo", func(t *testing.T) {
		now := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)
		cases := []struct {
			value time.Time
			want  string
		}{
			{value: now.Add(-30 * time.Second), want: "just now"},
			{value: now.Add(-10 * time.Minute), want: "10m ago"},
			{value: now.Add(-2 * time.Hour), want: "2h ago"},
			{value: now.Add(-24 * time.Hour), want: "1d ago"},
			{value: now.Add(-72 * time.Hour), want: "3d ago"},
		}
		for _, c := range cases {
			if got := seedFormatTimeAgo(now, c.value); got != c.want {
				t.Fatalf("seedFormatTimeAgo(%s) = %q, want %q", c.value, got, c.want)
			}
		}
	})
}

func TestSeedIsInScope(t *testing.T) {
	if !seedIsInScope(nil, "anything") {
		t.Fatal("seedIsInScope should return true for nil scope")
	}

	scoped := map[string]bool{"res-1": true}
	if seedIsInScope(scoped, "res-2") {
		t.Fatal("seedIsInScope should return false for missing resource")
	}
	if !seedIsInScope(scoped, "res-1") {
		t.Fatal("seedIsInScope should return true for scoped resource")
	}
}

func TestPatrolService_BuildScopedSet_WithCorrelation(t *testing.T) {
	ps := NewPatrolService(nil, nil)

	cfg := correlation.DefaultConfig()
	cfg.MinOccurrences = 1
	cfg.CorrelationWindow = 10 * time.Minute

	detector := correlation.NewDetector(cfg)
	now := time.Now()
	detector.RecordEvent(correlation.Event{
		ResourceID: "vm:node1:101",
		EventType:  correlation.EventType("alert"),
		Timestamp:  now.Add(-2 * time.Minute),
	})
	detector.RecordEvent(correlation.Event{
		ResourceID: "vm:node1:102",
		EventType:  correlation.EventType("alert"),
		Timestamp:  now.Add(-1 * time.Minute),
	})

	ps.correlationDetector = detector

	scope := &PatrolScope{ResourceIDs: []string{"vm:node1:101"}}
	scopedSet := ps.buildScopedSet(scope)
	if scopedSet == nil {
		t.Fatal("expected non-nil scoped set")
	}
	if !scopedSet["vm:node1:101"] || !scopedSet["vm:node1:102"] {
		t.Fatalf("expected correlated resources to be included, got: %+v", scopedSet)
	}
}

func TestPatrolService_BuildScopedSetForRuntime_TypeOnlyScope(t *testing.T) {
	ps := NewPatrolService(nil, nil)

	node := ur.NewNodeView(&ur.Resource{ID: "node-1", Name: "node-1", Type: ur.ResourceTypeAgent})

	runtimeState := newPatrolRuntimeState(models.StateSnapshot{
		Nodes: []models.Node{{ID: "node-1", Name: "node-1"}},
	})
	runtimeState.readState = &mockReadState{
		nodes: []*ur.NodeView{&node},
	}

	scopedSet := ps.buildScopedSetForRuntime(&PatrolScope{ResourceTypes: []string{"node"}}, runtimeState)
	if scopedSet == nil {
		t.Fatal("expected non-nil scoped set for type-only runtime scope")
	}
	if !scopedSet["node-1"] {
		t.Fatalf("expected runtime scoped set to include filtered node, got %+v", scopedSet)
	}
	if len(scopedSet) != 1 {
		t.Fatalf("expected runtime scoped set to contain only filtered resources, got %+v", scopedSet)
	}
}

func TestPatrolService_BuildScopedSetForRuntime_TypeOnlyScopeWithCorrelation(t *testing.T) {
	ps := NewPatrolService(nil, nil)

	cfg := correlation.DefaultConfig()
	cfg.MinOccurrences = 1
	cfg.CorrelationWindow = 10 * time.Minute

	detector := correlation.NewDetector(cfg)
	now := time.Now()
	detector.RecordEvent(correlation.Event{
		ResourceID: "node-1",
		EventType:  correlation.EventType("alert"),
		Timestamp:  now.Add(-2 * time.Minute),
	})
	detector.RecordEvent(correlation.Event{
		ResourceID: "qemu/101",
		EventType:  correlation.EventType("alert"),
		Timestamp:  now.Add(-time.Minute),
	})
	ps.correlationDetector = detector

	node := ur.NewNodeView(&ur.Resource{ID: "node-1", Name: "node-1", Type: ur.ResourceTypeAgent})
	runtimeState := newPatrolRuntimeState(models.StateSnapshot{
		Nodes: []models.Node{{ID: "node-1", Name: "node-1"}},
	})
	runtimeState.readState = &mockReadState{
		nodes: []*ur.NodeView{&node},
	}

	scopedSet := ps.buildScopedSetForRuntime(&PatrolScope{ResourceTypes: []string{"node"}}, runtimeState)
	if scopedSet == nil {
		t.Fatal("expected non-nil scoped set for correlated runtime scope")
	}
	if !scopedSet["node-1"] || !scopedSet["qemu/101"] {
		t.Fatalf("expected runtime scoped set to include correlated resource, got %+v", scopedSet)
	}
}

func TestBuildSeedContextState_TypeOnlyScopeUsesRuntimeScopedSet(t *testing.T) {
	ps := NewPatrolService(nil, nil)

	changeDetector := newLegacyChangeDetector(t,
		legacyCreatedChange("qemu/101", "vm-1", "vm"),
		legacyStatusChange("qemu/101", "vm-1", "vm", "running", "stopped"),
	)
	ps.SetChangeDetector(changeDetector)

	node := ur.NewNodeView(&ur.Resource{ID: "node-1", Name: "node-1", Type: ur.ResourceTypeAgent})
	runtimeState := newPatrolRuntimeState(models.StateSnapshot{
		Nodes: []models.Node{{ID: "node-1", Name: "node-1"}},
	})
	runtimeState.readState = &mockReadState{
		nodes: []*ur.NodeView{&node},
	}

	output, _ := ps.buildSeedContextState(runtimeState, &PatrolScope{ResourceTypes: []string{"node"}}, nil)
	if strings.Contains(output, "# Recent Infrastructure Changes") {
		t.Fatalf("expected type-only scoped patrol to omit out-of-scope recent changes, got: %s", output)
	}
	if strings.Contains(output, "vm-1") {
		t.Fatalf("expected type-only scoped patrol to omit unrelated VM change context, got: %s", output)
	}
}

func TestBuildSeedContextState_TypeOnlyScopeIncludesCorrelatedRuntimeChange(t *testing.T) {
	ps := NewPatrolService(nil, nil)

	changeDetector := newLegacyChangeDetector(t,
		legacyCreatedChange("qemu/101", "vm-1", "vm"),
		legacyStatusChange("qemu/101", "vm-1", "vm", "running", "stopped"),
	)
	ps.SetChangeDetector(changeDetector)

	cfg := correlation.DefaultConfig()
	cfg.MinOccurrences = 1
	cfg.CorrelationWindow = 10 * time.Minute
	detector := correlation.NewDetector(cfg)
	now := time.Now()
	detector.RecordEvent(correlation.Event{
		ResourceID: "node-1",
		EventType:  correlation.EventType("alert"),
		Timestamp:  now.Add(-2 * time.Minute),
	})
	detector.RecordEvent(correlation.Event{
		ResourceID: "qemu/101",
		EventType:  correlation.EventType("alert"),
		Timestamp:  now.Add(-time.Minute),
	})
	ps.correlationDetector = detector

	node := ur.NewNodeView(&ur.Resource{ID: "node-1", Name: "node-1", Type: ur.ResourceTypeAgent})
	runtimeState := newPatrolRuntimeState(models.StateSnapshot{
		Nodes: []models.Node{{ID: "node-1", Name: "node-1"}},
	})
	runtimeState.readState = &mockReadState{
		nodes: []*ur.NodeView{&node},
	}

	output, _ := ps.buildSeedContextState(runtimeState, &PatrolScope{ResourceTypes: []string{"node"}}, nil)
	if !strings.Contains(output, "# Recent Infrastructure Changes") {
		t.Fatalf("expected correlated change context to be included, got: %s", output)
	}
	if !strings.Contains(output, "vm-1") {
		t.Fatalf("expected correlated VM change context in type-only patrol, got: %s", output)
	}
}

func TestPatrolService_SeedPreviousRun(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	ps.runHistoryStore = NewPatrolRunHistoryStore(10)

	now := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)
	ps.runHistoryStore.Add(PatrolRunRecord{
		ID:               "run-1",
		StartedAt:        now.Add(-2 * time.Hour),
		Duration:         30 * time.Minute,
		Status:           "issues_found",
		NewFindings:      1,
		ExistingFindings: 2,
		ResolvedFindings: 1,
		RejectedFindings: 0,
		FindingsSummary:  "CPU warning on node1",
	})

	summary := ps.seedPreviousRun(now)
	if summary == "" {
		t.Fatal("expected previous run summary to be non-empty")
	}
	expectedParts := []string{
		"# Previous Patrol Run",
		"Status: issues_found",
		"duration: 30m",
		"Summary: CPU warning on node1",
		"Trigger: scheduled",
	}
	for _, part := range expectedParts {
		if !strings.Contains(summary, part) {
			t.Fatalf("expected summary to contain %q, got:\n%s", part, summary)
		}
	}
}

func TestPatrolMissingAssessmentIDsIncludesSeededAndQueriedFindings(t *testing.T) {
	result := &AIAnalysisResult{
		SeededFindingIDs:  []string{"seeded", "resolved-direct", "duplicate", "reported-existing"},
		QueriedFindingIDs: []string{"queried", "duplicate", "new-this-run", "reported-existing"},
		ReportedIDs:       []string{"new-this-run", "reported-existing"},
		NewFindingIDs:     []string{"new-this-run"},
		Assessments:       []PatrolFindingAssessment{{FindingID: "seeded", Verdict: "present"}},
		ResolvedIDs:       []string{"resolved-direct"},
	}
	missing := patrolMissingAssessmentIDs(result)
	if len(missing) != 3 || missing[0] != "duplicate" || missing[1] != "queried" || missing[2] != "reported-existing" {
		t.Fatalf("missing assessments = %v, want [duplicate queried reported-existing]", missing)
	}
}