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
Ground Patrol run summaries in accepted findings
rcourtman8b1781b013d4
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 030c636712..c5147b1aa8 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -74,6 +74,17 @@ canonical resource ID; the two diverge for most storage sources, so queryingthe canonical ID silently leaves the feature dormant. The forecast's own`resourceID` stays canonical so it can still be stamped onto findings keyed bycanonical resource ID.+Persisted Patrol run analysis is a display-safe summary, not an unchecked raw+model transcript. Infrastructure status and actions-taken text in run history+must be reconciled from the accepted structured Patrol result: accepted+findings, resolved finding IDs, run errors, and user-visible finding counts.+Rejected, failed, or attempted tool calls must not appear as actions taken, and+healthy/no-finding runs must not claim that an unaccepted+`patrol_report_finding` action occurred. Backup/PBS seed context must preserve+the source identity behind backup observations, including PBS instance,+datastore, and namespace when those fields are available, so model-authored+key observations can name the affected backup source rather than saying only+"PBS".The public Pulse Intelligence overview is a projection of those runtimecontracts, not a second Assistant tool inventory. It must point readers at thediff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex 70f283afe6..1305f826f4 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -149,7 +149,7 @@ type PatrolRunRecord struct {TriageFlags int `json:"triage_flags"` // Number of deterministic flags foundTriageSkippedLLM bool `json:"triage_skipped_llm,omitempty"` // Legacy: true for older quiet-triage runs// AI Analysis details- AIAnalysis string `json:"ai_analysis,omitempty"` // The AI's raw response/analysis+ AIAnalysis string `json:"ai_analysis,omitempty"` // Display-safe AI run analysis summaryInputTokens int `json:"input_tokens,omitempty"` // Tokens sent to AIOutputTokens int `json:"output_tokens,omitempty"` // Tokens received from AI// Tool call tracesdiff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex 8ae882fc99..b81081b87a 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -48,6 +48,14 @@ type AIAnalysisResult struct {Forecasts []seedForecast}+type patrolRunAnalysisRecordContext struct {+ ResourcesChecked int+ NewFindings int+ ExistingFindings int+ ResolvedFindings int+ ErrorCount int+}+const (patrolMinTurns = 20patrolMaxTurnsLimit = 80@@ -218,6 +226,171 @@ func CleanThinkingTokens(content string) string {return strings.TrimSpace(content)}+func patrolRunAIAnalysisForRecord(result *AIAnalysisResult, ctx patrolRunAnalysisRecordContext) string {+ if result == nil {+ return ""+ }+ response := strings.TrimSpace(result.Response)+ if response == "" {+ return ""+ }++ response = replacePatrolSummarySection(response, "Infrastructure Status", renderPatrolRecordStatusLine(ctx))+ response = replacePatrolSummarySection(response, "Actions Taken", renderPatrolAcceptedActions(result))+ return response+}++func renderPatrolRecordStatusLine(ctx patrolRunAnalysisRecordContext) string {+ resourceText := "resources"+ if ctx.ResourcesChecked == 1 {+ resourceText = "resource"+ }++ prefix := "Patrol scanned"+ if ctx.ResourcesChecked > 0 {+ prefix = fmt.Sprintf("Patrol scanned %d %s", ctx.ResourcesChecked, resourceText)+ }++ if ctx.ErrorCount > 0 {+ return fmt.Sprintf("%s; analysis completed with %d %s.", prefix, ctx.ErrorCount, seedCountLabel(ctx.ErrorCount, "error", "errors"))+ }++ parts := make([]string, 0, 3)+ if ctx.NewFindings > 0 {+ parts = append(parts, fmt.Sprintf("%d new", ctx.NewFindings))+ }+ if ctx.ExistingFindings > 0 {+ parts = append(parts, fmt.Sprintf("%d existing", ctx.ExistingFindings))+ }+ if ctx.ResolvedFindings > 0 {+ parts = append(parts, fmt.Sprintf("%d resolved", ctx.ResolvedFindings))+ }+ if len(parts) == 0 {+ return prefix + "; no accepted warning or critical Patrol findings recorded."+ }++ return fmt.Sprintf("%s; accepted Patrol finding activity: %s.", prefix, strings.Join(parts, ", "))+}++func renderPatrolAcceptedActions(result *AIAnalysisResult) string {+ if result == nil || (len(result.Findings) == 0 && len(result.ResolvedIDs) == 0) {+ return "- No findings reported — all clear."+ }++ var lines []string+ for _, finding := range result.Findings {+ if finding == nil {+ continue+ }+ severity := patrolSummaryInline(string(finding.Severity))+ if severity == "" {+ severity = "finding"+ }+ title := patrolSummaryInline(finding.Title)+ if title == "" {+ title = "Untitled finding"+ }+ resource := patrolSummaryInline(finding.ResourceName)+ if resource == "" {+ resource = patrolSummaryInline(finding.ResourceID)+ }+ if resource != "" {+ lines = append(lines, fmt.Sprintf("- %s: %s (%s)", severity, title, resource))+ } else {+ lines = append(lines, fmt.Sprintf("- %s: %s", severity, title))+ }+ }+ for _, resolvedID := range result.ResolvedIDs {+ resolvedID = patrolSummaryInline(resolvedID)+ if resolvedID == "" {+ continue+ }+ lines = append(lines, fmt.Sprintf("- resolved: %s", resolvedID))+ }+ if len(lines) == 0 {+ return "- No findings reported — all clear."+ }+ return strings.Join(lines, "\n")+}++func replacePatrolSummarySection(response, heading, body string) string {+ body = strings.TrimSpace(body)+ if strings.TrimSpace(response) == "" || body == "" {+ return strings.TrimSpace(response)+ }++ lines := strings.Split(response, "\n")+ target := strings.ToLower(strings.TrimSpace(heading))+ start := -1+ for i, line := range lines {+ if patrolSummaryHeadingName(line) == target {+ start = i+ break+ }+ }++ bodyLines := strings.Split(body, "\n")+ if start < 0 {+ out := append([]string(nil), lines...)+ if len(out) > 0 && strings.TrimSpace(out[len(out)-1]) != "" {+ out = append(out, "")+ }+ out = append(out, "### "+heading)+ out = append(out, bodyLines...)+ return strings.TrimSpace(strings.Join(out, "\n"))+ }++ end := len(lines)+ for i := start + 1; i < len(lines); i++ {+ if patrolSummaryLineStartsSection(lines[i]) {+ end = i+ break+ }+ }++ out := make([]string, 0, len(lines)-maxInt(0, end-start-1)+len(bodyLines))+ out = append(out, lines[:start+1]...)+ out = append(out, bodyLines...)+ if end < len(lines) {+ if strings.TrimSpace(out[len(out)-1]) != "" && strings.TrimSpace(lines[end]) != "" {+ out = append(out, "")+ }+ out = append(out, lines[end:]...)+ }++ return strings.TrimSpace(strings.Join(out, "\n"))+}++func patrolSummaryLineStartsSection(line string) bool {+ trimmed := strings.TrimSpace(line)+ if trimmed == "" {+ return false+ }+ if strings.HasPrefix(trimmed, "#") {+ return true+ }+ switch patrolSummaryHeadingName(line) {+ case "infrastructure status", "key observations", "actions taken":+ return true+ default:+ return false+ }+}++func patrolSummaryHeadingName(line string) string {+ trimmed := strings.TrimSpace(line)+ trimmed = strings.TrimLeft(trimmed, "#")+ trimmed = strings.TrimSpace(trimmed)+ trimmed = strings.Trim(trimmed, "*")+ trimmed = strings.TrimSpace(trimmed)+ trimmed = strings.TrimSuffix(trimmed, ":")+ return strings.ToLower(strings.TrimSpace(trimmed))+}++func patrolSummaryInline(value string) string {+ return strings.Join(strings.Fields(value), " ")+}+// runAIAnalysis uses the agentic tool-driven approach to analyze infrastructure.// The LLM investigates using Assistant tools and reports findings via patrol_report_finding.// An optional scope focuses the patrol on specific resources.@@ -977,11 +1150,13 @@ One sentence overall health verdict (e.g., "All 3 nodes and 18 guests are operat### Key Observations- Bullet each noteworthy observation with the **resource name** bolded and the metric or finding inline+- For backup or PBS observations, name the evidence source: PBS instance, datastore, and namespace when present. Do not collapse this to just "PBS"; if source fields are missing, say "PBS source unknown."- Only include items worth mentioning — skip anything completely normal- Group related items (e.g., all storage together, all compute together)### Actions Taken-- List each finding you reported or resolved, with its severity badge: ` + "`" + `⚠ warning` + "`" + `, ` + "`" + `🔴 critical` + "`" + `, ` + "`" + `✅ resolved` + "`" + `+- List only findings that the tools successfully accepted as reported or resolved, with its severity badge: ` + "`" + `⚠ warning` + "`" + `, ` + "`" + `🔴 critical` + "`" + `, ` + "`" + `✅ resolved` + "`" + `+- Do not list failed, rejected, or attempted tool calls as actions taken.- If no findings were created or resolved, write "No findings reported — all clear."Keep the summary factual, terse, and scannable. Do NOT repeat your investigation process or thinking. Do NOT use phrases like "Let me check..." or "I'll start by..." — only state results. Maximum 15 lines.`@@ -3092,7 +3267,7 @@ func (p *PatrolService) seedBackupAnalysisState(snap patrolRuntimeState, scopedSname = fmt.Sprintf("vmid-%d", bt.VMID)}if existing, ok := guestBackups[name]; !ok || bt.EndTime.After(existing.lastBackup) {- guestBackups[name] = &backupInfo{lastBackup: bt.EndTime, source: "pve"}+ guestBackups[name] = &backupInfo{lastBackup: bt.EndTime, source: "PVE task history"}}}@@ -3105,7 +3280,7 @@ func (p *PatrolService) seedBackupAnalysisState(snap patrolRuntimeState, scopedSname = fmt.Sprintf("vmid-%d", stb.VMID)}if existing, ok := guestBackups[name]; !ok || stb.Time.After(existing.lastBackup) {- guestBackups[name] = &backupInfo{lastBackup: stb.Time, source: "pve"}+ guestBackups[name] = &backupInfo{lastBackup: stb.Time, source: "PVE storage backup"}}}@@ -3120,7 +3295,7 @@ func (p *PatrolService) seedBackupAnalysisState(snap patrolRuntimeState, scopedScontinue}if existing, ok := guestBackups[name]; !ok || pb.BackupTime.After(existing.lastBackup) {- guestBackups[name] = &backupInfo{lastBackup: pb.BackupTime, source: "pbs"}+ guestBackups[name] = &backupInfo{lastBackup: pb.BackupTime, source: formatPBSBackupSource(pb)}}}@@ -3129,7 +3304,7 @@ func (p *PatrolService) seedBackupAnalysisState(snap patrolRuntimeState, scopedScontinue}if existing, ok := guestBackups[guest.name]; !ok || guest.lastBackup.After(existing.lastBackup) {- guestBackups[guest.name] = &backupInfo{lastBackup: guest.lastBackup, source: "pve"}+ guestBackups[guest.name] = &backupInfo{lastBackup: guest.lastBackup, source: "PVE guest metadata"}}}@@ -3154,9 +3329,13 @@ func (p *PatrolService) seedBackupAnalysisState(snap patrolRuntimeState, scopedSfor name := range allGuestNames {info, hasBackup := guestBackups[name]if !hasBackup {- staleGuests = append(staleGuests, fmt.Sprintf("%s (never)", name))+ staleGuests = append(staleGuests, fmt.Sprintf("%s (never; no PVE/PBS backup seen)", name))} else if info.lastBackup.Before(threshold48h) {- staleGuests = append(staleGuests, fmt.Sprintf("%s (last: %s)", name, seedFormatTimeAgo(now, info.lastBackup)))+ source := strings.TrimSpace(info.source)+ if source == "" {+ source = "source unknown"+ }+ staleGuests = append(staleGuests, fmt.Sprintf("%s (last: %s via %s)", name, seedFormatTimeAgo(now, info.lastBackup), source))} else {recentCount++}@@ -3172,6 +3351,33 @@ func (p *PatrolService) seedBackupAnalysisState(snap patrolRuntimeState, scopedSreturn sb.String()}+func formatPBSBackupSource(pb models.PBSBackup) string {+ instance := strings.TrimSpace(pb.Instance)+ datastore := strings.TrimSpace(pb.Datastore)+ namespace := strings.TrimSpace(pb.Namespace)++ if instance == "" && datastore == "" {+ return "PBS source unknown"+ }++ location := instance+ if location == "" {+ location = "PBS source unknown"+ }+ if datastore != "" {+ if location == "" || location == "PBS source unknown" {+ location = datastore+ } else {+ location += "/" + datastore+ }+ }++ if namespace == "" {+ namespace = "root"+ }+ return fmt.Sprintf("PBS %s namespace %s", location, namespace)+}+// seedHealthAndAlerts builds the disk health, alerts, connection health, kubernetes, and hosts sections.func (p *PatrolService) seedHealthAndAlertsState(snap patrolRuntimeState, scopedSet map[string]bool, cfg PatrolConfig, now time.Time) string {var sb strings.Builderdiff --git a/internal/ai/patrol_ai_intelligence_test.go b/internal/ai/patrol_ai_intelligence_test.goindex da0abf12d8..32766be3c9 100644--- a/internal/ai/patrol_ai_intelligence_test.go+++ b/internal/ai/patrol_ai_intelligence_test.go@@ -240,7 +240,13 @@ func TestSeedBackupAnalysis_StaleAndRecent(t *testing.T) {BackupTasks: []models.BackupTask{{VMID: 102, Status: "OK", EndTime: now.Add(-72 * time.Hour)}},StorageBackups: []models.StorageBackup{{VMID: 101, Time: now.Add(-36 * time.Hour)}},},- PBSBackups: []models.PBSBackup{{VMID: "102", BackupTime: now.Add(-72 * time.Hour)}},+ PBSBackups: []models.PBSBackup{{+ VMID: "102",+ Instance: "pbs-main",+ Datastore: "backup-vault",+ Namespace: "tenant-a",+ BackupTime: now.Add(-60 * time.Hour),+ }},}output := ps.seedBackupAnalysisState(patrolRuntimeStateForTest(ps, state), nil, now)@@ -250,17 +256,91 @@ func TestSeedBackupAnalysis_StaleAndRecent(t *testing.T) {if !strings.Contains(output, "Guests with no backup in >48h") {t.Fatalf("expected stale backup section, got: %s", output)}- if !strings.Contains(output, "ct-1 (never)") {- t.Fatalf("expected never-backed guest, got: %s", output)+ if !strings.Contains(output, "ct-1 (never; no PVE/PBS backup seen)") {+ t.Fatalf("expected never-backed guest to include source scope, got: %s", output)}- if !strings.Contains(output, "vm-2 (last:") {- t.Fatalf("expected stale vm entry, got: %s", output)+ if !strings.Contains(output, "vm-2 (last:") ||+ !strings.Contains(output, "via PBS pbs-main/backup-vault namespace tenant-a") {+ t.Fatalf("expected stale vm entry to include PBS source context, got: %s", output)}if !strings.Contains(output, "Guests with recent backups: 1/3") {t.Fatalf("expected recent backup count, got: %s", output)}}+func TestPatrolRunAIAnalysisForRecord_ReconcilesNoAcceptedActions(t *testing.T) {+ result := &AIAnalysisResult{+ Response: strings.Join([]string{+ "### Infrastructure Status",+ "All resources appear healthy.",+ "",+ "### Key Observations",+ "- Guest backup state should be checked.",+ "",+ "### Actions Taken",+ "- patrol_report_finding (warning): Orphaned backup for vm-101.",+ }, "\n"),+ RejectedFindings: 1,+ }++ output := patrolRunAIAnalysisForRecord(result, patrolRunAnalysisRecordContext{+ ResourcesChecked: 44,+ })++ if strings.Contains(output, "patrol_report_finding") {+ t.Fatalf("expected rejected tool call prose to be removed, got: %s", output)+ }+ if !strings.Contains(output, "Patrol scanned 44 resources; no accepted warning or critical Patrol findings recorded.") {+ t.Fatalf("expected reconciled status line, got: %s", output)+ }+ if !strings.Contains(output, "- No findings reported — all clear.") {+ t.Fatalf("expected no-action line, got: %s", output)+ }+ if !strings.Contains(output, "Guest backup state should be checked.") {+ t.Fatalf("expected key observations to be preserved, got: %s", output)+ }+}++func TestPatrolRunAIAnalysisForRecord_RendersAcceptedActions(t *testing.T) {+ result := &AIAnalysisResult{+ Response: strings.Join([]string{+ "Infrastructure Status:",+ "All clear.",+ "",+ "Key Observations:",+ "- Backup source context present.",+ "",+ "Actions Taken:",+ "- patrol_report_finding (warning): old wording.",+ }, "\n"),+ Findings: []*Finding{{+ Severity: FindingSeverityWarning,+ Title: "Orphaned backup requires cleanup",+ ResourceName: "pbs-main/backup-vault namespace tenant-a",+ }},+ ResolvedIDs: []string{"finding-123"},+ }++ output := patrolRunAIAnalysisForRecord(result, patrolRunAnalysisRecordContext{+ ResourcesChecked: 12,+ NewFindings: 1,+ ResolvedFindings: 1,+ })++ if strings.Contains(output, "old wording") || strings.Contains(output, "patrol_report_finding") {+ t.Fatalf("expected raw tool-call wording to be replaced, got: %s", output)+ }+ if !strings.Contains(output, "Patrol scanned 12 resources; accepted Patrol finding activity: 1 new, 1 resolved.") {+ t.Fatalf("expected accepted finding status, got: %s", output)+ }+ if !strings.Contains(output, "- warning: Orphaned backup requires cleanup (pbs-main/backup-vault namespace tenant-a)") {+ t.Fatalf("expected accepted finding action, got: %s", output)+ }+ if !strings.Contains(output, "- resolved: finding-123") {+ t.Fatalf("expected resolved action, got: %s", output)+ }+}+func TestSeedBackupAnalysisState_ScopesGuestsToRuntime(t *testing.T) {now := time.Now()ps := NewPatrolService(nil, nil)diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.goindex 530b4e7c5b..1d9c45c4fb 100644--- a/internal/ai/patrol_run.go+++ b/internal/ai/patrol_run.go@@ -627,7 +627,13 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge// Add AI analysis details if availableif runStats.aiAnalysis != nil {- runRecord.AIAnalysis = runStats.aiAnalysis.Response+ runRecord.AIAnalysis = patrolRunAIAnalysisForRecord(runStats.aiAnalysis, patrolRunAnalysisRecordContext{+ ResourcesChecked: runStats.resourceCount,+ NewFindings: runStats.newFindings,+ ExistingFindings: runStats.existingFindings,+ ResolvedFindings: resolvedCount,+ ErrorCount: runStats.errors,+ })runRecord.InputTokens = runStats.aiAnalysis.InputTokensrunRecord.OutputTokens = runStats.aiAnalysis.OutputTokensrunRecord.TriageFlags = runStats.triageFlags@@ -991,7 +997,13 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)}if runStats.aiAnalysis != nil {- runRecord.AIAnalysis = runStats.aiAnalysis.Response+ runRecord.AIAnalysis = patrolRunAIAnalysisForRecord(runStats.aiAnalysis, patrolRunAnalysisRecordContext{+ ResourcesChecked: runStats.resourceCount,+ NewFindings: runStats.newFindings,+ ExistingFindings: runStats.existingFindings,+ ResolvedFindings: resolvedFindings,+ ErrorCount: runStats.errors,+ })runRecord.InputTokens = runStats.aiAnalysis.InputTokensrunRecord.OutputTokens = runStats.aiAnalysis.OutputTokensrunRecord.TriageFlags = runStats.triageFlags