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.

68.3 KB
Raw Blame
package ai

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
	"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"
	"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
	"github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
)

type patrolTestStateProvider struct {
	state models.StateSnapshot
}

func (p *patrolTestStateProvider) ReadSnapshot() models.StateSnapshot {
	return p.state
}

// patrolMockChatService implements ChatServiceProvider and chatServiceExecutorAccessor for testing.
type patrolMockChatService struct {
	executor                *tools.PulseToolExecutor
	executePatrolStreamFunc func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error)
}

func (m *patrolMockChatService) CreateSession(ctx context.Context) (*ChatSession, error) {
	return &ChatSession{ID: "mock-session"}, nil
}

func (m *patrolMockChatService) ExecuteStream(ctx context.Context, req ChatExecuteRequest, callback ChatStreamCallback) error {
	return nil
}

func (m *patrolMockChatService) ExecutePatrolStream(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {
	if m.executePatrolStreamFunc != nil {
		return m.executePatrolStreamFunc(ctx, req, callback)
	}
	return &PatrolStreamResponse{}, nil
}

func (m *patrolMockChatService) GetMessages(ctx context.Context, sessionID string) ([]ChatMessage, error) {
	return nil, nil
}

func (m *patrolMockChatService) DeleteSession(ctx context.Context, sessionID string) error {
	return nil
}

func (m *patrolMockChatService) ReloadConfig(ctx context.Context, cfg *config.AIConfig) error {
	return nil
}

func (m *patrolMockChatService) GetExecutor() *tools.PulseToolExecutor {
	return m.executor
}

func TestPatrolService_DismissFinding(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	f := &Finding{
		ID:           "f1",
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "node-1",
		ResourceName: "node-1",
		ResourceType: "node",
		Title:        "High CPU",
	}
	ps.findings.Add(f)

	if err := ps.DismissFinding("f1", "not_an_issue", "expected during maintenance"); err != nil {
		t.Fatalf("dismiss finding: %v", err)
	}
	stored := ps.findings.Get("f1")
	if stored == nil || stored.DismissedReason != "not_an_issue" {
		t.Fatalf("expected finding to be dismissed, got %+v", stored)
	}
	if stored.UserNote != "expected during maintenance" {
		t.Fatalf("expected dismissal note to be preserved, got %q", stored.UserNote)
	}

	if err := ps.DismissFinding("f1", "bad_reason", ""); err == nil {
		t.Fatal("expected error for invalid dismissal reason")
	}
}

func TestPatrolService_DismissFinding_RejectsPatrolRuntimeFinding(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	f := &Finding{
		ID:           "runtime-1",
		Key:          patrolRuntimeFindingKey,
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryReliability,
		ResourceID:   patrolRuntimeResourceID,
		ResourceName: "Pulse Patrol Service",
		ResourceType: "service",
		Title:        "Pulse Patrol: Provider billing or quota issue",
	}
	ps.findings.Add(f)

	err := ps.DismissFinding("runtime-1", "not_an_issue", "ignore it")
	if err == nil {
		t.Fatal("expected Patrol runtime finding dismissal to be rejected")
	}
	if got := err.Error(); !strings.Contains(got, "cannot be dismissed manually") {
		t.Fatalf("unexpected error: %q", got)
	}
	if got := err.Error(); !strings.Contains(got, "Pulse Intelligence settings") {
		t.Fatalf("dismissal guidance must point to Pulse Intelligence settings: %q", got)
	}

	stored := ps.findings.Get("runtime-1")
	if stored == nil {
		t.Fatal("expected runtime finding to remain present")
	}
	if stored.DismissedReason != "" {
		t.Fatalf("expected runtime finding to remain active, got dismissed reason %q", stored.DismissedReason)
	}
}

func TestPatrolService_RejectManualActionForRuntimeFindingUsesProviderSettingsGuidance(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	ps.findings.Add(&Finding{
		ID:           "runtime-1",
		Key:          patrolRuntimeFindingKey,
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryReliability,
		ResourceID:   patrolRuntimeResourceID,
		ResourceName: "Pulse Patrol Service",
		ResourceType: "service",
		Title:        "Pulse Patrol: Provider not ready",
	})

	err := ps.RejectManualActionForRuntimeFinding("runtime-1", "acknowledged")
	if err == nil {
		t.Fatal("expected Patrol runtime finding manual action to be rejected")
	}
	got := err.Error()
	if !strings.Contains(got, "fix Patrol provider configuration in Pulse Intelligence settings") {
		t.Fatalf("manual action guidance = %q", got)
	}
	if strings.Contains(got, "AI settings") {
		t.Fatalf("manual action guidance must not reference legacy AI settings: %q", got)
	}
}

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

	lowState := models.StateSnapshot{
		Nodes: []models.Node{
			{
				ID:     "node-low",
				Name:   "node-low",
				Status: "online",
				CPU:    0.20,
				Memory: models.Memory{Usage: 30.0},
			},
		},
	}
	lowAdapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, lowState))
	_, _, err := lowAdapter.CreateFinding(tools.PatrolFindingInput{
		Key:          "cpu-high",
		Severity:     "warning",
		Category:     "performance",
		ResourceID:   "node-low",
		ResourceName: "node-low",
		ResourceType: "node",
		Title:        "High CPU",
		Description:  "CPU usage is high",
		Evidence:     "CPU > 90%",
	})
	if err == nil {
		t.Fatal("expected low CPU warning finding to be rejected")
	}

	highState := models.StateSnapshot{
		Nodes: []models.Node{
			{
				ID:     "node-high",
				Name:   "node-high",
				Status: "online",
				CPU:    0.90,
				Memory: models.Memory{Usage: 80.0},
			},
		},
	}
	highAdapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, highState))
	_, _, err = highAdapter.CreateFinding(tools.PatrolFindingInput{
		Key:          "cpu-high",
		Severity:     "warning",
		Category:     "performance",
		ResourceID:   "node-high",
		ResourceName: "node-high",
		ResourceType: "node",
		Title:        "High CPU",
		Description:  "CPU usage is high",
		Evidence:     "CPU > 90%",
	})
	if err != nil {
		t.Fatalf("expected high CPU warning finding to be accepted, got %v", err)
	}
}

func TestPatrolService_ForcePatrol_RecordsRun(t *testing.T) {
	persistence := config.NewConfigPersistence(t.TempDir())
	svc := NewService(persistence, nil)
	svc.cfg = &config.AIConfig{Enabled: true, PatrolModel: "mock:model"}
	svc.provider = &mockProvider{}

	executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
	mockCS := &patrolMockChatService{
		executor: executor,
		executePatrolStreamFunc: func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {
			creator := executor.GetPatrolFindingCreator()
			if creator == nil {
				return nil, fmt.Errorf("patrol finding creator not set")
			}
			_, _, _ = creator.CreateFinding(tools.PatrolFindingInput{
				Severity:     "warning",
				Category:     "performance",
				ResourceID:   "vm-100",
				ResourceName: "web-server",
				ResourceType: "vm",
				Title:        "High CPU",
				Description:  "CPU usage is high",
				Evidence:     "CPU > 90%",
			})
			return &PatrolStreamResponse{Content: "Analysis complete"}, nil
		},
	}
	svc.SetChatService(mockCS)

	stateProvider := &patrolTestStateProvider{
		state: models.StateSnapshot{
			VMs: []models.VM{
				{ID: "vm-100", VMID: 100, Name: "web-server", Node: "pve-1", Status: "running", CPU: 0.95},
			},
			Nodes: []models.Node{
				{ID: "node-1", Name: "pve-1", Status: "online"},
			},
		},
	}

	ps := NewPatrolService(svc, stateProvider)
	ps.SetConfig(PatrolConfig{
		Enabled:       true,
		Interval:      10 * time.Minute,
		AnalyzeNodes:  true,
		AnalyzeGuests: true,
	})

	before := ps.runHistoryStore.Count()
	ps.ForcePatrol(context.Background())

	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		if ps.runHistoryStore.Count() > before {
			return
		}
		time.Sleep(20 * time.Millisecond)
	}

	t.Fatalf("expected ForcePatrol to record a run (count stayed at %d)", before)
}

func TestVerifyFixResolved_UsesReadStateWithoutSnapshotProvider(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{NodeCPUWarning: 90}

	nodeView := unifiedresources.NewNodeView(&unifiedresources.Resource{
		ID:     "node-1",
		Name:   "node-1",
		Type:   unifiedresources.ResourceTypeAgent,
		Status: unifiedresources.StatusOnline,
		Proxmox: &unifiedresources.ProxmoxData{
			NodeName: "node-1",
		},
		Metrics: &unifiedresources.ResourceMetrics{
			CPU: &unifiedresources.MetricValue{Percent: 20},
		},
	})
	ps.SetReadState(&mockReadState{nodes: []*unifiedresources.NodeView{&nodeView}})

	verified, err := ps.VerifyFixResolved(context.Background(), "node-1", "node", "cpu-high", "")
	if err != nil {
		t.Fatalf("expected read-state-backed verification to run, got %v", err)
	}
	if !verified {
		t.Fatalf("expected read-state-backed verification to resolve healthy node")
	}
}

func TestVerifyFixResolved_RecordsVerificationAsActivityWithoutReplacingLastFullPatrol(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{NodeCPUWarning: 90}

	nodeView := unifiedresources.NewNodeView(&unifiedresources.Resource{
		ID:     "node-1",
		Name:   "node-1",
		Type:   unifiedresources.ResourceTypeAgent,
		Status: unifiedresources.StatusOnline,
		Proxmox: &unifiedresources.ProxmoxData{
			NodeName: "node-1",
		},
		Metrics: &unifiedresources.ResourceMetrics{
			CPU: &unifiedresources.MetricValue{Percent: 20},
		},
	})
	ps.SetReadState(&mockReadState{nodes: []*unifiedresources.NodeView{&nodeView}})

	lastFullPatrol := time.Now().Add(-1 * time.Hour).UTC().Truncate(time.Second)
	ps.mu.Lock()
	ps.lastFullPatrol = lastFullPatrol
	ps.mu.Unlock()

	verified, err := ps.VerifyFixResolved(context.Background(), "node-1", "node", "cpu-high", "finding-1")
	if err != nil {
		t.Fatalf("expected verification to succeed, got %v", err)
	}
	if !verified {
		t.Fatal("expected verification to resolve the issue")
	}

	status := ps.GetStatus()
	if status.LastPatrolAt == nil || !status.LastPatrolAt.Equal(lastFullPatrol) {
		t.Fatalf("last full patrol = %v, want %v", status.LastPatrolAt, lastFullPatrol)
	}
	if status.LastActivityAt == nil {
		t.Fatal("expected verification run to update last activity")
	}
	if !status.LastActivityAt.After(lastFullPatrol) {
		t.Fatalf("expected last activity %v to be after last full patrol %v", *status.LastActivityAt, lastFullPatrol)
	}
	if status.LastDuration <= 0 {
		t.Fatalf("expected verification run to update last duration, got %v", status.LastDuration)
	}
	if status.ResourcesChecked != 1 {
		t.Fatalf("resources checked = %d, want 1", status.ResourcesChecked)
	}

	runs := ps.GetRunHistory(1)
	if len(runs) != 1 {
		t.Fatalf("expected one verification run, got %d", len(runs))
	}
	if runs[0].Type != "verification" {
		t.Fatalf("run type = %q, want verification", runs[0].Type)
	}
	if runs[0].ResourcesChecked != 1 {
		t.Fatalf("verification run resources_checked = %d, want 1", runs[0].ResourcesChecked)
	}
}

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

	verified, err := ps.VerifyFixResolved(context.Background(), "node-1", "node", "cpu-high", "")
	if err == nil {
		t.Fatal("expected verification to fail without runtime state")
	}
	if verified {
		t.Fatal("expected verification result to be false on failure")
	}
	if err != nil && !errors.Is(err, aicontracts.ErrVerificationUnknown) {
		t.Fatalf("expected verification unknown error, got %v", err)
	}
}

func TestExecuteToolCallTreatsSharedApprovalAndPolicyMarkersAsInconclusive(t *testing.T) {
	tests := []struct {
		name        string
		resultText  string
		wantMessage string
	}{
		{
			name:        "approval required",
			resultText:  agentcapabilities.ApprovalRequiredToolMarker("rm -rf /", "call-1", "needs approval", "approval-1", "approve in Pulse"),
			wantMessage: "tool requires approval",
		},
		{
			name:        "policy blocked",
			resultText:  agentcapabilities.PolicyBlockedToolMarker("rm -rf /", "blocked"),
			wantMessage: "tool blocked by security policy",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
			executor.RegisterTool(tools.RegisteredTool{
				Definition: tools.Tool{
					Name:        "patrol_marker_probe",
					Description: "test-only marker probe",
				},
				Invocation: tools.StaticInvocation(agentcapabilities.ToolCallKindRead, agentcapabilities.MutationNone),
				Handler: func(context.Context, *tools.PulseToolExecutor, map[string]interface{}) (tools.CallToolResult, error) {
					return tools.NewTextResult(tt.resultText), nil
				},
			})

			record, err := executeToolCall(context.Background(), executor, "patrol_marker_probe", nil)
			if err == nil {
				t.Fatalf("expected shared marker to fail closed, got record %+v", record)
			}
			if !errors.Is(err, aicontracts.ErrVerificationUnknown) {
				t.Fatalf("expected verification unknown, got %v", err)
			}
			if !strings.Contains(err.Error(), tt.wantMessage) {
				t.Fatalf("expected %q in error, got %v", tt.wantMessage, err)
			}
		})
	}
}

// --- Configurable threshold tests ---

func TestActionabilityThreshold_DefaultFallback(t *testing.T) {
	// Zero thresholds → should fall back to old defaults (50/60/70)
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{} // all zero

	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, models.StateSnapshot{}))

	if got := adapter.actionabilityThreshold("cpu", "node"); got != 50.0 {
		t.Errorf("cpu threshold = %v, want 50.0", got)
	}
	if got := adapter.actionabilityThreshold("memory", "vm"); got != 60.0 {
		t.Errorf("guest memory threshold = %v, want 60.0", got)
	}
	if got := adapter.actionabilityThreshold("memory", "node"); got != 60.0 {
		t.Errorf("node memory threshold (zero → default) = %v, want 60.0", got)
	}
	if got := adapter.actionabilityThreshold("disk", "vm"); got != 70.0 {
		t.Errorf("disk threshold = %v, want 70.0", got)
	}
	if got := adapter.actionabilityThreshold("storage", "storage"); got != 70.0 {
		t.Errorf("storage threshold = %v, want 70.0", got)
	}
}

func TestActionabilityThreshold_CustomThresholds(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{
		NodeCPUWatch:   65,
		NodeMemWatch:   70,
		GuestMemWatch:  72,
		GuestDiskWatch: 80,
		StorageWatch:   75,
	}

	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, models.StateSnapshot{}))

	if got := adapter.actionabilityThreshold("cpu", "node"); got != 65.0 {
		t.Errorf("cpu threshold = %v, want 65.0", got)
	}
	if got := adapter.actionabilityThreshold("memory", "node"); got != 70.0 {
		t.Errorf("node memory threshold = %v, want 70.0", got)
	}
	if got := adapter.actionabilityThreshold("memory", "vm"); got != 72.0 {
		t.Errorf("guest memory threshold = %v, want 72.0", got)
	}
	if got := adapter.actionabilityThreshold("memory", "container"); got != 72.0 {
		t.Errorf("container memory threshold = %v, want 72.0 (guest)", got)
	}
	if got := adapter.actionabilityThreshold("disk", "vm"); got != 80.0 {
		t.Errorf("disk threshold = %v, want 80.0", got)
	}
	if got := adapter.actionabilityThreshold("storage", "storage"); got != 75.0 {
		t.Errorf("storage threshold = %v, want 75.0", got)
	}
}

func TestIsActionable_CustomThresholdsRespected(t *testing.T) {
	// Set a high CPU watch threshold (85%) - value at 60% should be rejected
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{NodeCPUWatch: 85}

	state := models.StateSnapshot{
		Nodes: []models.Node{
			{ID: "node-1", Name: "node-1", CPU: 0.60, Memory: models.Memory{Usage: 30}},
		},
	}
	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, state))

	finding := &Finding{
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "node-1",
		ResourceType: "node",
		Title:        "High CPU usage",
	}

	if adapter.isActionable(finding) {
		t.Fatal("finding at 60% CPU should be rejected with 85% threshold")
	}

	// Now set lower threshold (40%) - same 60% value should pass
	ps.thresholds = PatrolThresholds{NodeCPUWatch: 40}
	adapter2 := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, state))

	if !adapter2.isActionable(finding) {
		t.Fatal("finding at 60% CPU should be accepted with 40% threshold")
	}
}

func TestIsActionable_NodeMemoryUsesNodeThreshold(t *testing.T) {
	// A node at 78% memory should pass with NodeMemWatch=75 but would fail
	// with GuestMemWatch=80. This test verifies the correct threshold is selected.
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{
		NodeMemWatch:  75, // node threshold: 75%
		GuestMemWatch: 80, // guest threshold: 80%
	}

	state := models.StateSnapshot{
		Nodes: []models.Node{
			{ID: "node-1", Name: "node-1", CPU: 0.40, Memory: models.Memory{Used: 78, Total: 100}},
		},
	}
	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, state))

	nodeFinding := &Finding{
		Key:          "memory-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "node-1",
		ResourceType: "node",
		Title:        "High memory usage",
	}

	// 78% > NodeMemWatch (75%) → should be actionable
	if !adapter.isActionable(nodeFinding) {
		t.Fatal("node at 78% memory should pass with NodeMemWatch=75")
	}

	// Same memory level on a VM should be rejected (78% < GuestMemWatch 80%)
	vmState := models.StateSnapshot{
		VMs: []models.VM{
			{ID: "vm-1", Name: "vm-1", CPU: 0.40, Memory: models.Memory{Usage: 78}},
		},
	}
	vmAdapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, vmState))

	vmFinding := &Finding{
		Key:          "memory-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "vm-1",
		ResourceType: "vm",
		Title:        "High memory usage",
	}

	// 78% < GuestMemWatch (80%) → should be rejected
	if vmAdapter.isActionable(vmFinding) {
		t.Fatal("VM at 78% memory should be rejected with GuestMemWatch=80")
	}
}

func TestVerifyBackupFreshState_UsesReadStateWhenLegacySlicesEmpty(t *testing.T) {
	now := time.Now()
	state := newPatrolRuntimeState(models.StateSnapshot{})
	vmResource := &unifiedresources.Resource{
		ID:     "reg-qemu/101",
		Name:   "vm-1",
		Type:   unifiedresources.ResourceTypeVM,
		Status: unifiedresources.StatusOnline,
		Proxmox: &unifiedresources.ProxmoxData{
			SourceID:   "qemu/101",
			VMID:       101,
			NodeName:   "pve1",
			LastBackup: now.Add(-24 * time.Hour),
		},
	}
	vm := unifiedresources.NewVMView(vmResource)
	vmView := &vm
	state.readState = &mockReadState{vms: []*unifiedresources.VMView{vmView}}

	ok, err := verifyBackupFreshState(state, "101")
	if err != nil {
		t.Fatalf("expected readState-backed backup verification to succeed, got %v", err)
	}
	if !ok {
		t.Fatal("expected recent backup to verify via readState")
	}
}

func TestVerifyMetricRecoveredState_UsesReadStateWhenLegacySlicesEmpty(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{})
	nodeView := unifiedresources.NewNodeView(&unifiedresources.Resource{
		ID:     "n1",
		Name:   "node-1",
		Type:   unifiedresources.ResourceTypeAgent,
		Status: unifiedresources.StatusOnline,
		Proxmox: &unifiedresources.ProxmoxData{
			NodeName: "node-1",
		},
		Metrics: &unifiedresources.ResourceMetrics{
			CPU: &unifiedresources.MetricValue{Percent: 40},
		},
	})
	state.readState = &mockReadState{nodes: []*unifiedresources.NodeView{&nodeView}}

	ok, err := verifyMetricRecoveredState(state, PatrolThresholds{NodeCPUWarning: 90}, "cpu-high", "n1", "node")
	if err != nil {
		t.Fatalf("expected readState-backed metric verification to succeed, got %v", err)
	}
	if !ok {
		t.Fatal("expected CPU metric to verify as recovered via readState")
	}
}

func TestVerifyMetricRecoveredState_UsesTypedLookupWhenIDsCollide(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{})
	nodeView := unifiedresources.NewNodeView(&unifiedresources.Resource{
		ID:     "shared-id",
		Name:   "node-1",
		Type:   unifiedresources.ResourceTypeAgent,
		Status: unifiedresources.StatusOnline,
		Metrics: &unifiedresources.ResourceMetrics{
			CPU: &unifiedresources.MetricValue{Percent: 40},
		},
	})
	storageView := unifiedresources.NewStoragePoolView(&unifiedresources.Resource{
		ID:     "shared-id",
		Name:   "local",
		Type:   unifiedresources.ResourceTypeStorage,
		Status: unifiedresources.StatusOnline,
		Metrics: &unifiedresources.ResourceMetrics{
			Disk: &unifiedresources.MetricValue{Percent: 55},
		},
	})
	state.readState = &mockReadState{
		nodes:   []*unifiedresources.NodeView{&nodeView},
		storage: []*unifiedresources.StoragePoolView{&storageView},
	}

	ok, err := verifyMetricRecoveredState(state, PatrolThresholds{StorageWarning: 90}, "disk-high", "shared-id", "storage")
	if err != nil {
		t.Fatalf("expected typed storage lookup to succeed despite colliding IDs, got %v", err)
	}
	if !ok {
		t.Fatal("expected storage metric to verify as recovered via typed lookup")
	}
}

func TestVerifyMetricRecoveredState_UsesPhysicalDiskVerification(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{})
	state.unifiedResourceProvider = &mockUnifiedResourceProvider{
		getByTypeFunc: func(t unifiedresources.ResourceType) []unifiedresources.Resource {
			if t != unifiedresources.ResourceTypePhysicalDisk {
				return nil
			}
			return []unifiedresources.Resource{
				{
					ID:   "disk-1",
					Name: "disk-1",
					Type: unifiedresources.ResourceTypePhysicalDisk,
					PhysicalDisk: &unifiedresources.PhysicalDiskMeta{
						DevPath:     "/dev/sda",
						Health:      "PASSED",
						Wearout:     90,
						Temperature: 40,
					},
				},
			}
		},
	}

	ok, err := verifyMetricRecoveredState(state, PatrolThresholds{}, "disk-high", "disk-1", "physical_disk")
	if err != nil {
		t.Fatalf("expected physical disk verification to succeed, got %v", err)
	}
	if !ok {
		t.Fatal("expected healthy physical disk to verify as recovered")
	}
}

func TestIsActionable_ReadStateWithPhysicalDiskInventoryDoesNotRejectDiskFinding(t *testing.T) {
	patrol := NewPatrolService(nil, nil)
	adapter := patrolFindingCreatorAdapter{
		patrol: patrol,
		snap: patrolRuntimeState{
			readState: &mockReadState{
				nodes: []*unifiedresources.NodeView{
					func() *unifiedresources.NodeView {
						v := unifiedresources.NewNodeView(&unifiedresources.Resource{
							ID:   "node-1",
							Name: "node-1",
							Type: unifiedresources.ResourceTypeAgent,
						})
						return &v
					}(),
				},
			},
			unifiedResourceProvider: &mockUnifiedResourceProvider{
				getByTypeFunc: func(t unifiedresources.ResourceType) []unifiedresources.Resource {
					if t != unifiedresources.ResourceTypePhysicalDisk {
						return nil
					}
					return []unifiedresources.Resource{
						{
							ID:   "disk-1",
							Name: "disk-1",
							Type: unifiedresources.ResourceTypePhysicalDisk,
							PhysicalDisk: &unifiedresources.PhysicalDiskMeta{
								DevPath: "/dev/sda",
								Health:  "FAILED",
							},
						},
					}
				},
			},
		},
	}

	if !adapter.isActionable(&Finding{
		ResourceID:   "disk-1",
		ResourceName: "/dev/sda",
		ResourceType: "physical_disk",
		Severity:     FindingSeverityWarning,
		Key:          "disk-high",
		Title:        "Disk health warning",
	}) {
		t.Fatal("expected physical disk finding to remain actionable when disk inventory exists")
	}
}

func TestVerifyGuestReachabilityState_UsesReadStateWhenLegacySlicesEmpty(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	ps.SetGuestProber(&mockGuestProber{
		agents: map[string]string{"pve1": "agent-1"},
		results: map[string]map[string]PingResult{
			"agent-1": {
				"10.0.0.1": {Reachable: true},
			},
		},
	})

	state := newPatrolRuntimeState(models.StateSnapshot{})
	state.readState = &mockReadState{
		vms: []*unifiedresources.VMView{
			newTestVMView("qemu/100", "vm-1", 100, "pve1", "", unifiedresources.StatusOnline, false, []string{"10.0.0.1"}),
		},
	}

	ok, err := ps.verifyGuestReachabilityState(context.Background(), state, "100")
	if err != nil {
		t.Fatalf("expected readState-backed reachability verification to succeed, got %v", err)
	}
	if !ok {
		t.Fatal("expected guest to verify as reachable via readState")
	}
}

func TestIsActionable_UsesReadStateWhenLegacySlicesEmpty(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{NodeCPUWatch: 40}

	state := newPatrolRuntimeState(models.StateSnapshot{})
	nodeView := unifiedresources.NewNodeView(&unifiedresources.Resource{
		ID:     "node-1",
		Name:   "node-1",
		Type:   unifiedresources.ResourceTypeAgent,
		Status: unifiedresources.StatusOnline,
		Metrics: &unifiedresources.ResourceMetrics{
			CPU: &unifiedresources.MetricValue{Percent: 60},
		},
	})
	state.readState = &mockReadState{nodes: []*unifiedresources.NodeView{&nodeView}}
	adapter := newPatrolFindingCreatorAdapterState(ps, state)

	finding := &Finding{
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "node-1",
		ResourceType: "node",
		Title:        "High CPU usage",
	}

	if !adapter.isActionable(finding) {
		t.Fatal("expected finding to remain actionable via readState metrics")
	}
}

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

	state := newPatrolRuntimeState(models.StateSnapshot{})
	nodeView := unifiedresources.NewNodeView(&unifiedresources.Resource{
		ID:     "node-1",
		Name:   "node-1",
		Type:   unifiedresources.ResourceTypeAgent,
		Status: unifiedresources.StatusOnline,
		Metrics: &unifiedresources.ResourceMetrics{
			CPU: &unifiedresources.MetricValue{Percent: 80},
		},
	})
	state.readState = &mockReadState{nodes: []*unifiedresources.NodeView{&nodeView}}
	adapter := newPatrolFindingCreatorAdapterState(ps, state)

	finding := &Finding{
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "missing-node",
		ResourceType: "node",
		Title:        "High CPU usage",
	}

	if adapter.isActionable(finding) {
		t.Fatal("expected missing resource to be rejected when readState inventory is available")
	}
}

func TestIsBaselineAnomaly_NoStore(t *testing.T) {
	// No baseline store → always returns false (safe fallback)
	ps := NewPatrolService(nil, nil)
	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, models.StateSnapshot{}))

	if adapter.isBaselineAnomaly("node-1", "cpu", 45.0) {
		t.Fatal("expected false when no baseline store is set")
	}
}

func TestIsActionable_AnomalyBypass(t *testing.T) {
	// Set up a baseline store with learned baselines.
	// CPU at 45% is below the 50% default threshold, but is anomalous
	// relative to a baseline of mean=20, stddev=5 (z-score = 5).
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{} // defaults: CPU watch = 0 → fallback 50%

	bsCfg := DefaultBaselineConfig()
	bsCfg.MinSamples = 5 // Lower for test
	bs := NewBaselineStore(bsCfg)

	// Learn a baseline: mean ~20%, stddev ~2.5%
	points := make([]BaselineMetricPoint, 50)
	for i := 0; i < 50; i++ {
		points[i] = BaselineMetricPoint{Value: 18.0 + float64(i%5), Timestamp: time.Now().Add(-time.Duration(i) * time.Hour)}
	}
	_ = bs.Learn("node-1", "node", "cpu", points)
	ps.baselineStore = bs

	state := models.StateSnapshot{
		Nodes: []models.Node{
			{ID: "node-1", Name: "node-1", CPU: 0.45, Memory: models.Memory{Usage: 30}},
		},
	}
	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, state))

	finding := &Finding{
		Key:        "cpu-high",
		Severity:   FindingSeverityWarning,
		Category:   FindingCategoryPerformance,
		ResourceID: "node-1",
		Title:      "High CPU usage",
	}

	// CPU at 45% is below 50% threshold BUT is anomalous (z-score ~5+)
	if !adapter.isActionable(finding) {
		t.Fatal("finding below threshold but anomalous should be allowed through")
	}
}

func TestIsActionable_BelowThresholdNoAnomaly(t *testing.T) {
	// CPU at 45% below 50% threshold, baseline mean is also ~45% → not anomalous → rejected.
	ps := NewPatrolService(nil, nil)
	ps.thresholds = PatrolThresholds{} // defaults

	bsCfg := DefaultBaselineConfig()
	bsCfg.MinSamples = 5
	bs := NewBaselineStore(bsCfg)

	// Learn a baseline: mean ~45%, close to current value
	points := make([]BaselineMetricPoint, 50)
	for i := 0; i < 50; i++ {
		points[i] = BaselineMetricPoint{Value: 43.0 + float64(i%5), Timestamp: time.Now().Add(-time.Duration(i) * time.Hour)}
	}
	_ = bs.Learn("node-1", "node", "cpu", points)
	ps.baselineStore = bs

	state := models.StateSnapshot{
		Nodes: []models.Node{
			{ID: "node-1", Name: "node-1", CPU: 0.45, Memory: models.Memory{Usage: 30}},
		},
	}
	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, state))

	finding := &Finding{
		Key:        "cpu-high",
		Severity:   FindingSeverityWarning,
		Category:   FindingCategoryPerformance,
		ResourceID: "node-1",
		Title:      "High CPU usage",
	}

	if adapter.isActionable(finding) {
		t.Fatal("finding below threshold with no anomaly should be rejected")
	}
}

func TestIsActionable_EscapeHatchesPreserved(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	state := models.StateSnapshot{
		Nodes: []models.Node{
			{ID: "node-1", Name: "node-1", CPU: 0.10, Memory: models.Memory{Usage: 10}},
		},
	}
	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, state))

	// Critical severity always passes
	critical := &Finding{
		Key:        "cpu-high",
		Severity:   FindingSeverityCritical,
		Category:   FindingCategoryPerformance,
		ResourceID: "node-1",
		Title:      "Critical CPU",
	}
	if !adapter.isActionable(critical) {
		t.Fatal("critical finding should always pass")
	}

	// Backup category always passes
	backup := &Finding{
		Key:        "backup-missing",
		Severity:   FindingSeverityWarning,
		Category:   FindingCategoryBackup,
		ResourceID: "node-1",
		Title:      "Missing backup",
	}
	if !adapter.isActionable(backup) {
		t.Fatal("backup finding should always pass")
	}

	// Reliability category always passes
	reliability := &Finding{
		Key:        "node-offline",
		Severity:   FindingSeverityWarning,
		Category:   FindingCategoryReliability,
		ResourceID: "node-1",
		Title:      "Node offline",
	}
	if !adapter.isActionable(reliability) {
		t.Fatal("reliability finding should always pass")
	}
}

func TestPatrolService_RecordFindingDoesNotGenerateTemplateRemediationPlan(t *testing.T) {
	engine := newTestRemediationEngine()
	ps := NewPatrolService(nil, nil)
	ps.SetRemediationEngine(engine)

	finding := &Finding{
		ID:             "finding-1",
		Key:            "service-restart",
		Severity:       FindingSeverityWarning,
		Category:       FindingCategoryReliability,
		ResourceID:     "vm-101",
		ResourceName:   "web",
		ResourceType:   "vm",
		Title:          "Unexpected restart detected",
		Description:    "Service restarted unexpectedly",
		Recommendation: "Investigate restart cause",
	}

	if !ps.recordFinding(finding) {
		t.Fatal("expected finding to be recorded as new")
	}

	plan := engine.GetPlanForFinding(finding.ID)
	if plan != nil {
		t.Fatalf("unexpected Pulse-authored remediation plan generated: %+v", plan)
	}
}

func TestPatrolFindingCreatorAdapter_ResolveFindingAndChecks(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	finding := &Finding{
		ID:           "resolve-1",
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "node-1",
		ResourceName: "node-1",
		ResourceType: "node",
		Title:        "High CPU",
	}
	ps.findings.Add(finding)

	var resolvedID string
	ps.unifiedFindingResolver = func(id string) {
		resolvedID = id
	}

	adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, models.StateSnapshot{}))
	if err := adapter.ResolveFinding(finding.ID, "resolved in test"); err != nil {
		t.Fatalf("ResolveFinding failed: %v", err)
	}
	if resolvedID != finding.ID {
		t.Fatalf("expected unified resolver to be called with %s, got %s", finding.ID, resolvedID)
	}
	if len(adapter.getResolvedIDs()) != 1 {
		t.Fatalf("expected resolved IDs to be tracked")
	}

	if adapter.HasCheckedFindings() {
		t.Fatal("expected HasCheckedFindings to be false before GetActiveFindings")
	}
	_ = adapter.GetActiveFindings("", "warning")
	if !adapter.HasCheckedFindings() {
		t.Fatal("expected HasCheckedFindings to be true after GetActiveFindings")
	}
	if adapter.HasCompleteFindingSnapshot() {
		t.Fatal("expected severity-filtered finding read not to count as a complete snapshot")
	}
	_ = adapter.GetActiveFindings("", "")
	if !adapter.HasCompleteFindingSnapshot() {
		t.Fatal("expected unfiltered finding read to establish the complete snapshot")
	}

	adapter = newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, models.StateSnapshot{}))
	_ = adapter.establishCoreFindingSnapshot()
	if !adapter.HasCheckedFindings() || !adapter.HasCompleteFindingSnapshot() {
		t.Fatal("expected core-owned finding load to establish the complete lifecycle snapshot")
	}
}

func TestPatrolFindingCreatorAdapter_GetActiveFindings_UsesScopedRuntimeState(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	inScope := &Finding{
		ID:           "scope-in",
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "app-1",
		ResourceName: "web",
		ResourceType: "app-container",
		Title:        "Scoped app finding",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	outOfScope := &Finding{
		ID:           "scope-out",
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "app-2",
		ResourceName: "db",
		ResourceType: "app-container",
		Title:        "Global app finding",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	ps.findings.Add(inScope)
	ps.findings.Add(outOfScope)

	state := newPatrolRuntimeState(models.StateSnapshot{
		DockerHosts: []models.DockerHost{
			{
				ID: "docker-host-1",
				Containers: []models.DockerContainer{
					{ID: "app-1", Name: "web"},
				},
			},
		},
	})

	adapter := newPatrolFindingCreatorAdapterState(ps, state)
	active := adapter.GetActiveFindings("", "warning")
	if len(active) != 1 {
		t.Fatalf("expected 1 scoped active finding, got %+v", active)
	}
	if active[0].ID != inScope.ID {
		t.Fatalf("expected in-scope finding %s, got %+v", inScope.ID, active)
	}
}

func TestPatrolFindingCreatorAdapter_ResolveFinding_RejectsOutOfScopeFinding(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	inScope := &Finding{
		ID:           "scope-in",
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "app-1",
		ResourceName: "web",
		ResourceType: "app-container",
		Title:        "Scoped app finding",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	outOfScope := &Finding{
		ID:           "scope-out",
		Key:          "cpu-high",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "app-2",
		ResourceName: "db",
		ResourceType: "app-container",
		Title:        "Global app finding",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	ps.findings.Add(inScope)
	ps.findings.Add(outOfScope)

	state := newPatrolRuntimeState(models.StateSnapshot{
		DockerHosts: []models.DockerHost{
			{
				ID: "docker-host-1",
				Containers: []models.DockerContainer{
					{ID: "app-1", Name: "web"},
				},
			},
		},
	})

	adapter := newPatrolFindingCreatorAdapterState(ps, state)
	if err := adapter.ResolveFinding(outOfScope.ID, "resolved in test"); err == nil {
		t.Fatal("expected out-of-scope resolve to fail")
	}
	stored := ps.findings.Get(outOfScope.ID)
	if stored == nil || stored.ResolvedAt != nil {
		t.Fatalf("expected out-of-scope finding to remain unresolved, got %+v", stored)
	}
	if err := adapter.ResolveFinding(inScope.ID, "resolved in test"); err != nil {
		t.Fatalf("expected in-scope resolve to succeed, got %v", err)
	}
}

func TestPatrolFindingCreatorAdapter_ResolveFinding_RejectsContradictoryContainerHealth(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	finding := &Finding{
		ID:           "container-health-active",
		Key:          "health-check-failed",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryReliability,
		ResourceID:   "app-1",
		ResourceName: "web",
		ResourceType: "app-container",
		Title:        "Container health check is failing",
		Description:  "The provider health check is unhealthy",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	ps.findings.Add(finding)

	unhealthy := newPatrolRuntimeState(models.StateSnapshot{
		DockerHosts: []models.DockerHost{{
			ID: "docker-host-1",
			Containers: []models.DockerContainer{{
				ID: "app-1", Name: "web", State: "running", Health: "unhealthy",
			}},
		}},
	})
	adapter := newPatrolFindingCreatorAdapterState(ps, unhealthy)
	err := adapter.ResolveFinding(finding.ID, "model claimed the issue cleared")
	if err == nil || !strings.Contains(err.Error(), "still reports container health unhealthy") {
		t.Fatalf("contradictory resolution error = %v", err)
	}
	if stored := ps.findings.Get(finding.ID); stored == nil || stored.IsResolved() {
		t.Fatalf("contradictory provider state must keep finding active: %+v", stored)
	}

	healthy := newPatrolRuntimeState(models.StateSnapshot{
		DockerHosts: []models.DockerHost{{
			ID: "docker-host-1",
			Containers: []models.DockerContainer{{
				ID: "app-1", Name: "web", State: "running", Health: "healthy",
			}},
		}},
	})
	adapter = newPatrolFindingCreatorAdapterState(ps, healthy)
	if err := adapter.ResolveFinding(finding.ID, "provider health is now healthy"); err != nil {
		t.Fatalf("healthy provider state should permit lifecycle resolution: %v", err)
	}
	if stored := ps.findings.Get(finding.ID); stored == nil || !stored.IsResolved() {
		t.Fatalf("healthy provider state did not resolve finding: %+v", stored)
	}
}

func TestPatrolService_GetAllFindingsIncludingResolved_IncludesResolvedAndDismissedSortsActiveFirst(t *testing.T) {
	// GetAllFindingsIncludingResolved is the audit-trail accessor used by the
	// Patrol UI's Resolved tab. Until it landed, the trust strip credited
	// "N auto-resolved" but the operator could not click through to see
	// what those N findings actually were — the /api/ai/patrol/findings
	// endpoint only returned active findings. This test locks in:
	//   - resolved + dismissed findings are returned (not just active)
	//   - the warning-severity floor still applies (watch/info filtered)
	//   - active findings sort before resolved within the result
	ps := NewPatrolService(nil, nil)
	now := time.Now()
	older := now.Add(-2 * time.Hour)
	pastResolved := now.Add(-time.Hour)

	active := &Finding{
		ID:           "active-warn",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryReliability,
		ResourceID:   "vm-1",
		ResourceName: "web",
		Title:        "Active warning",
		DetectedAt:   older,
		LastSeenAt:   now,
	}
	resolved := &Finding{
		ID:           "resolved-warn",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryBackup,
		ResourceID:   "vm-2",
		ResourceName: "db",
		Title:        "Resolved backup failure",
		DetectedAt:   older,
		LastSeenAt:   older,
		ResolvedAt:   &pastResolved,
		AutoResolved: true,
	}
	dismissed := &Finding{
		ID:              "dismissed-warn",
		Severity:        FindingSeverityWarning,
		Category:        FindingCategoryGeneral,
		ResourceID:      "vm-3",
		ResourceName:    "cache",
		Title:           "Dismissed as expected",
		DetectedAt:      older,
		LastSeenAt:      older,
		DismissedReason: "expected_behavior",
	}
	belowSeverity := &Finding{
		ID:           "watch-noise",
		Severity:     FindingSeverityWatch,
		Category:     FindingCategoryPerformance,
		ResourceID:   "vm-4",
		ResourceName: "noise",
		Title:        "Below warning floor",
		DetectedAt:   older,
		LastSeenAt:   now,
	}

	ps.findings.Add(active)
	ps.findings.Add(resolved)
	ps.findings.Add(dismissed)
	ps.findings.Add(belowSeverity)

	got := ps.GetAllFindingsIncludingResolved()
	gotIDs := make([]string, 0, len(got))
	for _, f := range got {
		gotIDs = append(gotIDs, f.ID)
	}

	// Active-warn must be first (active before resolved/dismissed).
	if len(got) == 0 || got[0].ID != "active-warn" {
		t.Fatalf("expected active finding first, got order %v", gotIDs)
	}
	// Resolved and dismissed warnings must be present.
	resolvedSeen := false
	dismissedSeen := false
	for _, f := range got {
		if f.ID == "resolved-warn" {
			resolvedSeen = true
		}
		if f.ID == "dismissed-warn" {
			dismissedSeen = true
		}
		if f.ID == "watch-noise" {
			t.Errorf("watch-severity finding leaked through warning floor: %v", gotIDs)
		}
	}
	if !resolvedSeen {
		t.Errorf("expected resolved finding in result, got %v", gotIDs)
	}
	if !dismissedSeen {
		t.Errorf("expected dismissed finding in result, got %v", gotIDs)
	}
}

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

	// Keys with deterministic verifiers (mirrors the FULL dispatch switch in
	// verifyFixDeterministically — hasDeterministicVerifierForKey is the
	// single source of truth for both the LLM-resolve gate and the verified
	// stale-finding reconcile pass; it previously listed only the two
	// tool-based keys and silently skipped verification that existed for
	// the state-only verifiers). Alias keys normalize onto canonical keys.
	for _, key := range []string{
		"backup-stale", "cpu-high", "memory-high", "disk-high",
		"guest-unreachable", "smart-failure", "backup-failed",
		"high-cpu", "high-memory", "high-disk",
	} {
		if !ps.hasDeterministicVerifierForKey(key) {
			t.Errorf("hasDeterministicVerifierForKey(%q) = false, want true", key)
		}
	}
	for _, key := range []string{"", "unknown-key", "node-offline", "service-restart", "pbs-job-failed", "restart-loop"} {
		if ps.hasDeterministicVerifierForKey(key) {
			t.Errorf("hasDeterministicVerifierForKey(%q) = true, want false", key)
		}
	}
}

func TestPatrolFindingCreatorAdapter_ResolveFinding_SkipsVerifierForCategoriesThatSupportStaleAutoResolve(t *testing.T) {
	// Performance category supports stale-auto-resolve by contract, so
	// the LLM can resolve it freely. The new gate must not engage for
	// these categories — even if a deterministic verifier existed for
	// the key, the contract permits resolve on absence.
	ps := NewPatrolService(nil, nil)
	finding := &Finding{
		ID:           "perf-1",
		Key:          "cpu-high", // no deterministic verifier anyway
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryPerformance,
		ResourceID:   "node-1",
		ResourceName: "pve-1",
		ResourceType: "node",
		Title:        "CPU sustained high",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	ps.findings.Add(finding)

	adapter := newPatrolFindingCreatorAdapterState(ps, newPatrolRuntimeState(models.StateSnapshot{}))
	if err := adapter.ResolveFinding(finding.ID, "no longer hot"); err != nil {
		t.Fatalf("expected resolve to succeed for performance category, got %v", err)
	}
	if stored := ps.findings.Get(finding.ID); stored == nil || stored.ResolvedAt == nil {
		t.Fatalf("expected finding to be resolved, got %+v", stored)
	}
}

func TestPatrolFindingCreatorAdapter_ResolveFinding_RejectsWhenVerifierIsInconclusive(t *testing.T) {
	// For event/persistent categories with a registered deterministic
	// verifier (backup-failed in this case), an inconclusive verifier
	// outcome must reject the LLM's resolve attempt. Earlier behaviour
	// was "fail open — allow resolve and warn" which let the
	// auto_resolved → re-detected cycle continue any time the verifier
	// errored. Resolution of an event finding is effectively permanent
	// (next detection registers as a regression and inflates counters),
	// so the safe default is to refuse and ask the operator or a
	// re-run to confirm.
	//
	// We trigger the inconclusive path by calling VerifyFixResolved on
	// a service that doesn't have a chat service / executor wired up,
	// which causes getExecutorForVerification to return an
	// ErrVerificationUnknown error — exactly the "fail-closed" code
	// path the gate now defends.
	ps := NewPatrolService(nil, nil)
	finding := &Finding{
		ID:           "backup-1",
		Key:          "backup-failed",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryBackup,
		ResourceID:   "vm-100",
		ResourceName: "delly",
		ResourceType: "backup",
		Title:        "Backup failed",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	ps.findings.Add(finding)

	adapter := newPatrolFindingCreatorAdapterState(ps, newPatrolRuntimeState(models.StateSnapshot{}))
	err := adapter.ResolveFinding(finding.ID, "no backup failures in current investigation")
	if err == nil {
		t.Fatal("expected resolve to fail when deterministic verifier is inconclusive; got nil error (fail-open regression)")
	}
	if !strings.Contains(err.Error(), "inconclusive") {
		t.Errorf("expected error to mention 'inconclusive', got: %v", err)
	}
	if stored := ps.findings.Get(finding.ID); stored == nil {
		t.Fatal("expected finding to remain in store")
	} else if stored.ResolvedAt != nil {
		t.Fatalf("expected finding to remain unresolved on inconclusive verification, got ResolvedAt=%v", stored.ResolvedAt)
	}
}

func TestPatrolFindingCreatorAdapter_ResolveFinding_FallsThroughWhenNoVerifierAvailable(t *testing.T) {
	// Reliability category does NOT support stale-auto-resolve, but
	// "node-offline" has no deterministic verifier. The gate must fall
	// through to current trust-the-LLM behavior rather than blocking
	// resolves for every event/persistent category we haven't built a
	// verifier for yet.
	ps := NewPatrolService(nil, nil)
	finding := &Finding{
		ID:           "rel-1",
		Key:          "node-offline",
		Severity:     FindingSeverityWarning,
		Category:     FindingCategoryReliability,
		ResourceID:   "node-1",
		ResourceName: "pve-1",
		ResourceType: "node",
		Title:        "Node offline",
		DetectedAt:   time.Now().Add(-time.Hour),
		LastSeenAt:   time.Now().Add(-time.Hour),
	}
	ps.findings.Add(finding)

	adapter := newPatrolFindingCreatorAdapterState(ps, newPatrolRuntimeState(models.StateSnapshot{}))
	if err := adapter.ResolveFinding(finding.ID, "node is back online"); err != nil {
		t.Fatalf("expected resolve to succeed when no verifier is registered, got %v", err)
	}
	if stored := ps.findings.Get(finding.ID); stored == nil || stored.ResolvedAt == nil {
		t.Fatalf("expected finding to be resolved, got %+v", stored)
	}
}

// TestGenerateRemediationPlanFromInvestigationIsDeleted pins the sixth
// side door closed: the path that copied Fix.Commands into an executable
// enterprise remediation plan must not return. Typed remediation flows
// only through the action proposal channel.
func TestGenerateRemediationPlanFromInvestigationIsDeleted(t *testing.T) {
	source, err := os.ReadFile("patrol_findings.go")
	if err != nil {
		t.Fatalf("read patrol_findings.go: %v", err)
	}
	src := string(source)
	for _, forbidden := range []string{
		"generateRemediationPlanFromInvestigation",
		"inv.ProposedFix.Commands",
	} {
		if strings.Contains(src, forbidden) {
			t.Fatalf("command-backed remediation path must stay deleted; found %q", forbidden)
		}
	}
}

func TestPatrolFindingAssessmentLifecycle(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		VMs: []models.VM{{ID: "vm-401", Name: "web", VMID: 401}},
	})
	ps := NewPatrolService(nil, nil)
	makeFinding := func(id, key string) *Finding {
		return &Finding{
			ID: id, Key: key, Severity: FindingSeverityWarning,
			Category: FindingCategoryReliability, ResourceID: "vm-401",
			ResourceName: "web", ResourceType: "vm", Title: "Service issue " + id,
			Description: "service is unhealthy: " + key, Evidence: "old evidence",
		}
	}
	present := makeFinding("assessment-present", "service-unhealthy")
	uncertain := makeFinding("assessment-uncertain", "dependency-unknown")
	resolved := makeFinding("assessment-resolved", "configuration-gap")
	ps.findings.Add(present)
	ps.findings.Add(uncertain)
	ps.findings.Add(resolved)
	presentBefore := ps.findings.Get(present.ID)
	uncertainBefore := ps.findings.Get(uncertain.ID)

	adapter := newPatrolFindingCreatorAdapterState(ps, state)
	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: present.ID, Verdict: "present", Evidence: "health probe still fails", Reason: "current probe reconfirms the issue",
	}); err != nil {
		t.Fatalf("assess present: %v", err)
	}
	presentAfter := ps.findings.Get(present.ID)
	if presentAfter.TimesRaised != presentBefore.TimesRaised+1 || presentAfter.Evidence != "health probe still fails" {
		t.Fatalf("present assessment did not refresh finding: before=%+v after=%+v", presentBefore, presentAfter)
	}

	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: uncertain.ID, Verdict: "uncertain", Evidence: "dependency endpoint timed out", Reason: "no affirmative health result",
	}); err != nil {
		t.Fatalf("assess uncertain: %v", err)
	}
	uncertainAfter := ps.findings.Get(uncertain.ID)
	if uncertainAfter.TimesRaised != uncertainBefore.TimesRaised || uncertainAfter.IsResolved() {
		t.Fatalf("uncertain assessment must keep finding unchanged and active: before=%+v after=%+v", uncertainBefore, uncertainAfter)
	}

	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: resolved.ID, Verdict: "resolved", Evidence: "configuration now matches policy", Reason: "current configuration is compliant",
	}); err != nil {
		t.Fatalf("assess resolved: %v", err)
	}
	if got := ps.findings.Get(resolved.ID); got == nil || !got.IsResolved() {
		t.Fatalf("resolved assessment did not close finding: %+v", got)
	}

	assessments := adapter.getAssessments()
	if len(assessments) != 3 {
		t.Fatalf("assessment count = %d, want 3", len(assessments))
	}
	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: present.ID, Verdict: "present", Evidence: "duplicate", Reason: "duplicate",
	}); err == nil {
		t.Fatal("expected duplicate terminal assessment to be rejected")
	}
}

func TestPatrolFindingAssessmentTolerantIDResolution(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		VMs: []models.VM{{ID: "vm-402", Name: "web2", VMID: 402}},
	})
	ps := NewPatrolService(nil, nil)
	longID := "update-analysis-docker:2d51085a-447a-4f4d-9245-b0858467d0ea/503c70797abd93f0a209e10e499eb20f93f604cb87762aa262d521caf054b14a"
	finding := &Finding{
		ID: longID, Key: "docker-update", Severity: FindingSeverityWarning,
		Category: FindingCategoryReliability, ResourceID: "vm-402",
		ResourceName: "web2", ResourceType: "vm", Title: "Docker update pending",
		Description: "update analysis", Evidence: "old evidence",
	}
	ps.findings.Add(finding)
	adapter := newPatrolFindingCreatorAdapterState(ps, state)

	// The dominant weak-model failure: the key prefix is dropped.
	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: "2d51085a-447a-4f4d-9245-b0858467d0ea/503c70797abd93f0a209e10e499eb20f93f604cb87762aa262d521caf054b14a",
		Verdict:   "present", Evidence: "still pending", Reason: "reconfirmed",
	}); err != nil {
		t.Fatalf("prefix-stripped ID should resolve to the active finding: %v", err)
	}
	assessments := adapter.getAssessments()
	if len(assessments) != 1 || assessments[0].FindingID != longID {
		t.Fatalf("assessment must record the canonical finding ID, got %+v", assessments)
	}

	// A retry with another mangled variant of the same ID must hit the
	// duplicate-verdict guard, not create a second assessment.
	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: "update-analysis-docker:2d51085a-447a-4f4d-9245-b0858467d0ea",
		Verdict:   "present", Evidence: "dup", Reason: "dup",
	}); err == nil {
		t.Fatal("expected duplicate assessment via mangled variant to be rejected")
	}
}

func TestPatrolFindingAssessmentUnknownIDListsActiveIDs(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		VMs: []models.VM{{ID: "vm-403", Name: "web3", VMID: 403}},
	})
	ps := NewPatrolService(nil, nil)
	finding := &Finding{
		ID: "reliability:vm-403:service-down", Key: "service-down", Severity: FindingSeverityWarning,
		Category: FindingCategoryReliability, ResourceID: "vm-403",
		ResourceName: "web3", ResourceType: "vm", Title: "Service down",
		Description: "down", Evidence: "probe",
	}
	ps.findings.Add(finding)
	adapter := newPatrolFindingCreatorAdapterState(ps, state)

	err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: "a1b2c3d4-e5f6-7890-1234-567890abcdef",
		Verdict:   "present", Evidence: "e", Reason: "r",
	})
	if err == nil {
		t.Fatal("hallucinated ID must not resolve")
	}
	if !strings.Contains(err.Error(), "reliability:vm-403:service-down") {
		t.Fatalf("error must list the valid active finding ids, got %v", err)
	}
}

func TestPatrolFindingAssessmentAmbiguousFragmentDoesNotResolve(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		VMs: []models.VM{{ID: "vm-404", Name: "web4", VMID: 404}},
	})
	ps := NewPatrolService(nil, nil)
	for _, id := range []string{"update-analysis-docker:aaaa-shared-prefix-1", "update-analysis-docker:aaaa-shared-prefix-2"} {
		ps.findings.Add(&Finding{
			ID: id, Key: id, Severity: FindingSeverityWarning,
			Category: FindingCategoryReliability, ResourceID: "vm-404",
			ResourceName: "web4", ResourceType: "vm", Title: id,
			Description: "d", Evidence: "e",
		})
	}
	adapter := newPatrolFindingCreatorAdapterState(ps, state)

	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: "update-analysis-docker:aaaa-shared-prefix",
		Verdict:   "present", Evidence: "e", Reason: "r",
	}); err == nil {
		t.Fatal("ambiguous fragment matching two findings must not resolve")
	}
}

func TestPatrolFindingAdapterSeparatesRequestedLifecycleScopeFromEvidenceScope(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		VMs: []models.VM{
			{ID: "vm-requested", Name: "requested", VMID: 501},
			{ID: "vm-context", Name: "context-only", VMID: 502},
		},
	})
	ps := NewPatrolService(nil, nil)
	for _, finding := range []*Finding{
		{ID: "requested-finding", Key: "service-unhealthy", Severity: FindingSeverityWarning, Category: FindingCategoryReliability, ResourceID: "vm-requested", ResourceName: "requested", ResourceType: "vm", Title: "Requested workload unhealthy"},
		{ID: "context-finding", Key: "updates-pending", Severity: FindingSeverityWarning, Category: FindingCategoryReliability, ResourceID: "vm-context", ResourceName: "context-only", ResourceType: "vm", Title: "Context host updates pending"},
	} {
		ps.findings.Add(finding)
	}

	adapter := newPatrolFindingCreatorAdapterState(ps, state)
	adapter.setFindingScope([]string{"vm-requested"})
	active := adapter.GetActiveFindings("", "")
	if len(active) != 1 || active[0].ID != "requested-finding" {
		t.Fatalf("active findings = %+v, want only requested-finding", active)
	}

	if _, _, err := adapter.CreateFinding(tools.PatrolFindingInput{
		ResourceID: "vm-context", ResourceName: "context-only", ResourceType: "vm",
		Key: "context-new", Severity: "warning", Category: "reliability", Title: "Context-only issue",
		Description: "context-only evidence", Evidence: "context-only evidence", Recommendation: "review context-only issue",
	}); err == nil || !strings.Contains(err.Error(), "outside the requested patrol finding scope") {
		t.Fatalf("context-only finding must be rejected by lifecycle scope, got %v", err)
	}
}

func TestPatrolFindingAdapterRepairsOnlyUnknownIDsFromUniqueScopedIdentity(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		Nodes: []models.Node{
			{ID: "node-requested", Name: "requested", Status: "online"},
			{ID: "node-context", Name: "context-only", Status: "online"},
		},
	})
	adapter := newPatrolFindingCreatorAdapterState(NewPatrolService(nil, nil), state)
	adapter.setFindingScope([]string{"node-requested"})

	input := tools.PatrolFindingInput{
		ResourceID: "node-reques7ed", ResourceName: "requested", ResourceType: "node",
	}
	repaired, ok := adapter.canonicalizeUnknownFindingResource(input)
	if !ok || repaired.ResourceID != "node-requested" {
		t.Fatalf("unknown transcription error repair = (%+v, %t), want canonical node-requested", repaired, ok)
	}

	input.ResourceID = "node-context"
	if got, ok := adapter.canonicalizeUnknownFindingResource(input); ok || got.ResourceID != "node-context" {
		t.Fatalf("real out-of-scope ID must not be redirected by a scoped name: (%+v, %t)", got, ok)
	}

	input.ResourceID = "node-reques7ed"
	input.ResourceType = "vm"
	if _, ok := adapter.canonicalizeUnknownFindingResource(input); ok {
		t.Fatal("resource type mismatch must not be repaired")
	}

	ambiguousState := newPatrolRuntimeState(models.StateSnapshot{
		Nodes: []models.Node{
			{ID: "node-a", Name: "duplicate", Status: "online"},
			{ID: "node-b", Name: "duplicate", Status: "online"},
		},
	})
	ambiguous := newPatrolFindingCreatorAdapterState(NewPatrolService(nil, nil), ambiguousState)
	ambiguous.setFindingScope([]string{"node-a"})
	if _, ok := ambiguous.canonicalizeUnknownFindingResource(tools.PatrolFindingInput{
		ResourceID: "node-typo", ResourceName: "duplicate", ResourceType: "node",
	}); ok {
		t.Fatal("ambiguous exact names must not be repaired even when only one record is in scope")
	}
}

func TestPatrolFindingAdapterRejectsKnownSiblingIDAndNameMismatch(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		DockerHosts: []models.DockerHost{{
			ID: "docker-host-1",
			Containers: []models.DockerContainer{
				{ID: "app-container-healthy", Name: "control", State: "running", Health: "healthy"},
				{ID: "app-container-unhealthy", Name: "existing", State: "running", Health: "unhealthy"},
			},
		}},
	})
	ps := NewPatrolService(nil, nil)
	adapter := newPatrolFindingCreatorAdapterState(ps, state)
	adapter.setFindingScope([]string{"app-container-healthy", "app-container-unhealthy"})

	input := tools.PatrolFindingInput{
		ResourceID: "app-container-healthy", ResourceName: "existing", ResourceType: "app-container",
		Key: "health-check-failed", Severity: "warning", Category: "reliability",
		Title: "Container health check is unhealthy", Description: "The existing container is unhealthy.",
		Impact: "Requests may fail.", Recommendation: "Inspect the health check.",
		Evidence: "Current provider health for existing is unhealthy.",
	}
	if _, isNew, err := adapter.CreateFinding(input); err == nil || isNew || !strings.Contains(err.Error(), "resource identity mismatch") {
		t.Fatalf("mismatched sibling report = (%t, %v), want identity validation error", isNew, err)
	}
	if active := ps.findings.GetActive(FindingSeverityInfo); len(active) != 0 {
		t.Fatalf("mismatched sibling report persisted findings: %+v", active)
	}

	input.ResourceID = "app-container-unhealthy"
	if findingID, isNew, err := adapter.CreateFinding(input); err != nil || !isNew || findingID == "" {
		t.Fatalf("coherent canonical report = (%q, %t, %v), want new finding", findingID, isNew, err)
	}
}

func TestPatrolFindingAdapterCanAssessSeededRuntimeFindingDuringScopedRun(t *testing.T) {
	state := newPatrolRuntimeState(models.StateSnapshot{
		VMs: []models.VM{{ID: "vm-requested", Name: "requested", VMID: 501}},
	})
	ps := NewPatrolService(nil, nil)
	runtimeFinding := &Finding{
		ID: patrolRuntimeFindingKey, Key: patrolRuntimeFindingKey,
		Severity: FindingSeverityWarning, Category: FindingCategoryReliability,
		ResourceID: patrolRuntimeResourceID, ResourceName: "Pulse Patrol Service",
		ResourceType: "service", Title: "Pulse Patrol provider interrupted",
	}
	ps.findings.Add(runtimeFinding)

	adapter := newPatrolFindingCreatorAdapterState(ps, state)
	adapter.setFindingScope([]string{"vm-requested"})
	active := adapter.GetActiveFindings("", "")
	if len(active) != 1 || active[0].ID != runtimeFinding.ID {
		t.Fatalf("active findings = %+v, want seeded Patrol runtime finding", active)
	}
	if err := adapter.AssessFinding(tools.PatrolFindingAssessmentInput{
		FindingID: runtimeFinding.ID, Verdict: "uncertain",
		Evidence: "the prior provider interruption is not infrastructure evidence",
		Reason:   "the current scoped run has not completed yet",
	}); err != nil {
		t.Fatalf("assess seeded runtime finding in scoped run: %v", err)
	}
	assessments := adapter.getAssessments()
	if len(assessments) != 1 || assessments[0].FindingID != runtimeFinding.ID || assessments[0].Verdict != "uncertain" {
		t.Fatalf("runtime finding assessments = %+v", assessments)
	}
}

func TestPatrolFindingAdapterDistinguishesSameRunCreationFromExistingRereport(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	input := tools.PatrolFindingInput{
		ResourceID: "camera-1", ResourceName: "Camera 1", ResourceType: "host",
		Key: "camera-offline", Severity: "warning", Category: "reliability",
		Title: "Camera is unavailable", Description: "The camera is offline.",
		Impact: "Recording is unavailable.", Recommendation: "Restore availability.",
		Evidence: "Current status is offline.",
	}

	firstRun := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeState{})
	if active := firstRun.GetActiveFindings("", ""); len(active) != 0 {
		t.Fatalf("initial active findings = %+v, want none", active)
	}
	findingID, isNew, err := firstRun.CreateFinding(input)
	if err != nil || !isNew {
		t.Fatalf("first report = (%q, %t, %v), want a new finding", findingID, isNew, err)
	}
	beforeDuplicate := ps.findings.Get(findingID)
	duplicateID, duplicateIsNew, duplicateErr := firstRun.CreateFinding(input)
	var alreadyReported *tools.PatrolFindingAlreadyReportedError
	if !errors.As(duplicateErr, &alreadyReported) || alreadyReported.FindingID != findingID || duplicateID != findingID || !duplicateIsNew {
		t.Fatalf("same-run duplicate report = (%q, %t, %v), want typed already-reported outcome for %q", duplicateID, duplicateIsNew, duplicateErr, findingID)
	}
	afterDuplicate := ps.findings.Get(findingID)
	if beforeDuplicate == nil || afterDuplicate == nil || afterDuplicate.TimesRaised != beforeDuplicate.TimesRaised || !afterDuplicate.LastSeenAt.Equal(beforeDuplicate.LastSeenAt) {
		t.Fatalf("same-run duplicate mutated finding: before=%+v after=%+v", beforeDuplicate, afterDuplicate)
	}
	// This models a findings read racing with or following the accepted report.
	// The new finding may be returned, but it is not an existing-finding verdict
	// candidate in the run that created it.
	firstRun.GetActiveFindings("", "")
	firstResult := &AIAnalysisResult{
		ReportedIDs:       firstRun.getReportedFindingIDs(),
		NewFindingIDs:     firstRun.getNewFindingIDs(),
		QueriedFindingIDs: firstRun.getQueriedFindingIDs(),
	}
	if missing := patrolMissingAssessmentIDs(firstResult); len(missing) != 0 {
		t.Fatalf("same-run new finding unexpectedly needs assessment: %v", missing)
	}
	beforeNoOp := ps.findings.Get(findingID)
	for _, verdict := range []string{"present", "uncertain", "resolved"} {
		err := firstRun.AssessFinding(tools.PatrolFindingAssessmentInput{
			FindingID: findingID, Verdict: verdict, Evidence: "same-run evidence", Reason: "same-run report is authoritative",
		})
		var alreadyDecided *tools.PatrolFindingAlreadyDecidedError
		if !errors.As(err, &alreadyDecided) || alreadyDecided.FindingID != findingID {
			t.Fatalf("same-run %s assessment error = %v, want typed already-decided outcome", verdict, err)
		}
	}
	afterNoOp := ps.findings.Get(findingID)
	if len(firstRun.getAssessments()) != 0 || afterNoOp == nil || !afterNoOp.IsActive() || afterNoOp.TimesRaised != beforeNoOp.TimesRaised {
		t.Fatalf("same-run assessment mutated new finding: before=%+v after=%+v assessments=%+v", beforeNoOp, afterNoOp, firstRun.getAssessments())
	}

	secondRun := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeState{})
	secondRun.GetActiveFindings("", "")
	reportedID, isNew, err := secondRun.CreateFinding(input)
	if err != nil || isNew || reportedID != findingID {
		t.Fatalf("second report = (%q, %t, %v), want existing %q", reportedID, isNew, err, findingID)
	}
	secondResult := &AIAnalysisResult{
		ReportedIDs:       secondRun.getReportedFindingIDs(),
		NewFindingIDs:     secondRun.getNewFindingIDs(),
		QueriedFindingIDs: secondRun.getQueriedFindingIDs(),
	}
	missing := patrolMissingAssessmentIDs(secondResult)
	if len(missing) != 1 || missing[0] != findingID {
		t.Fatalf("re-reported existing finding missing assessments = %v, want [%s]", missing, findingID)
	}
}

func TestPatrolFindingAdapterCanonicalizesContainerHealthKeyVariantsAcrossRuns(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	firstInput := tools.PatrolFindingInput{
		ResourceID: "app-container-1", ResourceName: "api", ResourceType: "app-container",
		Key: "health-check-failed", Severity: "warning", Category: "reliability",
		Title: "Container health check is failing", Description: "The container is unhealthy.",
		Impact: "Requests may fail.", Recommendation: "Inspect the health check.",
		Evidence: "Current provider health is unhealthy.",
	}

	firstRun := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeState{})
	findingID, isNew, err := firstRun.CreateFinding(firstInput)
	if err != nil || !isNew {
		t.Fatalf("first report = (%q, %t, %v), want a new finding", findingID, isNew, err)
	}

	for _, variant := range []string{"container-health-failing", "app-container-unhealthy", "app-container-health-check-failed", "container-health-unhealthy", "health-check-unhealthy", "unhealthy-health-check", "docker-health-check-failure"} {
		secondInput := firstInput
		secondInput.Key = variant
		secondInput.Title = "Container health is failing while running"
		secondRun := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeState{})
		secondRun.GetActiveFindings("", "")
		reportedID, secondIsNew, err := secondRun.CreateFinding(secondInput)
		if err != nil || secondIsNew || reportedID != findingID {
			t.Fatalf("variant %q report = (%q, %t, %v), want existing %q", variant, reportedID, secondIsNew, err, findingID)
		}
	}
	if active := ps.findings.GetActive(FindingSeverityInfo); len(active) != 1 || active[0].ID != findingID || active[0].Key != "health-check-failed" {
		t.Fatalf("active findings = %+v, want one canonical health-check finding", active)
	}
}

func TestPatrolFindingAdapterTreatsStoppedContainerStateAsAlertOwned(t *testing.T) {
	ps := NewPatrolService(nil, nil)
	state := newPatrolRuntimeState(models.StateSnapshot{
		DockerHosts: []models.DockerHost{{
			ID: "docker-host-1",
			Containers: []models.DockerContainer{
				{ID: "dependency", Name: "database", State: "exited", Health: "unhealthy"},
				{ID: "client", Name: "jellyfin", State: "running", Health: "unhealthy"},
			},
		}},
	})
	adapter := newPatrolFindingCreatorAdapterState(ps, state)
	adapter.setFindingScope([]string{"dependency", "client"})

	alertOwned := tools.PatrolFindingInput{
		ResourceID: "dependency", ResourceName: "database", ResourceType: "app-container",
		Key: "container-exited-unhealthy", Severity: "warning", Category: "reliability",
		Title: "Container exited with unhealthy status", Description: "The dependency container is exited and not running.",
		Recommendation: "Inspect why it exited.", Evidence: "Current provider state is exited and unhealthy.",
	}
	findingID, isNew, err := adapter.CreateFinding(alertOwned)
	var ownedByAlerts *tools.PatrolFindingOwnedByAlertsError
	if !errors.As(err, &ownedByAlerts) || ownedByAlerts.FindingID != findingID || isNew {
		t.Fatalf("alert-owned report = (%q, %t, %v), want typed no-op", findingID, isNew, err)
	}
	if stored := ps.findings.Get(findingID); stored != nil || len(adapter.getReportedFindingIDs()) != 0 {
		t.Fatalf("alert-owned report was persisted: stored=%+v reported=%v", stored, adapter.getReportedFindingIDs())
	}

	deeperIssue := alertOwned
	deeperIssue.Key = "oom-killed"
	deeperIssue.Title = "Container stopped after an out-of-memory kill"
	deeperIssue.Description = "The runtime recorded a distinct out-of-memory termination."
	deeperIssue.Evidence = "Provider state records OOMKilled=true."
	if _, created, createErr := adapter.CreateFinding(deeperIssue); createErr != nil || !created {
		t.Fatalf("deeper stopped-container issue = (%t, %v), want accepted finding", created, createErr)
	}

	downstream := alertOwned
	downstream.ResourceID = "client"
	downstream.ResourceName = "jellyfin"
	downstream.Key = "playback-health-degraded"
	downstream.Title = "Playback service health check is failing"
	downstream.Description = "The running playback service is unhealthy."
	downstream.Evidence = "Current provider state is running and unhealthy."
	if _, created, createErr := adapter.CreateFinding(downstream); createErr != nil || !created {
		t.Fatalf("distinct downstream degradation = (%t, %v), want accepted finding", created, createErr)
	}
}