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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
perf(ai): gate and batch Patrol's per-alert auto-resolve model calls
rcourtman2f967406dffa
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 8cf8dcac4f..5f48f408ba 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -4523,6 +4523,30 @@ transition. Re-detections of an already-active finding update`TimesRaised` and `LastSeenAt` only — they must not append a `detected`lifecycle event, because a heartbeat is not a transition.+Patrol's alert auto-resolve review (`reviewAndResolveAlertsState` in+`internal/ai/patrol_run.go`) is model-owned in the resolve direction+and cost-gated in the keep direction. Local state never resolves an+alert: only a parsed model RESOLVE verdict (or operator action) clears+one. But an aged active alert whose trigger condition demonstrably+still holds in the current runtime snapshot — a metric alert whose+looked-up current value is still at/above its positive threshold, or+an offline-family alert whose node/agent/VM/system-container resource+is present and still not online (`alertStillFiringState`) — must be+skipped without a billed model call, because a correct review could+only answer KEEP. Every uncertain case (unknown alert type, missing+resource, unmapped metric, non-positive threshold, resource types the+online check does not model) still goes to the model. The remaining+candidates are reviewed in batched `QuickAnalysis` calls of at most+`patrolAlertReviewBatchSize` alerts with numbered per-alert verdict+lines; verdict parsing is fail-safe (unparseable or out-of-range+verdicts default to KEEP, a bare `RESOLVE:` response is honored only+for single-alert batches), and the recorded usage events carry use+case `patrol` with `TargetType` `alert_autoresolve` so cost telemetry+can decompose alert-review spend from the main Patrol analysis pass.+This replaced the prior one-model-call-per-alert-per-run loop that+re-asked the same question about standing alerts every interval and+dominated Patrol's billed call volume in production telemetry.+The findings store now consults a `ResourceOperatorStateProvider`during the new-finding path. The interface lives in `internal/ai` toavoid an import cycle with `internal/unifiedresources`; the API layerdiff --git a/internal/ai/patrol_alerts_review_test.go b/internal/ai/patrol_alerts_review_test.goindex 2ee3d21d04..4a7bdf44ca 100644--- a/internal/ai/patrol_alerts_review_test.go+++ b/internal/ai/patrol_alerts_review_test.go@@ -5,105 +5,103 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")-func TestShouldResolveAlert_DoesNotResolveUsageWithoutModel(t *testing.T) {+func TestAlertStillFiring_MetricAtOrAboveThresholdSkipsModelReview(t *testing.T) {ps := NewPatrolService(nil, nil)- now := time.Now()-- usageAlert := AlertInfo{+ state := models.StateSnapshot{+ Storage: []models.Storage{{ID: "storage-1", Usage: 95}},+ }+ alert := AlertInfo{ID: "alert-usage",Type: "usage",ResourceID: "storage-1",Value: 92,Threshold: 90,- StartTime: now.Add(-2 * time.Hour),- }- state := models.StateSnapshot{- Storage: []models.Storage{{ID: "storage-1", Usage: 80}},- }- resolved, reason := ps.shouldResolveAlertState(context.Background(), usageAlert, patrolRuntimeStateForTest(ps, state), nil, "")- if resolved || reason != "" {- t.Fatalf("expected usage alert to remain unresolved without model review, got resolved=%v reason=%q", resolved, reason)- }-- missingAlert := AlertInfo{- ID: "alert-missing",- Type: "usage",- ResourceID: "storage-2",- Value: 95,- Threshold: 90,- StartTime: now.Add(-25 * time.Hour),}- resolved, reason = ps.shouldResolveAlertState(context.Background(), missingAlert, patrolRuntimeStateForTest(ps, state), nil, "")- if resolved || reason != "" {- t.Fatalf("expected missing storage alert to remain unresolved without model review, got resolved=%v reason=%q", resolved, reason)+ if !ps.alertStillFiringState(alert, patrolRuntimeStateForTest(ps, state)) {+ t.Fatalf("expected usage alert still above threshold to be treated as still firing")}}-func TestShouldResolveAlert_ReadStateDoesNotResolveWithoutModel(t *testing.T) {+func TestAlertStillFiring_UncertainCasesGoToModel(t *testing.T) {ps := NewPatrolService(nil, nil)- now := time.Now()- alert := AlertInfo{- ID: "alert-usage-readstate",- Type: "usage",- ResourceID: "storage-1",- Value: 92,- Threshold: 90,- StartTime: now.Add(-2 * time.Hour),- }-- registry := unifiedresources.NewRegistry(nil)- registry.IngestSnapshot(models.StateSnapshot{+ state := models.StateSnapshot{Storage: []models.Storage{{ID: "storage-1", Usage: 80}},- })+ Nodes: []models.Node{{ID: "node-1", Name: "node-1", CPU: 0.10, Status: "online"}},+ }+ snap := patrolRuntimeStateForTest(ps, state)- resolved, reason := ps.shouldResolveAlertState(context.Background(), alert, patrolRuntimeState{readState: registry}, nil, "")- if resolved || reason != "" {- t.Fatalf("expected readState alert to remain unresolved without model review, got resolved=%v reason=%q", resolved, reason)+ cases := []struct {+ name string+ alert AlertInfo+ }{+ {"metric below threshold", AlertInfo{Type: "usage", ResourceID: "storage-1", Threshold: 90}},+ {"resource missing", AlertInfo{Type: "usage", ResourceID: "storage-gone", Threshold: 90}},+ {"zero threshold", AlertInfo{Type: "cpu", ResourceID: "node-1", ResourceType: "node", Threshold: 0}},+ {"unknown alert type", AlertInfo{Type: "disk-health", ResourceID: "node-1", ResourceType: "node", Threshold: 1}},+ {"offline resource missing", AlertInfo{Type: "offline", ResourceID: "vm-gone", ResourceType: "vm"}},+ {"offline unhandled resource type", AlertInfo{Type: "offline", ResourceID: "storage-1", ResourceType: "storage"}},+ }+ for _, tc := range cases {+ if ps.alertStillFiringState(tc.alert, snap) {+ t.Errorf("%s: expected alert to go to model review, but gate claimed still firing", tc.name)+ }}}-func TestShouldResolveAlert_CPUAndOfflineDoNotResolveWithoutModel(t *testing.T) {+func TestAlertStillFiring_OfflineResourceStillDownSkipsModelReview(t *testing.T) {ps := NewPatrolService(nil, nil)- now := time.Now()-- cpuAlert := AlertInfo{- ID: "alert-cpu",- Type: "cpu",- ResourceID: "node-1",- ResourceName: "node-1",- ResourceType: "node",- Value: 95,- Threshold: 90,- StartTime: now.Add(-30 * time.Minute),- }state := models.StateSnapshot{- Nodes: []models.Node{{ID: "node-1", Name: "node-1", CPU: 0.10, Status: "online"}},- }- resolved, reason := ps.shouldResolveAlertState(context.Background(), cpuAlert, patrolRuntimeStateForTest(ps, state), nil, "")- if resolved || reason != "" {- t.Fatalf("expected cpu alert to remain unresolved without model review, got resolved=%v reason=%q", resolved, reason)+ VMs: []models.VM{{ID: "vm-1", Name: "vm-1", Status: "stopped"}},}+ snap := patrolRuntimeStateForTest(ps, state)- offlineAlert := AlertInfo{+ alert := AlertInfo{ID: "alert-offline",Type: "offline",ResourceID: "vm-1",ResourceName: "vm-1",ResourceType: "vm",- StartTime: now.Add(-30 * time.Minute),}- state.VMs = []models.VM{{ID: "vm-1", Name: "vm-1", Status: "running"}}- resolved, reason = ps.shouldResolveAlertState(context.Background(), offlineAlert, patrolRuntimeStateForTest(ps, state), nil, "")- if resolved || reason != "" {- t.Fatalf("expected offline alert to remain unresolved without model review, got resolved=%v reason=%q", resolved, reason)+ if !ps.alertStillFiringState(alert, snap) {+ t.Fatalf("expected offline alert for a still-stopped VM to be treated as still firing")+ }++ state.VMs[0].Status = "running"+ snap = patrolRuntimeStateForTest(ps, state)+ if ps.alertStillFiringState(alert, snap) {+ t.Fatalf("expected offline alert for a running VM to go to model review")+ }+}++func TestAlertStillFiring_ReadState(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ registry := unifiedresources.NewRegistry(nil)+ registry.IngestSnapshot(models.StateSnapshot{+ Storage: []models.Storage{{ID: "storage-1", Usage: 95, Used: 95, Total: 100}},+ })+ snap := patrolRuntimeState{readState: registry}++ alert := AlertInfo{+ ID: "alert-usage-readstate",+ Type: "usage",+ ResourceID: "storage-1",+ Value: 92,+ Threshold: 90,+ }+ if !ps.alertStillFiringState(alert, snap) {+ t.Fatalf("expected readState usage alert above threshold to be treated as still firing")}}-func TestReviewAndResolveAlerts(t *testing.T) {+// Without a model, nothing resolves — Pulse must not use local heuristics to+// decide an issue has cleared, even when the metric has dropped below its+// threshold.+func TestReviewAndResolveAlerts_NoModelResolvesNothing(t *testing.T) {ps := NewPatrolService(nil, nil)resolver := &stubAlertResolver{}ps.alertResolver = resolver@@ -128,6 +126,7 @@ func TestReviewAndResolveAlerts(t *testing.T) {},}+ // Usage has dropped below threshold — only a model review may resolve.state := models.StateSnapshot{Storage: []models.Storage{{ID: "storage-1", Usage: 70}}}resolved := ps.reviewAndResolveAlertsState(context.Background(), patrolRuntimeStateForTest(ps, state), false, "")if resolved != 0 {@@ -137,3 +136,93 @@ func TestReviewAndResolveAlerts(t *testing.T) {t.Fatalf("expected no alerts to be resolved, got %v", resolver.clears)}}++func TestReviewAndResolveAlerts_StillFiringMakesNoModelCalls(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ resolver := &stubAlertResolver{}+ ps.alertResolver = resolver+ provider := &mockPatrolProvider{response: "ALERT 1: RESOLVE: should never be asked"}+ ps.aiService = &Service{+ provider: provider,+ cfg: &config.AIConfig{Enabled: true, PatrolModel: "mock:model"},+ }++ now := time.Now()+ resolver.alerts = []AlertInfo{+ {+ ID: "still-firing",+ Type: "usage",+ ResourceID: "storage-1",+ Value: 95,+ Threshold: 90,+ StartTime: now.Add(-2 * time.Hour),+ },+ }++ // Usage still above threshold — the review could only answer KEEP.+ state := models.StateSnapshot{Storage: []models.Storage{{ID: "storage-1", Usage: 95}}}+ resolved := ps.reviewAndResolveAlertsState(context.Background(), patrolRuntimeStateForTest(ps, state), true, "")+ if resolved != 0 {+ t.Fatalf("expected no resolutions, got %d", resolved)+ }+ if provider.calls != 0 {+ t.Fatalf("expected no model calls for a still-firing alert, got %d", provider.calls)+ }+ if len(resolver.clears) != 0 {+ t.Fatalf("expected no alerts to be resolved, got %v", resolver.clears)+ }+}++func TestReviewAndResolveAlerts_BatchedModelReviewResolves(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ resolver := &stubAlertResolver{}+ ps.alertResolver = resolver+ provider := &mockPatrolProvider{response: "ALERT 1: RESOLVE: usage back to normal\nALERT 2: KEEP: still verifying"}+ ps.aiService = &Service{+ provider: provider,+ cfg: &config.AIConfig{Enabled: true, PatrolModel: "mock:model"},+ }++ now := time.Now()+ resolver.alerts = []AlertInfo{+ {+ ID: "cleared",+ Type: "usage",+ ResourceID: "storage-1",+ Value: 95,+ Threshold: 90,+ StartTime: now.Add(-2 * time.Hour),+ },+ {+ ID: "ambiguous",+ Type: "offline",+ ResourceID: "vm-1",+ ResourceName: "vm-1",+ ResourceType: "vm",+ StartTime: now.Add(-2 * time.Hour),+ },+ {+ ID: "too-recent",+ Type: "usage",+ ResourceID: "storage-1",+ Value: 95,+ Threshold: 90,+ StartTime: now.Add(-5 * time.Minute),+ },+ }++ state := models.StateSnapshot{+ Storage: []models.Storage{{ID: "storage-1", Usage: 70}},+ VMs: []models.VM{{ID: "vm-1", Name: "vm-1", Status: "running"}},+ }+ resolved := ps.reviewAndResolveAlertsState(context.Background(), patrolRuntimeStateForTest(ps, state), true, "")+ if provider.calls != 1 {+ t.Fatalf("expected one batched model call for two review candidates, got %d", provider.calls)+ }+ if resolved != 1 {+ t.Fatalf("expected exactly one resolution, got %d", resolved)+ }+ if len(resolver.clears) != 1 || resolver.clears[0] != "cleared" {+ t.Fatalf("expected only the model-resolved alert to clear, got %v", resolver.clears)+ }+}diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.goindex 471cd46eb1..664bf81e2e 100644--- a/internal/ai/patrol_run.go+++ b/internal/ai/patrol_run.go@@ -7,6 +7,7 @@ import ("context""crypto/sha256""fmt"+ "regexp""strconv""strings""time"@@ -2156,6 +2157,15 @@ func (p *PatrolService) GetCurrentStreamOutput() (string, string) {// reviewAndResolveAlerts uses AI to review active alerts and resolve those where the issue is fixed.// This is the core of autonomous alert management - the AI looks at each alert, checks current state,// and determines if the underlying issue has been resolved.+//+// Two structural cost controls run before any model call:+// - alerts whose trigger condition demonstrably still holds in the current+// snapshot (metric still at/above threshold, resource still offline) are+// skipped — a correct review could only answer KEEP, so the question is+// not worth a billed call. Resolution stays model-owned: Pulse never+// locally decides that an issue HAS cleared.+// - the remaining candidates are reviewed in batched model calls instead+// of one call per alert.func (p *PatrolService) reviewAndResolveAlertsState(ctx context.Context, state patrolRuntimeState, llmAllowed bool, executionID string) int {p.mu.RLock()resolver := p.alertResolver@@ -2171,44 +2181,58 @@ func (p *PatrolService) reviewAndResolveAlertsState(ctx context.Context, state preturn 0}+ aiSvc := aiService+ if !llmAllowed {+ aiSvc = nil+ }+ if aiSvc == nil || !aiSvc.IsEnabled() {+ return 0+ }+// Only review alerts that have been active for at least 10 minutes// This avoids thrashing on transient alertsminAge := 10 * time.Minutevar alertsToReview []AlertInfo+ stillFiring := 0for _, alert := range activeAlerts {- if time.Since(alert.StartTime) >= minAge {- alertsToReview = append(alertsToReview, alert)+ if time.Since(alert.StartTime) < minAge {+ continue}+ if p.alertStillFiringState(alert, state) {+ stillFiring+++ continue+ }+ alertsToReview = append(alertsToReview, alert)}if len(alertsToReview) == 0 {+ if stillFiring > 0 {+ log.Debug().+ Int("still_firing", stillFiring).+ Msg("AI Patrol: All aged alerts still demonstrably firing, skipping model review")+ }return 0}log.Info().Int("total_active", len(activeAlerts)).Int("to_review", len(alertsToReview)).+ Int("still_firing_skipped", stillFiring).Msg("AI Patrol: Reviewing alerts for auto-resolution")resolvedCount := 0-- aiSvc := aiService- if !llmAllowed {- aiSvc = nil- }-- for _, alert := range alertsToReview {- shouldResolve, reason := p.shouldResolveAlertState(ctx, alert, state, aiSvc, executionID)- if shouldResolve {- if resolver.ResolveAlert(alert.ID) {- resolvedCount++- log.Info().- Str("alertID", alert.ID).- Str("resource", alert.ResourceName).- Str("reason", reason).- Dur("age", time.Since(alert.StartTime)).- Msg("AI Patrol: Auto-resolved alert - issue no longer detected")- }+ for _, verdict := range p.reviewAlertsWithModelState(ctx, alertsToReview, state, aiSvc, executionID) {+ if !verdict.resolve {+ continue+ }+ if resolver.ResolveAlert(verdict.alert.ID) {+ resolvedCount+++ log.Info().+ Str("alertID", verdict.alert.ID).+ Str("resource", verdict.alert.ResourceName).+ Str("reason", verdict.reason).+ Dur("age", time.Since(verdict.alert.StartTime)).+ Msg("AI Patrol: Auto-resolved alert - issue no longer detected")}}@@ -2221,16 +2245,39 @@ func (p *PatrolService) reviewAndResolveAlertsState(ctx context.Context, state preturn resolvedCount}-// shouldResolveAlert determines if an alert should be auto-resolved based on-// model review of current state. Pulse can gather context and enforce the-// resolution gate, but it must not use local alert-type heuristics to decide-// that an infrastructure issue has cleared.-func (p *PatrolService) shouldResolveAlertState(ctx context.Context, alert AlertInfo, snap patrolRuntimeState, aiService *Service, executionID string) (bool, string) {- if aiService != nil && aiService.IsEnabled() {- return p.askAIAboutAlertState(ctx, alert, snap, aiService, executionID)+// alertStillFiringState reports whether the current runtime snapshot still+// demonstrably shows the alert's trigger condition — a metric alert whose+// current value is still at or above its threshold, or an offline alert+// whose resource is still not online. For these alerts a correct model+// review can only answer KEEP, so Patrol skips the billed call and keeps+// the alert. The gate never decides that an issue HAS cleared: anything+// uncertain (unknown alert type, missing resource, unmapped metric)+// returns false so the model still owns the resolution decision.+func (p *PatrolService) alertStillFiringState(alert AlertInfo, snap patrolRuntimeState) bool {+ switch alert.Type {+ case "cpu", "memory", "usage", "disk":+ if alert.Threshold <= 0 {+ return false+ }+ // getCurrentMetricValueState returns -1 when the resource or metric+ // is unknown, which can never satisfy a positive threshold.+ return p.getCurrentMetricValueState(alert, snap) >= alert.Threshold+ case "offline", "powered-off", "host-offline":+ resource := lookupPatrolAlertResourceState(alert, snap)+ if !resource.found {+ // Resource is gone from the snapshot — the model should judge+ // whether the alert resolves as removed.+ return false+ }+ switch resource.resourceType {+ case "node", "agent", "vm", "system-container":+ return !p.isResourceOnlineState(alert, snap)+ default:+ return false+ }+ default:+ return false}-- return false, ""}// getCurrentMetricValue gets the current value of the metric that triggered the alert@@ -2462,53 +2509,129 @@ func (p *PatrolService) isResourceOnlineState(alert AlertInfo, snap patrolRuntim}}-// askAIAboutAlert uses the AI to determine if an alert should be resolved-func (p *PatrolService) askAIAboutAlertState(ctx context.Context, alert AlertInfo, snap patrolRuntimeState, aiService *Service, executionID string) (bool, string) {- alertType := patrolAlertLookupType(alert)- // Build a focused prompt for the AI- prompt := fmt.Sprintf(`Review this alert and determine if it should be auto-resolved based on current state.+// patrolAlertReviewBatchSize caps how many alerts are reviewed per model+// call so a large alert backlog cannot build an unbounded prompt.+const patrolAlertReviewBatchSize = 20-ALERT:-- ID: %s-- Type: %s-- Resource: %s (%s)-- Message: %s-- Value when triggered: %.1f-- Threshold: %.1f-- Active for: %s+type patrolAlertReviewVerdict struct {+ alert AlertInfo+ resolve bool+ reason string+}-CURRENT STATE OF THIS RESOURCE:-%s+// patrolAlertVerdictLine matches one per-alert verdict line in a batched+// alert-review model response, e.g. "ALERT 2: RESOLVE: usage back to 40%".+var patrolAlertVerdictLine = regexp.MustCompile(`(?im)^\s*ALERT\s+(\d+)\s*:\s*(RESOLVE|KEEP)\b\s*:?\s*(.*)$`)++// reviewAlertsWithModelState reviews the candidate alerts with the model in+// batched calls and returns one verdict per alert, in order. Alerts whose+// verdict cannot be parsed from the model response default to KEEP.+func (p *PatrolService) reviewAlertsWithModelState(ctx context.Context, candidates []AlertInfo, snap patrolRuntimeState, aiService *Service, executionID string) []patrolAlertReviewVerdict {+ verdicts := make([]patrolAlertReviewVerdict, 0, len(candidates))+ for start := 0; start < len(candidates); start += patrolAlertReviewBatchSize {+ end := min(start+patrolAlertReviewBatchSize, len(candidates))+ verdicts = append(verdicts, p.reviewAlertBatchState(ctx, candidates[start:end], snap, aiService, executionID)...)+ }+ return verdicts+}-Should this alert be RESOLVED because the underlying issue is fixed?-Respond with ONLY one of:-- RESOLVE: <brief reason>-- KEEP: <brief reason>`,- alert.ID, alert.Type, alert.ResourceName, alertType,- alert.Message, alert.Value, alert.Threshold, alert.Duration,- p.getResourceCurrentStateState(alert, snap))+// reviewAlertBatchState asks the model for a RESOLVE/KEEP verdict on each+// alert in one call. Any error or unparseable verdict keeps the alert —+// the fail-safe direction matches the single-alert behavior this replaces.+func (p *PatrolService) reviewAlertBatchState(ctx context.Context, batch []AlertInfo, snap patrolRuntimeState, aiService *Service, executionID string) []patrolAlertReviewVerdict {+ verdicts := make([]patrolAlertReviewVerdict, len(batch))+ for i, alert := range batch {+ verdicts[i] = patrolAlertReviewVerdict{alert: alert}+ }// Use a quick, low-cost AI callresponse, err := aiService.QuickAnalysis(ctx, QuickAnalysisRequest{- Prompt: prompt,+ Prompt: p.buildAlertReviewPromptState(batch, snap),ExecutionID: executionID,UseCase: "patrol",+ TargetType: "alert_autoresolve",})if err != nil {- log.Debug().Err(err).Str("alertID", alert.ID).Msg("AI Patrol: Failed to get AI judgment on alert")- return false, ""+ log.Debug().Err(err).Int("alerts", len(batch)).Msg("AI Patrol: Failed to get AI judgment on alert batch")+ return verdicts+ }++ matched := applyAlertReviewResponse(verdicts, response)++ // Single-alert fallback: accept a bare "RESOLVE: <reason>" response+ // without the "ALERT 1:" prefix, matching the pre-batch prompt contract.+ if len(batch) == 1 && !matched {+ trimmed := strings.TrimSpace(response)+ if strings.HasPrefix(strings.ToUpper(trimmed), "RESOLVE:") {+ verdicts[0].resolve = true+ verdicts[0].reason = patrolAlertResolveReason(strings.TrimPrefix(trimmed[len("RESOLVE:"):], " "))+ }}- response = strings.TrimSpace(response)- if strings.HasPrefix(strings.ToUpper(response), "RESOLVE:") {- reason := strings.TrimSpace(strings.TrimPrefix(response, "RESOLVE:"))- if reason == "" {- reason = strings.TrimSpace(strings.TrimPrefix(strings.ToUpper(response), "RESOLVE:"))+ return verdicts+}++// buildAlertReviewPromptState formats the batched alert-review prompt: one+// numbered section per alert with its trigger details and current resource+// state, plus strict per-line verdict output instructions.+func (p *PatrolService) buildAlertReviewPromptState(batch []AlertInfo, snap patrolRuntimeState) string {+ var sb strings.Builder+ sb.WriteString("Review these active alerts and determine, for each, if it should be auto-resolved based on current state.\n")+ for i, alert := range batch {+ alertType := patrolAlertLookupType(alert)+ sb.WriteString(fmt.Sprintf(`+ALERT %d:+- ID: %s+- Type: %s+- Resource: %s (%s)+- Message: %s+- Value when triggered: %.1f+- Threshold: %.1f+- Active for: %s++CURRENT STATE OF THIS RESOURCE:+%s+`,+ i+1, alert.ID, alert.Type, alert.ResourceName, alertType,+ alert.Message, alert.Value, alert.Threshold, alert.Duration,+ p.getResourceCurrentStateState(alert, snap)))+ }+ sb.WriteString(`+For each alert, should it be RESOLVED because the underlying issue is fixed?+Respond with EXACTLY one line per alert, in order, and nothing else:+ALERT <number>: RESOLVE: <brief reason>+or+ALERT <number>: KEEP: <brief reason>`)+ return sb.String()+}++// applyAlertReviewResponse parses per-alert verdict lines from the model+// response into verdicts. The first line seen for each alert number wins;+// out-of-range numbers are ignored. Returns whether any line matched.+func applyAlertReviewResponse(verdicts []patrolAlertReviewVerdict, response string) bool {+ matched := false+ seen := make(map[int]bool)+ for _, m := range patrolAlertVerdictLine.FindAllStringSubmatch(response, -1) {+ idx, err := strconv.Atoi(m[1])+ if err != nil || idx < 1 || idx > len(verdicts) || seen[idx] {+ continue+ }+ seen[idx] = true+ matched = true+ if strings.EqualFold(m[2], "RESOLVE") {+ verdicts[idx-1].resolve = true+ verdicts[idx-1].reason = patrolAlertResolveReason(m[3])}- return true, "Patrol: " + reason}+ return matched+}- return false, ""+func patrolAlertResolveReason(raw string) string {+ reason := strings.TrimSpace(raw)+ if reason == "" {+ reason = "issue no longer detected"+ }+ return "Patrol: " + reason}// getResourceCurrentState returns a description of the resource's current statediff --git a/internal/ai/patrol_run_additional_test.go b/internal/ai/patrol_run_additional_test.goindex dcb2c6efc0..56c399dfd6 100644--- a/internal/ai/patrol_run_additional_test.go+++ b/internal/ai/patrol_run_additional_test.go@@ -2,6 +2,7 @@ package aiimport ("context"+ "fmt""strings""testing""time"@@ -16,10 +17,12 @@ type mockPatrolProvider struct {response stringerr errorlastReq providers.ChatRequest+ calls int}func (m *mockPatrolProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {m.lastReq = req+ m.calls++if m.err != nil {return nil, m.err}@@ -43,7 +46,71 @@ type mockPatrolStateProvider struct {func (m mockPatrolStateProvider) ReadSnapshot() models.StateSnapshot { return m.state }-func TestPatrolService_AskAIAboutAlert(t *testing.T) {+func TestPatrolService_ReviewAlertBatch(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ provider := &mockPatrolProvider{response: "ALERT 1: RESOLVE: cpu back to normal\nALERT 2: KEEP: still high"}+ aiSvc := &Service{+ provider: provider,+ cfg: &config.AIConfig{PatrolModel: "mock:model"},+ }++ alertsToReview := []AlertInfo{+ {+ ID: "a1",+ Type: "cpu",+ ResourceName: "node1",+ ResourceType: "node",+ Message: "high cpu",+ Value: 90,+ Threshold: 80,+ Duration: "5m",+ },+ {+ ID: "a-usage",+ Type: "usage",+ ResourceName: "local",+ ResourceType: "usage",+ ResourceID: "storage-1",+ Message: "high usage",+ Value: 92,+ Threshold: 90,+ Duration: "20m",+ },+ }+ state := models.StateSnapshot{+ Nodes: []models.Node{{ID: "node1", Name: "node1", CPU: 10}},+ Storage: []models.Storage{{ID: "storage-1", Name: "local", Usage: 91, Status: "active"}},+ }++ verdicts := ps.reviewAlertsWithModelState(context.Background(), alertsToReview, patrolRuntimeStateForTest(ps, state), aiSvc, "patrol-run-123")+ if provider.calls != 1 {+ t.Fatalf("expected one batched model call for two alerts, got %d", provider.calls)+ }+ if len(verdicts) != 2 {+ t.Fatalf("expected one verdict per alert, got %d", len(verdicts))+ }+ if !verdicts[0].resolve {+ t.Fatalf("expected first alert to resolve")+ }+ if !strings.Contains(verdicts[0].reason, "cpu back to normal") {+ t.Fatalf("expected resolution reason, got %q", verdicts[0].reason)+ }+ if verdicts[1].resolve {+ t.Fatalf("expected second alert to stay unresolved")+ }+ prompt := provider.lastReq.Messages[1].Content+ if !strings.Contains(prompt, "Resource: node1 (node)") {+ t.Fatalf("expected prompt to include canonical node resource type, got %q", prompt)+ }+ if !strings.Contains(prompt, "Resource: local (storage)") {+ t.Fatalf("expected prompt to normalize usage alerts to storage, got %q", prompt)+ }+ if provider.lastReq.ExecutionID != "patrol-run-123" {+ t.Fatalf("execution_id=%q want patrol-run-123", provider.lastReq.ExecutionID)+ }+}++func TestPatrolService_ReviewAlertBatch_SingleAlertBareResolveFallback(t *testing.T) {ps := NewPatrolService(nil, nil)provider := &mockPatrolProvider{response: "RESOLVE: looks good"}aiSvc := &Service{@@ -56,55 +123,73 @@ func TestPatrolService_AskAIAboutAlert(t *testing.T) {Type: "cpu",ResourceName: "node1",ResourceType: "node",- Message: "high cpu",Value: 90,Threshold: 80,- Duration: "5m",}state := models.StateSnapshot{Nodes: []models.Node{{ID: "node1", Name: "node1", CPU: 10}}}- resolved, reason := ps.askAIAboutAlertState(context.Background(), alert, patrolRuntimeStateForTest(ps, state), aiSvc, "patrol-run-123")- if !resolved {- t.Fatalf("expected alert to resolve")+ verdicts := ps.reviewAlertsWithModelState(context.Background(), []AlertInfo{alert}, patrolRuntimeStateForTest(ps, state), aiSvc, "patrol-run-bare")+ if len(verdicts) != 1 || !verdicts[0].resolve {+ t.Fatalf("expected bare RESOLVE response to resolve the single alert, got %+v", verdicts)}- if reason == "" {- t.Fatalf("expected resolution reason")+ if !strings.Contains(verdicts[0].reason, "looks good") {+ t.Fatalf("expected resolution reason, got %q", verdicts[0].reason)}- if !strings.Contains(provider.lastReq.Messages[1].Content, "Resource: node1 (node)") {- t.Fatalf("expected prompt to include canonical node resource type, got %q", provider.lastReq.Messages[1].Content)+}++func TestPatrolService_ReviewAlertBatch_UnparseableKeepsAll(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ provider := &mockPatrolProvider{response: "Everything appears to be operating within normal parameters."}+ aiSvc := &Service{+ provider: provider,+ cfg: &config.AIConfig{PatrolModel: "mock:model"},}- if provider.lastReq.ExecutionID != "patrol-run-123" {- t.Fatalf("execution_id=%q want patrol-run-123", provider.lastReq.ExecutionID)++ alertsToReview := []AlertInfo{+ {ID: "a1", Type: "cpu", ResourceName: "node1", ResourceType: "node"},+ {ID: "a2", Type: "memory", ResourceName: "node1", ResourceType: "node"},+ }+ state := models.StateSnapshot{Nodes: []models.Node{{ID: "node1", Name: "node1"}}}++ verdicts := ps.reviewAlertsWithModelState(context.Background(), alertsToReview, patrolRuntimeStateForTest(ps, state), aiSvc, "")+ for i, v := range verdicts {+ if v.resolve {+ t.Fatalf("expected unparseable response to keep alert %d, got %+v", i, v)+ }}}-func TestPatrolService_AskAIAboutAlert_NormalizesUsageType(t *testing.T) {+func TestPatrolService_ReviewAlertBatch_ChunksLargeBacklogs(t *testing.T) {ps := NewPatrolService(nil, nil)- provider := &mockPatrolProvider{response: "KEEP: still high"}+ provider := &mockPatrolProvider{response: "ALERT 1: KEEP: still investigating"}aiSvc := &Service{provider: provider,cfg: &config.AIConfig{PatrolModel: "mock:model"},}- alert := AlertInfo{- ID: "a-usage",- Type: "usage",- ResourceName: "local",- ResourceType: "usage",- ResourceID: "storage-1",- Message: "high usage",- Value: 92,- Threshold: 90,- Duration: "20m",- }- state := models.StateSnapshot{Storage: []models.Storage{{ID: "storage-1", Name: "local", Usage: 91, Status: "active"}}}-- resolved, _ := ps.askAIAboutAlertState(context.Background(), alert, patrolRuntimeStateForTest(ps, state), aiSvc, "patrol-run-usage")- if resolved {- t.Fatalf("expected alert to stay unresolved")- }- if !strings.Contains(provider.lastReq.Messages[1].Content, "Resource: local (storage)") {- t.Fatalf("expected prompt to normalize usage alerts to storage, got %q", provider.lastReq.Messages[1].Content)+ alertsToReview := make([]AlertInfo, patrolAlertReviewBatchSize+1)+ for i := range alertsToReview {+ alertsToReview[i] = AlertInfo{ID: fmt.Sprintf("a%d", i), Type: "cpu", ResourceName: "node1", ResourceType: "node"}+ }+ state := models.StateSnapshot{Nodes: []models.Node{{ID: "node1", Name: "node1"}}}++ verdicts := ps.reviewAlertsWithModelState(context.Background(), alertsToReview, patrolRuntimeStateForTest(ps, state), aiSvc, "")+ if provider.calls != 2 {+ t.Fatalf("expected %d alerts to review in 2 chunked calls, got %d calls", len(alertsToReview), provider.calls)+ }+ if len(verdicts) != len(alertsToReview) {+ t.Fatalf("expected %d verdicts, got %d", len(alertsToReview), len(verdicts))+ }+}++func TestApplyAlertReviewResponse_FirstLinePerAlertWins(t *testing.T) {+ verdicts := []patrolAlertReviewVerdict{{alert: AlertInfo{ID: "a1"}}}+ matched := applyAlertReviewResponse(verdicts, "ALERT 1: RESOLVE: fixed\nALERT 1: KEEP: on second thought\nALERT 9: RESOLVE: out of range")+ if !matched {+ t.Fatalf("expected verdict lines to match")+ }+ if !verdicts[0].resolve {+ t.Fatalf("expected first verdict line to win, got %+v", verdicts[0])}}diff --git a/internal/ai/patrol_run_test.go b/internal/ai/patrol_run_test.goindex e6dd001742..9e96481126 100644--- a/internal/ai/patrol_run_test.go+++ b/internal/ai/patrol_run_test.go@@ -2035,99 +2035,69 @@ func TestAlertResolutionHelpers_UseReadStateForAppContainer(t *testing.T) {}}-// --- shouldResolveAlert (model-owned, no local auto-resolution without AI) ---+// --- alert auto-resolve review (model-owned, no local auto-resolution without AI) ----func TestShouldResolveAlert_StorageUsageDroppedDoesNotResolveWithoutAI(t *testing.T) {+// Alerts whose trigger condition may have cleared go to model review; without+// a model available, nothing resolves — local state never resolves an alert.+func TestReviewAndResolveAlerts_ClearedConditionsDoNotResolveWithoutAI(t *testing.T) {ps := NewPatrolService(nil, nil)- state := models.StateSnapshot{- Storage: []models.Storage{- {ID: "s1", Name: "local", Usage: 70.0, Status: "active"},- },- }-- alert := AlertInfo{- ID: "a1",- ResourceID: "s1",- ResourceType: "usage",- Type: "usage",- Threshold: 85.0,- Value: 88.0,- StartTime: time.Now().Add(-1 * time.Hour),- }-- shouldResolve, reason := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")- if shouldResolve || reason != "" {- t.Errorf("expected alert to remain unresolved without AI review, got resolved=%v reason=%q", shouldResolve, reason)- }-}--func TestShouldResolveAlert_CPUDroppedDoesNotResolveWithoutAI(t *testing.T) {- ps := NewPatrolService(nil, nil)- state := models.StateSnapshot{- Nodes: []models.Node{- {ID: "n1", Name: "node-1", CPU: 0.5, Memory: models.Memory{Usage: 40.0}},+ resolver := &mockAlertResolver{+ alerts: []AlertInfo{+ {+ ID: "a-usage",+ ResourceID: "s1",+ ResourceType: "usage",+ Type: "usage",+ Threshold: 85.0,+ Value: 88.0,+ StartTime: time.Now().Add(-1 * time.Hour),+ },+ {+ ID: "a-cpu",+ ResourceID: "n1",+ ResourceType: "node",+ Type: "cpu",+ Threshold: 90.0,+ Value: 95.0,+ StartTime: time.Now().Add(-30 * time.Minute),+ },+ {+ ID: "a-offline",+ ResourceID: "n1",+ ResourceType: "node",+ Type: "offline",+ StartTime: time.Now().Add(-1 * time.Hour),+ },+ {+ ID: "a-missing",+ ResourceID: "gone",+ ResourceType: "node",+ Type: "cpu",+ Threshold: 90.0,+ Value: 95.0,+ StartTime: time.Now().Add(-30 * time.Minute),+ },},}+ ps.mu.Lock()+ ps.alertResolver = resolver+ ps.mu.Unlock()- alert := AlertInfo{- ID: "a1",- ResourceID: "n1",- ResourceType: "node",- Type: "cpu",- Threshold: 90.0,- Value: 95.0,- StartTime: time.Now().Add(-30 * time.Minute),- }-- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")- if shouldResolve {- t.Error("expected alert to remain unresolved without AI review")- }-}--func TestShouldResolveAlert_OfflineNowOnlineDoesNotResolveWithoutAI(t *testing.T) {- ps := NewPatrolService(nil, nil)state := models.StateSnapshot{- Nodes: []models.Node{- {ID: "n1", Name: "node-1", Status: "online"},- },- }-- alert := AlertInfo{- ID: "a1",- ResourceID: "n1",- ResourceType: "node",- Type: "offline",- StartTime: time.Now().Add(-1 * time.Hour),- }-- shouldResolve, reason := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")- if shouldResolve || reason != "" {- t.Errorf("expected offline alert to remain unresolved without AI review, got resolved=%v reason=%q", shouldResolve, reason)+ Storage: []models.Storage{{ID: "s1", Name: "local", Usage: 70.0, Status: "active"}},+ Nodes: []models.Node{{ID: "n1", Name: "node-1", CPU: 0.5, Memory: models.Memory{Usage: 40.0}, Status: "online"}},}-}-func TestShouldResolveAlert_NoMatch(t *testing.T) {- ps := NewPatrolService(nil, nil)- state := models.StateSnapshot{} // resource not in state-- alert := AlertInfo{- ID: "a1",- ResourceID: "n1",- ResourceType: "node",- Type: "cpu",- Threshold: 90.0,- Value: 95.0,- StartTime: time.Now().Add(-30 * time.Minute),+ result := ps.reviewAndResolveAlertsState(nil, patrolRuntimeStateForTest(ps, state), true, "")+ if result != 0 {+ t.Errorf("expected no alerts resolved without AI review, got %d", result)}-- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")- if shouldResolve {- t.Error("expected alert NOT to be resolved when resource not found")+ if len(resolver.resolved) != 0 {+ t.Errorf("expected no alerts resolved without AI review, got %v", resolver.resolved)}}-func TestShouldResolveAlert_StorageStillHigh(t *testing.T) {+func TestAlertStillFiring_StorageStillHigh(t *testing.T) {ps := NewPatrolService(nil, nil)state := models.StateSnapshot{Storage: []models.Storage{@@ -2145,16 +2115,17 @@ func TestShouldResolveAlert_StorageStillHigh(t *testing.T) {StartTime: time.Now().Add(-1 * time.Hour),}- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")- if shouldResolve {- t.Error("expected alert NOT to be resolved (storage usage still above threshold)")+ if !ps.alertStillFiringState(alert, patrolRuntimeStateForTest(ps, state)) {+ t.Error("expected still-above-threshold storage alert to be treated as still firing")}}-// Regression test: CPU at 95% (0.95 raw) must NOT auto-resolve a 90% threshold alert.-// Before the fix, getCurrentMetricValue returned 0.95 (raw fraction) which was always-// below the 90.0 percentage threshold, causing every CPU alert to incorrectly auto-resolve.-func TestShouldResolveAlert_CPUScaleRegression(t *testing.T) {+// Regression test: node CPU is a 0-1 fraction in the model snapshot and must be+// scaled to a percentage before threshold comparison. Before the fix,+// getCurrentMetricValue returned 0.95 (raw fraction) which was always below the+// 90.0 percentage threshold — under the still-firing gate that would send every+// high-CPU alert to a pointless model review on every run.+func TestAlertStillFiring_CPUScaleRegression(t *testing.T) {ps := NewPatrolService(nil, nil)state := models.StateSnapshot{Nodes: []models.Node{@@ -2172,9 +2143,8 @@ func TestShouldResolveAlert_CPUScaleRegression(t *testing.T) {StartTime: time.Now().Add(-30 * time.Minute),}- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")- if shouldResolve {- t.Error("expected CPU alert NOT to be resolved (95% is still above 90% threshold)")+ if !ps.alertStillFiringState(alert, patrolRuntimeStateForTest(ps, state)) {+ t.Error("expected 95% CPU against a 90% threshold to be treated as still firing")}}diff --git a/internal/ai/service.go b/internal/ai/service.goindex 55395e996d..5c9c89f7b3 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -214,6 +214,10 @@ type QuickAnalysisRequest struct {Prompt string `json:"prompt"`ExecutionID string `json:"execution_id,omitempty"`UseCase string `json:"use_case,omitempty"`+ // TargetType tags the recorded usage event so cost telemetry can+ // distinguish sub-workloads sharing a use case (e.g. patrol alert+ // auto-resolve reviews vs the main patrol pass).+ TargetType string `json:"target_type,omitempty"`}// PatrolStreamResponse contains the results of a patrol execution via the chat service@@ -1880,6 +1884,7 @@ func (s *Service) QuickAnalysis(ctx context.Context, req QuickAnalysisRequest) (RequestModel: model,ResponseModel: resp.Model,UseCase: useCase,+ TargetType: strings.TrimSpace(req.TargetType),InputTokens: resp.InputTokens,OutputTokens: resp.OutputTokens,})