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
Add Proxmox lifecycle Patrol detectors
rcourtmana10f309c95f3
diff --git a/docs/release-control/v6/internal/records/protection-posture-proxmox-guest-lifecycle-2026-07-13.md b/docs/release-control/v6/internal/records/protection-posture-proxmox-guest-lifecycle-2026-07-13.mdnew file mode 100644index 0000000000..1e0d6589b2--- /dev/null+++ b/docs/release-control/v6/internal/records/protection-posture-proxmox-guest-lifecycle-2026-07-13.md@@ -0,0 +1,41 @@+# Proxmox guest lifecycle Patrol loop — 2026-07-13++## Outcome++Pulse now has a production Patrol detector-to-verified-fix path for Proxmox VM+and LXC lifecycle incidents. A fresh running-to-stopped transition creates a+bounded reliability finding only when the stopped resource advertises its exact+governed `start` capability. The normal shared action lifecycle then plans,+asks for approval, dispatches through the owning node agent, records the audit,+and reconciles the finding from canonical verification truth.++## Safety floor++- First observations seed a baseline; guests already stopped at startup do not+ become incidents.+- Stale, missing, repeated-clock, unknown, template, locked, and capability-less+ observations do not emit or clear findings.+- VM and LXC routes require their exact resource-owned lifecycle handlers.+- Finding evidence contains only bounded Proxmox identity/state facts and no+ command, path, credential, token, or raw provider output.+- Execution success stays separate from postcondition truth. `fix_verified`+ requires a confirmed independent Proxmox control-plane observation.++## Proof++- `internal/ai/findings_proxmox_lifecycle_test.go` proves VM/LXC transitions,+ baseline behavior, freshness/capability/guest guardrails, recovery/removal,+ and production Patrol wiring before the provider gate.+- `internal/unifiedresources/views_test.go` proves detached lifecycle+ capabilities and canonical per-source freshness on VM/LXC typed views.+- `internal/api/proxmox_patrol_integration_test.go` proves the full finding,+ exact `start {}` proposal, human decision, `qm start` dispatch, independent+ Proxmox API verification, durable action audit, terminal notification, and+ originating finding reconciliation to `fix_verified`.++## Residual++This closes the missing Proxmox lifecycle detector floor within the broader+Monitor-First Patrol Workbench candidate. It does not claim that whole candidate+lane complete. Mobile approval presentation and decision/execution parity+remain governed separately by `lane-followup:mobile-post-rc-hardening`.diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 114dfdc2d5..2a8fdbd2a1 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -8444,7 +8444,7 @@},{"id": "protection-posture-attention-queue",- "summary": "Pulse now has a durable strong-version product direction, but the current lane map does not yet model the simple user-facing shape as one governed surface: authenticated launch stays monitor-first on platform and dashboard surfaces, Patrol remains the named checking-loop destination for findings, approvals, and explain-act-verify work, Assistant explains selected context, and coverage signals appear only when attached to relevant monitor or Patrol context instead of becoming a generic Home front door or calm-day proof strip. Without an explicit lane-expansion record, work can drift into Home-first surfaces, Patrol renames, generic Assistant polish, or read-only object-browser copies instead of proving simple monitor-first operations.",+ "summary": "Pulse now has a durable strong-version product direction and a production Proxmox VM/LXC detector-to-independent-verification Patrol slice, but the current lane map does not yet model the simple user-facing shape as one governed surface: authenticated launch stays monitor-first on platform and dashboard surfaces, Patrol remains the named checking-loop destination for findings, approvals, and explain-act-verify work, Assistant explains selected context, and coverage signals appear only when attached to relevant monitor or Patrol context instead of becoming a generic Home front door or calm-day proof strip. Without an explicit lane-expansion record, work can drift into Home-first surfaces, Patrol renames, generic Assistant polish, or read-only object-browser copies instead of proving simple monitor-first operations.","owner": "project-owner","status": "planned","recorded_at": "2026-06-25",@@ -8477,6 +8477,11 @@"path": "docs/release-control/v6/internal/records/protection-posture-attention-queue-strong-version-2026-06-25.md","kind": "file"},+ {+ "repo": "pulse",+ "path": "docs/release-control/v6/internal/records/protection-posture-proxmox-guest-lifecycle-2026-07-13.md",+ "kind": "file"+ },{"repo": "pulse","path": "docs/release-control/v6/internal/records/pulse-intelligence-proactive-operations-lane-2026-05-08.md",@@ -8487,6 +8492,16 @@"path": "docs/release-control/v6/internal/SOURCE_OF_TRUTH.md","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/ai/findings_proxmox_lifecycle.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/findings_proxmox_lifecycle_test.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/api/proxmox_guest_action_observer.go",@@ -8497,6 +8512,11 @@"path": "internal/api/proxmox_guest_action_result.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/api/proxmox_patrol_integration_test.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/monitoring/proxmox_action_observer.go",diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 6c6fbd99d7..7d0c877dbe 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -5913,3 +5913,32 @@ confirmation remains useful evidence but projects toand terminal push copy stays explicitly inconclusive. This keeps legacysingle-outcome consumers conservative while `ActionDisposition.ActionResultV2`retains both truth axes and the evidence source.++### Proxmox guest lifecycle Patrol detector floor++`internal/ai/findings_proxmox_lifecycle.go` owns the deterministic production+detector for Proxmox VM and LXC stopped transitions. The first observation is a+baseline only: Patrol may emit a finding only when a fresh Proxmox source+observation moves the same canonical guest from running to stopped at a newer+source timestamp. Admission also requires the exact current resource-owned+`start` capability and matching `proxmox.vm.lifecycle` or+`proxmox.ct.lifecycle` handler. Templates, locked guests, stale or missing+source authority, repeated timestamps, unknown states, and capability loss+fail closed. Existing stopped guests therefore do not become findings merely+because Patrol or Pulse restarted.++The watcher runs before the model-provider gate whenever guest analysis is+enabled, so detection is not conditional on an available LLM. Fresh running+evidence reconciles an active finding; stale or incomplete state does not, and+explicit resource removal uses its own typed resolution reason. Finding+evidence is bounded to guest kind, stopped state, Proxmox instance/node/VMID,+and observation time and carries no command, credential, token, or provider+mutation authority. Operator maintenance and intentionally-offline intent+continue through the shared finding-store suppression boundary.++The non-lab integration proof takes the emitted finding through an exact empty-+parameter `start` proposal, shared planning, separate human approval, durable+node-agent dispatch, canonical action audit, and server-side Proxmox API+observation. Only confirmed independent evidence projects the originating+finding to `fix_verified`; command success or same-agent status alone cannot+produce the green terminal state.diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 4c8c0219a8..b17c6b06a9 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -1655,3 +1655,9 @@ the Proxmox API, validates the requested guest identity, and stamps serverobservation time. It must not satisfy this contract from cached resource stateor node-agent telemetry: the action layer depends on this read remaining in atrust domain distinct from the node agent that executes `qm` / `pct`.++Canonical Proxmox VM/LXC typed views also expose the monitoring-owned source+delivery status and timestamp alongside guest power state. Downstream Patrol+transition detection consumes that status instead of inventing a fixed stale+window: a stopped guest can have fresh inventory, while a stale source cannot+authoritatively prove either a stopped transition or recovery.diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 578f72775f..a70806b91a 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1650,6 +1650,11 @@ when the owning node command agent is disconnected, and records disabled-statecontext in `actionReadiness`. Proxmox platform pages and detail drawers mayconsume those fields, but they must not treat row status, VMID, node name, orguest metadata as separate permission to run `qm` / `pct` or provider calls.+Typed VM and system-container read views expose detached capability slices and+per-source delivery status for internal consumers. A Patrol detector must bind+to the exact resource-owned lifecycle capability and consume the canonical+Proxmox source status/timestamp; it must not reconstruct action availability or+freshness from guest power state or a locally hard-coded polling window.`InfrastructureSummary.tsx` and `infrastructureSummaryModel.ts` now surface`degraded` and `alerting` resource counts alongside the existing `online` anddiff --git a/internal/ai/findings_proxmox_lifecycle.go b/internal/ai/findings_proxmox_lifecycle.gonew file mode 100644index 0000000000..392dd354f2--- /dev/null+++ b/internal/ai/findings_proxmox_lifecycle.go@@ -0,0 +1,217 @@+package ai++import (+ "fmt"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++const (+ proxmoxGuestLifecycleFindingSource = "proxmox-guest-lifecycle"+ proxmoxGuestStoppedFindingKey = "proxmox-guest-stopped"+ proxmoxGuestStoppedFindingIDPrefix = "proxmox:guest:stopped:"+ proxmoxGuestLifecycleResolveRunning = "proxmox_guest_lifecycle:running"+ proxmoxGuestLifecycleResolveRemoved = "proxmox_guest_lifecycle:resource_removed"+ proxmoxVMLifecycleCapabilityHandler = "proxmox.vm.lifecycle"+ proxmoxLXCLifecycleCapabilityHandler = "proxmox.ct.lifecycle"+)++type proxmoxGuestLifecycleSnapshot struct {+ id string+ name string+ resourceType unifiedresources.ResourceType+ kind string+ status unifiedresources.ResourceStatus+ node string+ instance string+ vmid int+ template bool+ lock string+ observedAt time.Time+ sourceFresh bool+ capabilities []unifiedresources.ResourceCapability+}++type proxmoxGuestLifecycleWatcher struct {+ mu sync.Mutex+ prior map[string]proxmoxGuestLifecycleSnapshot+}++func newProxmoxGuestLifecycleWatcher() *proxmoxGuestLifecycleWatcher {+ return &proxmoxGuestLifecycleWatcher{prior: make(map[string]proxmoxGuestLifecycleSnapshot)}+}++// DetectProxmoxGuestLifecycleFindings is the pure detector used by Patrol and+// the end-to-end action lifecycle proof. A stopped guest is actionable only+// when it was freshly observed running before a newer, fresh stopped+// observation and the stopped resource advertises the exact governed start+// capability for its guest kind.+func DetectProxmoxGuestLifecycleFindings(before, after unifiedresources.ReadState, now time.Time) []*Finding {+ previous := proxmoxGuestLifecycleSnapshots(before)+ current := proxmoxGuestLifecycleSnapshots(after)+ ids := sortedProxmoxGuestLifecycleIDs(current)+ findings := make([]*Finding, 0)+ for _, id := range ids {+ afterSnapshot := current[id]+ beforeSnapshot, ok := previous[id]+ if !ok || !proxmoxGuestStoppedTransition(beforeSnapshot, afterSnapshot) {+ continue+ }+ findings = append(findings, buildProxmoxGuestStoppedFinding(afterSnapshot, now.UTC()))+ }+ return findings+}++func (w *proxmoxGuestLifecycleWatcher) Observe(state patrolRuntimeState, active []*Finding, now time.Time) (emit []*Finding, resolve []resolveSentinel) {+ if w == nil {+ return nil, nil+ }+ if state.readState == nil {+ state = state.withDerivedProviders()+ }+ if state.readState == nil {+ return nil, nil+ }++ current := proxmoxGuestLifecycleSnapshots(state.readState)+ activeByResource := make(map[string]*Finding)+ for _, finding := range active {+ if finding == nil || finding.Source != proxmoxGuestLifecycleFindingSource {+ continue+ }+ activeByResource[strings.TrimSpace(finding.ResourceID)] = finding+ }++ w.mu.Lock()+ defer w.mu.Unlock()+ if w.prior == nil {+ w.prior = make(map[string]proxmoxGuestLifecycleSnapshot)+ }++ resolved := make(map[string]struct{})+ for _, id := range sortedProxmoxGuestLifecycleIDs(current) {+ snapshot := current[id]+ activeFinding := activeByResource[id]+ if snapshot.authoritative() {+ switch {+ case activeFinding != nil && snapshot.status == unifiedresources.StatusOnline:+ resolve = append(resolve, resolveSentinel{DedupKey: activeFinding.ID, Reason: proxmoxGuestLifecycleResolveRunning})+ resolved[activeFinding.ID] = struct{}{}+ case activeFinding != nil && snapshot.startable():+ emit = append(emit, buildProxmoxGuestStoppedFinding(snapshot, now.UTC()))+ case activeFinding == nil:+ if previous, ok := w.prior[id]; ok && proxmoxGuestStoppedTransition(previous, snapshot) {+ emit = append(emit, buildProxmoxGuestStoppedFinding(snapshot, now.UTC()))+ }+ }+ w.prior[id] = snapshot+ }+ }++ for id := range w.prior {+ if _, present := current[id]; !present {+ delete(w.prior, id)+ }+ }+ for _, finding := range activeByResource {+ if _, present := current[strings.TrimSpace(finding.ResourceID)]; present {+ continue+ }+ if _, alreadyResolved := resolved[finding.ID]; alreadyResolved {+ continue+ }+ resolve = append(resolve, resolveSentinel{DedupKey: finding.ID, Reason: proxmoxGuestLifecycleResolveRemoved})+ }+ return emit, resolve+}++func proxmoxGuestLifecycleSnapshots(readState unifiedresources.ReadState) map[string]proxmoxGuestLifecycleSnapshot {+ snapshots := make(map[string]proxmoxGuestLifecycleSnapshot)+ if readState == nil {+ return snapshots+ }+ for _, vm := range readState.VMs() {+ if vm == nil || strings.TrimSpace(vm.ID()) == "" {+ continue+ }+ freshness, ok := vm.SourceStatus(unifiedresources.SourceProxmox)+ snapshots[strings.TrimSpace(vm.ID())] = proxmoxGuestLifecycleSnapshot{+ id: strings.TrimSpace(vm.ID()), name: strings.TrimSpace(vm.Name()), resourceType: unifiedresources.ResourceTypeVM,+ kind: "VM", status: vm.Status(), node: vm.Node(), instance: vm.Instance(), vmid: vm.VMID(), template: vm.Template(), lock: strings.TrimSpace(vm.Lock()),+ observedAt: freshness.LastSeen.UTC(), sourceFresh: ok && strings.EqualFold(strings.TrimSpace(freshness.Status), "online") && !freshness.LastSeen.IsZero(),+ capabilities: vm.Capabilities(),+ }+ }+ for _, container := range readState.Containers() {+ if container == nil || strings.TrimSpace(container.ID()) == "" {+ continue+ }+ freshness, ok := container.SourceStatus(unifiedresources.SourceProxmox)+ snapshots[strings.TrimSpace(container.ID())] = proxmoxGuestLifecycleSnapshot{+ id: strings.TrimSpace(container.ID()), name: strings.TrimSpace(container.Name()), resourceType: unifiedresources.ResourceTypeSystemContainer,+ kind: "LXC", status: container.Status(), node: container.Node(), instance: container.Instance(), vmid: container.VMID(), template: container.Template(), lock: strings.TrimSpace(container.Lock()),+ observedAt: freshness.LastSeen.UTC(), sourceFresh: ok && strings.EqualFold(strings.TrimSpace(freshness.Status), "online") && !freshness.LastSeen.IsZero(),+ capabilities: container.Capabilities(),+ }+ }+ return snapshots+}++func sortedProxmoxGuestLifecycleIDs(snapshots map[string]proxmoxGuestLifecycleSnapshot) []string {+ ids := make([]string, 0, len(snapshots))+ for id := range snapshots {+ ids = append(ids, id)+ }+ sort.Strings(ids)+ return ids+}++func (s proxmoxGuestLifecycleSnapshot) authoritative() bool {+ if !s.sourceFresh || s.observedAt.IsZero() || s.id == "" || s.vmid <= 0 || s.template || s.lock != "" {+ return false+ }+ return s.status == unifiedresources.StatusOnline || s.status == unifiedresources.StatusOffline+}++func (s proxmoxGuestLifecycleSnapshot) startable() bool {+ if !s.authoritative() || s.status != unifiedresources.StatusOffline {+ return false+ }+ wantHandler := proxmoxVMLifecycleCapabilityHandler+ if s.resourceType == unifiedresources.ResourceTypeSystemContainer {+ wantHandler = proxmoxLXCLifecycleCapabilityHandler+ }+ for _, capability := range s.capabilities {+ if strings.TrimSpace(capability.Name) == "start" && strings.TrimSpace(capability.InternalHandler) == wantHandler {+ return true+ }+ }+ return false+}++func proxmoxGuestStoppedTransition(before, after proxmoxGuestLifecycleSnapshot) bool {+ return before.authoritative() && before.status == unifiedresources.StatusOnline &&+ after.startable() && after.observedAt.After(before.observedAt)+}++func buildProxmoxGuestStoppedFinding(snapshot proxmoxGuestLifecycleSnapshot, now time.Time) *Finding {+ name := snapshot.name+ if name == "" {+ name = snapshot.id+ }+ id := proxmoxGuestStoppedFindingIDPrefix + snapshot.id+ return &Finding{+ ID: id, Key: proxmoxGuestStoppedFindingKey, Severity: FindingSeverityWarning, Category: FindingCategoryReliability,+ ResourceID: snapshot.id, ResourceName: name, ResourceType: string(snapshot.resourceType), Node: snapshot.node,+ Title: fmt.Sprintf("Proxmox %s %s stopped", snapshot.kind, name),+ Description: fmt.Sprintf("Pulse observed %s transition from running to stopped across fresh Proxmox inventory updates.", name),+ Impact: "Services provided by this guest may be unavailable until it is started or the stop is confirmed as intentional.",+ Recommendation: "Review the guest and approve the governed Start action if this stop was not intentional.",+ Evidence: fmt.Sprintf("kind=%s status=stopped instance=%s node=%s vmid=%d observed_at=%s", strings.ToLower(snapshot.kind), snapshot.instance, snapshot.node, snapshot.vmid, snapshot.observedAt.Format(time.RFC3339)),+ Source: proxmoxGuestLifecycleFindingSource, DetectedAt: now, LastSeenAt: now,+ }+}diff --git a/internal/ai/findings_proxmox_lifecycle_test.go b/internal/ai/findings_proxmox_lifecycle_test.gonew file mode 100644index 0000000000..8c6e0c13f8--- /dev/null+++ b/internal/ai/findings_proxmox_lifecycle_test.go@@ -0,0 +1,169 @@+package ai++import (+ "context"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++func TestPatrolRunWiresProxmoxGuestLifecycleWatcherBeforeProviderGate(t *testing.T) {+ now := time.Now().UTC()+ patrol := NewPatrolService(nil, nil)+ patrol.SetReadState(proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now),+ ))+ patrol.runPatrol(context.Background())++ patrol.SetReadState(proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second)),+ ))+ patrol.runPatrol(context.Background())++ finding := patrol.GetFindings().Get("proxmox:guest:stopped:vm:160")+ if finding == nil || finding.ResolvedAt != nil || finding.Source != proxmoxGuestLifecycleFindingSource {+ t.Fatalf("production Patrol finding=%#v", finding)+ }+}++func TestDetectProxmoxGuestLifecycleFindingsEmitsVMAndLXCStoppedTransitions(t *testing.T) {+ now := time.Now().UTC()+ before := proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now),+ proxmoxLifecycleTestResource("system-container:101", unifiedresources.ResourceTypeSystemContainer, unifiedresources.StatusOnline, now),+ )+ after := proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second)),+ proxmoxLifecycleTestResource("system-container:101", unifiedresources.ResourceTypeSystemContainer, unifiedresources.StatusOffline, now.Add(10*time.Second)),+ )++ findings := DetectProxmoxGuestLifecycleFindings(before, after, now.Add(10*time.Second))+ if len(findings) != 2 {+ t.Fatalf("findings=%#v, want VM and LXC stopped transitions", findings)+ }+ if findings[0].ID != "proxmox:guest:stopped:system-container:101" || findings[1].ID != "proxmox:guest:stopped:vm:160" {+ t.Fatalf("finding IDs=%q/%q", findings[0].ID, findings[1].ID)+ }+ for _, finding := range findings {+ if finding.Key != proxmoxGuestStoppedFindingKey || finding.Source != proxmoxGuestLifecycleFindingSource || finding.Severity != FindingSeverityWarning || finding.Category != FindingCategoryReliability {+ t.Fatalf("finding=%#v", finding)+ }+ if len(finding.Evidence) == 0 || len(finding.Evidence) > 384 {+ t.Fatalf("unbounded evidence=%q", finding.Evidence)+ }+ for _, forbidden := range []string{"qm ", "pct ", "command", "token", "secret"} {+ if strings.Contains(strings.ToLower(finding.Evidence), forbidden) {+ t.Fatalf("finding evidence exposes execution detail %q: %s", forbidden, finding.Evidence)+ }+ }+ }+}++func TestProxmoxGuestLifecycleWatcherSeedsWithoutFlaggingExistingStoppedGuests(t *testing.T) {+ now := time.Now().UTC()+ watcher := newProxmoxGuestLifecycleWatcher()+ emit, resolve := watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now),+ )}, nil, now)+ if len(emit) != 0 || len(resolve) != 0 {+ t.Fatalf("first stopped observation must seed only: emit=%#v resolve=%#v", emit, resolve)+ }+}++func TestProxmoxGuestLifecycleWatcherFailsClosedOnFreshnessCapabilityAndGuestGuards(t *testing.T) {+ now := time.Now().UTC()+ resourceIDs := []string{"vm:stale", "vm:same-clock", "vm:no-capability", "vm:template", "vm:locked"}+ running := make([]unifiedresources.Resource, 0, len(resourceIDs))+ for _, id := range resourceIDs {+ running = append(running, proxmoxLifecycleTestResource(id, unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now))+ }+ watcher := newProxmoxGuestLifecycleWatcher()+ watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(running...)}, nil, now)++ stale := proxmoxLifecycleTestResource("vm:stale", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second))+ stale.SourceStatus[unifiedresources.SourceProxmox] = unifiedresources.SourceStatus{Status: "stale", LastSeen: now.Add(10 * time.Second)}+ sameClock := proxmoxLifecycleTestResource("vm:same-clock", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now)+ noCapability := proxmoxLifecycleTestResource("vm:no-capability", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second))+ noCapability.Capabilities = nil+ template := proxmoxLifecycleTestResource("vm:template", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second))+ template.Proxmox.Template = true+ locked := proxmoxLifecycleTestResource("vm:locked", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second))+ locked.Proxmox.Lock = "backup"++ emit, resolve := watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(stale, sameClock, noCapability, template, locked)}, nil, now.Add(10*time.Second))+ if len(emit) != 0 || len(resolve) != 0 {+ t.Fatalf("guarded observations must remain unknown: emit=%#v resolve=%#v", emit, resolve)+ }+}++func TestProxmoxGuestLifecycleWatcherReconcilesOnlyFreshRunningOrRemoval(t *testing.T) {+ now := time.Now().UTC()+ watcher := newProxmoxGuestLifecycleWatcher()+ watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now),+ )}, nil, now)+ emit, _ := watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second)),+ )}, nil, now.Add(10*time.Second))+ if len(emit) != 1 {+ t.Fatalf("emit=%#v, want transition finding", emit)+ }+ active := []*Finding{emit[0]}++ staleRunning := proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now.Add(20*time.Second))+ staleRunning.SourceStatus[unifiedresources.SourceProxmox] = unifiedresources.SourceStatus{Status: "stale", LastSeen: now.Add(20 * time.Second)}+ _, resolve := watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(staleRunning)}, active, now.Add(20*time.Second))+ if len(resolve) != 0 {+ t.Fatalf("stale running state must not resolve active finding: %#v", resolve)+ }++ _, resolve = watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now.Add(30*time.Second)),+ )}, active, now.Add(30*time.Second))+ if len(resolve) != 1 || resolve[0].DedupKey != emit[0].ID || resolve[0].Reason != proxmoxGuestLifecycleResolveRunning {+ t.Fatalf("fresh running resolution=%#v", resolve)+ }++ watcher = newProxmoxGuestLifecycleWatcher()+ watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now),+ )}, active, now)+ _, resolve = watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState()}, active, now.Add(time.Second))+ if len(resolve) != 1 || resolve[0].Reason != proxmoxGuestLifecycleResolveRemoved {+ t.Fatalf("resource removal resolution=%#v", resolve)+ }+}++func proxmoxLifecycleReadState(resources ...unifiedresources.Resource) unifiedresources.ReadState {+ registry := unifiedresources.NewRegistry(nil)+ registry.IngestResources(resources)+ return registry+}++func proxmoxLifecycleTestResource(id string, resourceType unifiedresources.ResourceType, status unifiedresources.ResourceStatus, observedAt time.Time) unifiedresources.Resource {+ handler := proxmoxVMLifecycleCapabilityHandler+ platform := "qemu"+ vmid := 160+ if resourceType == unifiedresources.ResourceTypeSystemContainer {+ handler = proxmoxLXCLifecycleCapabilityHandler+ platform = "lxc"+ vmid = 101+ }+ capabilityName := "shutdown"+ if status == unifiedresources.StatusOffline {+ capabilityName = "start"+ }+ return unifiedresources.Resource{+ ID: id, Type: resourceType, Technology: platform, Name: "guest-" + id, Status: status, LastSeen: observedAt, UpdatedAt: observedAt,+ Sources: []unifiedresources.DataSource{unifiedresources.SourceProxmox},+ SourceStatus: map[unifiedresources.DataSource]unifiedresources.SourceStatus{+ unifiedresources.SourceProxmox: {Status: "online", LastSeen: observedAt},+ },+ Proxmox: &unifiedresources.ProxmoxData{SourceID: "homelab:delly:" + id, NodeName: "delly", Instance: "homelab", VMID: vmid},+ Capabilities: []unifiedresources.ResourceCapability{{+ Name: capabilityName, Type: unifiedresources.CapabilityTypeCommon, MinimumApprovalLevel: unifiedresources.ApprovalAdmin, Platform: platform, InternalHandler: handler,+ }},+ }+}diff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex 9c589dfc3a..e0f0107d5b 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -471,9 +471,10 @@ type PatrolService struct {// same resource so a noisy host surfaces as one storm finding rather// than several concurrent per-symptom rows. Owned for the service// lifetime; in-memory only, no goroutine.- stormThrottler *findingStormThrottler- updateSafetyWatcher *UpdateSafetyWatcher- aptWorkflowWatcher *aptWorkflowWatcher+ stormThrottler *findingStormThrottler+ updateSafetyWatcher *UpdateSafetyWatcher+ aptWorkflowWatcher *aptWorkflowWatcher+ proxmoxGuestLifecycleWatcher *proxmoxGuestLifecycleWatcher// PDM alert bridge -- polls the PDM resource list on each patrol cycle// and emits reliability findings for offline nodes and failed guests.// Nil source makes Observe a no-op when PDM env configuration is absent.@@ -703,6 +704,7 @@ func NewPatrolService(aiService *Service, stateProvider StateProvider) *PatrolSep.findings.SetStormThrottler(p.stormThrottler)p.updateSafetyWatcher = newUpdateSafetyWatcher()p.aptWorkflowWatcher = newAPTWorkflowWatcher()+ p.proxmoxGuestLifecycleWatcher = newProxmoxGuestLifecycleWatcher()p.pdmAlertBridge = newPDMAlertBridge(newPDMAlertSourceFromEnv())return p}diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.goindex b7cd8c48e8..50edf6c23b 100644--- a/internal/ai/patrol_run.go+++ b/internal/ai/patrol_run.go@@ -448,6 +448,23 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge}}+ if cfg.AnalyzeGuests && p.proxmoxGuestLifecycleWatcher != nil {+ proxmoxEmit, proxmoxResolve := p.proxmoxGuestLifecycleWatcher.Observe(state, p.findings.GetActive(FindingSeverityInfo), time.Now())+ for _, f := range proxmoxEmit {+ trackFinding(f)+ }+ for _, sentinel := range proxmoxResolve {+ if p.findings.ResolveWithReason(sentinel.DedupKey, sentinel.Reason) {+ p.mu.RLock()+ resolveUnified := p.unifiedFindingResolver+ p.mu.RUnlock()+ if resolveUnified != nil {+ resolveUnified(sentinel.DedupKey)+ }+ }+ }+ }+// Run PDM alert bridge on every patrol cycle if a source is configured.// Nil source guard mirrors the MVP no-op behavior; the real HTTP client// is wired in a follow-on. Direct FindingsStore.Add bypasses push.diff --git a/internal/api/proxmox_patrol_integration_test.go b/internal/api/proxmox_patrol_integration_test.gonew file mode 100644index 0000000000..b3b7aef69e--- /dev/null+++ b/internal/api/proxmox_patrol_integration_test.go@@ -0,0 +1,149 @@+package api++import (+ "bytes"+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/relay"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++func TestProxmoxStoppedDetectorProposalApprovalDispatchIndependentVerificationAndFindingReconciliation(t *testing.T) {+ now := time.Now().UTC()+ running := proxmoxPatrolVMResource(unified.StatusOnline, now)+ stopped := proxmoxPatrolVMResource(unified.StatusOffline, now.Add(10*time.Second))+ findings := ai.DetectProxmoxGuestLifecycleFindings(+ proxmoxPatrolReadState(running),+ proxmoxPatrolReadState(stopped),+ now.Add(10*time.Second),+ )+ if len(findings) != 1 {+ t.Fatalf("detected findings=%#v", findings)+ }+ finding := findings[0]+ if finding.ID != "proxmox:guest:stopped:vm:160" || finding.Key != "proxmox-guest-stopped" {+ t.Fatalf("finding=%#v", finding)+ }++ resources := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})+ resources.SetStateProvider(resourceUnifiedSeedProvider{+ snapshot: models.StateSnapshot{LastUpdate: stopped.LastSeen},+ resources: []unified.Resource{stopped},+ })+ agents := &fakeDockerActionAgentCommander{results: []*agentexec.CommandResultPayload{+ {RequestID: "dispatch", Success: true, ExitCode: 0, Stdout: "start requested"},+ {RequestID: "verify", Success: true, ExitCode: 0, Stdout: "status: running"},+ }}+ observer := &fakeProxmoxGuestPostconditionObserver{observations: []proxmoxGuestPostconditionObservation{+ proxmoxGuestActionObservation(now.Add(-time.Second), "stopped", 0, "proxmox-control-plane:default:homelab"),+ proxmoxGuestActionObservation(now.Add(time.Minute), "running", 5, "proxmox-control-plane:default:homelab"),+ }}+ resources.SetActionExecutor(newRoutedActionExecutor(resources, newProxmoxGuestActionExecutor(resources, agents, observer)))++ aiHandler, patrol, _, _ := setupAIHandlerWithPatrol(t)+ notifications := make(chan relay.PushNotificationPayload, 1)+ patrol.SetPushNotifyCallback(func(payload relay.PushNotificationPayload) { notifications <- payload })+ if !patrol.GetFindings().Add(finding) {+ t.Fatal("deterministic Proxmox finding was not admitted")+ }+ investigations := newTestInvestigationStore()+ investigation := investigations.Create(finding.ID, "proxmox-lifecycle-session")+ aiHandler.investigationStores = map[string]aicontracts.InvestigationStore{"default": investigations}+ aiHandler.SetResourceStoreProvider(resources.getStore)+ resources.SetActionTransitionPublisher(aiHandler.ReconcilePatrolActionTransition)++ proposal := aicontracts.ActionProposal{+ ProposalID: "proposal-" + finding.ID, FindingID: finding.ID, InvestigationID: investigation.ID,+ ResourceID: finding.ResourceID, CapabilityName: "start", Params: map[string]any{},+ Reason: "Restore the stopped Proxmox guest through its exact governed lifecycle capability.",+ EvidenceIDs: []string{"finding-evidence:" + finding.ID},+ }+ disposition, err := NewPatrolActionBroker("default", resources).Submit(context.Background(), proposal)+ if err != nil {+ t.Fatalf("Submit: %v", err)+ }+ if disposition.State != string(unified.ActionStatePending) || !disposition.Plan.RequiresApproval {+ t.Fatalf("planned disposition=%#v", disposition)+ }++ decision := httptest.NewRecorder()+ decisionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+disposition.ActionID+"/decision", bytes.NewBufferString(`{"outcome":"approved","reason":"restore service"}`))+ decisionReq.SetPathValue("id", disposition.ActionID)+ decisionReq = decisionReq.WithContext(auth.WithUser(decisionReq.Context(), "[email protected]"))+ resources.HandleDecideAction(decision, actionHandlerTestRequest(decisionReq, ""))+ if decision.Code != http.StatusOK {+ t.Fatalf("decision status=%d body=%s", decision.Code, decision.Body.String())+ }++ execution := httptest.NewRecorder()+ executionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+disposition.ActionID+"/execute", bytes.NewBufferString(`{"reason":"execute approved Proxmox start"}`))+ executionReq.SetPathValue("id", disposition.ActionID)+ executionReq = executionReq.WithContext(auth.WithUser(executionReq.Context(), "[email protected]"))+ resources.HandleExecuteAction(execution, actionHandlerTestRequest(executionReq, ""))+ if execution.Code != http.StatusOK {+ t.Fatalf("execution status=%d body=%s", execution.Code, execution.Body.String())+ }++ store, err := resources.getStore("default")+ if err != nil {+ t.Fatal(err)+ }+ audit, found, err := store.GetActionAudit(disposition.ActionID)+ if err != nil || !found || audit.State != unified.ActionStateCompleted || audit.Origin == nil || audit.Origin.FindingID != finding.ID || len(audit.Request.Params) != 0 {+ t.Fatalf("terminal audit found=%v err=%v audit=%#v", found, err, audit)+ }+ truth := unified.CanonicalActionResultV2(audit)+ if truth.Execution.Status != unified.ActionExecutionSucceeded || truth.Verification.Status != unified.ActionVerificationConfirmed || truth.Verification.EvidenceClass != unified.ActionEvidenceIndependent || len(truth.Verification.Evidence) != 1 {+ t.Fatalf("terminal action truth=%#v", truth)+ }+ if truth.Verification.Evidence[0].ObserverKind != "proxmox_control_plane" || truth.Verification.Evidence[0].ObserverTrustDomain == truth.Verification.Evidence[0].ExecutorTrustDomain {+ t.Fatalf("independent evidence=%#v", truth.Verification.Evidence[0])+ }+ if len(agents.calls) != 2 || agents.calls[0].Command != "qm start 160" || agents.calls[1].Command != "qm status 160" {+ t.Fatalf("typed Proxmox calls=%#v", agents.calls)+ }++ reconciled := patrol.GetFindings().Get(finding.ID)+ if reconciled == nil || reconciled.ResolvedAt == nil || reconciled.InvestigationOutcome != string(aicontracts.OutcomeFixVerified) {+ t.Fatalf("reconciled finding=%#v", reconciled)+ }+ select {+ case notification := <-notifications:+ if notification.Type != "fix_completed" || notification.ActionType != "view_fix_result" {+ t.Fatalf("terminal notification=%#v", notification)+ }+ default:+ t.Fatal("verified Proxmox finding notification was not published")+ }+}++func proxmoxPatrolReadState(resource unified.Resource) unified.ReadState {+ registry := unified.NewRegistry(nil)+ registry.IngestResources([]unified.Resource{resource})+ return registry+}++func proxmoxPatrolVMResource(status unified.ResourceStatus, observedAt time.Time) unified.Resource {+ resource := proxmoxGuestActionResource("vm:160", unified.ResourceTypeVM, "running", observedAt)+ resource.Status = status+ resource.LastSeen = observedAt+ resource.UpdatedAt = observedAt+ resource.SourceStatus[unified.SourceProxmox] = unified.SourceStatus{Status: "online", LastSeen: observedAt}+ if status == unified.StatusOffline {+ resource.Capabilities = []unified.ResourceCapability{{+ Name: "start", Type: unified.CapabilityTypeCommon, Description: "Start this Proxmox VM",+ MinimumApprovalLevel: unified.ApprovalAdmin, Platform: "qemu", InternalHandler: proxmoxVMLifecycleHandler,+ }}+ }+ return resource+}diff --git a/internal/unifiedresources/views.go b/internal/unifiedresources/views.goindex 30ca2dd66a..ae11a9a49a 100644--- a/internal/unifiedresources/views.go+++ b/internal/unifiedresources/views.go@@ -222,6 +222,24 @@ func (v VMView) LastSeen() time.Time {return v.r.LastSeen}+// SourceStatus returns the canonical delivery freshness recorded for one+// source. Consumers must use this instead of inferring source freshness from a+// guest's power state: a stopped guest can still have fresh Proxmox inventory.+func (v VMView) SourceStatus(source DataSource) (SourceStatus, bool) {+ if v.r == nil {+ return SourceStatus{}, false+ }+ status, ok := v.r.SourceStatus[source]+ return status, ok+}++func (v VMView) Capabilities() []ResourceCapability {+ if v.r == nil {+ return nil+ }+ return append([]ResourceCapability(nil), v.r.Capabilities...)+}+func (v VMView) ParentID() string {if v.r == nil || v.r.ParentID == nil {return ""@@ -490,6 +508,24 @@ func (v ContainerView) LastSeen() time.Time {return v.r.LastSeen}+// SourceStatus returns the canonical delivery freshness recorded for one+// source. Consumers must use this instead of inferring source freshness from a+// guest's power state: a stopped guest can still have fresh Proxmox inventory.+func (v ContainerView) SourceStatus(source DataSource) (SourceStatus, bool) {+ if v.r == nil {+ return SourceStatus{}, false+ }+ status, ok := v.r.SourceStatus[source]+ return status, ok+}++func (v ContainerView) Capabilities() []ResourceCapability {+ if v.r == nil {+ return nil+ }+ return append([]ResourceCapability(nil), v.r.Capabilities...)+}+func (v ContainerView) ParentID() string {if v.r == nil || v.r.ParentID == nil {return ""diff --git a/internal/unifiedresources/views_test.go b/internal/unifiedresources/views_test.goindex ff22558688..86df4367d8 100644--- a/internal/unifiedresources/views_test.go+++ b/internal/unifiedresources/views_test.go@@ -58,9 +58,13 @@ func TestView_VMViewAccessors(t *testing.T) {Name: "app-vm",Status: StatusOnline,LastSeen: now,- Tags: []string{"prod", "tier:web"},- ParentID: &parentID,- Identity: ResourceIdentity{IPAddresses: []string{"10.0.0.10", "fd00::10"}},+ SourceStatus: map[DataSource]SourceStatus{+ SourceProxmox: {Status: "online", LastSeen: now},+ },+ Capabilities: []ResourceCapability{{Name: "shutdown", InternalHandler: "proxmox.vm.lifecycle"}},+ Tags: []string{"prod", "tier:web"},+ ParentID: &parentID,+ Identity: ResourceIdentity{IPAddresses: []string{"10.0.0.10", "fd00::10"}},Proxmox: &ProxmoxData{SourceID: " vm-source-1 ",NodeName: " pve-a ",@@ -150,6 +154,17 @@ func TestView_VMViewAccessors(t *testing.T) {if !v.LastSeen().Equal(now) {t.Fatalf("expected LastSeen %v, got %v", now, v.LastSeen())}+ if freshness, ok := v.SourceStatus(SourceProxmox); !ok || freshness.Status != "online" || !freshness.LastSeen.Equal(now) {+ t.Fatalf("expected fresh Proxmox source status, got %+v ok=%v", freshness, ok)+ }+ capabilities := v.Capabilities()+ if len(capabilities) != 1 || capabilities[0].Name != "shutdown" {+ t.Fatalf("expected lifecycle capabilities, got %+v", capabilities)+ }+ capabilities[0].Name = "mutated"+ if got := v.Capabilities(); len(got) != 1 || got[0].Name != "shutdown" {+ t.Fatalf("expected detached lifecycle capabilities, got %+v", got)+ }if v.ParentID() != parentID {t.Fatalf("expected ParentID %q, got %q", parentID, v.ParentID())}@@ -223,9 +238,13 @@ func TestView_VMViewAccessors(t *testing.T) {zero.DiskRead() != 0 ||zero.DiskWrite() != 0 ||zero.Lock() != "" ||- zero.IPAddresses() != nil {+ zero.IPAddresses() != nil ||+ zero.Capabilities() != nil {t.Fatalf("expected zero values for nil resource, got %+v", zero)}+ if _, ok := zero.SourceStatus(SourceProxmox); ok {+ t.Fatal("nil VM view must not report source freshness")+ }})t.Run("NilProxmoxAndMetricsAreSafe", func(t *testing.T) {@@ -300,9 +319,13 @@ func TestView_ContainerViewAccessors(t *testing.T) {Name: "db-ct",Status: StatusWarning,LastSeen: now,- Tags: []string{"prod", "tier:db"},- ParentID: &parentID,- Identity: ResourceIdentity{IPAddresses: []string{"10.0.0.20"}},+ SourceStatus: map[DataSource]SourceStatus{+ SourceProxmox: {Status: "online", LastSeen: now},+ },+ Capabilities: []ResourceCapability{{Name: "start", InternalHandler: "proxmox.ct.lifecycle"}},+ Tags: []string{"prod", "tier:db"},+ ParentID: &parentID,+ Identity: ResourceIdentity{IPAddresses: []string{"10.0.0.20"}},Proxmox: &ProxmoxData{SourceID: " ct-source-1 ",NodeName: " pve-b ",@@ -372,6 +395,17 @@ func TestView_ContainerViewAccessors(t *testing.T) {if !v.LastSeen().Equal(now) {t.Fatalf("expected LastSeen %v, got %v", now, v.LastSeen())}+ if freshness, ok := v.SourceStatus(SourceProxmox); !ok || freshness.Status != "online" || !freshness.LastSeen.Equal(now) {+ t.Fatalf("expected fresh Proxmox source status, got %+v ok=%v", freshness, ok)+ }+ capabilities := v.Capabilities()+ if len(capabilities) != 1 || capabilities[0].Name != "start" {+ t.Fatalf("expected lifecycle capabilities, got %+v", capabilities)+ }+ capabilities[0].Name = "mutated"+ if got := v.Capabilities(); len(got) != 1 || got[0].Name != "start" {+ t.Fatalf("expected detached lifecycle capabilities, got %+v", got)+ }if v.ParentID() != parentID || v.ParentName() != "" {t.Fatalf("expected parent id=%q name=%q, got id=%q name=%q", parentID, "", v.ParentID(), v.ParentName())}@@ -421,9 +455,13 @@ func TestView_ContainerViewAccessors(t *testing.T) {zero.DiskRead() != 0 ||zero.DiskWrite() != 0 ||zero.Lock() != "" ||- zero.IPAddresses() != nil {+ zero.IPAddresses() != nil ||+ zero.Capabilities() != nil {t.Fatalf("expected zero values for nil resource, got %+v", zero)}+ if _, ok := zero.SourceStatus(SourceProxmox); ok {+ t.Fatal("nil container view must not report source freshness")+ }})t.Run("NilProxmoxAndMetricsAreSafe", func(t *testing.T) {