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
attach forecast proposals onto patrol RemediationPlan
rcourtman2e064e6c6c56
diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.goindex 1e55129b23..a683065400 100644--- a/internal/ai/patrol_findings.go+++ b/internal/ai/patrol_findings.go@@ -190,6 +190,14 @@ func (p *PatrolService) generateRemediationPlan(finding *Finding) {plan.Warnings = append(plan.Warnings, "Review steps carefully before execution")}+ // Capacity-forecast proposal attachment: when a capacity finding has+ // a registered deterministic action template, attach the proposal so+ // FindingsPanel can render the forecast approval card. RequiresApproval+ // is invariant on the template side; we never auto-execute.+ if proposal := buildCapacityActionProposal(finding); proposal != nil {+ plan.ProposedActionPlan = proposal+ }+if err := engine.CreatePlan(plan); err != nil {log.Debug().Err(err).diff --git a/internal/ai/patrol_findings_capacity_proposal.go b/internal/ai/patrol_findings_capacity_proposal.gonew file mode 100644index 0000000000..1d221da5fe--- /dev/null+++ b/internal/ai/patrol_findings_capacity_proposal.go@@ -0,0 +1,191 @@+// patrol_findings_capacity_proposal.go: glue between the patrol finding+// pipeline and the deterministic forecast-driven action templates in+// internal/ai/forecast.+//+// Lives in its own file (rather than in patrol_findings.go) because the+// projection is self-contained and easy to grow as more capacity-forecast+// resource types come online (e.g. PVE node disk, Ceph OSD usage). Adding a+// new resource type generally means: (1) register a template in+// capacity_action_templates.go, (2) extend metricForCapacityFinding /+// resourceTypeForCapacityFinding here, and that's it.+package ai++import (+ "regexp"+ "strconv"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/forecast"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"+)++// percentInTitle pulls a leading percentage value out of a finding title+// such as "Storage pool tank at 87.3% usage". This is best-effort - if a+// future signal detector phrases its title differently, the proposal still+// renders, just without a current-value snapshot.+var percentInTitle = regexp.MustCompile(`(\d+(?:\.\d+)?)\s*%`)++// buildCapacityActionProposal returns a wire-side ProposedActionPlan when+// the finding is a capacity finding for a resource type that has a+// registered template, or nil otherwise. The pipeline calls this before+// engine.CreatePlan so the proposal lands on the same RemediationPlan that+// FindingsPanel already loads from /api/ai/remediation/plans.+//+// Read-side and approval-gated. The template registry guarantees+// RequiresApproval=true; this helper additionally guarantees Allowed+// flows through unchanged (no escalation here).+func buildCapacityActionProposal(finding *Finding) *aicontracts.ProposedActionPlan {+ if finding == nil {+ return nil+ }+ if finding.Category != FindingCategoryCapacity {+ return nil+ }++ resourceType := normalizedCapacityResourceType(finding)+ metric := metricForCapacityFinding(finding, resourceType)+ if !forecast.HasCapacityActionTemplate(resourceType, metric) {+ return nil+ }++ currentValue := extractCurrentValue(finding)++ // PredictedValue / TimeToThreshold are best-effort: the forecast+ // service is available on the patrol service via SetForecastService+ // in some deployments, but the wire-in must not depend on it being+ // configured. When unavailable, we surface the current value alone -+ // the finding crossing threshold is itself sufficient signal to+ // propose remediation per the lane brief.+ predictedValue := currentValue+ thresholdValue := capacityThresholdForFinding(resourceType)++ plan := forecast.BuildActionPlanForFinding(forecast.CapacityFindingInput{+ FindingID: finding.ID,+ ResourceID: finding.ResourceID,+ ResourceName: finding.ResourceName,+ ResourceType: resourceType,+ Node: finding.Node,+ Metric: metric,+ CurrentValue: currentValue,+ PredictedValue: predictedValue,+ ThresholdValue: thresholdValue,+ Now: time.Now().UTC(),+ })+ if plan == nil {+ return nil+ }+ return projectCapacityProposal(plan, metric, currentValue, predictedValue, thresholdValue)+}++// normalizedCapacityResourceType maps the finding's ResourceType to a+// template-registry key. Findings carry resource_type values in+// historical conventions (storage, vm, system-container, pbs); we leave+// them as-is and let the registry's lower-case lookup do the matching.+func normalizedCapacityResourceType(finding *Finding) string {+ rt := strings.TrimSpace(finding.ResourceType)+ return rt+}++// metricForCapacityFinding returns the metric name the registry expects+// for the given resource type. Capacity findings today don't carry an+// explicit metric field, so we pick the canonical one for the resource+// type. Storage/PBS use usage_percent; guests use disk_usage_percent.+func metricForCapacityFinding(_ *Finding, resourceType string) string {+ switch strings.ToLower(strings.TrimSpace(resourceType)) {+ case "storage", "pbs", "pbs-datastore":+ return "usage_percent"+ case "vm", "qemu", "lxc", "system-container":+ return "disk_usage_percent"+ default:+ return ""+ }+}++// capacityThresholdForFinding returns the warning threshold Pulse uses to+// flag a resource as a capacity concern. We surface this on the proposal+// so the operator sees the same threshold that triggered the finding.+//+// These values mirror SignalThresholds defaults in patrol_signals.go;+// keeping the literal here avoids a dependency on the running+// PatrolService config and matches the brief's "or the finding evidence+// already exceeds a configured threshold" path.+func capacityThresholdForFinding(resourceType string) float64 {+ switch strings.ToLower(strings.TrimSpace(resourceType)) {+ case "storage", "pbs", "pbs-datastore":+ return 75.0+ case "vm", "qemu", "lxc", "system-container":+ return 85.0+ default:+ return 0+ }+}++// extractCurrentValue parses the trailing "X.Y%" out of a capacity+// finding title. The signal detectors in patrol_signals.go consistently+// format these as "Storage pool tank at 87.3% usage" / "High disk usage on+// foo: 92.1%". When parsing fails we return 0; the proposal still renders.+func extractCurrentValue(finding *Finding) float64 {+ if finding == nil {+ return 0+ }+ matches := percentInTitle.FindStringSubmatch(finding.Title)+ if len(matches) < 2 {+ matches = percentInTitle.FindStringSubmatch(finding.Description)+ }+ if len(matches) < 2 {+ return 0+ }+ v, err := strconv.ParseFloat(matches[1], 64)+ if err != nil {+ return 0+ }+ return v+}++// projectCapacityProposal converts a unifiedresources.ActionPlan (the+// shape templates produce, suitable for the action engine) into the+// aicontracts.ProposedActionPlan wire projection that rides on the+// RemediationPlan to the frontend.+//+// We deliberately keep the projection narrow (no execution params, no+// resource version hashes) because the frontend only needs enough to+// render a card. The full ActionPlan is re-derived at execute time.+func projectCapacityProposal(+ plan *unifiedresources.ActionPlan,+ metric string,+ currentValue, predictedValue, thresholdValue float64,+) *aicontracts.ProposedActionPlan {+ if plan == nil {+ return nil+ }+ out := &aicontracts.ProposedActionPlan{+ ActionID: plan.ActionID,+ Allowed: plan.Allowed,+ RequiresApproval: plan.RequiresApproval,+ ApprovalPolicy: string(plan.ApprovalPolicy),+ Message: plan.Message,+ Source: forecast.CapacityActionPlanSource,+ PlannedAt: plan.PlannedAt,+ ExpiresAt: plan.ExpiresAt,+ ProjectedMetric: &aicontracts.ProposedMetricSummary{+ Metric: metric,+ CurrentValue: currentValue,+ PredictedValue: predictedValue,+ ThresholdValue: thresholdValue,+ },+ }+ if plan.Preflight != nil {+ out.Preflight = &aicontracts.ProposedActionPreflight{+ Target: plan.Preflight.Target,+ CurrentState: plan.Preflight.CurrentState,+ IntendedChange: plan.Preflight.IntendedChange,+ DryRunAvailable: plan.Preflight.DryRunAvailable,+ DryRunSummary: plan.Preflight.DryRunSummary,+ SafetyChecks: append([]string(nil), plan.Preflight.SafetyChecks...),+ VerificationSteps: append([]string(nil), plan.Preflight.VerificationSteps...),+ }+ }+ return out+}diff --git a/internal/ai/patrol_findings_capacity_proposal_test.go b/internal/ai/patrol_findings_capacity_proposal_test.gonew file mode 100644index 0000000000..fde5d6e080--- /dev/null+++ b/internal/ai/patrol_findings_capacity_proposal_test.go@@ -0,0 +1,203 @@+package ai++import (+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/forecast"+)++func TestBuildCapacityActionProposal_AttachesProposalForCapacityFinding(t *testing.T) {+ finding := &Finding{+ ID: "f-cap-1",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ ResourceID: "node-a/storage/tank",+ ResourceName: "tank",+ ResourceType: "storage",+ Title: "Storage pool tank at 87.3% usage",+ }++ proposal := buildCapacityActionProposal(finding)+ if proposal == nil {+ t.Fatal("expected ProposedActionPlan for storage capacity finding, got nil")+ }+ if !proposal.RequiresApproval {+ t.Error("RequiresApproval = false; capacity proposals must always be approval-gated")+ }+ if proposal.Allowed {+ t.Error("Allowed = true; current templates ship preflight-only (Allowed=false)")+ }+ if proposal.Source != forecast.CapacityActionPlanSource {+ t.Errorf("Source = %q; want %q so the frontend renders the capacity-forecast card", proposal.Source, forecast.CapacityActionPlanSource)+ }+ if proposal.ProjectedMetric == nil {+ t.Fatal("ProjectedMetric must be populated so the operator sees current/projected/threshold")+ }+ if proposal.ProjectedMetric.Metric != "usage_percent" {+ t.Errorf("ProjectedMetric.Metric = %q; want usage_percent for storage", proposal.ProjectedMetric.Metric)+ }+ if proposal.ProjectedMetric.CurrentValue == 0 {+ t.Error("ProjectedMetric.CurrentValue = 0; expected 87.3 parsed from finding title")+ }+ if proposal.Preflight == nil {+ t.Fatal("Preflight projection must be present so the card surfaces SafetyChecks")+ }+ if len(proposal.Preflight.SafetyChecks) == 0 {+ t.Error("Preflight.SafetyChecks must round-trip from the template")+ }+ if proposal.ActionID == "" || !strings.HasPrefix(proposal.ActionID, "capacity-forecast-") {+ t.Errorf("ActionID = %q; want capacity-forecast- prefix", proposal.ActionID)+ }+}++func TestBuildCapacityActionProposal_ReturnsNilForNonCapacityFinding(t *testing.T) {+ cases := []struct {+ name string+ category FindingCategory+ }{+ {"performance", FindingCategoryPerformance},+ {"reliability", FindingCategoryReliability},+ {"backup", FindingCategoryBackup},+ {"security", FindingCategorySecurity},+ {"general", FindingCategoryGeneral},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ finding := &Finding{+ ID: "f-noncap",+ Severity: FindingSeverityWarning,+ Category: tc.category,+ ResourceID: "node-a/storage/tank",+ ResourceName: "tank",+ ResourceType: "storage",+ Title: "Storage pool tank at 87.3% usage",+ }+ if proposal := buildCapacityActionProposal(finding); proposal != nil {+ t.Fatalf("expected nil proposal for category %s; got %+v", tc.category, proposal)+ }+ })+ }+}++func TestBuildCapacityActionProposal_ReturnsNilForUnregisteredResourceType(t *testing.T) {+ finding := &Finding{+ ID: "f-cap-unknown",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ ResourceID: "agent/raid/0",+ ResourceName: "controller-0",+ ResourceType: "agent_raid",+ Title: "RAID controller has no capacity template",+ }+ if proposal := buildCapacityActionProposal(finding); proposal != nil {+ t.Fatalf("expected nil proposal for unregistered resource type; got %+v", proposal)+ }+}++func TestBuildCapacityActionProposal_VMDiskFindingMatchesGuestTemplate(t *testing.T) {+ finding := &Finding{+ ID: "f-vm-cap",+ Severity: FindingSeverityCritical,+ Category: FindingCategoryCapacity,+ ResourceID: "node-a/qemu/101",+ ResourceName: "appserver",+ ResourceType: "qemu",+ Title: "appserver disk at 95.2% used",+ }+ proposal := buildCapacityActionProposal(finding)+ if proposal == nil {+ t.Fatal("expected proposal for qemu disk finding, got nil")+ }+ if proposal.ProjectedMetric == nil || proposal.ProjectedMetric.Metric != "disk_usage_percent" {+ t.Errorf("ProjectedMetric.Metric = %v; want disk_usage_percent for guest disk", proposal.ProjectedMetric)+ }+ if proposal.ProjectedMetric.CurrentValue == 0 {+ t.Error("CurrentValue = 0; expected parsed value from title")+ }+}++func TestGenerateRemediationPlan_AttachesProposalForCapacityFinding(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ engine := newTestRemediationEngine()+ ps.SetRemediationEngine(engine)++ finding := &Finding{+ ID: "f-gen-cap",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ ResourceID: "node-a/storage/tank",+ ResourceName: "tank",+ ResourceType: "storage",+ Title: "Storage pool tank at 88.2% usage",+ Description: "Tank pool exceeded warning threshold.",+ DetectedAt: time.Now(),+ }++ ps.generateRemediationPlan(finding)++ plan := engine.GetPlanForFinding(finding.ID)+ if plan == nil {+ t.Fatal("expected remediation plan to be created for capacity finding")+ }+ if plan.ProposedActionPlan == nil {+ t.Fatal("RemediationPlan.ProposedActionPlan = nil; capacity finding should attach a proposal via the forecast template registry")+ }+ if !plan.ProposedActionPlan.RequiresApproval {+ t.Error("attached proposal must have RequiresApproval=true")+ }+ if plan.ProposedActionPlan.Source != forecast.CapacityActionPlanSource {+ t.Errorf("attached proposal Source = %q; want %q", plan.ProposedActionPlan.Source, forecast.CapacityActionPlanSource)+ }+}++func TestGenerateRemediationPlan_DoesNotAttachProposalForNonCapacityFinding(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ engine := newTestRemediationEngine()+ ps.SetRemediationEngine(engine)++ finding := &Finding{+ ID: "f-gen-perf",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryPerformance,+ ResourceID: "node-a/qemu/101",+ ResourceName: "appserver",+ ResourceType: "qemu",+ Title: "High CPU on appserver: 92.0%",+ Description: "Sustained CPU usage above warning threshold.",+ DetectedAt: time.Now(),+ }++ ps.generateRemediationPlan(finding)++ plan := engine.GetPlanForFinding(finding.ID)+ if plan == nil {+ t.Fatal("expected remediation plan to be created for performance finding")+ }+ if plan.ProposedActionPlan != nil {+ t.Fatalf("non-capacity finding must not attach a forecast proposal; got %+v", plan.ProposedActionPlan)+ }+}++func TestExtractCurrentValue(t *testing.T) {+ cases := []struct {+ name string+ title string+ want float64+ }{+ {"trailing percent", "Storage pool tank at 87.3% usage", 87.3},+ {"colon then percent", "High disk usage on foo: 95%", 95.0},+ {"integer percent", "Disk used 100%", 100.0},+ {"no percent", "Storage pool tank running low", 0},+ {"percent in middle", "appserver disk at 92.5% used", 92.5},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := extractCurrentValue(&Finding{Title: tc.title})+ if got != tc.want {+ t.Errorf("extractCurrentValue(%q) = %v; want %v", tc.title, got, tc.want)+ }+ })+ }+}diff --git a/pkg/aicontracts/remediation.go b/pkg/aicontracts/remediation.goindex 6e0b7a94c9..b585a35664 100644--- a/pkg/aicontracts/remediation.go+++ b/pkg/aicontracts/remediation.go@@ -77,6 +77,64 @@ type RemediationPlan struct {Warnings []string `json:"warnings,omitempty"`CreatedAt time.Time `json:"created_at"`ExpiresAt *time.Time `json:"expires_at,omitempty"`++ // ProposedActionPlan is an optional deterministic remediation proposal+ // attached by the patrol pipeline (currently only forecast-driven+ // capacity proposals - see internal/ai/forecast.BuildActionPlanForFinding).+ // It is a wire-side projection of unifiedresources.ActionPlan; the+ // projection lives here so pkg/aicontracts stays free of a dependency+ // on internal/. The frontend renders proposals with Source ==+ // "capacity_forecast" as a distinguishable approve/reject card in+ // FindingsPanel.tsx; everything else falls back to the generic plan+ // surface. Always nil for plans that have no attached proposal -+ // remediation behavior is unchanged when the field is absent.+ ProposedActionPlan *ProposedActionPlan `json:"proposed_action_plan,omitempty"`+}++// ProposedActionPlan is the wire-side projection of a deterministic action+// proposal attached to a RemediationPlan. RequiresApproval is invariant -+// every proposed plan must carry an explicit approval gate. Allowed=false+// signals "no write capability is wired yet; this is a preflight-only+// proposal" - the operator may still approve to record intent, but+// execution is not connected.+type ProposedActionPlan struct {+ ActionID string `json:"actionId"`+ CapabilityName string `json:"capabilityName,omitempty"`+ Allowed bool `json:"allowed"`+ RequiresApproval bool `json:"requiresApproval"`+ ApprovalPolicy string `json:"approvalPolicy,omitempty"`+ Message string `json:"message,omitempty"`+ Source string `json:"source,omitempty"`+ ProjectedMetric *ProposedMetricSummary `json:"projectedMetric,omitempty"`+ Preflight *ProposedActionPreflight `json:"preflight,omitempty"`+ PlannedAt time.Time `json:"plannedAt,omitempty"`+ ExpiresAt time.Time `json:"expiresAt,omitempty"`+}++// ProposedActionPreflight mirrors unifiedresources.ActionPreflight on the+// wire so the frontend can render the proposed change without depending on+// internal types.+type ProposedActionPreflight struct {+ Target string `json:"target,omitempty"`+ CurrentState string `json:"currentState,omitempty"`+ IntendedChange string `json:"intendedChange,omitempty"`+ DryRunAvailable bool `json:"dryRunAvailable"`+ DryRunSummary string `json:"dryRunSummary,omitempty"`+ SafetyChecks []string `json:"safetyChecks,omitempty"`+ VerificationSteps []string `json:"verificationSteps,omitempty"`+}++// ProposedMetricSummary is the operator-facing "why this proposal exists"+// snapshot - current metric value, projected value at horizon, threshold,+// and (optional) time-to-threshold-breach in seconds. The frontend renders+// this in the capacity-forecast approval card so the operator can decide+// without digging into Patrol metrics.+type ProposedMetricSummary struct {+ Metric string `json:"metric"`+ CurrentValue float64 `json:"currentValue"`+ PredictedValue float64 `json:"predictedValue,omitempty"`+ ThresholdValue float64 `json:"thresholdValue,omitempty"`+ TimeToThresholdSeconds *int64 `json:"timeToThresholdSeconds,omitempty"`}// RemediationExecution tracks the execution of a remediation plan.