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
Sweep missing Patrol verdicts with a bounded follow-up pass
rcourtmanbdebc0242ff4
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex c982d83701..ada43eaf45 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -103,6 +103,17 @@ calls remain authoritative and must not be repeated; the repair projectioncontains only finding lifecycle tools and may correct only the rejected callsfrom the returned validation evidence. A repair attempt never erases theoriginal failed call from run history or qualification scoring.+When the main analysis pass completes without a provider error but leaves+seeded or queried active findings with no accepted verdict, the run performs+one bounded assessment sweep before the incomplete-assessment error is+recorded: a follow-up pass on the `patrol-assess` session that presents+exactly the missing findings (id, title, severity, resource, truncated stored+evidence), runs through the same tool executor so `patrol_assess_finding`+verdicts land via the shared adapter and tolerant ID resolution, forbids+further investigation and new findings, accepts `uncertain` as a complete+honest verdict, and is capped at the missing-finding count plus two turns,+never more than twelve. Verdicts still missing after the sweep keep the+existing run-level incomplete-assessment error.Investigation and interactive profiles retain a tool-free final summary; aWatch finding write at the deadline is followed only by the existing boundedsummary path. A capability-unavailablediff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex fddde80a36..43054186c6 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -933,10 +933,119 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRunti}}+ // --- Assessment completion sweep ---+ // Smaller models sometimes end the main pass without filing a+ // patrol_assess_finding verdict for every active finding, which turns an+ // otherwise healthy run into "Patrol needs attention" on every cycle.+ // Give the model one bounded follow-up pass scoped to exactly the missing+ // verdicts before the run is declared incomplete.+ if missing := patrolMissingAssessmentIDs(buildAnalysisResult(finalContent, collectedToolCalls, inputTokens, outputTokens)); len(missing) > 0 {+ log.Warn().+ Int("missing_assessments", len(missing)).+ Msg("AI Patrol: Verdicts missing after main pass, running assessment sweep")++ sweepResp, sweepErr := p.runAssessmentSweep(ctx, missing, executionID)+ if sweepErr != nil {+ log.Warn().Err(sweepErr).Msg("AI Patrol: Assessment sweep failed")+ } else if sweepResp != nil {+ inputTokens += sweepResp.InputTokens+ outputTokens += sweepResp.OutputTokens+ remaining := patrolMissingAssessmentIDs(buildAnalysisResult(finalContent, collectedToolCalls, inputTokens, outputTokens))+ log.Info().+ Int("swept", len(missing)-len(remaining)).+ Int("remaining", len(remaining)).+ Msg("AI Patrol: Assessment sweep completed")+ }+ }+// Findings were already created via tool calls — collect themreturn buildAnalysisResult(finalContent, collectedToolCalls, inputTokens, outputTokens), nil}+// runAssessmentSweep runs a bounded follow-up model pass that files the+// patrol_assess_finding verdicts the main pass left missing. Uncertain is an+// accepted verdict, so the pass asks for an honest call on the presented+// evidence instead of a re-investigation.+func (p *PatrolService) runAssessmentSweep(ctx context.Context, missingIDs []string, executionID string) (*PatrolStreamResponse, error) {+ cs := p.aiService.GetChatService()+ if cs == nil {+ return nil, fmt.Errorf("chat service not available for assessment sweep")+ }+ if err := p.aiService.CheckBudget("patrol"); err != nil {+ log.Warn().Err(err).Msg("AI Patrol: Budget exceeded, skipping assessment sweep")+ return nil, fmt.Errorf("patrol assessment sweep skipped: %w", err)+ }++ pending := make([]*Finding, 0, len(missingIDs))+ for _, findingID := range missingIDs {+ if finding := p.findings.Get(findingID); finding != nil {+ pending = append(pending, finding)+ }+ }+ if len(pending) == 0 {+ return nil, nil+ }++ maxTurns := len(pending) + 2+ if maxTurns > 12 {+ maxTurns = 12+ }++ resp, err := cs.ExecutePatrolStream(ctx, PatrolExecuteRequest{+ Prompt: buildAssessmentSweepUserPrompt(pending),+ SystemPrompt: buildAssessmentSweepSystemPrompt(),+ SessionID: "patrol-assess",+ ExecutionID: executionID,+ UseCase: "patrol",+ MaxTurns: maxTurns,+ }, func(event ChatStreamEvent) {+ // Not streamed to the frontend — verdicts land via the adapter.+ })++ if resp != nil {+ p.recordPatrolUsage(resp.InputTokens, resp.OutputTokens)+ }+ if err != nil {+ return nil, err+ }+ return resp, nil+}++func buildAssessmentSweepSystemPrompt() string {+ return `You are completing a patrol run. The main pass ended without filing a verdict for every active finding.++Tools: patrol_assess_finding++Instructions:+1. For EACH finding listed below, call patrol_assess_finding exactly once, copying the finding id exactly as shown.+2. Use verdict "present" when the evidence shows the issue continues, "resolved" when it shows the issue cleared, and "uncertain" when the evidence below cannot tell you.+3. "uncertain" with a short reason is a valid, honest verdict. Never skip a finding.+4. Do NOT investigate further and do NOT report new findings.`+}++func buildAssessmentSweepUserPrompt(pending []*Finding) string {+ var sb strings.Builder+ sb.WriteString("These active findings still need a verdict from this patrol run.\n")+ sb.WriteString("Call patrol_assess_finding once per finding.\n\n")++ for i, finding := range pending {+ sb.WriteString(fmt.Sprintf("## Finding %d\n", i+1))+ sb.WriteString(fmt.Sprintf("- **ID**: %s\n", finding.ID))+ sb.WriteString(fmt.Sprintf("- **Title**: %s\n", finding.Title))+ sb.WriteString(fmt.Sprintf("- **Severity**: %s\n", finding.Severity))+ sb.WriteString(fmt.Sprintf("- **Resource**: %s (ID: %s, Type: %s)\n", finding.ResourceName, finding.ResourceID, finding.ResourceType))+ if evidence := strings.TrimSpace(finding.Evidence); evidence != "" {+ if len(evidence) > 500 {+ evidence = evidence[:500] + "…"+ }+ sb.WriteString(fmt.Sprintf("- **Last evidence**: ```\n%s\n```\n", evidence))+ }+ sb.WriteString("\n")+ }++ return sb.String()+}+func computePatrolMaxTurns(resourceCount int, scope *PatrolScope) int {minTurns := patrolMinTurnsmaxTurns := patrolMaxTurnsLimitdiff --git a/internal/ai/patrol_assessment_sweep_test.go b/internal/ai/patrol_assessment_sweep_test.gonew file mode 100644index 0000000000..8d9929fe55--- /dev/null+++ b/internal/ai/patrol_assessment_sweep_test.go@@ -0,0 +1,110 @@+package ai++import (+ "context"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++func TestAssessmentSweepPromptBuilders(t *testing.T) {+ systemPrompt := buildAssessmentSweepSystemPrompt()+ if !strings.Contains(systemPrompt, "patrol_assess_finding") {+ t.Fatalf("expected sweep system prompt to name the assessment tool")+ }+ if !strings.Contains(systemPrompt, "uncertain") || !strings.Contains(systemPrompt, "Never skip a finding") {+ t.Fatalf("expected sweep system prompt to allow uncertain and forbid skipping")+ }+ if !strings.Contains(systemPrompt, "Do NOT investigate further") {+ t.Fatalf("expected sweep system prompt to forbid re-investigation")+ }++ longEvidence := strings.Repeat("x", 600)+ pending := []*Finding{+ {+ ID: "0e7c5dbb86bdebe9",+ Title: "Powered Off on docker-host-edge-02",+ Severity: FindingSeverityWarning,+ ResourceID: "docker-host-edge-02",+ ResourceName: "docker-host-edge-02",+ ResourceType: "docker",+ Evidence: longEvidence,+ },+ }+ userPrompt := buildAssessmentSweepUserPrompt(pending)+ if !strings.Contains(userPrompt, "0e7c5dbb86bdebe9") || !strings.Contains(userPrompt, "Powered Off on docker-host-edge-02") {+ t.Fatalf("expected sweep user prompt to carry finding id and title: %s", userPrompt)+ }+ if strings.Contains(userPrompt, longEvidence) {+ t.Fatalf("expected long evidence to be truncated")+ }+ if !strings.Contains(userPrompt, strings.Repeat("x", 500)+"…") {+ t.Fatalf("expected truncated evidence marker in prompt")+ }+}++func TestRunAssessmentSweepFilesRequest(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ svc := NewService(persistence, nil)++ var captured PatrolExecuteRequest+ svc.SetChatService(&patrolMockChatService{+ executePatrolStreamFunc: func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {+ captured = req+ return &PatrolStreamResponse{Content: "ok", InputTokens: 5, OutputTokens: 9}, nil+ },+ })++ ps := NewPatrolService(svc, nil)+ ps.findings.Add(&Finding{+ ID: "0e7c5dbb86bdebe9",+ Title: "Powered Off on docker-host-edge-02",+ Severity: FindingSeverityWarning,+ ResourceID: "docker-host-edge-02",+ ResourceName: "docker-host-edge-02",+ ResourceType: "docker",+ })++ resp, err := ps.runAssessmentSweep(context.Background(), []string{"0e7c5dbb86bdebe9"}, "patrol-run-sweep")+ if err != nil {+ t.Fatalf("expected sweep to succeed, got %v", err)+ }+ if resp == nil || resp.InputTokens != 5 || resp.OutputTokens != 9 {+ t.Fatalf("unexpected sweep response: %+v", resp)+ }+ if captured.SessionID != "patrol-assess" {+ t.Fatalf("expected patrol-assess session, got %q", captured.SessionID)+ }+ if captured.MaxTurns != 3 {+ t.Fatalf("expected maxTurns len(pending)+2=3, got %d", captured.MaxTurns)+ }+ if !strings.Contains(captured.Prompt, "0e7c5dbb86bdebe9") {+ t.Fatalf("expected prompt to list the missing finding id")+ }+}++func TestRunAssessmentSweepSkipsWhenFindingsGone(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ svc := NewService(persistence, nil)++ called := false+ svc.SetChatService(&patrolMockChatService{+ executePatrolStreamFunc: func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {+ called = true+ return &PatrolStreamResponse{Content: "ok"}, nil+ },+ })++ ps := NewPatrolService(svc, nil)+ resp, err := ps.runAssessmentSweep(context.Background(), []string{"no-longer-active"}, "patrol-run-sweep")+ if err != nil {+ t.Fatalf("expected nil error when nothing pending, got %v", err)+ }+ if resp != nil {+ t.Fatalf("expected nil response when nothing pending, got %+v", resp)+ }+ if called {+ t.Fatal("expected no model call when the missing findings are no longer active")+ }+}