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.

54.5 KB
Raw Blame
package api

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
	"github.com/rcourtman/pulse-go-rewrite/internal/ai"
	"github.com/rcourtman/pulse-go-rewrite/internal/ai/learning"
	"github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"
	"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 scopedPatrolStateProvider struct {
	state models.StateSnapshot
}

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

func setupAIHandlerWithPatrol(t *testing.T) (*AISettingsHandler, *ai.PatrolService, *unified.UnifiedStore, *learning.LearningStore) {
	t.Helper()

	tmp := t.TempDir()
	cfg := &config.Config{DataPath: tmp}
	persistence := config.NewConfigPersistence(tmp)
	handler := newTestAISettingsHandler(cfg, persistence, nil)
	handler.defaultAIService.SetStateProvider(&stubStateProvider{})

	patrol := handler.defaultAIService.GetPatrolService()
	if patrol == nil {
		t.Fatalf("expected patrol service to be initialized")
	}

	unifiedStore := unified.NewUnifiedStore(unified.DefaultAlertToFindingConfig())
	handler.SetUnifiedStore(unifiedStore)

	learningStore := learning.NewLearningStore(learning.LearningStoreConfig{})
	handler.SetLearningStore(learningStore)

	return handler, patrol, unifiedStore, learningStore
}

func addPatrolFinding(t *testing.T, patrol *ai.PatrolService, id string, detectedAt time.Time) *ai.Finding {
	t.Helper()
	return addPatrolFindingForResource(t, patrol, id, detectedAt, "vm-1", "CPU spike")
}

func addPatrolFindingForResource(t *testing.T, patrol *ai.PatrolService, id string, detectedAt time.Time, resourceID string, title string) *ai.Finding {
	t.Helper()

	finding := &ai.Finding{
		ID:           id,
		Key:          "key-" + id,
		Severity:     ai.FindingSeverityWarning,
		Category:     ai.FindingCategoryPerformance,
		Title:        title,
		Description:  "CPU high",
		ResourceID:   resourceID,
		ResourceName: resourceID,
		ResourceType: "vm",
		DetectedAt:   detectedAt,
		LastSeenAt:   detectedAt,
	}
	patrol.GetFindings().Add(finding)
	return finding
}

func addUnifiedFinding(store *unified.UnifiedStore, id string, detectedAt time.Time) *unified.UnifiedFinding {
	finding := &unified.UnifiedFinding{
		ID:           id,
		Source:       unified.SourceAIPatrol,
		Severity:     unified.SeverityWarning,
		Category:     unified.CategoryPerformance,
		ResourceID:   "vm-1",
		ResourceName: "vm-1",
		ResourceType: "vm",
		Title:        "CPU spike",
		Description:  "CPU high",
		DetectedAt:   detectedAt,
	}
	store.AddFromAI(finding)
	return finding
}

func addPatrolRuntimeFinding(t *testing.T, patrol *ai.PatrolService, id string, detectedAt time.Time) *ai.Finding {
	t.Helper()

	finding := &ai.Finding{
		ID:           id,
		Key:          "ai-patrol-error",
		Severity:     ai.FindingSeverityWarning,
		Category:     ai.FindingCategoryReliability,
		Title:        "Pulse Patrol: Provider billing or quota issue",
		Description:  "Patrol could not complete because provider billing or quota needs attention",
		ResourceID:   "ai-service",
		ResourceName: "Pulse Patrol Service",
		ResourceType: "service",
		DetectedAt:   detectedAt,
		LastSeenAt:   detectedAt,
	}
	patrol.GetFindings().Add(finding)
	return finding
}

func addUnifiedRuntimeFinding(store *unified.UnifiedStore, id string, detectedAt time.Time) *unified.UnifiedFinding {
	finding := &unified.UnifiedFinding{
		ID:           id,
		Source:       unified.SourceAIPatrol,
		Severity:     unified.SeverityWarning,
		Category:     unified.CategoryReliability,
		ResourceID:   "ai-service",
		ResourceName: "Pulse Patrol Service",
		ResourceType: "service",
		Title:        "Pulse Patrol: Provider billing or quota issue",
		Description:  "Patrol could not complete because provider billing or quota needs attention",
		DetectedAt:   detectedAt,
	}
	store.AddFromAI(finding)
	return finding
}

type agentStableErrorEnvelope = agentcapabilities.ErrorEnvelope

func TestHandleGetPatrolStatus_DistinguishesLastFullPatrolFromLastActivity(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)

	lastPatrolAt := time.Date(2026, 3, 12, 9, 30, 0, 0, time.UTC)
	lastActivityAt := lastPatrolAt.Add(8 * time.Minute)
	setUnexportedField(t, patrol, "lastFullPatrol", lastPatrolAt)
	setUnexportedField(t, patrol, "lastActivity", lastActivityAt)

	req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/status", nil)
	rec := httptest.NewRecorder()

	handler.HandleGetPatrolStatus(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	var resp PatrolStatusResponse
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}

	if resp.LastPatrolAt == nil || !resp.LastPatrolAt.Equal(lastPatrolAt) {
		t.Fatalf("last_patrol_at = %v, want %v", resp.LastPatrolAt, lastPatrolAt)
	}
	if resp.LastActivityAt == nil || !resp.LastActivityAt.Equal(lastActivityAt) {
		t.Fatalf("last_activity_at = %v, want %v", resp.LastActivityAt, lastActivityAt)
	}
}

func TestHandleGetPatrolStatus_ExposesScopedTriggerStatus(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	patrol.SetTriggerManager(ai.NewTriggerManager(ai.DefaultTriggerManagerConfig()))
	patrol.SetEventTriggerConfig(ai.PatrolEventTriggerConfig{
		AlertTriggersEnabled:   false,
		AnomalyTriggersEnabled: true,
	})

	req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/status", nil)
	rec := httptest.NewRecorder()

	handler.HandleGetPatrolStatus(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	var resp PatrolStatusResponse
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}

	if resp.TriggerStatus == nil {
		t.Fatal("expected trigger_status to be populated")
	}
	if resp.TriggerStatus.AlertTriggersEnabled {
		t.Fatal("expected alert trigger source to report disabled")
	}
	if !resp.TriggerStatus.AnomalyTriggersEnabled {
		t.Fatal("expected anomaly trigger source to report enabled")
	}
	if resp.TriggerStatus.EventTriggersBlocked {
		t.Fatal("expected trigger status not to report a runtime block")
	}
}

func TestHandleGetPatrolStatus_ExposesEventTriggerRuntimeBlock(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	patrol.SetTriggerManager(ai.NewTriggerManager(ai.DefaultTriggerManagerConfig()))
	patrol.SetEventTriggerConfig(ai.PatrolEventTriggerConfig{
		AlertTriggersEnabled:   true,
		AnomalyTriggersEnabled: true,
	})
	patrol.SetEventTriggerBlock(ai.BackgroundAutomationEventTriggerBlock())

	req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/status", nil)
	rec := httptest.NewRecorder()

	handler.HandleGetPatrolStatus(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	var resp PatrolStatusResponse
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}

	if resp.TriggerStatus == nil {
		t.Fatal("expected trigger_status to be populated")
	}
	if !resp.TriggerStatus.EventTriggersBlocked {
		t.Fatal("expected trigger status to expose runtime block")
	}
	if resp.TriggerStatus.EventTriggersBlockedReason != ai.EventTriggerBlockReasonBackgroundAutomationDisabled {
		t.Fatalf("event trigger block reason = %q", resp.TriggerStatus.EventTriggersBlockedReason)
	}
	if resp.TriggerStatus.EventTriggersBlockedMessage == "" {
		t.Fatal("expected user-facing event trigger block message")
	}
	if !resp.TriggerStatus.AlertTriggersEnabled || !resp.TriggerStatus.AnomalyTriggersEnabled {
		t.Fatal("expected runtime block not to rewrite configured trigger preferences")
	}
}

func TestPatrolActionHandlers_NoAIService_ReturnStructuredServiceUnavailable(t *testing.T) {
	tmp := t.TempDir()
	cfg := &config.Config{DataPath: tmp}
	handler := newTestAISettingsHandler(cfg, nil, nil)

	tests := []struct {
		name          string
		method        string
		path          string
		body          string
		handler       func(http.ResponseWriter, *http.Request)
		agentEnvelope bool
	}{
		{
			name:    "force_patrol",
			method:  http.MethodPost,
			path:    "/api/ai/patrol/run",
			handler: handler.HandleForcePatrol,
		},
		{
			name:          "acknowledge",
			method:        http.MethodPost,
			path:          "/api/ai/patrol/acknowledge",
			body:          `{"finding_id":"finding-1"}`,
			handler:       handler.HandleAcknowledgeFinding,
			agentEnvelope: true,
		},
		{
			name:          "snooze",
			method:        http.MethodPost,
			path:          "/api/ai/patrol/snooze",
			body:          `{"finding_id":"finding-1","duration_hours":1}`,
			handler:       handler.HandleSnoozeFinding,
			agentEnvelope: true,
		},
		{
			name:          "resolve",
			method:        http.MethodPost,
			path:          "/api/ai/patrol/resolve",
			body:          `{"finding_id":"finding-1"}`,
			handler:       handler.HandleResolveFinding,
			agentEnvelope: true,
		},
		{
			name:    "note",
			method:  http.MethodPost,
			path:    "/api/ai/patrol/findings/note",
			body:    `{"finding_id":"finding-1","note":"keep watching"}`,
			handler: handler.HandleSetFindingNote,
		},
		{
			name:          "dismiss",
			method:        http.MethodPost,
			path:          "/api/ai/patrol/dismiss",
			body:          `{"finding_id":"finding-1","reason":"expected_behavior"}`,
			handler:       handler.HandleDismissFinding,
			agentEnvelope: true,
		},
		{
			name:    "suppress",
			method:  http.MethodPost,
			path:    "/api/ai/patrol/suppress",
			body:    `{"finding_id":"finding-1"}`,
			handler: handler.HandleSuppressFinding,
		},
		{
			name:    "clear_all",
			method:  http.MethodDelete,
			path:    "/api/ai/patrol/findings?confirm=true",
			handler: handler.HandleClearAllFindings,
		},
		{
			name:    "add_suppression_rule",
			method:  http.MethodPost,
			path:    "/api/ai/patrol/suppressions",
			body:    `{"description":"known benign workload"}`,
			handler: handler.HandleAddSuppressionRule,
		},
		{
			name:    "delete_suppression_rule",
			method:  http.MethodDelete,
			path:    "/api/ai/patrol/suppressions/rule-1",
			handler: handler.HandleDeleteSuppressionRule,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			req := newLoopbackRequest(tc.method, tc.path, strings.NewReader(tc.body))
			rec := httptest.NewRecorder()

			tc.handler(rec, req)

			if rec.Code != http.StatusServiceUnavailable {
				t.Fatalf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
			}

			if tc.agentEnvelope {
				var resp agentStableErrorEnvelope
				if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
					t.Fatalf("decode response: %v", err)
				}
				if resp.Error != "patrol_unavailable" {
					t.Fatalf("error = %q, want patrol_unavailable", resp.Error)
				}
				if resp.Message != "Pulse Patrol service not available" {
					t.Fatalf("message = %q, want Pulse Patrol service not available", resp.Message)
				}
				return
			}

			var resp APIError
			if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
				t.Fatalf("decode response: %v", err)
			}
			if resp.Code != "service_unavailable" {
				t.Fatalf("code = %q, want service_unavailable", resp.Code)
			}
			if resp.ErrorMessage != "Pulse Patrol service not available" {
				t.Fatalf("error = %q, want Pulse Patrol service not available", resp.ErrorMessage)
			}
		})
	}
}

func TestPatrolFindingLifecycleHandlers_ReturnAgentStableValidationErrors(t *testing.T) {
	handler, _, _, _ := setupAIHandlerWithPatrol(t)

	tests := []struct {
		name        string
		path        string
		body        string
		handler     func(http.ResponseWriter, *http.Request)
		wantMessage string
		wantDetails map[string]string
	}{
		{
			name:        "acknowledge_missing_finding_id",
			path:        "/api/ai/patrol/acknowledge",
			body:        `{}`,
			handler:     handler.HandleAcknowledgeFinding,
			wantMessage: "finding_id is required",
			wantDetails: map[string]string{"finding_id": "required"},
		},
		{
			name:        "snooze_invalid_duration",
			path:        "/api/ai/patrol/snooze",
			body:        `{"finding_id":"finding-1","duration_hours":0}`,
			handler:     handler.HandleSnoozeFinding,
			wantMessage: "duration_hours must be positive",
			wantDetails: map[string]string{"duration_hours": "must be positive"},
		},
		{
			name:        "dismiss_invalid_reason",
			path:        "/api/ai/patrol/dismiss",
			body:        `{"finding_id":"finding-1","reason":"invalid_reason"}`,
			handler:     handler.HandleDismissFinding,
			wantMessage: "Invalid reason. Valid values: not_an_issue, expected_behavior, will_fix_later",
			wantDetails: map[string]string{"reason": "must be one of not_an_issue, expected_behavior, will_fix_later"},
		},
		{
			name:        "resolve_invalid_json",
			path:        "/api/ai/patrol/resolve",
			body:        `{`,
			handler:     handler.HandleResolveFinding,
			wantMessage: "Invalid request body",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := newLoopbackRequest(http.MethodPost, tt.path, strings.NewReader(tt.body))
			rec := httptest.NewRecorder()

			tt.handler(rec, req)

			if rec.Code != http.StatusBadRequest {
				t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
			}

			var resp agentStableErrorEnvelope
			if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
				t.Fatalf("decode response: %v", err)
			}
			if resp.Error != "invalid_finding_request" {
				t.Fatalf("error = %q, want invalid_finding_request", resp.Error)
			}
			if resp.Message != tt.wantMessage {
				t.Fatalf("message = %q, want %q", resp.Message, tt.wantMessage)
			}
			for key, want := range tt.wantDetails {
				if got := resp.Details[key]; got != want {
					t.Fatalf("details[%q] = %q, want %q; details=%v", key, got, want, resp.Details)
				}
			}
			if len(tt.wantDetails) == 0 && len(resp.Details) != 0 {
				t.Fatalf("details = %v, want empty", resp.Details)
			}
		})
	}
}

func TestPatrolFindingLifecycleHandlers_ReturnAgentStableNotFoundErrors(t *testing.T) {
	handler, _, _, _ := setupAIHandlerWithPatrol(t)

	tests := []struct {
		name        string
		path        string
		body        string
		handler     func(http.ResponseWriter, *http.Request)
		wantMessage string
	}{
		{
			name:        "acknowledge",
			path:        "/api/ai/patrol/acknowledge",
			body:        `{"finding_id":"missing"}`,
			handler:     handler.HandleAcknowledgeFinding,
			wantMessage: "Finding not found",
		},
		{
			name:        "snooze",
			path:        "/api/ai/patrol/snooze",
			body:        `{"finding_id":"missing","duration_hours":1}`,
			handler:     handler.HandleSnoozeFinding,
			wantMessage: "Finding not found or already resolved",
		},
		{
			name:        "resolve",
			path:        "/api/ai/patrol/resolve",
			body:        `{"finding_id":"missing"}`,
			handler:     handler.HandleResolveFinding,
			wantMessage: "Finding not found or already resolved",
		},
		{
			name:        "dismiss",
			path:        "/api/ai/patrol/dismiss",
			body:        `{"finding_id":"missing","reason":"expected_behavior"}`,
			handler:     handler.HandleDismissFinding,
			wantMessage: "Finding not found",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := newLoopbackRequest(http.MethodPost, tt.path, strings.NewReader(tt.body))
			rec := httptest.NewRecorder()

			tt.handler(rec, req)

			if rec.Code != http.StatusNotFound {
				t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusNotFound, rec.Body.String())
			}

			var resp agentStableErrorEnvelope
			if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
				t.Fatalf("decode response: %v", err)
			}
			if resp.Error != "finding_not_found" {
				t.Fatalf("error = %q, want finding_not_found", resp.Error)
			}
			if resp.Message != tt.wantMessage {
				t.Fatalf("message = %q, want %q", resp.Message, tt.wantMessage)
			}
		})
	}
}

func TestHandleAddSuppressionRuleRejectsImplicitBroadScope(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)

	req := newLoopbackRequest(
		http.MethodPost,
		"/api/ai/patrol/suppressions",
		strings.NewReader(`{"resource_id":"","resource_name":"Any","category":"capacity","description":"too broad"}`),
	)
	rec := httptest.NewRecorder()

	handler.HandleAddSuppressionRule(rec, req)

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest)
	}
	if rules := patrol.GetFindings().GetSuppressionRules(); len(rules) != 0 {
		t.Fatalf("expected no suppression rules, got %d", len(rules))
	}
}

func TestHandleAddSuppressionRuleAllowsExplicitBroadScope(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)

	req := newLoopbackRequest(
		http.MethodPost,
		"/api/ai/patrol/suppressions",
		strings.NewReader(`{"resource_id":"","resource_name":"Any","category":"capacity","description":"known capacity noise","allow_broad_scope":true}`),
	)
	rec := httptest.NewRecorder()

	handler.HandleAddSuppressionRule(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
	}
	rules := patrol.GetFindings().GetSuppressionRules()
	if len(rules) != 1 {
		t.Fatalf("rules = %d, want 1", len(rules))
	}
	if rules[0].ResourceID != "" || rules[0].Category != ai.FindingCategoryCapacity {
		t.Fatalf("unexpected rule scope: resource=%q category=%q", rules[0].ResourceID, rules[0].Category)
	}
}

func TestHandleAcknowledgeFinding_PatrolAndUnified(t *testing.T) {
	handler, patrol, unifiedStore, learningStore := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-2 * time.Hour)
	addPatrolFinding(t, patrol, "finding-ack", detectedAt)
	addUnifiedFinding(unifiedStore, "finding-ack", detectedAt)

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/acknowledge", strings.NewReader(`{"finding_id":"finding-ack"}`))
	rec := httptest.NewRecorder()

	handler.HandleAcknowledgeFinding(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	patrolFinding := patrol.GetFindings().Get("finding-ack")
	if patrolFinding == nil || patrolFinding.AcknowledgedAt == nil {
		t.Fatalf("expected patrol finding to be acknowledged")
	}

	unifiedFinding := unifiedStore.Get("finding-ack")
	if unifiedFinding == nil || unifiedFinding.AcknowledgedAt == nil {
		t.Fatalf("expected unified finding to be acknowledged")
	}

	stats := learningStore.GetStatistics()
	if stats.TotalFeedbackRecords != 1 {
		t.Fatalf("feedback records = %d, want 1", stats.TotalFeedbackRecords)
	}
}

func TestHandleAcknowledgeFinding_UnifiedOnly(t *testing.T) {
	handler, patrol, unifiedStore, learningStore := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-1 * time.Hour)
	addUnifiedFinding(unifiedStore, "finding-unified-only", detectedAt)

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/acknowledge", strings.NewReader(`{"finding_id":"finding-unified-only"}`))
	rec := httptest.NewRecorder()

	handler.HandleAcknowledgeFinding(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	if patrol.GetFindings().Get("finding-unified-only") != nil {
		t.Fatalf("expected patrol finding to be absent")
	}

	unifiedFinding := unifiedStore.Get("finding-unified-only")
	if unifiedFinding == nil || unifiedFinding.AcknowledgedAt == nil {
		t.Fatalf("expected unified finding to be acknowledged")
	}

	stats := learningStore.GetStatistics()
	if stats.TotalFeedbackRecords != 1 {
		t.Fatalf("feedback records = %d, want 1", stats.TotalFeedbackRecords)
	}
}

func TestHandleSnoozeFinding_CapsDuration(t *testing.T) {
	handler, patrol, unifiedStore, learningStore := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-30 * time.Minute)
	addPatrolFinding(t, patrol, "finding-snooze", detectedAt)
	addUnifiedFinding(unifiedStore, "finding-snooze", detectedAt)

	body := `{"finding_id":"finding-snooze","duration_hours":200}`
	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/snooze", strings.NewReader(body))
	rec := httptest.NewRecorder()

	handler.HandleSnoozeFinding(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	var resp map[string]interface{}
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	message, _ := resp["message"].(string)
	if !strings.Contains(message, "168") {
		t.Fatalf("expected capped duration in message, got %q", message)
	}

	patrolFinding := patrol.GetFindings().Get("finding-snooze")
	if patrolFinding == nil || patrolFinding.SnoozedUntil == nil {
		t.Fatalf("expected snoozed patrol finding")
	}
	if patrolFinding.SnoozedUntil.Before(time.Now().Add(167 * time.Hour)) {
		t.Fatalf("snooze duration not applied")
	}

	unifiedFinding := unifiedStore.Get("finding-snooze")
	if unifiedFinding == nil || unifiedFinding.SnoozedUntil == nil {
		t.Fatalf("expected snoozed unified finding")
	}

	stats := learningStore.GetStatistics()
	if stats.TotalFeedbackRecords != 1 {
		t.Fatalf("feedback records = %d, want 1", stats.TotalFeedbackRecords)
	}
}

func TestHandleResolveFinding_SetsResolved(t *testing.T) {
	handler, patrol, unifiedStore, learningStore := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-2 * time.Hour)
	addPatrolFinding(t, patrol, "finding-resolve", detectedAt)
	addUnifiedFinding(unifiedStore, "finding-resolve", detectedAt)

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/resolve", strings.NewReader(`{"finding_id":"finding-resolve","resolution_note":"fixed after restarting the worker"}`))
	rec := httptest.NewRecorder()

	handler.HandleResolveFinding(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	patrolFinding := patrol.GetFindings().Get("finding-resolve")
	if patrolFinding == nil || patrolFinding.ResolvedAt == nil {
		t.Fatalf("expected patrol finding to be resolved")
	}
	if patrolFinding.UserNote != "fixed after restarting the worker" {
		t.Fatalf("patrol finding resolution note = %q", patrolFinding.UserNote)
	}

	unifiedFinding := unifiedStore.Get("finding-resolve")
	if unifiedFinding == nil || unifiedFinding.ResolvedAt == nil {
		t.Fatalf("expected unified finding to be resolved")
	}

	stats := learningStore.GetStatistics()
	if stats.TotalFeedbackRecords != 1 {
		t.Fatalf("feedback records = %d, want 1", stats.TotalFeedbackRecords)
	}
}

func TestHandleDismissFinding_ValidReason(t *testing.T) {
	handler, patrol, unifiedStore, learningStore := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-3 * time.Hour)
	addPatrolFinding(t, patrol, "finding-dismiss", detectedAt)
	addUnifiedFinding(unifiedStore, "finding-dismiss", detectedAt)

	payload := map[string]string{
		"finding_id": "finding-dismiss",
		"reason":     "expected_behavior",
		"note":       "known load test",
	}
	body, _ := json.Marshal(payload)
	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/dismiss", bytes.NewReader(body))
	rec := httptest.NewRecorder()

	handler.HandleDismissFinding(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	patrolFinding := patrol.GetFindings().Get("finding-dismiss")
	if patrolFinding == nil || patrolFinding.DismissedReason != "expected_behavior" {
		t.Fatalf("expected patrol finding to be dismissed")
	}
	if patrolFinding.UserNote != "known load test" {
		t.Fatalf("expected patrol note to be recorded")
	}

	unifiedFinding := unifiedStore.Get("finding-dismiss")
	if unifiedFinding == nil || unifiedFinding.DismissedReason != "expected_behavior" {
		t.Fatalf("expected unified finding to be dismissed")
	}
	if unifiedFinding.UserNote != "known load test" {
		t.Fatalf("expected unified note to be recorded")
	}

	stats := learningStore.GetStatistics()
	if stats.TotalFeedbackRecords != 1 {
		t.Fatalf("feedback records = %d, want 1", stats.TotalFeedbackRecords)
	}
}

func TestHandleDeleteSuppressionRule_ReopensFindingInBothStores(t *testing.T) {
	handler, patrol, unifiedStore, _ := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-3 * time.Hour)
	addPatrolFinding(t, patrol, "finding-reopen", detectedAt)
	addUnifiedFinding(unifiedStore, "finding-reopen", detectedAt)
	if !patrol.GetFindings().Dismiss("finding-reopen", "expected_behavior", "known load test") {
		t.Fatal("expected patrol finding dismissal to succeed")
	}
	if !unifiedStore.Dismiss("finding-reopen", "expected_behavior", "known load test") {
		t.Fatal("expected unified finding dismissal to succeed")
	}

	req := newLoopbackRequest(http.MethodDelete, "/api/ai/patrol/suppressions/finding_finding-reopen", nil)
	rec := httptest.NewRecorder()

	handler.HandleDeleteSuppressionRule(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}
	patrolFinding := patrol.GetFindings().Get("finding-reopen")
	if patrolFinding == nil || patrolFinding.DismissedReason != "" || patrolFinding.Suppressed {
		t.Fatalf("expected patrol finding to be reopened: %+v", patrolFinding)
	}
	if patrolFinding.UserNote != "known load test" {
		t.Fatalf("expected patrol note to survive reopen, got %q", patrolFinding.UserNote)
	}
	unifiedFinding := unifiedStore.Get("finding-reopen")
	if unifiedFinding == nil || unifiedFinding.DismissedReason != "" || unifiedFinding.Suppressed {
		t.Fatalf("expected unified finding to be reopened: %+v", unifiedFinding)
	}
	if unifiedFinding.UserNote != "known load test" {
		t.Fatalf("expected unified note to survive reopen, got %q", unifiedFinding.UserNote)
	}
}

func TestHandleSuppressFinding_SetsSuppressed(t *testing.T) {
	handler, patrol, unifiedStore, learningStore := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-45 * time.Minute)
	addPatrolFinding(t, patrol, "finding-suppress", detectedAt)
	addUnifiedFinding(unifiedStore, "finding-suppress", detectedAt)

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/suppress", strings.NewReader(`{"finding_id":"finding-suppress"}`))
	rec := httptest.NewRecorder()

	handler.HandleSuppressFinding(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	patrolFinding := patrol.GetFindings().Get("finding-suppress")
	if patrolFinding == nil || !patrolFinding.Suppressed {
		t.Fatalf("expected patrol finding to be suppressed")
	}
	if patrolFinding.DismissedReason != "suppressed" {
		t.Fatalf("expected patrol dismissal reason to be set")
	}

	unifiedFinding := unifiedStore.Get("finding-suppress")
	if unifiedFinding == nil || !unifiedFinding.Suppressed {
		t.Fatalf("expected unified finding to be suppressed")
	}
	if unifiedFinding.DismissedReason != "not_an_issue" {
		t.Fatalf("expected unified dismissal reason to be not_an_issue")
	}

	stats := learningStore.GetStatistics()
	if stats.TotalFeedbackRecords != 1 {
		t.Fatalf("feedback records = %d, want 1", stats.TotalFeedbackRecords)
	}
}

func TestHandlePatrolRuntimeFindingActions_AreRejected(t *testing.T) {
	handler, patrol, unifiedStore, learningStore := setupAIHandlerWithPatrol(t)

	detectedAt := time.Now().Add(-30 * time.Minute)
	addPatrolRuntimeFinding(t, patrol, "finding-runtime", detectedAt)
	addUnifiedRuntimeFinding(unifiedStore, "finding-runtime", detectedAt)

	tests := []struct {
		name          string
		path          string
		body          string
		handler       func(http.ResponseWriter, *http.Request)
		wantPhrase    string
		wantAgentCode string
	}{
		{
			name:          "acknowledge",
			path:          "/api/ai/patrol/acknowledge",
			body:          `{"finding_id":"finding-runtime"}`,
			handler:       handler.HandleAcknowledgeFinding,
			wantPhrase:    "cannot be acknowledged manually",
			wantAgentCode: "finding_action_not_allowed",
		},
		{
			name:          "snooze",
			path:          "/api/ai/patrol/snooze",
			body:          `{"finding_id":"finding-runtime","duration_hours":24}`,
			handler:       handler.HandleSnoozeFinding,
			wantPhrase:    "cannot be snoozed manually",
			wantAgentCode: "finding_action_not_allowed",
		},
		{
			name:          "resolve",
			path:          "/api/ai/patrol/resolve",
			body:          `{"finding_id":"finding-runtime"}`,
			handler:       handler.HandleResolveFinding,
			wantPhrase:    "cannot be resolved manually",
			wantAgentCode: "finding_action_not_allowed",
		},
		{
			name:          "dismiss",
			path:          "/api/ai/patrol/dismiss",
			body:          `{"finding_id":"finding-runtime","reason":"expected_behavior","note":"ignore"}`,
			handler:       handler.HandleDismissFinding,
			wantPhrase:    "cannot be dismissed manually",
			wantAgentCode: "finding_action_not_allowed",
		},
		{
			name:       "suppress",
			path:       "/api/ai/patrol/suppress",
			body:       `{"finding_id":"finding-runtime"}`,
			handler:    handler.HandleSuppressFinding,
			wantPhrase: "cannot be suppressed manually",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := newLoopbackRequest(http.MethodPost, tt.path, strings.NewReader(tt.body))
			rec := httptest.NewRecorder()

			tt.handler(rec, req)

			if rec.Code != http.StatusConflict {
				t.Fatalf("status = %d, want 409", rec.Code)
			}
			if tt.wantAgentCode != "" {
				var resp agentStableErrorEnvelope
				if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
					t.Fatalf("decode response: %v", err)
				}
				if resp.Error != tt.wantAgentCode {
					t.Fatalf("error = %q, want %q", resp.Error, tt.wantAgentCode)
				}
				if !strings.Contains(resp.Message, tt.wantPhrase) {
					t.Fatalf("expected message to contain %q, got %q", tt.wantPhrase, resp.Message)
				}
				return
			}
			if !strings.Contains(rec.Body.String(), tt.wantPhrase) {
				t.Fatalf("expected response to contain %q, got %q", tt.wantPhrase, rec.Body.String())
			}
		})
	}

	patrolFinding := patrol.GetFindings().Get("finding-runtime")
	if patrolFinding == nil {
		t.Fatal("expected runtime finding to remain present")
	}
	if patrolFinding.AcknowledgedAt != nil {
		t.Fatal("expected runtime finding to remain unacknowledged")
	}
	if patrolFinding.SnoozedUntil != nil {
		t.Fatal("expected runtime finding to remain unsnoozed")
	}
	if patrolFinding.ResolvedAt != nil {
		t.Fatal("expected runtime finding to remain unresolved")
	}
	if patrolFinding.DismissedReason != "" {
		t.Fatalf("expected runtime finding to remain undismissed, got %q", patrolFinding.DismissedReason)
	}
	if patrolFinding.Suppressed {
		t.Fatal("expected runtime finding to remain unsuppressed")
	}

	unifiedFinding := unifiedStore.Get("finding-runtime")
	if unifiedFinding == nil {
		t.Fatal("expected unified runtime finding to remain present")
	}
	if unifiedFinding.AcknowledgedAt != nil {
		t.Fatal("expected unified runtime finding to remain unacknowledged")
	}
	if unifiedFinding.SnoozedUntil != nil {
		t.Fatal("expected unified runtime finding to remain unsnoozed")
	}
	if unifiedFinding.ResolvedAt != nil {
		t.Fatal("expected unified runtime finding to remain unresolved")
	}
	if unifiedFinding.DismissedReason != "" {
		t.Fatalf("expected unified runtime finding to remain undismissed, got %q", unifiedFinding.DismissedReason)
	}

	stats := learningStore.GetStatistics()
	if stats.TotalFeedbackRecords != 0 {
		t.Fatalf("feedback records = %d, want 0", stats.TotalFeedbackRecords)
	}
}

func TestHandleGetFindingsHistory_StartTimeFilter(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)

	oldTime := time.Now().Add(-3 * time.Hour)
	recentTime := time.Now().Add(-30 * time.Minute)
	addPatrolFindingForResource(t, patrol, "finding-old", oldTime, "vm-old", "Old CPU spike")
	addPatrolFindingForResource(t, patrol, "finding-recent", recentTime, "vm-recent", "Recent CPU spike")

	startTime := time.Now().Add(-1 * time.Hour).UTC().Format(time.RFC3339)
	req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/history?start_time="+startTime, nil)
	rec := httptest.NewRecorder()

	handler.HandleGetFindingsHistory(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}

	var findings []ai.Finding
	if err := json.Unmarshal(rec.Body.Bytes(), &findings); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if len(findings) != 1 {
		t.Fatalf("findings = %d, want 1", len(findings))
	}
	if findings[0].ID != "finding-recent" {
		t.Fatalf("expected recent finding, got %s", findings[0].ID)
	}
}

func seedReadyAnthropicPatrolRuntime(t *testing.T, handler *AISettingsHandler) {
	t.Helper()

	aiCfg := config.NewDefaultAIConfig()
	aiCfg.Enabled = true
	aiCfg.Model = "anthropic:claude-3-5-sonnet-latest"
	aiCfg.AnthropicAPIKey = "test-key"
	if err := handler.defaultPersistence.SaveAIConfig(*aiCfg); err != nil {
		t.Fatalf("SaveAIConfig: %v", err)
	}
	if err := handler.defaultAIService.Reload(); err != nil {
		t.Fatalf("Reload: %v", err)
	}
}

func TestHandleForcePatrol_ConfigDisabled(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	seedReadyAnthropicPatrolRuntime(t, handler)

	cfg := ai.DefaultPatrolConfig()
	cfg.Enabled = false
	patrol.SetConfig(cfg)

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil)
	rec := httptest.NewRecorder()

	handler.HandleForcePatrol(rec, req)

	if rec.Code != http.StatusConflict {
		t.Fatalf("status = %d, want 409", rec.Code)
	}
	var payload APIError
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("decode error payload: %v", err)
	}
	if payload.Code != "patrol_disabled" {
		t.Fatalf("code = %q, want patrol_disabled", payload.Code)
	}
}

func TestHandleForcePatrolRejectsDuplicateAfterSynchronousAcceptance(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	seedReadyAnthropicPatrolRuntime(t, handler)
	setUnexportedField(t, patrol, "runInProgress", true)
	setUnexportedField(t, patrol, "currentRunID", "run-active")
	setUnexportedField(t, patrol, "runStartedAt", time.Now())

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil)
	rec := httptest.NewRecorder()
	handler.HandleForcePatrol(rec, req)

	if rec.Code != http.StatusConflict {
		t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())
	}
	var payload APIError
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("decode error payload: %v", err)
	}
	if payload.Code != "patrol_already_running" {
		t.Fatalf("code = %q, want patrol_already_running", payload.Code)
	}
	if payload.Details["current_run_id"] != "run-active" {
		t.Fatalf("current_run_id = %q, want run-active", payload.Details["current_run_id"])
	}
}

func TestHandleForcePatrolRejectsBusyScopedRequestInsteadOfAcknowledgingDroppedWork(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	seedReadyAnthropicPatrolRuntime(t, handler)
	handler.defaultAIService.SetStateProvider(&scopedPatrolStateProvider{state: models.StateSnapshot{
		VMs: []models.VM{{ID: "vm-101", Name: "web", VMID: 101}},
	}})
	setUnexportedField(t, patrol, "runInProgress", true)
	setUnexportedField(t, patrol, "currentRunID", "run-active")
	setUnexportedField(t, patrol, "runStartedAt", time.Now())

	req := newLoopbackRequest(
		http.MethodPost,
		"/api/ai/patrol/run",
		bytes.NewReader([]byte(`{"resource_ids":["vm-101"]}`)),
	)
	rec := httptest.NewRecorder()
	handler.HandleForcePatrol(rec, req)

	if rec.Code != http.StatusConflict {
		t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())
	}
	var payload APIError
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("decode error payload: %v", err)
	}
	if payload.Code != "patrol_already_running" {
		t.Fatalf("code = %q, want patrol_already_running", payload.Code)
	}
	if payload.Details["current_run_id"] != "run-active" {
		t.Fatalf("current_run_id = %q, want run-active", payload.Details["current_run_id"])
	}
}

func TestHandleForcePatrol_BlocksNotReadyPatrolModel(t *testing.T) {
	handler, _, _, _ := setupAIHandlerWithPatrol(t)

	model := "ollama:deepseek-r1:7b-llama-distill-q4_K_M"
	aiCfg := config.NewDefaultAIConfig()
	aiCfg.Enabled = true
	aiCfg.Model = model
	aiCfg.PatrolModel = model
	aiCfg.OllamaBaseURL = "http://127.0.0.1:11434"
	if err := handler.defaultPersistence.SaveAIConfig(*aiCfg); err != nil {
		t.Fatalf("SaveAIConfig: %v", err)
	}
	if err := handler.defaultAIService.Reload(); err != nil {
		t.Fatalf("Reload: %v", err)
	}

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil)
	rec := httptest.NewRecorder()

	handler.HandleForcePatrol(rec, req)

	if rec.Code != http.StatusConflict {
		t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())
	}
	var payload APIError
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("decode error payload: %v", err)
	}
	if payload.Code != "patrol_readiness_not_ready" {
		t.Fatalf("code = %q, want patrol_readiness_not_ready", payload.Code)
	}
	if !strings.Contains(payload.ErrorMessage, "reasoning-only model family") {
		t.Fatalf("error = %q", payload.ErrorMessage)
	}
	if payload.Details["model"] != model {
		t.Fatalf("model detail = %q, want %q", payload.Details["model"], model)
	}
}

func TestHandleForcePatrol_BlocksIncompleteContinuationDespitePassingDimensions(t *testing.T) {
	provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "provider unavailable", http.StatusServiceUnavailable)
	}))
	defer provider.Close()

	tmp := t.TempDir()
	cfg := &config.Config{DataPath: tmp}
	persistence := config.NewConfigPersistence(tmp)
	aiCfg := config.NewDefaultAIConfig()
	aiCfg.Enabled = true
	aiCfg.Model = "ollama:test-model"
	aiCfg.PatrolModel = aiCfg.Model
	aiCfg.OllamaBaseURL = provider.URL
	if err := persistence.SaveAIConfig(*aiCfg); err != nil {
		t.Fatal(err)
	}
	handler := newTestAISettingsHandler(cfg, persistence, nil)
	// Obtain the production cache identity against a local provider, then
	// reproduce a saved evaluation whose continuation failed after its probes.
	result := handler.defaultAIService.RunPatrolModelReadiness(context.Background(), config.AIProviderOllama, "test-model")
	if result.CacheKey == "" {
		t.Fatal("expected a persisted evaluation identity")
	}
	result.Success = false
	result.PatrolCapable = false
	result.TransportHealthy = true
	result.Status = ai.PatrolModelReadinessWarning
	result.Cause = ai.PatrolFailureCauseProviderConnection
	result.MaxVerifiedMode = ""
	result.Summary = "Provider stopped before continuation completed."
	result.Dimensions.Connectivity = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessPass}
	result.Dimensions.ToolProtocol = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessPass, Attempts: 3, Passed: 3}
	result.Dimensions.ContextQuality = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessPass, Attempts: 2, Passed: 2}
	result.Dimensions.Latency = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessNotAssessed}
	result.Modes.Monitor = ai.PatrolModeSuitability{Status: ai.PatrolModeNotAssessed, Summary: result.Summary}
	result.Modes.Approval = ai.PatrolModeSuitability{Status: ai.PatrolModeNotSuitable}
	payload, err := json.Marshal(struct {
		Result     ai.PatrolModelReadinessResult `json:"result"`
		CacheKey   string                        `json:"cache_key"`
		RecordedAt time.Time                     `json:"recorded_at"`
	}{result, result.CacheKey, time.Now().UTC()})
	if err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(tmp, "ai_patrol_model_readiness.json"), payload, 0o600); err != nil {
		t.Fatal(err)
	}
	handler = newTestAISettingsHandler(cfg, persistence, nil)
	handler.defaultAIService.SetStateProvider(&stubStateProvider{})
	if cached, _ := handler.defaultAIService.CachedPatrolModelReadiness(); cached == nil {
		t.Fatal("expected the saved evaluation to survive restart")
	}
	readiness := handler.buildPatrolReadiness(context.Background(), handler.defaultAIService, true)
	for _, id := range []string{"tools", "context_quality", "latency"} {
		if check := requirePatrolReadinessCheck(t, readiness, id); check.Status == patrolReadinessNotReady {
			t.Fatalf("display dimension %s unexpectedly blocks the fixture: %+v", id, check)
		}
	}
	if check := requirePatrolReadinessCheck(t, readiness, "runtime"); check.Status != patrolReadinessNotReady {
		t.Fatalf("execution check = %+v, want not ready", check)
	}
	rec := httptest.NewRecorder()
	handler.HandleForcePatrol(rec, newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil))
	if rec.Code != http.StatusConflict {
		t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())
	}
	var response APIError
	if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
		t.Fatal(err)
	}
	if response.Code != "patrol_readiness_not_ready" {
		t.Fatalf("code = %q, want patrol_readiness_not_ready", response.Code)
	}
}

func TestHandleForcePatrol_CommunityTierIgnoresRecentScopedActivityForFullPatrolRateLimit(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	seedReadyAnthropicPatrolRuntime(t, handler)
	handler.defaultAIService.SetLicenseChecker(communityLicenseChecker{})

	setUnexportedField(t, patrol, "lastActivity", time.Now().Add(-10*time.Minute))

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil)
	rec := httptest.NewRecorder()

	handler.HandleForcePatrol(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())
	}
	if strings.Contains(rec.Body.String(), "patrol_rate_limited") {
		t.Fatalf("expected community force patrol to ignore scoped-only activity, got %s", rec.Body.String())
	}
	var response struct {
		Accepted  bool   `json:"accepted"`
		RunID     string `json:"run_id"`
		StartedAt string `json:"started_at"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
		t.Fatalf("decode acceptance response: %v", err)
	}
	if !response.Accepted || response.RunID == "" || response.StartedAt == "" {
		t.Fatalf("incomplete acceptance response: %+v", response)
	}
}

func TestHandleForcePatrol_CommunityTierFailedRunDoesNotConsumeHourlySlot(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	seedReadyAnthropicPatrolRuntime(t, handler)
	handler.defaultAIService.SetLicenseChecker(communityLicenseChecker{})

	// A recent full run that FAILED must not consume the Community hourly
	// slot: retesting a broken provider or configuration would otherwise cost
	// an hour per attempt (discussion #1571).
	failedHistory := ai.NewPatrolRunHistoryStore(ai.MaxPatrolRunHistory)
	failedHistory.Add(ai.PatrolRunRecord{
		ID:          "run-recent-failure",
		Type:        "patrol",
		CompletedAt: time.Now().Add(-10 * time.Minute),
		Status:      "error",
		ErrorCount:  1,
	})
	setUnexportedField(t, patrol, "runHistoryStore", failedHistory)
	setUnexportedField(t, patrol, "lastFullPatrol", time.Now().Add(-10*time.Minute))

	req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil)
	rec := httptest.NewRecorder()
	handler.HandleForcePatrol(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())
	}
	if strings.Contains(rec.Body.String(), "patrol_rate_limited") {
		t.Fatalf("expected failed run to leave the hourly slot free, got %s", rec.Body.String())
	}
}

func TestBuildManualScopedPatrolScope(t *testing.T) {
	cases := []struct {
		name   string
		req    manualScopedPatrolRequest
		wantOK bool
		check  func(*testing.T, ai.PatrolScope)
	}{
		{
			name:   "empty body falls back to full run",
			req:    manualScopedPatrolRequest{},
			wantOK: false,
		},
		{
			name:   "whitespace-only ids fall back to full run",
			req:    manualScopedPatrolRequest{ResourceIDs: []string{"  "}},
			wantOK: false,
		},
		{
			name:   "resource ids build a manual quick scope",
			req:    manualScopedPatrolRequest{ResourceIDs: []string{"vm-101", " vm-102 "}, AlertIdentifier: "alert-1", AlertType: "cpu"},
			wantOK: true,
			check: func(t *testing.T, s ai.PatrolScope) {
				t.Helper()
				if s.Reason != ai.TriggerReasonManual {
					t.Errorf("reason = %q, want manual", s.Reason)
				}
				if s.Depth != ai.PatrolDepthQuick {
					t.Errorf("depth = %v, want quick", s.Depth)
				}
				if len(s.ResourceIDs) != 2 || s.ResourceIDs[0] != "vm-101" || s.ResourceIDs[1] != "vm-102" {
					t.Errorf("resource ids = %v", s.ResourceIDs)
				}
				if s.AlertIdentifier != "alert-1" {
					t.Errorf("alert identifier = %q", s.AlertIdentifier)
				}
				if !strings.Contains(s.Context, "cpu") {
					t.Errorf("context = %q, want alert type", s.Context)
				}
			},
		},
		{
			name:   "resource types only still scopes",
			req:    manualScopedPatrolRequest{ResourceTypes: []string{"vm"}},
			wantOK: true,
			check: func(t *testing.T, s ai.PatrolScope) {
				t.Helper()
				if len(s.ResourceTypes) != 1 || s.ResourceTypes[0] != "vm" {
					t.Errorf("resource types = %v", s.ResourceTypes)
				}
			},
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			scope, ok := buildManualScopedPatrolScope(tc.req)
			if ok != tc.wantOK {
				t.Fatalf("hasScope = %v, want %v", ok, tc.wantOK)
			}
			if !ok {
				return
			}
			tc.check(t, scope)
		})
	}
}

func TestHandleForcePatrol_ScopedRequestBypassesFullRunCadenceGate(t *testing.T) {
	handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
	seedReadyAnthropicPatrolRuntime(t, handler)
	handler.defaultAIService.SetStateProvider(&scopedPatrolStateProvider{state: models.StateSnapshot{
		VMs: []models.VM{{ID: "vm-101", Name: "web", VMID: 101}},
	}})
	handler.defaultAIService.SetLicenseChecker(communityLicenseChecker{})

	// A recent successful full patrol puts Community tier inside the 1/hour
	// full-run gate, so a fleet-wide request would be rate-limited.
	recentHistory := ai.NewPatrolRunHistoryStore(ai.MaxPatrolRunHistory)
	recentHistory.Add(ai.PatrolRunRecord{
		ID:          "run-recent-success",
		Type:        "patrol",
		CompletedAt: time.Now().Add(-10 * time.Minute),
		Status:      "healthy",
	})
	setUnexportedField(t, patrol, "runHistoryStore", recentHistory)
	setUnexportedField(t, patrol, "lastFullPatrol", time.Now().Add(-10*time.Minute))

	// Scoped request: must succeed despite the full-run cadence window.
	scopedReq := newLoopbackRequest(
		http.MethodPost,
		"/api/ai/patrol/run",
		bytes.NewReader([]byte(`{"resource_ids":["vm-101"],"alert_identifier":"alert-1","alert_type":"cpu"}`)),
	)
	scopedRec := httptest.NewRecorder()
	handler.HandleForcePatrol(scopedRec, scopedReq)

	if scopedRec.Code != http.StatusOK {
		t.Fatalf("scoped status = %d, want 200: %s", scopedRec.Code, scopedRec.Body.String())
	}
	if !strings.Contains(scopedRec.Body.String(), "targeted Patrol check") {
		t.Fatalf("scoped response = %s, want targeted Patrol check message", scopedRec.Body.String())
	}

	// Contrast: an empty body (full run) on the same recent-full state is gated.
	fullReq := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil)
	fullRec := httptest.NewRecorder()
	handler.HandleForcePatrol(fullRec, fullReq)

	if fullRec.Code != http.StatusTooManyRequests {
		t.Fatalf("full status = %d, want 429 rate limited: %s", fullRec.Code, fullRec.Body.String())
	}
	if !strings.Contains(fullRec.Body.String(), "patrol_rate_limited") {
		t.Fatalf("full response = %s, want patrol_rate_limited", fullRec.Body.String())
	}
}

func TestPatrolObjectiveAPIContractKeepsCoverageServerOwned(t *testing.T) {
	handler, _, _, _ := setupAIHandlerWithPatrol(t)

	createReq := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/objectives", strings.NewReader(`{"brief":"Keep cameras online","resource_ids":["camera-1"]}`))
	createRec := httptest.NewRecorder()
	handler.HandlePatrolObjectives(createRec, createReq)
	if createRec.Code != http.StatusCreated {
		t.Fatalf("create status = %d, body=%s", createRec.Code, createRec.Body.String())
	}
	var objective ai.PatrolObjective
	if err := json.Unmarshal(createRec.Body.Bytes(), &objective); err != nil {
		t.Fatalf("decode objective: %v", err)
	}
	if objective.Coverage.State != ai.PatrolObjectiveUncovered || objective.Coverage.ReasonCode != "observer_missing" {
		t.Fatalf("new objective coverage = %+v", objective.Coverage)
	}

	forgedReq := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/objectives", strings.NewReader(`{"brief":"Keep cameras online","coverage":{"state":"covered"}}`))
	forgedRec := httptest.NewRecorder()
	handler.HandlePatrolObjectives(forgedRec, forgedReq)
	if forgedRec.Code != http.StatusBadRequest {
		t.Fatalf("forged coverage status = %d, body=%s", forgedRec.Code, forgedRec.Body.String())
	}
}

// A completed action remains authoritative for its original investigation,
// even after the same finding represents a new occurrence of the failure.
func TestPatrolHistoricalActionCannotResolveRecurringFinding(t *testing.T) {
	persistence := config.NewConfigPersistence(t.TempDir())
	newService := func() *ai.Service {
		svc := ai.NewService(nil, nil)
		svc.SetStateProvider(&MockStateProvider{})
		if err := svc.GetPatrolService().GetFindings().SetPersistence(ai.NewFindingsPersistenceAdapter(persistence)); err != nil {
			t.Fatal(err)
		}
		return svc
	}
	svc := newService()
	findings := svc.GetPatrolService().GetFindings()
	report := func() {
		findings.Add(&ai.Finding{ID: "recurring", Key: "health-check-failed", ResourceID: "vm:42", ResourceType: "vm",
			Title: "Service health check failed", Severity: ai.FindingSeverityWarning, Category: ai.FindingCategoryReliability})
	}
	report()
	investigations := newTestInvestigationStore()
	auditDirectory := t.TempDir()
	audits, err := unifiedresources.NewSQLiteResourceStore(auditDirectory, "default")
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { audits.Close() })
	handler := &AISettingsHandler{defaultAIService: svc,
		investigationStores:   map[string]aicontracts.InvestigationStore{"default": investigations},
		resourceStoreProvider: func(string) (unifiedresources.ResourceStore, error) { return audits, nil },
	}
	var history []*aicontracts.InvestigationSession
	for occurrence := 1; occurrence <= 3; occurrence++ {
		t.Run(fmt.Sprintf("occurrence-%d", occurrence), func(t *testing.T) {
			for _, previous := range history {
				before := findings.Get("recurring")
				svc.GetPatrolService().SetInvestigationOrchestrator(&stubInvestigationOrchestrator{session: previous})
				for _, suffix := range []string{"/investigation", "/investigation/messages"} {
					req := httptest.NewRequest(http.MethodGet, "/api/ai/findings/recurring"+suffix, nil)
					rec := httptest.NewRecorder()
					if suffix == "/investigation" {
						handler.HandleGetInvestigation(rec, req)
					} else {
						handler.HandleGetInvestigationMessages(rec, req)
					}
					if rec.Code != http.StatusNotFound {
						t.Fatalf("current occurrence read returned historical session: status=%d body=%s", rec.Code, rec.Body.String())
					}
				}
				hydrated := handler.hydratePatrolInvestigationAction("default", previous)
				if hydrated.Outcome != aicontracts.OutcomeFixVerified || hydrated.Action == nil {
					t.Fatal("historical investigation lost its verified action")
				}
				audit, found, err := audits.GetActionAudit(hydrated.Action.ActionID)
				if err != nil || !found {
					t.Fatalf("historical audit: found=%v err=%v", found, err)
				}
				handler.ReconcilePatrolActionTransition("default", audit)
				after := findings.Get("recurring")
				if after.ResolvedAt != nil || !after.ShouldInvestigate("full") || after.InvestigationRecord != nil {
					t.Fatalf("historical action closed occurrence %d: resolved=%v outcome=%q session=%q", occurrence, after.ResolvedAt, after.InvestigationOutcome, after.InvestigationSessionID)
				}
				if len(after.Lifecycle) != len(before.Lifecycle) {
					t.Fatal("historical action changed the current occurrence's lifecycle")
				}
			}
			if !findings.Get("recurring").ShouldInvestigate("full") {
				t.Fatal("new occurrence is not eligible for investigation")
			}
			current := investigations.Create("recurring", fmt.Sprintf("session-%d", occurrence))
			current.Status = aicontracts.InvestigationStatusCompleted
			current.Summary = "Current process stalled; restart proposed."
			investigations.Update(current)
			findings.UpdateInvestigation("recurring", current.SessionID, "running", "", nil, 1)
			for _, previous := range history {
				handler.hydratePatrolInvestigationAction("default", previous)
				if got := findings.Get("recurring"); got.ResolvedAt != nil || got.InvestigationSessionID != current.SessionID || got.InvestigationOutcome != "" {
					t.Fatal("historical result overwrote the new running investigation")
				}
			}
			audit := recurrenceVerifiedAudit(t, current)
			if _, _, err := audits.CreateActionAudit(audit, nil); err != nil {
				t.Fatal(err)
			}
			handler.ReconcilePatrolActionTransition("default", audit)
			if got := findings.Get("recurring"); got.ResolvedAt == nil || got.InvestigationOutcome != string(aicontracts.OutcomeFixVerified) || got.InvestigationRecord == nil || got.InvestigationRecord.ID != current.ID {
				t.Fatalf("current verified action did not resolve its occurrence: %#v", got)
			}
			history = append(history, current)
		})
		if t.Failed() {
			return
		}
		if occurrence < 3 {
			report()
			if occurrence == 2 {
				// Reconstruct persisted findings and action audit before the third
				// occurrence, matching the unattended controller restart.
				if err := findings.ForceSave(); err != nil {
					t.Fatal(err)
				}
				if err := audits.Close(); err != nil {
					t.Fatal(err)
				}
				audits, err = unifiedresources.NewSQLiteResourceStore(auditDirectory, "default")
				if err != nil {
					t.Fatal(err)
				}
				svc = newService()
				findings = svc.GetPatrolService().GetFindings()
				handler.defaultAIService = svc
			}
		}
	}
}

func recurrenceVerifiedAudit(t *testing.T, investigation *aicontracts.InvestigationSession) unifiedresources.ActionAuditRecord {
	t.Helper()
	now := time.Now().UTC()
	evidence := unifiedresources.ActionEvidence{Version: 1, ID: "health-" + investigation.ID,
		ObserverID: "daemon-observer", ObserverKind: "docker_daemon_observer", ObserverTrustDomain: "daemon", ExecutorTrustDomain: "agent",
		Method: "typed_docker_daemon_observation", SubjectID: "vm:42", ObservedAt: now, ReceivedAt: now, Summary: "Service health check passed"}
	canonical, err := unifiedresources.NormalizeActionResultV2(unifiedresources.ActionResultV2{Version: 2,
		Execution: unifiedresources.ActionExecutionTruth{Status: unifiedresources.ActionExecutionSucceeded},
		Verification: unifiedresources.ActionVerificationTruth{Status: unifiedresources.ActionVerificationConfirmed,
			EvidenceClass: unifiedresources.ActionEvidenceIndependent, Evidence: []unifiedresources.ActionEvidence{evidence}},
		Compensation: unifiedresources.ActionCompensationTruth{Support: unifiedresources.ActionCompensationUnavailable, Status: unifiedresources.ActionCompensationNotAvailable},
	})
	if err != nil {
		t.Fatal(err)
	}
	id := "action-" + investigation.ID
	return unifiedresources.ActionAuditRecord{ID: id, CreatedAt: now, UpdatedAt: now, State: unifiedresources.ActionStateCompleted,
		Request: unifiedresources.ActionRequest{RequestID: id, ResourceID: "vm:42", CapabilityName: "restart", RequestedBy: "pulse_patrol"},
		Plan:    unifiedresources.ActionPlan{ActionID: id, RequestID: id, Allowed: true},
		Origin:  &unifiedresources.ActionOrigin{Surface: patrolActionOriginSurface, FindingID: investigation.FindingID, InvestigationID: investigation.ID, ProposalID: id},
		Result:  &unifiedresources.ExecutionResult{Success: true, ActionResultV2: &canonical},
	}
}