Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Add unified guest intelligence to patrol seed context

rcourtman34ca42745810
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index 43bd066fd4..ad9ea2b704 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -237,6 +237,7 @@ type PatrolService struct {
findings *FindingsStore
knowledgeStore *knowledge.Store // For per-resource notes in patrol context
discoveryStore *servicediscovery.Store // For AI-discovered infrastructure context
+ guestProber GuestProber // For pre-patrol guest reachability checks
metricsHistory MetricsHistoryProvider // For trend analysis and predictions
baselineStore *baseline.Store // For anomaly detection via learned baselines
changeDetector *ChangeDetector // For tracking infrastructure changes
diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.go
index 77ab0442ef..32ba1695dd 100644
--- a/internal/ai/patrol_ai.go
+++ b/internal/ai/patrol_ai.go
@@ -205,8 +205,13 @@ func (p *PatrolService) runAIAnalysis(ctx context.Context, state models.StateSna
return nil, fmt.Errorf("patrol skipped: %w", err)
}
+ // Gather guest intelligence (discovery + reachability) before building seed context
+ intelCtx, intelCancel := context.WithTimeout(ctx, 5*time.Second)
+ guestIntel := p.gatherGuestIntelligence(intelCtx, state)
+ intelCancel()
+
// Build minimal seed context (resource inventory + thresholds + findings + notes)
- seedContext, seededFindingIDs := p.buildSeedContext(state, scope)
+ seedContext, seededFindingIDs := p.buildSeedContext(state, scope, guestIntel)
if strings.TrimSpace(seedContext) == "" {
return nil, nil
}
@@ -474,6 +479,11 @@ func (p *PatrolService) runAIAnalysis(ctx context.Context, state models.StateSna
sigThresholds := SignalThresholdsFromPatrol(p.thresholds)
p.mu.RUnlock()
detectedSignals := DetectSignals(signalToolCalls, sigThresholds)
+
+ // Merge reachability signals from pre-patrol guest probing
+ reachabilitySignals := DetectReachabilitySignals(guestIntel)
+ detectedSignals = append(detectedSignals, reachabilitySignals...)
+
if len(detectedSignals) > 0 {
log.Info().
Int("detected_signals", len(detectedSignals)).
@@ -829,6 +839,8 @@ func signalKey(s DetectedSignal) string {
return "backup-stale"
case SignalActiveAlert:
return "active-alert"
+ case SignalGuestUnreachable:
+ return "guest-unreachable"
default:
return "deterministic-signal"
}
@@ -850,6 +862,8 @@ func signalTitle(s DetectedSignal) string {
return "Backup is stale"
case SignalActiveAlert:
return "Active alert detected"
+ case SignalGuestUnreachable:
+ return fmt.Sprintf("Guest unreachable: %s", s.ResourceName)
default:
return "Infrastructure signal detected"
}
@@ -871,6 +885,8 @@ func defaultRecommendationForSignal(s DetectedSignal) string {
return "Ensure backups are scheduled and completing successfully; run a new backup."
case SignalActiveAlert:
return "Investigate the active alert and resolve the underlying issue."
+ case SignalGuestUnreachable:
+ return "Investigate why this guest is not responding to ping. Check network configuration, firewall rules, or whether the guest has crashed."
default:
return "Investigate the signal and take corrective action if needed."
}
@@ -917,7 +933,9 @@ You have access to the following tools to investigate infrastructure:
You are provided with the current state of the user's infrastructure below, including resource metrics, storage health, backup status, disk health, active alerts, baselines, and connection health. This gives you a complete point-in-time snapshot without needing to query for it.
-**Step 1 — Analyze the snapshot.** Scan the data for anything notable: high usage, backup gaps, disk health issues, resources above baseline, stopped resources that should be running, storage trending full, etc.
+The seed context includes service identity (from discovery) and reachability data when available. Guests marked UNREACHABLE are running according to Proxmox but did not respond to ICMP ping from their host node. This may indicate a network issue, guest crash, or firewall blocking ICMP. Use pulse_read to check guest logs or pulse_discovery for service details.
+
+**Step 1 — Analyze the snapshot.** Scan the data for anything notable: high usage, backup gaps, disk health issues, resources above baseline, stopped resources that should be running, storage trending full, unreachable guests, etc.
**Step 2 — Investigate deeper.** For anything notable you spotted, use your tools to understand whether it's actually a problem:
- Use **pulse_metrics** with historical windows (1h, 6h, 24h) to check if a high metric is trending up or just a momentary spike. A resource at 60% and rising is more interesting than one sitting steady at 75%.
@@ -1031,7 +1049,7 @@ type seedForecast struct {
// It pre-assembles current metrics, storage health, backup status, disk health, alerts,
// connection health, and baselines/trends so the model can analyze without tool calls.
// Tools remain available for targeted deep-dives.
-func (p *PatrolService) buildSeedContext(state models.StateSnapshot, scope *PatrolScope) (string, []string) {
+func (p *PatrolService) buildSeedContext(state models.StateSnapshot, scope *PatrolScope, guestIntel map[string]*GuestIntelligence) (string, []string) {
var sb strings.Builder
p.mu.RLock()
@@ -1043,7 +1061,7 @@ func (p *PatrolService) buildSeedContext(state models.StateSnapshot, scope *Patr
sb.WriteString(p.seedPreviousRun(now))
intel := p.seedPrecomputeIntelligence(state, scopedSet, now)
- sb.WriteString(p.seedResourceInventory(state, scopedSet, cfg, now, intel.isQuiet))
+ sb.WriteString(p.seedResourceInventory(state, scopedSet, cfg, now, intel.isQuiet, guestIntel))
p.seedPMGSnapshot(&sb, state, scopedSet, cfg, intel.isQuiet)
sb.WriteString(p.seedBackupAnalysis(state, now))
sb.WriteString(p.seedHealthAndAlerts(state, scopedSet, cfg, now))
@@ -1327,7 +1345,7 @@ func (p *PatrolService) seedPrecomputeIntelligence(state models.StateSnapshot, s
}
// seedResourceInventory builds the node, guest, docker, storage, ceph, and PBS sections.
-func (p *PatrolService) seedResourceInventory(state models.StateSnapshot, scopedSet map[string]bool, cfg PatrolConfig, now time.Time, isQuiet bool) string {
+func (p *PatrolService) seedResourceInventory(state models.StateSnapshot, scopedSet map[string]bool, cfg PatrolConfig, now time.Time, isQuiet bool, guestIntel map[string]*GuestIntelligence) string {
var sb strings.Builder
// --- Node Metrics ---
@@ -1394,6 +1412,8 @@ func (p *PatrolService) seedResourceInventory(state models.StateSnapshot, scoped
name, gType, node, status string
cpu, mem, disk float64
lastBackup time.Time
+ service string // from discovery, e.g. "PostgreSQL 15" or "-"
+ reachable string // "yes", "NO", or "-"
}
var guests []guestRow
@@ -1402,20 +1422,26 @@ func (p *PatrolService) seedResourceInventory(state models.StateSnapshot, scoped
if vm.Template || !seedIsInScope(scopedSet, vm.ID) {
continue
}
+ gi := guestIntel[vm.ID]
guests = append(guests, guestRow{
name: vm.Name, gType: "vm", node: vm.Node, status: vm.Status,
cpu: vm.CPU * 100, mem: vm.Memory.Usage, disk: vm.Disk.Usage,
lastBackup: vm.LastBackup,
+ service: formatService(gi),
+ reachable: formatReachable(reachableFromIntel(gi)),
})
}
for _, ct := range state.Containers {
if ct.Template || !seedIsInScope(scopedSet, ct.ID) {
continue
}
+ gi := guestIntel[ct.ID]
guests = append(guests, guestRow{
name: ct.Name, gType: "lxc", node: ct.Node, status: ct.Status,
cpu: ct.CPU * 100, mem: ct.Memory.Usage, disk: ct.Disk.Usage,
lastBackup: ct.LastBackup,
+ service: formatService(gi),
+ reachable: formatReachable(reachableFromIntel(gi)),
})
}
}
@@ -1423,27 +1449,66 @@ func (p *PatrolService) seedResourceInventory(state models.StateSnapshot, scoped
if len(guests) > 0 {
if isQuiet && scopedSet == nil {
running, stopped := 0, 0
+ var unreachableNames []string
for _, g := range guests {
if g.status == "running" {
running++
} else {
stopped++
}
+ if g.reachable == "NO" {
+ unreachableNames = append(unreachableNames, g.name)
+ }
+ }
+ if len(unreachableNames) > 0 {
+ sb.WriteString(fmt.Sprintf("# Guests: %d running, %d stopped. %d UNREACHABLE: %s\n\n",
+ running, stopped, len(unreachableNames), strings.Join(unreachableNames, ", ")))
+ } else {
+ hasReachabilityData := false
+ for _, g := range guests {
+ if g.reachable != "-" {
+ hasReachabilityData = true
+ break
+ }
+ }
+ if hasReachabilityData {
+ sb.WriteString(fmt.Sprintf("# Guests: %d running, %d stopped, no issues detected. All reachable.\n\n", running, stopped))
+ } else {
+ sb.WriteString(fmt.Sprintf("# Guests: %d running, %d stopped, no issues detected.\n\n", running, stopped))
+ }
}
- sb.WriteString(fmt.Sprintf("# Guests: %d running, %d stopped, no issues detected.\n\n", running, stopped))
} else {
sb.WriteString("# Guest Metrics\n")
- sb.WriteString("| Name | Type | Node | CPU | Mem | Disk | Status | Last Backup |\n")
- sb.WriteString("|------|------|------|-----|-----|------|--------|-------------|\n")
+ sb.WriteString("| Name | Type | Node | Service | CPU | Mem | Disk | Status | Reachable | Last Backup |\n")
+ sb.WriteString("|------|------|------|---------|-----|-----|------|--------|-----------|-------------|\n")
for _, g := range guests {
backup := "never"
if !g.lastBackup.IsZero() {
backup = seedFormatTimeAgo(now, g.lastBackup)
}
- sb.WriteString(fmt.Sprintf("| %s | %s | %s | %.0f%% | %.0f%% | %.0f%% | %s | %s |\n",
- g.name, g.gType, g.node, g.cpu, g.mem, g.disk, g.status, backup))
+ sb.WriteString(fmt.Sprintf("| %s | %s | %s | %s | %.0f%% | %.0f%% | %.0f%% | %s | %s | %s |\n",
+ g.name, g.gType, g.node, g.service, g.cpu, g.mem, g.disk, g.status, g.reachable, backup))
}
sb.WriteString("\n")
+
+ // Add service health issues section for unreachable running guests
+ var issues []serviceHealthIssue
+ for _, g := range guests {
+ if g.status == "running" && g.reachable == "NO" {
+ svc := g.service
+ if svc == "-" {
+ svc = strings.ToUpper(g.gType) // "VM" or "LXC"
+ }
+ issues = append(issues, serviceHealthIssue{
+ name: g.name,
+ service: svc,
+ node: g.node,
+ })
+ }
+ }
+ if section := buildServiceHealthIssues(issues); section != "" {
+ sb.WriteString(section)
+ }
}
}
diff --git a/internal/ai/patrol_ai_more_test.go b/internal/ai/patrol_ai_more_test.go
index 314ff29a89..7ce574e1c6 100644
--- a/internal/ai/patrol_ai_more_test.go
+++ b/internal/ai/patrol_ai_more_test.go
@@ -285,7 +285,7 @@ func TestSeedResourceInventory_QuietSummary(t *testing.T) {
},
}
- out := ps.seedResourceInventory(state, nil, cfg, time.Now(), true)
+ out := ps.seedResourceInventory(state, nil, cfg, time.Now(), true, nil)
if !strings.Contains(out, "# Nodes: All 2") {
t.Fatalf("expected quiet node summary, got: %s", out)
}
@@ -406,7 +406,7 @@ func TestSeedResourceInventory_DetailedSections(t *testing.T) {
},
}
- out := ps.seedResourceInventory(state, nil, cfg, now, false)
+ out := ps.seedResourceInventory(state, nil, cfg, now, false, nil)
for _, part := range []string{
"# Node Metrics",
"# Guest Metrics",
diff --git a/internal/ai/patrol_context_additional_test.go b/internal/ai/patrol_context_additional_test.go
index 941dbf000a..c780faf443 100644
--- a/internal/ai/patrol_context_additional_test.go
+++ b/internal/ai/patrol_context_additional_test.go
@@ -26,7 +26,7 @@ func TestPatrolService_buildSeedContext_QuietSummary(t *testing.T) {
},
}
- seed, _ := ps.buildSeedContext(state, nil)
+ seed, _ := ps.buildSeedContext(state, nil, nil)
if !strings.Contains(seed, "# Nodes: All 1 healthy") {
t.Fatalf("expected quiet node summary, got:\n%s", seed)
}
@@ -44,7 +44,7 @@ func TestPatrolService_buildSeedContext_ScopeSection(t *testing.T) {
Depth: PatrolDepthQuick,
}
- seed, _ := ps.buildSeedContext(models.StateSnapshot{}, scope)
+ seed, _ := ps.buildSeedContext(models.StateSnapshot{}, scope, nil)
if !strings.Contains(seed, "# Patrol Scope") {
t.Fatalf("expected patrol scope section, got:\n%s", seed)
}
diff --git a/internal/ai/patrol_init.go b/internal/ai/patrol_init.go
index 2c8c4926c2..c4f1a2d499 100644
--- a/internal/ai/patrol_init.go
+++ b/internal/ai/patrol_init.go
@@ -406,6 +406,22 @@ func (p *PatrolService) GetDiscoveryStore() *servicediscovery.Store {
return p.discoveryStore
}
+// SetGuestProber sets the guest prober for pre-patrol reachability checks.
+// This enables the patrol service to ping guests via connected host agents.
+func (p *PatrolService) SetGuestProber(prober GuestProber) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.guestProber = prober
+ log.Info().Msg("AI Patrol: Guest prober set for reachability checks")
+}
+
+// GetGuestProber returns the guest prober for external access.
+func (p *PatrolService) GetGuestProber() GuestProber {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.guestProber
+}
+
// SetMetricsHistoryProvider sets the metrics history provider for enriched context
// This enables the patrol service to compute trends and predictions based on historical data
func (p *PatrolService) SetMetricsHistoryProvider(provider MetricsHistoryProvider) {
diff --git a/internal/ai/patrol_intelligence.go b/internal/ai/patrol_intelligence.go
new file mode 100644
index 0000000000..ab9f82886f
--- /dev/null
+++ b/internal/ai/patrol_intelligence.go
@@ -0,0 +1,282 @@
+// patrol_intelligence.go provides pre-patrol guest intelligence gathering:
+// service identity from the discovery store and network reachability via host agents.
+package ai
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+ "sync"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery"
+ "github.com/rs/zerolog/log"
+)
+
+// GuestProber checks reachability of guest IPs via connected host agents.
+type GuestProber interface {
+ // GetAgentForHost returns the agent ID for a given hostname, if connected.
+ GetAgentForHost(hostname string) (agentID string, ok bool)
+ // PingGuests pings a list of IPs from a specific agent and returns results.
+ PingGuests(ctx context.Context, agentID string, ips []string) (map[string]PingResult, error)
+}
+
+// PingResult holds the result of a reachability check for a single IP.
+type PingResult struct {
+ Reachable bool
+}
+
+// GuestIntelligence enriches a single guest with discovery and reachability data.
+type GuestIntelligence struct {
+ Name string // Human-readable guest name (e.g. "db-server")
+ GuestType string // "vm" or "lxc"
+ ServiceName string // e.g. "PostgreSQL 15", "Nginx" (from discovery)
+ ServiceType string // e.g. "postgres", "nginx" (from discovery)
+ Reachable *bool // nil = not checked (no agent/no IP), true/false = checked
+}
+
+// gatherGuestIntelligence builds a map of guest intelligence keyed by guest ID
+// (e.g. "qemu/100" or "lxc/101"). It loads discovery data for service identity
+// and probes reachability via host agents. The entire operation is best-effort
+// and capped at 5 seconds — errors are logged but never block patrol.
+func (p *PatrolService) gatherGuestIntelligence(ctx context.Context, state models.StateSnapshot) map[string]*GuestIntelligence {
+ intel := make(map[string]*GuestIntelligence)
+
+ // Phase 1: Load discovery data for service identity
+ p.mu.RLock()
+ ds := p.discoveryStore
+ p.mu.RUnlock()
+
+ // Build discovery index: (resourceType, hostID, resourceID) -> discovery
+ type discoveryKey struct {
+ resourceType servicediscovery.ResourceType
+ hostID string
+ resourceID string
+ }
+ discoveryIndex := make(map[discoveryKey]*servicediscovery.ResourceDiscovery)
+
+ if ds != nil {
+ discoveries, err := ds.List()
+ if err != nil {
+ log.Warn().Err(err).Msg("AI Patrol: Failed to list discoveries for guest intelligence")
+ } else {
+ for _, d := range discoveries {
+ key := discoveryKey{
+ resourceType: d.ResourceType,
+ hostID: d.HostID,
+ resourceID: d.ResourceID,
+ }
+ discoveryIndex[key] = d
+ }
+ }
+ }
+
+ // Phase 2: Build GuestIntelligence entry for every guest
+ // Also collect running guests with IPs grouped by node for reachability probing.
+ type guestIPInfo struct {
+ guestID string
+ ip string
+ }
+ nodeGuests := make(map[string][]guestIPInfo) // node name -> guests with IPs
+
+ for _, vm := range state.VMs {
+ if vm.Template {
+ continue
+ }
+ gi := &GuestIntelligence{
+ Name: vm.Name,
+ GuestType: "vm",
+ }
+
+ // Look up discovery
+ vmidStr := strconv.Itoa(vm.VMID)
+ if d, ok := discoveryIndex[discoveryKey{servicediscovery.ResourceTypeVM, vm.Node, vmidStr}]; ok {
+ gi.ServiceName = d.ServiceName
+ gi.ServiceType = d.ServiceType
+ }
+ // Also check Instance as hostID (some deployments use instance name)
+ if gi.ServiceName == "" && vm.Instance != "" && vm.Instance != vm.Node {
+ if d, ok := discoveryIndex[discoveryKey{servicediscovery.ResourceTypeVM, vm.Instance, vmidStr}]; ok {
+ gi.ServiceName = d.ServiceName
+ gi.ServiceType = d.ServiceType
+ }
+ }
+
+ intel[vm.ID] = gi
+
+ // Collect for reachability (only running guests with known IPs)
+ if vm.Status == "running" && len(vm.IPAddresses) > 0 {
+ nodeGuests[vm.Node] = append(nodeGuests[vm.Node], guestIPInfo{
+ guestID: vm.ID,
+ ip: vm.IPAddresses[0],
+ })
+ }
+ }
+
+ for _, ct := range state.Containers {
+ if ct.Template {
+ continue
+ }
+ gi := &GuestIntelligence{
+ Name: ct.Name,
+ GuestType: "lxc",
+ }
+
+ // Look up discovery
+ vmidStr := strconv.Itoa(ct.VMID)
+ if d, ok := discoveryIndex[discoveryKey{servicediscovery.ResourceTypeLXC, ct.Node, vmidStr}]; ok {
+ gi.ServiceName = d.ServiceName
+ gi.ServiceType = d.ServiceType
+ }
+ if gi.ServiceName == "" && ct.Instance != "" && ct.Instance != ct.Node {
+ if d, ok := discoveryIndex[discoveryKey{servicediscovery.ResourceTypeLXC, ct.Instance, vmidStr}]; ok {
+ gi.ServiceName = d.ServiceName
+ gi.ServiceType = d.ServiceType
+ }
+ }
+
+ intel[ct.ID] = gi
+
+ if ct.Status == "running" && len(ct.IPAddresses) > 0 {
+ nodeGuests[ct.Node] = append(nodeGuests[ct.Node], guestIPInfo{
+ guestID: ct.ID,
+ ip: ct.IPAddresses[0],
+ })
+ }
+ }
+
+ // Phase 3: Reachability probing via host agents
+ p.mu.RLock()
+ prober := p.guestProber
+ p.mu.RUnlock()
+
+ if prober == nil || len(nodeGuests) == 0 {
+ return intel
+ }
+
+ var wg sync.WaitGroup
+ var mu sync.Mutex // protects intel map writes
+
+ for node, guests := range nodeGuests {
+ agentID, ok := prober.GetAgentForHost(node)
+ if !ok {
+ continue
+ }
+
+ // Collect unique IPs for this node
+ ips := make([]string, 0, len(guests))
+ ipSeen := make(map[string]bool)
+ for _, g := range guests {
+ if !ipSeen[g.ip] {
+ ips = append(ips, g.ip)
+ ipSeen[g.ip] = true
+ }
+ }
+
+ wg.Add(1)
+ go func(node, agentID string, ips []string, guests []guestIPInfo) {
+ defer wg.Done()
+
+ results, err := prober.PingGuests(ctx, agentID, ips)
+ if err != nil {
+ log.Warn().Err(err).Str("node", node).Msg("AI Patrol: Guest ping probe failed")
+ return
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ for _, g := range guests {
+ if result, ok := results[g.ip]; ok {
+ gi := intel[g.guestID]
+ if gi != nil {
+ reachable := result.Reachable
+ gi.Reachable = &reachable
+ }
+ }
+ }
+ }(node, agentID, ips, guests)
+ }
+
+ // Wait for all probes to complete (bounded by caller's context timeout)
+ done := make(chan struct{})
+ go func() {
+ wg.Wait()
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ // All probes completed
+ case <-ctx.Done():
+ log.Warn().Msg("AI Patrol: Guest reachability probing timed out")
+ }
+
+ probed := 0
+ for _, gi := range intel {
+ if gi.Reachable != nil {
+ probed++
+ }
+ }
+ if probed > 0 {
+ log.Debug().
+ Int("probed", probed).
+ Int("total_guests", len(intel)).
+ Msg("AI Patrol: Guest reachability probing complete")
+ }
+
+ return intel
+}
+
+// formatReachable returns the display string for the Reachable column.
+func formatReachable(r *bool) string {
+ if r == nil {
+ return "-"
+ }
+ if *r {
+ return "yes"
+ }
+ return "NO"
+}
+
+// formatService returns the display string for the Service column.
+func formatService(gi *GuestIntelligence) string {
+ if gi == nil || gi.ServiceName == "" {
+ return "-"
+ }
+ name := gi.ServiceName
+ if len(name) > 25 {
+ name = name[:22] + "..."
+ }
+ return name
+}
+
+// reachableFromIntel extracts the Reachable pointer from a GuestIntelligence entry.
+// Returns nil if the entry is nil (no intelligence available).
+func reachableFromIntel(gi *GuestIntelligence) *bool {
+ if gi == nil {
+ return nil
+ }
+ return gi.Reachable
+}
+
+// serviceHealthIssue represents a running guest that is unreachable.
+type serviceHealthIssue struct {
+ name string
+ service string
+ node string
+}
+
+// buildServiceHealthIssues returns a markdown section listing the given issues.
+// Returns empty string if no issues.
+func buildServiceHealthIssues(issues []serviceHealthIssue) string {
+ if len(issues) == 0 {
+ return ""
+ }
+
+ result := "# Service Health Issues\n"
+ for _, iss := range issues {
+ result += fmt.Sprintf("- %s (%s on %s): Running but UNREACHABLE\n", iss.name, iss.service, iss.node)
+ }
+ result += "\n"
+ return result
+}
diff --git a/internal/ai/patrol_prober.go b/internal/ai/patrol_prober.go
new file mode 100644
index 0000000000..65eceb040a
--- /dev/null
+++ b/internal/ai/patrol_prober.go
@@ -0,0 +1,84 @@
+// patrol_prober.go implements GuestProber using the agentexec system to run
+// ping commands on connected host agents.
+package ai
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+)
+
+// agentExecProber implements GuestProber using the agent execution server.
+type agentExecProber struct {
+ server *agentexec.Server
+}
+
+// NewAgentExecProber creates a GuestProber that runs ping commands via connected agents.
+func NewAgentExecProber(server *agentexec.Server) GuestProber {
+ return &agentExecProber{server: server}
+}
+
+// GetAgentForHost returns the agent ID for a given hostname, if connected.
+func (p *agentExecProber) GetAgentForHost(hostname string) (string, bool) {
+ if p.server == nil {
+ return "", false
+ }
+ return p.server.GetAgentForHost(hostname)
+}
+
+// PingGuests pings a list of IPs from a specific agent and returns results.
+// It composes a batch shell command that runs all pings concurrently as background
+// subshells, so total wall time is ~1 second regardless of guest count.
+func (p *agentExecProber) PingGuests(ctx context.Context, agentID string, ips []string) (map[string]PingResult, error) {
+ if p.server == nil {
+ return nil, fmt.Errorf("agent exec server not available")
+ }
+ if len(ips) == 0 {
+ return map[string]PingResult{}, nil
+ }
+
+ // Build batch ping command: all pings run as background subshells
+ // Each outputs REACH:<ip>:UP or REACH:<ip>:DOWN
+ var sb strings.Builder
+ sb.WriteString("for ip in")
+ for _, ip := range ips {
+ sb.WriteString(" ")
+ sb.WriteString(ip)
+ }
+ sb.WriteString("; do (ping -c1 -W1 \"$ip\" >/dev/null 2>&1 && echo \"REACH:$ip:UP\" || echo \"REACH:$ip:DOWN\") & done; wait")
+
+ result, err := p.server.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
+ RequestID: uuid.New().String(),
+ Command: sb.String(),
+ TargetType: "host",
+ Timeout: 5, // seconds — generous for parallel pings
+ })
+ if err != nil {
+ return nil, fmt.Errorf("ping command failed: %w", err)
+ }
+
+ return parsePingOutput(result.Stdout), nil
+}
+
+// parsePingOutput parses the output of the batch ping command.
+// Expected lines: "REACH:<ip>:UP" or "REACH:<ip>:DOWN"
+func parsePingOutput(output string) map[string]PingResult {
+ results := make(map[string]PingResult)
+ for _, line := range strings.Split(output, "\n") {
+ line = strings.TrimSpace(line)
+ if !strings.HasPrefix(line, "REACH:") {
+ continue
+ }
+ parts := strings.SplitN(line, ":", 3)
+ if len(parts) != 3 {
+ continue
+ }
+ ip := parts[1]
+ up := parts[2] == "UP"
+ results[ip] = PingResult{Reachable: up}
+ }
+ return results
+}
diff --git a/internal/ai/patrol_signals.go b/internal/ai/patrol_signals.go
index 140d1e65e3..3580f4b22e 100644
--- a/internal/ai/patrol_signals.go
+++ b/internal/ai/patrol_signals.go
@@ -72,13 +72,14 @@ func SignalThresholdsFromPatrol(pt PatrolThresholds) SignalThresholds {
}
const (
- SignalSMARTFailure SignalType = "smart_failure"
- SignalHighCPU SignalType = "high_cpu"
- SignalHighMemory SignalType = "high_memory"
- SignalHighDisk SignalType = "high_disk"
- SignalBackupFailed SignalType = "backup_failed"
- SignalBackupStale SignalType = "backup_stale"
- SignalActiveAlert SignalType = "active_alert"
+ SignalSMARTFailure SignalType = "smart_failure"
+ SignalHighCPU SignalType = "high_cpu"
+ SignalHighMemory SignalType = "high_memory"
+ SignalHighDisk SignalType = "high_disk"
+ SignalBackupFailed SignalType = "backup_failed"
+ SignalBackupStale SignalType = "backup_stale"
+ SignalActiveAlert SignalType = "active_alert"
+ SignalGuestUnreachable SignalType = "guest_unreachable"
)
// DetectedSignal represents a problem signal found in tool call results.
@@ -763,6 +764,34 @@ func deduplicateSignals(signals []DetectedSignal) []DetectedSignal {
return result
}
+// DetectReachabilitySignals returns signals for running guests that are unreachable.
+// This is separate from tool-call-based detection since reachability comes from
+// pre-patrol probing, not from LLM tool calls.
+func DetectReachabilitySignals(guestIntel map[string]*GuestIntelligence) []DetectedSignal {
+ var signals []DetectedSignal
+ for guestID, gi := range guestIntel {
+ if gi == nil || gi.Reachable == nil || *gi.Reachable {
+ continue
+ }
+ name := gi.Name
+ if name == "" {
+ name = guestID
+ }
+ summary := fmt.Sprintf("Guest %s is running but not responding to ping", name)
+ signals = append(signals, DetectedSignal{
+ SignalType: SignalGuestUnreachable,
+ ResourceID: guestID,
+ ResourceName: name,
+ ResourceType: gi.GuestType,
+ SuggestedSeverity: "warning",
+ Category: "connectivity",
+ Summary: summary,
+ Evidence: "ICMP ping from host node returned no response",
+ })
+ }
+ return signals
+}
+
// UnmatchedSignals returns signals that don't have a corresponding finding already reported.
// A signal is considered matched if any finding shares the same ResourceID AND Category.
func UnmatchedSignals(signals []DetectedSignal, findings []*Finding) []DetectedSignal {
diff --git a/internal/api/router.go b/internal/api/router.go
index 5917cdd1de..a104c48417 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -2563,6 +2563,11 @@ func (r *Router) initializeAIIntelligenceServices(ctx context.Context, dataDir s
patrol.SetRemediationEngine(remediationEngine)
}
+ // Wire guest prober for pre-patrol reachability checks via host agents
+ if r.agentExecServer != nil {
+ patrol.SetGuestProber(ai.NewAgentExecProber(r.agentExecServer))
+ }
+
// NOTE: Unified finding callback is wired in StartPatrol after findings persistence is loaded
log.Info().Msg("AI Intelligence: Patrol context providers wired up")