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
Update AI core services and adapters
rcourtmane194e17159ff
diff --git a/internal/ai/alert_triggered.go b/internal/ai/alert_triggered.goindex f84c1ae162..9d56f8f481 100644--- a/internal/ai/alert_triggered.go+++ b/internal/ai/alert_triggered.go@@ -196,18 +196,12 @@ func (a *AlertTriggeredAnalyzer) analyzeResource(alert *alerts.Alert, resourceKeDur("duration", duration).Msg("Alert-triggered AI analysis completed with findings")- // Add findings to the patrol service's findings store and trigger investigations- if a.patrolService != nil && a.patrolService.findings != nil {+ // Add findings through the patrol pipeline to keep behavior consistent+ if a.patrolService != nil {for _, finding := range findings {// Link finding to the triggering alertfinding.AlertID = alert.ID- isNew := a.patrolService.findings.Add(finding)-- // Trigger AI investigation for new warning/critical findings- // This is the key connection: alert fires → rule-based finding → AI investigates- if isNew {- a.patrolService.MaybeInvestigateFinding(finding)- }+ a.patrolService.recordFinding(finding)}}} else {diff --git a/internal/ai/discovery_adapter.go b/internal/ai/discovery_adapter.goindex cd0ae0f44b..03972a984e 100644--- a/internal/ai/discovery_adapter.go+++ b/internal/ai/discovery_adapter.go@@ -4,11 +4,11 @@ import ("context""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"- "github.com/rcourtman/pulse-go-rewrite/internal/aidiscovery""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery")-// discoveryCommandAdapter adapts agentexec.Server to aidiscovery.CommandExecutor+// discoveryCommandAdapter adapts agentexec.Server to servicediscovery.CommandExecutortype discoveryCommandAdapter struct {server *agentexec.Server}@@ -18,10 +18,10 @@ func newDiscoveryCommandAdapter(server *agentexec.Server) *discoveryCommandAdaptreturn &discoveryCommandAdapter{server: server}}-// ExecuteCommand implements aidiscovery.CommandExecutor-func (a *discoveryCommandAdapter) ExecuteCommand(ctx context.Context, agentID string, cmd aidiscovery.ExecuteCommandPayload) (*aidiscovery.CommandResultPayload, error) {+// ExecuteCommand implements servicediscovery.CommandExecutor+func (a *discoveryCommandAdapter) ExecuteCommand(ctx context.Context, agentID string, cmd servicediscovery.ExecuteCommandPayload) (*servicediscovery.CommandResultPayload, error) {if a.server == nil {- return &aidiscovery.CommandResultPayload{+ return &servicediscovery.CommandResultPayload{RequestID: cmd.RequestID,Success: false,Error: "agent server not available",@@ -39,7 +39,7 @@ func (a *discoveryCommandAdapter) ExecuteCommand(ctx context.Context, agentID stresult, err := a.server.ExecuteCommand(ctx, agentID, execCmd)if err != nil {- return &aidiscovery.CommandResultPayload{+ return &servicediscovery.CommandResultPayload{RequestID: cmd.RequestID,Success: false,Error: err.Error(),@@ -47,7 +47,7 @@ func (a *discoveryCommandAdapter) ExecuteCommand(ctx context.Context, agentID st}// Convert result back- return &aidiscovery.CommandResultPayload{+ return &servicediscovery.CommandResultPayload{RequestID: result.RequestID,Success: result.Success,Stdout: result.Stdout,@@ -58,16 +58,16 @@ func (a *discoveryCommandAdapter) ExecuteCommand(ctx context.Context, agentID st}, nil}-// GetConnectedAgents implements aidiscovery.CommandExecutor-func (a *discoveryCommandAdapter) GetConnectedAgents() []aidiscovery.ConnectedAgent {+// GetConnectedAgents implements servicediscovery.CommandExecutor+func (a *discoveryCommandAdapter) GetConnectedAgents() []servicediscovery.ConnectedAgent {if a.server == nil {return nil}agents := a.server.GetConnectedAgents()- result := make([]aidiscovery.ConnectedAgent, len(agents))+ result := make([]servicediscovery.ConnectedAgent, len(agents))for i, agent := range agents {- result[i] = aidiscovery.ConnectedAgent{+ result[i] = servicediscovery.ConnectedAgent{AgentID: agent.AgentID,Hostname: agent.Hostname,Version: agent.Version,@@ -79,7 +79,7 @@ func (a *discoveryCommandAdapter) GetConnectedAgents() []aidiscovery.ConnectedAgreturn result}-// IsAgentConnected implements aidiscovery.CommandExecutor+// IsAgentConnected implements servicediscovery.CommandExecutorfunc (a *discoveryCommandAdapter) IsAgentConnected(agentID string) bool {if a.server == nil {return false@@ -92,7 +92,7 @@ func (a *discoveryCommandAdapter) IsAgentConnected(agentID string) bool {return false}-// discoveryStateAdapter adapts StateProvider to aidiscovery.StateProvider+// discoveryStateAdapter adapts StateProvider to servicediscovery.StateProvidertype discoveryStateAdapter struct {provider StateProvider}@@ -102,18 +102,18 @@ func newDiscoveryStateAdapter(provider StateProvider) *discoveryStateAdapter {return &discoveryStateAdapter{provider: provider}}-// GetState implements aidiscovery.StateProvider-func (a *discoveryStateAdapter) GetState() aidiscovery.StateSnapshot {+// GetState implements servicediscovery.StateProvider+func (a *discoveryStateAdapter) GetState() servicediscovery.StateSnapshot {if a.provider == nil {- return aidiscovery.StateSnapshot{}+ return servicediscovery.StateSnapshot{}}state := a.provider.GetState()// Convert VMs- vms := make([]aidiscovery.VM, len(state.VMs))+ vms := make([]servicediscovery.VM, len(state.VMs))for i, vm := range state.VMs {- vms[i] = aidiscovery.VM{+ vms[i] = servicediscovery.VM{VMID: vm.VMID,Name: vm.Name,Node: vm.Node,@@ -123,9 +123,9 @@ func (a *discoveryStateAdapter) GetState() aidiscovery.StateSnapshot {}// Convert Containers- containers := make([]aidiscovery.Container, len(state.Containers))+ containers := make([]servicediscovery.Container, len(state.Containers))for i, c := range state.Containers {- containers[i] = aidiscovery.Container{+ containers[i] = servicediscovery.Container{VMID: c.VMID,Name: c.Name,Node: c.Node,@@ -135,26 +135,26 @@ func (a *discoveryStateAdapter) GetState() aidiscovery.StateSnapshot {}// Convert Docker hosts- dockerHosts := make([]aidiscovery.DockerHost, len(state.DockerHosts))+ dockerHosts := make([]servicediscovery.DockerHost, len(state.DockerHosts))for i, dh := range state.DockerHosts {- containers := make([]aidiscovery.DockerContainer, len(dh.Containers))+ containers := make([]servicediscovery.DockerContainer, len(dh.Containers))for j, dc := range dh.Containers {- ports := make([]aidiscovery.DockerPort, len(dc.Ports))+ ports := make([]servicediscovery.DockerPort, len(dc.Ports))for k, p := range dc.Ports {- ports[k] = aidiscovery.DockerPort{+ ports[k] = servicediscovery.DockerPort{PublicPort: p.PublicPort,PrivatePort: p.PrivatePort,Protocol: p.Protocol,}}- mounts := make([]aidiscovery.DockerMount, len(dc.Mounts))+ mounts := make([]servicediscovery.DockerMount, len(dc.Mounts))for k, m := range dc.Mounts {- mounts[k] = aidiscovery.DockerMount{+ mounts[k] = servicediscovery.DockerMount{Source: m.Source,Destination: m.Destination,}}- containers[j] = aidiscovery.DockerContainer{+ containers[j] = servicediscovery.DockerContainer{ID: dc.ID,Name: dc.Name,Image: dc.Image,@@ -164,14 +164,14 @@ func (a *discoveryStateAdapter) GetState() aidiscovery.StateSnapshot {Mounts: mounts,}}- dockerHosts[i] = aidiscovery.DockerHost{+ dockerHosts[i] = servicediscovery.DockerHost{AgentID: dh.AgentID,Hostname: dh.Hostname,Containers: containers,}}- return aidiscovery.StateSnapshot{+ return servicediscovery.StateSnapshot{VMs: vms,Containers: containers,DockerHosts: dockerHosts,diff --git a/internal/ai/investigation_adapter.go b/internal/ai/investigation_adapter.goindex abb4e4cf7e..630def9b81 100644--- a/internal/ai/investigation_adapter.go+++ b/internal/ai/investigation_adapter.go@@ -49,17 +49,20 @@ func (a *InvestigationOrchestratorAdapter) GetInvestigationByFinding(findingID s// Convert to ai package's InvestigationSession typesession := &InvestigationSession{- ID: inv.ID,- FindingID: inv.FindingID,- SessionID: inv.SessionID,- Status: string(inv.Status),- StartedAt: inv.StartedAt,- CompletedAt: inv.CompletedAt,- TurnCount: inv.TurnCount,- Outcome: string(inv.Outcome),- Summary: inv.Summary,- Error: inv.Error,- ApprovalID: inv.ApprovalID,+ ID: inv.ID,+ FindingID: inv.FindingID,+ SessionID: inv.SessionID,+ Status: string(inv.Status),+ StartedAt: inv.StartedAt,+ CompletedAt: inv.CompletedAt,+ TurnCount: inv.TurnCount,+ Outcome: string(inv.Outcome),+ ToolsAvailable: inv.ToolsAvailable,+ ToolsUsed: inv.ToolsUsed,+ EvidenceIDs: inv.EvidenceIDs,+ Summary: inv.Summary,+ Error: inv.Error,+ ApprovalID: inv.ApprovalID,}if inv.ProposedFix != nil {diff --git a/internal/ai/knowledge/store.go b/internal/ai/knowledge/store.goindex 9bbdc759fb..5554530411 100644--- a/internal/ai/knowledge/store.go+++ b/internal/ai/knowledge/store.go@@ -46,10 +46,12 @@ type GuestKnowledge struct {// Store manages persistent knowledge storage with encryptiontype Store struct {- dataDir string- mu sync.RWMutex- cache map[string]*GuestKnowledge- crypto *crypto.CryptoManager+ dataDir string+ mu sync.RWMutex+ cache map[string]*GuestKnowledge+ crypto *crypto.CryptoManager+ discoveryContextProvider func() string+ discoveryContextProviderForResources func(resourceIDs []string) string}var newCryptoManagerAt = crypto.NewCryptoManagerAt@@ -505,10 +507,316 @@ finalize:return result}+// FormatForContextForResources returns a summary of saved knowledge scoped to specific resources.+// This avoids dumping global notes into targeted patrol runs.+func (s *Store) FormatForContextForResources(resourceIDs []string) string {+ if len(resourceIDs) == 0 {+ return ""+ }++ const maxGuests = 10+ const maxBytes = 8000++ guests, err := s.ListGuests()+ if err != nil || len(guests) == 0 {+ return ""+ }++ resourceTokens := buildResourceIDTokenSet(resourceIDs)+ if len(resourceTokens) == 0 {+ return ""+ }++ // Load only matching guests with notes and sort by most recently updated+ type guestWithTime struct {+ id string+ knowledge *GuestKnowledge+ }+ var guestsWithNotes []guestWithTime++ for _, guestID := range guests {+ if !matchesResourceTokens(guestID, resourceTokens) {+ continue+ }+ knowledge, err := s.GetKnowledge(guestID)+ if err != nil || len(knowledge.Notes) == 0 {+ continue+ }+ guestsWithNotes = append(guestsWithNotes, guestWithTime{id: guestID, knowledge: knowledge})+ }++ if len(guestsWithNotes) == 0 {+ return ""+ }++ // Sort by UpdatedAt descending (most recent first)+ for i := 0; i < len(guestsWithNotes)-1; i++ {+ for j := i + 1; j < len(guestsWithNotes); j++ {+ if guestsWithNotes[j].knowledge.UpdatedAt.After(guestsWithNotes[i].knowledge.UpdatedAt) {+ guestsWithNotes[i], guestsWithNotes[j] = guestsWithNotes[j], guestsWithNotes[i]+ }+ }+ }++ totalGuests := len(guestsWithNotes)+ totalNotes := 0+ for _, g := range guestsWithNotes {+ totalNotes += len(g.knowledge.Notes)+ }++ // Limit to maxGuests+ truncatedGuests := false+ if len(guestsWithNotes) > maxGuests {+ guestsWithNotes = guestsWithNotes[:maxGuests]+ truncatedGuests = true+ }++ var sections []string+ includedNotes := 0+ currentBytes := 0++ for _, g := range guestsWithNotes {+ knowledge := g.knowledge++ guestName := knowledge.GuestName+ if guestName == "" {+ guestName = g.id+ }++ byCategory := make(map[string][]Note)+ for _, note := range knowledge.Notes {+ byCategory[note.Category] = append(byCategory[note.Category], note)+ }++ guestSection := fmt.Sprintf("\n### %s (%s)", guestName, knowledge.GuestType)++ categoryOrder := []string{"credential", "service", "path", "config", "learning", "infrastructure"}+ for _, cat := range categoryOrder {+ notes, ok := byCategory[cat]+ if !ok || len(notes) == 0 {+ continue+ }+ for _, note := range notes {+ content := note.Content+ if cat == "credential" && len(content) > 6 {+ content = content[:2] + "****" + content[len(content)-2:]+ }+ noteLine := fmt.Sprintf("\n- **%s**: %s", note.Title, content)++ if currentBytes+len(guestSection)+len(noteLine) > maxBytes {+ if includedNotes > 0 {+ log.Warn().+ Int("total_notes", totalNotes).+ Int("included_notes", includedNotes).+ Int("total_guests", totalGuests).+ Int("max_bytes", maxBytes).+ Msg("Knowledge context truncated to prevent bloat - consider cleaning up old notes")+ }+ goto finalize+ }+ guestSection += noteLine+ includedNotes+++ }+ }++ currentBytes += len(guestSection)+ sections = append(sections, guestSection)+ }++finalize:+ if len(sections) == 0 {+ return ""+ }++ var header string+ if truncatedGuests || includedNotes < totalNotes {+ header = fmt.Sprintf("\n\n## Saved Knowledge (%d/%d notes from %d/%d guests, most recent)\n",+ includedNotes, totalNotes, len(sections), totalGuests)+ } else {+ header = fmt.Sprintf("\n\n## Saved Knowledge (%d notes across %d guests)\n", totalNotes, len(sections))+ }+ result := header+ result += "This is information learned from previous sessions. Use it to avoid rediscovery.\n"+ result += strings.Join(sections, "\n")++ return result+}++// SetDiscoveryContextProvider sets the function that provides discovery context.+// This allows the knowledge store to include deep-scanned infrastructure info+// (service versions, CLI access, config paths, ports) in the context for investigations.+func (s *Store) SetDiscoveryContextProvider(provider func() string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.discoveryContextProvider = provider+}++// SetDiscoveryContextProviderForResources sets the provider for scoped discovery context.+// This allows Patrol to request discovery context for specific resources.+func (s *Store) SetDiscoveryContextProviderForResources(provider func(resourceIDs []string) string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.discoveryContextProviderForResources = provider+}+// GetInfrastructureContext returns all discovered infrastructure formatted for AI context.// This is specifically used by Patrol and investigations to understand where services run// and how to interact with them (e.g., knowing PBS runs in Docker so commands need docker exec).+//+// It combines two sources:+// 1. Discovery data (deep-scanned service details, versions, CLI access, ports)+// 2. Legacy knowledge notes (for backward compatibility)func (s *Store) GetInfrastructureContext() string {+ s.mu.RLock()+ discoveryProvider := s.discoveryContextProvider+ s.mu.RUnlock()++ var sb strings.Builder++ // First, include discovery context (the rich, deep-scanned data)+ if discoveryProvider != nil {+ if discoveryContext := discoveryProvider(); discoveryContext != "" {+ sb.WriteString(discoveryContext)+ }+ }++ // Then, include legacy knowledge notes (for backward compatibility)+ legacyContext := s.getLegacyInfrastructureContext()+ if legacyContext != "" {+ // Only add if we don't already have discovery context+ // (discovery is more comprehensive and replaces legacy notes)+ if sb.Len() == 0 {+ sb.WriteString(legacyContext)+ }+ }++ return sb.String()+}++// GetInfrastructureContextForResources returns discovery context scoped to specific resources.+// If no scoped provider is configured, it returns an empty string to avoid over-broad context.+func (s *Store) GetInfrastructureContextForResources(resourceIDs []string) string {+ if len(resourceIDs) == 0 {+ return s.GetInfrastructureContext()+ }++ s.mu.RLock()+ provider := s.discoveryContextProviderForResources+ s.mu.RUnlock()++ if provider == nil {+ return ""+ }++ return provider(resourceIDs)+}++func buildResourceIDTokenSet(resourceIDs []string) map[string]struct{} {+ tokens := make(map[string]struct{})+ for _, id := range resourceIDs {+ addResourceIDTokens(tokens, id)+ }+ return tokens+}++func addResourceIDTokens(tokens map[string]struct{}, resourceID string) {+ trimmed := strings.TrimSpace(resourceID)+ if trimmed == "" {+ return+ }++ addToken(tokens, trimmed)++ if last := lastSegment(trimmed, '/'); last != "" {+ addToken(tokens, last)+ }+ if last := lastSegment(trimmed, ':'); last != "" {+ addToken(tokens, last)+ }++ lower := strings.ToLower(trimmed)+ if strings.HasPrefix(lower, "vm-") {+ addToken(tokens, trimmed[3:])+ }+ if strings.HasPrefix(lower, "ct-") {+ addToken(tokens, trimmed[3:])+ }+ if strings.HasPrefix(lower, "lxc-") {+ addToken(tokens, trimmed[4:])+ }++ if strings.Contains(lower, "qemu/") || strings.Contains(lower, "lxc/") || strings.HasPrefix(lower, "vm-") || strings.HasPrefix(lower, "ct-") {+ if digits := trailingDigits(trimmed); digits != "" {+ addToken(tokens, digits)+ }+ }++ if strings.Contains(trimmed, ":") {+ parts := strings.SplitN(trimmed, ":", 2)+ if len(parts) == 2 {+ rest := parts[1]+ if slash := strings.Index(rest, "/"); slash >= 0 {+ host := strings.TrimSpace(rest[:slash])+ container := strings.TrimSpace(rest[slash+1:])+ addToken(tokens, host)+ addToken(tokens, container)+ }+ }+ }+}++func matchesResourceTokens(guestID string, tokens map[string]struct{}) bool {+ if guestID == "" || len(tokens) == 0 {+ return false+ }+ guestTokens := buildResourceIDTokenSet([]string{guestID})+ for token := range guestTokens {+ if _, ok := tokens[token]; ok {+ return true+ }+ }+ return false+}++func addToken(tokens map[string]struct{}, value string) {+ trimmed := strings.TrimSpace(value)+ if trimmed == "" {+ return+ }+ tokens[strings.ToLower(trimmed)] = struct{}{}+}++func lastSegment(value string, sep byte) string {+ if value == "" {+ return ""+ }+ idx := strings.LastIndexByte(value, sep)+ if idx == -1 || idx+1 >= len(value) {+ return ""+ }+ return value[idx+1:]+}++func trailingDigits(value string) string {+ if value == "" {+ return ""+ }+ i := len(value)+ for i > 0 {+ c := value[i-1]+ if c < '0' || c > '9' {+ break+ }+ i--+ }+ if i == len(value) {+ return ""+ }+ return value[i:]+}++// getLegacyInfrastructureContext returns infrastructure context from legacy knowledge notes.+func (s *Store) getLegacyInfrastructureContext() string {guests, err := s.ListGuests()if err != nil || len(guests) == 0 {return ""diff --git a/internal/ai/knowledge/store_extended_test.go b/internal/ai/knowledge/store_extended_test.goindex 4c17e92935..efff718b57 100644--- a/internal/ai/knowledge/store_extended_test.go+++ b/internal/ai/knowledge/store_extended_test.go@@ -2,6 +2,7 @@ package knowledgeimport ("os"+ "strings""testing")@@ -123,6 +124,63 @@ func TestStore_SaveNote_UpdateExisting(t *testing.T) {}}+func TestStore_FormatForContextForResources_Scoped(t *testing.T) {+ tmpDir, err := os.MkdirTemp("", "knowledge-test")+ if err != nil {+ t.Fatalf("Failed to create temp dir: %v", err)+ }+ defer os.RemoveAll(tmpDir)++ store, err := NewStore(tmpDir)+ if err != nil {+ t.Fatalf("Failed to create store: %v", err)+ }++ // Seed knowledge for multiple resources+ if err := store.SaveNote("vm-100", "web-server", "vm", "config", "DB", "Postgres"); err != nil {+ t.Fatalf("Failed to save note: %v", err)+ }+ if err := store.SaveNote("qemu/200", "app", "vm", "service", "API", "FastAPI"); err != nil {+ t.Fatalf("Failed to save note: %v", err)+ }+ if err := store.SaveNote("host:alpha", "alpha", "host", "service", "Agent", "v1"); err != nil {+ t.Fatalf("Failed to save note: %v", err)+ }+ if err := store.SaveNote("docker:host1/container1", "container1", "docker", "service", "Web", "Nginx"); err != nil {+ t.Fatalf("Failed to save note: %v", err)+ }++ // Scope to a single VM by qemu resource ID+ scoped := store.FormatForContextForResources([]string{"qemu/100"})+ if scoped == "" {+ t.Fatalf("Expected scoped context, got empty")+ }+ if !strings.Contains(scoped, "web-server") {+ t.Fatalf("Expected vm-100 notes in scoped context")+ }+ if strings.Contains(scoped, "app") {+ t.Fatalf("Did not expect qemu/200 notes in scoped context")+ }++ // Scope to docker resource ID+ scoped = store.FormatForContextForResources([]string{"docker:host1/container1"})+ if !strings.Contains(scoped, "container1") {+ t.Fatalf("Expected docker container notes in scoped context")+ }+ if strings.Contains(scoped, "web-server") {+ t.Fatalf("Did not expect vm-100 notes in docker scoped context")+ }++ // Scope to host resource ID+ scoped = store.FormatForContextForResources([]string{"host:alpha"})+ if !strings.Contains(scoped, "alpha") {+ t.Fatalf("Expected host notes in scoped context")+ }+ if strings.Contains(scoped, "container1") {+ t.Fatalf("Did not expect docker notes in host scoped context")+ }+}+func TestStore_DeleteNote(t *testing.T) {tmpDir, err := os.MkdirTemp("", "knowledge-test")if err != nil {diff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex 2a4a854fc8..333aa68122 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -17,9 +17,9 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/knowledge""github.com/rcourtman/pulse-go-rewrite/internal/ai/memory""github.com/rcourtman/pulse-go-rewrite/internal/ai/remediation"- "github.com/rcourtman/pulse-go-rewrite/internal/aidiscovery""github.com/rcourtman/pulse-go-rewrite/internal/alerts""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery""github.com/rs/zerolog/log")@@ -211,17 +211,26 @@ type PatrolStatus struct {ErrorCount int `json:"error_count"`Healthy bool `json:"healthy"`IntervalMs int64 `json:"interval_ms"` // Patrol interval in milliseconds+ BlockedReason string `json:"blocked_reason,omitempty"`+ BlockedAt *time.Time `json:"blocked_at,omitempty"`}// PatrolRunRecord represents a single patrol check runtype PatrolRunRecord struct {- ID string `json:"id"`- StartedAt time.Time `json:"started_at"`- CompletedAt time.Time `json:"completed_at"`- Duration time.Duration `json:"-"`- DurationMs int64 `json:"duration_ms"`- Type string `json:"type"` // Always "patrol" now (kept for backwards compat)- ResourcesChecked int `json:"resources_checked"`+ ID string `json:"id"`+ StartedAt time.Time `json:"started_at"`+ CompletedAt time.Time `json:"completed_at"`+ Duration time.Duration `json:"-"`+ DurationMs int64 `json:"duration_ms"`+ Type string `json:"type"` // Always "patrol" now (kept for backwards compat)+ TriggerReason string `json:"trigger_reason,omitempty"`+ ScopeResourceIDs []string `json:"scope_resource_ids,omitempty"`+ ScopeResourceTypes []string `json:"scope_resource_types,omitempty"`+ ScopeDepth string `json:"scope_depth,omitempty"`+ ScopeContext string `json:"scope_context,omitempty"`+ AlertID string `json:"alert_id,omitempty"`+ FindingID string `json:"finding_id,omitempty"`+ ResourcesChecked int `json:"resources_checked"`// Breakdown by resource typeNodesChecked int `json:"nodes_checked"`GuestsChecked int `json:"guests_checked"`@@ -307,18 +316,21 @@ type InvestigationFinding struct {// InvestigationSession represents the result of an investigation (minimal interface)type InvestigationSession struct {- ID string `json:"id"`- FindingID string `json:"finding_id"`- SessionID string `json:"session_id"`- Status string `json:"status"`- StartedAt time.Time `json:"started_at"`- CompletedAt *time.Time `json:"completed_at,omitempty"`- TurnCount int `json:"turn_count"`- Outcome string `json:"outcome,omitempty"`- Summary string `json:"summary,omitempty"`- Error string `json:"error,omitempty"`- ProposedFix *InvestigationFix `json:"proposed_fix,omitempty"`- ApprovalID string `json:"approval_id,omitempty"`+ ID string `json:"id"`+ FindingID string `json:"finding_id"`+ SessionID string `json:"session_id"`+ Status string `json:"status"`+ StartedAt time.Time `json:"started_at"`+ CompletedAt *time.Time `json:"completed_at,omitempty"`+ TurnCount int `json:"turn_count"`+ Outcome string `json:"outcome,omitempty"`+ ToolsAvailable []string `json:"tools_available,omitempty"`+ ToolsUsed []string `json:"tools_used,omitempty"`+ EvidenceIDs []string `json:"evidence_ids,omitempty"`+ Summary string `json:"summary,omitempty"`+ Error string `json:"error,omitempty"`+ ProposedFix *InvestigationFix `json:"proposed_fix,omitempty"`+ ApprovalID string `json:"approval_id,omitempty"`}// InvestigationFix represents a proposed remediation action@@ -341,16 +353,16 @@ type PatrolService struct {thresholdProvider ThresholdProviderconfig PatrolConfigfindings *FindingsStore- knowledgeStore *knowledge.Store // For per-resource notes in patrol context- discoveryStore *aidiscovery.Store // For AI-discovered infrastructure context- metricsHistory MetricsHistoryProvider // For trend analysis and predictions- baselineStore *baseline.Store // For anomaly detection via learned baselines- changeDetector *ChangeDetector // For tracking infrastructure changes- remediationLog *RemediationLog // For tracking remediation actions- patternDetector *PatternDetector // For failure prediction from historical patterns- correlationDetector *CorrelationDetector // For multi-resource correlation- incidentStore *memory.IncidentStore // For incident timeline capture- alertResolver AlertResolver // For AI-based alert resolution+ knowledgeStore *knowledge.Store // For per-resource notes in patrol context+ discoveryStore *servicediscovery.Store // For AI-discovered infrastructure context+ metricsHistory MetricsHistoryProvider // For trend analysis and predictions+ baselineStore *baseline.Store // For anomaly detection via learned baselines+ changeDetector *ChangeDetector // For tracking infrastructure changes+ remediationLog *RemediationLog // For tracking remediation actions+ patternDetector *PatternDetector // For failure prediction from historical patterns+ correlationDetector *CorrelationDetector // For multi-resource correlation+ incidentStore *memory.IncidentStore // For incident timeline capture+ alertResolver AlertResolver // For AI-based alert resolution// New AI intelligence providers (Phase 6)learningProvider LearningProvider // For learned preferences from user feedback@@ -374,20 +386,24 @@ type PatrolService struct {// Unified findings callback - pushes findings to unified storeunifiedFindingCallback UnifiedFindingCallback+ // Unified resolver callback - marks findings resolved in unified store+ unifiedFindingResolver func(findingID string)// Cached thresholds (recalculated when thresholdProvider changes)thresholds PatrolThresholdsproactiveMode bool // When true, warn before thresholds; when false, use exact thresholds// Runtime state- running bool- runInProgress bool- stopCh chan struct{}- configChanged chan struct{} // Signal when config changes to reset ticker- lastPatrol time.Time- lastDuration time.Duration- resourcesChecked int- errorCount int+ running bool+ runInProgress bool+ stopCh chan struct{}+ configChanged chan struct{} // Signal when config changes to reset ticker+ lastPatrol time.Time+ lastDuration time.Duration+ resourcesChecked int+ errorCount int+ lastBlockedReason string+ lastBlockedAt time.Time// Patrol run history with persistence supportrunHistoryStore *PatrolRunHistoryStore@@ -521,6 +537,71 @@ func (p *PatrolService) SetUnifiedFindingCallback(cb UnifiedFindingCallback) {}}+// SetUnifiedFindingResolver sets the callback for marking findings resolved in the unified store.+func (p *PatrolService) SetUnifiedFindingResolver(cb func(findingID string)) {+ p.mu.Lock()+ defer p.mu.Unlock()+ p.unifiedFindingResolver = cb+ if cb != nil {+ log.Info().Msg("Unified finding resolver configured for patrol")+ }+}++// recordFinding stores a finding, syncs it to the unified store, and triggers follow-up actions.+func (p *PatrolService) recordFinding(f *Finding) bool {+ if p == nil || p.findings == nil || f == nil {+ return false+ }++ isNew := p.findings.Add(f)+ stored := p.findings.Get(f.ID)+ if stored == nil {+ return false+ }++ if isNew {+ log.Info().+ Str("finding_id", stored.ID).+ Str("severity", string(stored.Severity)).+ Str("resource", stored.ResourceName).+ Str("title", stored.Title).+ Msg("AI Patrol: New finding")++ // Generate remediation plan for actionable findings+ // Skip internal error findings (not actionable by users)+ if !(stored.Key == "ai-patrol-error" || stored.ResourceID == "ai-service") {+ p.generateRemediationPlan(stored)+ }+ }++ // Push to unified store only if finding is active (not suppressed/dismissed)+ if p.unifiedFindingCallback != nil && stored.IsActive() {+ p.unifiedFindingCallback(stored)+ }++ // Trigger autonomous investigation if enabled and finding warrants it+ p.MaybeInvestigateFinding(stored)++ return isNew+}++func (p *PatrolService) setBlockedReason(reason string) {+ if reason == "" {+ return+ }+ p.mu.Lock()+ p.lastBlockedReason = reason+ p.lastBlockedAt = time.Now()+ p.mu.Unlock()+}++func (p *PatrolService) clearBlockedReason() {+ p.mu.Lock()+ p.lastBlockedReason = ""+ p.lastBlockedAt = time.Time{}+ p.mu.Unlock()+}+// generateRemediationPlan creates a remediation plan for a finding if appropriate.// Only generates plans for critical/warning findings when a remediation engine is configured.func (p *PatrolService) generateRemediationPlan(finding *Finding) {@@ -897,9 +978,9 @@ func (p *PatrolService) GetKnowledgeStore() *knowledge.Store {return p.knowledgeStore}-// SetDiscoveryStore sets the AI discovery store for infrastructure context+// SetDiscoveryStore sets the discovery store for infrastructure context// This enables the patrol service to include discovered service info in prompts-func (p *PatrolService) SetDiscoveryStore(store *aidiscovery.Store) {+func (p *PatrolService) SetDiscoveryStore(store *servicediscovery.Store) {p.mu.Lock()defer p.mu.Unlock()p.discoveryStore = store@@ -907,7 +988,7 @@ func (p *PatrolService) SetDiscoveryStore(store *aidiscovery.Store) {}// GetDiscoveryStore returns the discovery store for external access-func (p *PatrolService) GetDiscoveryStore() *aidiscovery.Store {+func (p *PatrolService) GetDiscoveryStore() *servicediscovery.Store {p.mu.RLock()defer p.mu.RUnlock()return p.discoveryStore@@ -1055,6 +1136,34 @@ func (p *PatrolService) TriggerScopedPatrol(ctx context.Context, scope PatrolScoreturn}+ // Filter out empty resource IDs to prevent accidentally matching all resources+ filteredIDs := make([]string, 0, len(scope.ResourceIDs))+ for _, id := range scope.ResourceIDs {+ if trimmed := strings.TrimSpace(id); trimmed != "" {+ filteredIDs = append(filteredIDs, trimmed)+ }+ }+ scope.ResourceIDs = filteredIDs++ // Filter out empty resource types+ filteredTypes := make([]string, 0, len(scope.ResourceTypes))+ for _, t := range scope.ResourceTypes {+ if trimmed := strings.TrimSpace(t); trimmed != "" {+ filteredTypes = append(filteredTypes, trimmed)+ }+ }+ scope.ResourceTypes = filteredTypes++ // If no valid scope after filtering, skip - scheduled patrols provide full coverage+ if len(scope.ResourceIDs) == 0 && len(scope.ResourceTypes) == 0 {+ log.Debug().+ Str("reason", string(scope.Reason)).+ Msg("AI Patrol: Scoped patrol skipped - no valid resource IDs or types after filtering")+ return+ }++ scope = p.addDiscoveryScopeHint(scope)+// Log the scoped patrollog.Info().Str("reason", string(scope.Reason)).@@ -1064,16 +1173,68 @@ func (p *PatrolService) TriggerScopedPatrol(ctx context.Context, scope PatrolScoStr("context", scope.Context).Msg("AI Patrol: Running scoped patrol")- // If no specific resources or types are specified, run full patrol- if len(scope.ResourceIDs) == 0 && len(scope.ResourceTypes) == 0 {- p.runPatrol(ctx)- return- }-// Run scoped patrol with filtered resourcesp.runScopedPatrol(ctx, scope)}+func (p *PatrolService) addDiscoveryScopeHint(scope PatrolScope) PatrolScope {+ if len(scope.ResourceIDs) == 0 {+ return scope+ }++ if strings.Contains(strings.ToLower(scope.Context), "discovery:") {+ return scope+ }++ p.mu.RLock()+ discoveryStore := p.discoveryStore+ p.mu.RUnlock()++ if discoveryStore == nil {+ return scope+ }++ discoveries, err := discoveryStore.List()+ if err != nil || len(discoveries) == 0 {+ if err != nil {+ log.Debug().Err(err).Msg("AI Patrol: Failed to load discovery data for scope hints")+ }+ return scope+ }++ filtered := servicediscovery.FilterDiscoveriesByResourceIDs(discoveries, scope.ResourceIDs)+ hint := servicediscovery.FormatScopeHint(filtered)+ if hint == "" {+ return scope+ }+ if strings.Contains(scope.Context, hint) {+ return scope+ }++ const maxScopeContextLen = 240+ if scope.Context == "" {+ scope.Context = truncateScopeContext(hint, maxScopeContextLen)+ return scope+ }+ if len(scope.Context) >= maxScopeContextLen {+ return scope+ }++ scope.Context = truncateScopeContext(scope.Context+" | "+hint, maxScopeContextLen)++ return scope+}++func truncateScopeContext(value string, max int) string {+ if max <= 0 || len(value) <= max {+ return value+ }+ if max <= 3 {+ return value[:max]+ }+ return value[:max-3] + "..."+}+// runScopedPatrol runs a patrol on a filtered subset of resources.// This provides token-efficient analysis for event-driven patrols.func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope) {@@ -1091,13 +1252,28 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)}defer p.endRun()- // Check if circuit breaker allows LLM calls+ // Check if circuit breaker allows LLM calls.llmAllowed := breaker == nil || breaker.Allow()if !llmAllowed {- log.Warn().Msg("AI Patrol: Circuit breaker is open for scoped patrol, running heuristics only")+ log.Warn().Msg("AI Patrol: Circuit breaker is open for scoped patrol (LLM calls blocked)")}start := time.Now()+ var runStats struct {+ resourceCount int+ nodesChecked int+ guestsChecked int+ dockerChecked int+ storageChecked int+ hostsChecked int+ pbsChecked int+ kubernetesChecked int+ newFindings int+ existingFindings int+ findingIDs []string+ errors int+ aiAnalysis *AIAnalysisResult+ }// Get current stateif p.stateProvider == nil {@@ -1147,6 +1323,44 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)Str("reason", string(scope.Reason)).Msg("AI Patrol: Running scoped analysis")+ // Track run statistics+ if cfg.AnalyzeNodes {+ runStats.nodesChecked = len(filteredState.Nodes)+ }+ if cfg.AnalyzeGuests {+ runStats.guestsChecked = len(filteredState.VMs) + len(filteredState.Containers)+ }+ if cfg.AnalyzeDocker {+ runStats.dockerChecked = len(filteredState.DockerHosts)+ }+ if cfg.AnalyzeStorage {+ runStats.storageChecked = len(filteredState.Storage)+ }+ if cfg.AnalyzePBS {+ runStats.pbsChecked = len(filteredState.PBSInstances)+ }+ if cfg.AnalyzeHosts {+ runStats.hostsChecked = len(filteredState.Hosts)+ }+ if cfg.AnalyzeKubernetes {+ runStats.kubernetesChecked = len(filteredState.KubernetesClusters)+ }+ runStats.resourceCount = resourceCount++ trackFinding := func(f *Finding) {+ isNew := p.recordFinding(f)+ if isNew {+ if f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical {+ runStats.newFindings+++ }+ } else {+ runStats.existingFindings+++ }+ if f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical {+ runStats.findingIDs = append(runStats.findingIDs, f.ID)+ }+ }+// Determine if we can run LLM analysisaiServiceEnabled := p.aiService != nil && p.aiService.IsEnabled()hasPatrolFeature := aiServiceEnabled && p.aiService.HasLicenseFeature(FeatureAIPatrol)@@ -1159,96 +1373,106 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)} else if !llmAllowed {reason = "circuit breaker is open"}- log.Debug().Str("reason", reason).Msg("AI Patrol: Running scoped heuristic analysis only")- // Run heuristics on filtered state only- for _, f := range p.runHeuristicAnalysis(filteredState) {- isNew := p.findings.Add(f)- if isNew && (f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical) {- log.Info().- Str("finding_id", f.ID).- Str("severity", string(f.Severity)).- Str("resource", f.ResourceName).- Str("title", f.Title).- Msg("AI Patrol (scoped): New finding")- p.generateRemediationPlan(f)- }- // Push to unified store if active- if p.unifiedFindingCallback != nil {- if stored := p.findings.Get(f.ID); stored != nil && stored.IsActive() {- p.unifiedFindingCallback(stored)- }- }- }+ p.setBlockedReason(reason)+ log.Info().Str("reason", reason).Msg("AI Patrol: Skipping scoped run - AI unavailable")+ return} else {+ p.clearBlockedReason()// Run AI analysis on filtered state- aiResult, aiErr := p.runAIAnalysis(ctx, filteredState)+ aiResult, aiErr := p.runScopedAIAnalysis(ctx, filteredState, scope)if aiErr != nil {- log.Warn().Err(aiErr).Msg("AI Patrol (scoped): LLM analysis failed, running heuristics as safety net")- for _, f := range p.runHeuristicAnalysis(filteredState) {- isNew := p.findings.Add(f)- if isNew && (f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical) {- log.Info().- Str("finding_id", f.ID).- Str("severity", string(f.Severity)).- Str("resource", f.ResourceName).- Str("title", f.Title).- Msg("AI Patrol (scoped): New finding")- p.generateRemediationPlan(f)- }- // Push to unified store if active- if p.unifiedFindingCallback != nil {- if stored := p.findings.Get(f.ID); stored != nil && stored.IsActive() {- p.unifiedFindingCallback(stored)- }- }- }+ log.Warn().Err(aiErr).Msg("AI Patrol (scoped): LLM analysis failed")+ runStats.errors++} else if aiResult != nil {+ runStats.aiAnalysis = aiResultif len(aiResult.Findings) == 0 {- log.Warn().Msg("AI Patrol (scoped): LLM response contained no parseable findings, running heuristics as safety net")- for _, f := range p.runHeuristicAnalysis(filteredState) {- isNew := p.findings.Add(f)- if isNew && (f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical) {- log.Info().- Str("finding_id", f.ID).- Str("severity", string(f.Severity)).- Str("resource", f.ResourceName).- Str("title", f.Title).- Msg("AI Patrol (scoped): New finding")- p.generateRemediationPlan(f)- }- // Push to unified store if active- if p.unifiedFindingCallback != nil {- if stored := p.findings.Get(f.ID); stored != nil && stored.IsActive() {- p.unifiedFindingCallback(stored)- }- }- }+ log.Warn().Msg("AI Patrol (scoped): LLM response contained no parseable findings")} else {for _, f := range aiResult.Findings {- isNew := p.findings.Add(f)- if isNew && (f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical) {- log.Info().- Str("finding_id", f.ID).- Str("severity", string(f.Severity)).- Str("resource", f.ResourceName).- Str("title", f.Title).- Msg("AI Patrol (scoped): New finding")- if !(f.Key == "ai-patrol-error" || f.ResourceID == "ai-service") {- p.generateRemediationPlan(f)- }- }- // Push to unified store if active- if p.unifiedFindingCallback != nil {- if stored := p.findings.Get(f.ID); stored != nil && stored.IsActive() {- p.unifiedFindingCallback(stored)- }- }+ trackFinding(f)}}}}duration := time.Since(start)+ completedAt := time.Now()++ // Build findings summary string+ summary := p.findings.GetSummary()+ var findingsSummaryStr string+ var status string+ totalActive := summary.Critical + summary.Warning+ if totalActive == 0 {+ findingsSummaryStr = "All healthy"+ status = "healthy"+ } else {+ parts := []string{}+ if summary.Critical > 0 {+ parts = append(parts, fmt.Sprintf("%d critical", summary.Critical))+ }+ if summary.Warning > 0 {+ parts = append(parts, fmt.Sprintf("%d warning", summary.Warning))+ }+ findingsSummaryStr = fmt.Sprintf("%s", joinParts(parts))+ if summary.Critical > 0 {+ status = "critical"+ } else {+ status = "issues_found"+ }+ }+ if runStats.errors > 0 {+ status = "error"+ if findingsSummaryStr == "All healthy" {+ findingsSummaryStr = fmt.Sprintf("Analysis incomplete (%d errors)", runStats.errors)+ }+ }++ runRecord := PatrolRunRecord{+ ID: fmt.Sprintf("%d", start.UnixNano()),+ StartedAt: start,+ CompletedAt: completedAt,+ Duration: duration,+ DurationMs: duration.Milliseconds(),+ Type: "scoped",+ TriggerReason: string(scope.Reason),+ ScopeResourceIDs: scope.ResourceIDs,+ ScopeResourceTypes: scope.ResourceTypes,+ ScopeDepth: scope.Depth.String(),+ ScopeContext: scope.Context,+ AlertID: scope.AlertID,+ FindingID: scope.FindingID,+ ResourcesChecked: runStats.resourceCount,+ NodesChecked: runStats.nodesChecked,+ GuestsChecked: runStats.guestsChecked,+ DockerChecked: runStats.dockerChecked,+ StorageChecked: runStats.storageChecked,+ HostsChecked: runStats.hostsChecked,+ PBSChecked: runStats.pbsChecked,+ KubernetesChecked: runStats.kubernetesChecked,+ NewFindings: runStats.newFindings,+ ExistingFindings: runStats.existingFindings,+ FindingsSummary: findingsSummaryStr,+ FindingIDs: runStats.findingIDs,+ ErrorCount: runStats.errors,+ Status: status,+ }++ if runStats.aiAnalysis != nil {+ runRecord.AIAnalysis = runStats.aiAnalysis.Response+ runRecord.InputTokens = runStats.aiAnalysis.InputTokens+ runRecord.OutputTokens = runStats.aiAnalysis.OutputTokens+ }++ p.mu.Lock()+ p.lastPatrol = completedAt+ p.lastDuration = duration+ p.resourcesChecked = runStats.resourceCount+ p.errorCount = runStats.errors+ p.mu.Unlock()++ p.runHistoryStore.Add(runRecord)+log.Info().Dur("duration", duration).Int("resources", resourceCount).@@ -1534,11 +1758,15 @@ func (p *PatrolService) GetStatus() PatrolStatus {FindingsCount: len(p.findings.GetActive(FindingSeverityInfo)),ErrorCount: p.errorCount,IntervalMs: intervalMs,+ BlockedReason: p.lastBlockedReason,}if !p.lastPatrol.IsZero() {status.LastPatrolAt = &p.lastPatrol}+ if !p.lastBlockedAt.IsZero() {+ status.BlockedAt = &p.lastBlockedAt+ }// Calculate next patrol time only when patrol is enabledif p.config.Enabled && interval > 0 && !p.lastPatrol.IsZero() {@@ -1574,9 +1802,16 @@ func (p *PatrolService) SubscribeToStream() chan PatrolStreamEvent {// UnsubscribeFromStream removes a subscriberfunc (p *PatrolService) UnsubscribeFromStream(ch chan PatrolStreamEvent) {p.streamMu.Lock()+ _, exists := p.streamSubscribers[ch]delete(p.streamSubscribers, ch)p.streamMu.Unlock()- close(ch)++ // Only close if we actually removed it from the map+ // (broadcast may have already removed and closed it)+ if exists {+ defer func() { recover() }() // Safety net for race with broadcast cleanup+ close(ch)+ }}// broadcast sends an event to all subscribers@@ -1694,7 +1929,7 @@ func (p *PatrolService) patrolLoop(ctx context.Context) {}if !skipInitial {- p.runPatrol(ctx)+ p.runPatrolWithTrigger(ctx, TriggerReasonStartup, nil)}case <-p.stopCh:return@@ -1713,7 +1948,7 @@ func (p *PatrolService) patrolLoop(ctx context.Context) {for {select {case <-ticker.C:- p.runPatrol(ctx)+ p.runPatrolWithTrigger(ctx, TriggerReasonScheduled, nil)case alert := <-p.adHocTrigger:// Run immediate targeted patrol for this alert@@ -1743,8 +1978,13 @@ func (p *PatrolService) patrolLoop(ctx context.Context) {}}-// runPatrol executes a patrol run+// runPatrol executes a scheduled patrol runfunc (p *PatrolService) runPatrol(ctx context.Context) {+ p.runPatrolWithTrigger(ctx, TriggerReasonScheduled, nil)+}++// runPatrolWithTrigger executes a patrol run with trigger context+func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger TriggerReason, scope *PatrolScope) {p.mu.RLock()cfg := p.configbreaker := p.circuitBreaker@@ -1759,11 +1999,10 @@ func (p *PatrolService) runPatrol(ctx context.Context) {}defer p.endRun()- // Check if circuit breaker allows LLM calls- // We still run heuristics and basic analysis even when breaker is open+ // Check if circuit breaker allows LLM calls.llmAllowed := breaker == nil || breaker.Allow()if !llmAllowed {- log.Warn().Msg("AI Patrol: Circuit breaker is open, running heuristics only (no LLM calls)")+ log.Warn().Msg("AI Patrol: Circuit breaker is open (LLM calls blocked)")}start := time.Now()@@ -1800,47 +2039,22 @@ func (p *PatrolService) runPatrol(ctx context.Context) {// Helper to track findings// Note: Only warning+ severity findings count toward newFindings since watch/info are filtered from UItrackFinding := func(f *Finding) bool {- isNew := p.findings.Add(f)+ isNew := p.recordFinding(f)if isNew {// Only count warning+ findings as "new" for user-facing statsif f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical {runStats.newFindings++newFindings = append(newFindings, f)}- log.Info().- Str("finding_id", f.ID).- Str("severity", string(f.Severity)).- Str("resource", f.ResourceName).- Str("title", f.Title).- Msg("AI Patrol: New finding")-- // Generate remediation plan for actionable findings- // Skip internal error findings (not actionable by users)- // Using negated OR: generate only when NEITHER condition matches- if !(f.Key == "ai-patrol-error" || f.ResourceID == "ai-service") {- p.generateRemediationPlan(f)- }} else {runStats.existingFindings++}- // Push to unified store only if finding is active (not suppressed/dismissed)- // This ensures last_seen, severity, times_raised stay in sync for active findings- // but doesn't resurface findings the user has dismissed- if p.unifiedFindingCallback != nil {- if stored := p.findings.Get(f.ID); stored != nil && stored.IsActive() {- p.unifiedFindingCallback(stored)- }- }-// Only track warning+ severity finding IDs in the run recordif f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical {runStats.findingIDs = append(runStats.findingIDs, f.ID)}- // Trigger autonomous investigation if enabled and finding warrants it- p.MaybeInvestigateFinding(f)-return isNew}@@ -1875,7 +2089,7 @@ func (p *PatrolService) runPatrol(ctx context.Context) {hasPatrolFeature := aiServiceEnabled && p.aiService.HasLicenseFeature(FeatureAIPatrol)canRunLLM := hasPatrolFeature && llmAllowed- // Check if we can run LLM analysis (Pro feature + circuit breaker allows)+ // Check if we can run LLM analysis (AI-only patrol)if !canRunLLM {reason := "requires Pulse Pro license for LLM analysis"if !aiServiceEnabled {@@ -1883,11 +2097,11 @@ func (p *PatrolService) runPatrol(ctx context.Context) {} else if !llmAllowed {reason = "circuit breaker is open"}- log.Debug().Str("reason", reason).Msg("AI Patrol: Running heuristic analysis only")- for _, f := range p.runHeuristicAnalysis(state) {- trackFinding(f)- }+ p.setBlockedReason(reason)+ log.Info().Str("reason", reason).Msg("AI Patrol: Skipping run - AI unavailable")+ return} else {+ p.clearBlockedReason()// Run AI analysis using the LLM - this is the ONLY analysis method for Pro users// The LLM analyzes the infrastructure and identifies issuesaiResult, aiErr := p.runAIAnalysis(ctx, state)@@ -1932,19 +2146,10 @@ func (p *PatrolService) runPatrol(ctx context.Context) {LastSeenAt: time.Now(),}trackFinding(errorFinding)-- // Fall back to heuristic analysis so we still surface local issues- log.Debug().Msg("AI Patrol: Falling back to heuristic analysis after LLM error")- for _, f := range p.runHeuristicAnalysis(state) {- trackFinding(f)- }} else if aiResult != nil {runStats.aiAnalysis = aiResultif len(aiResult.Findings) == 0 {- log.Warn().Msg("AI Patrol: LLM response contained no parseable findings, running heuristics as safety net")- for _, f := range p.runHeuristicAnalysis(state) {- trackFinding(f)- }+ log.Warn().Msg("AI Patrol: LLM response contained no parseable findings")} else {for _, f := range aiResult.Findings {trackFinding(f)@@ -1980,7 +2185,7 @@ func (p *PatrolService) runPatrol(ctx context.Context) {resolvedCount += runbookResolved// AI-based alert review: check active alerts against current state and auto-resolve fixed issues- // Pass llmAllowed so it knows whether AI calls are allowed (heuristics always run)+ // Pass llmAllowed so it knows whether AI calls are allowed.alertsResolved := p.reviewAndResolveAlerts(ctx, state, llmAllowed)if alertsResolved > 0 {log.Info().Int("alerts_resolved", alertsResolved).Msg("AI Patrol: Auto-resolved alerts where issues are fixed")@@ -2029,6 +2234,7 @@ func (p *PatrolService) runPatrol(ctx context.Context) {Duration: duration,DurationMs: duration.Milliseconds(),Type: patrolType,+ TriggerReason: string(trigger),ResourcesChecked: runStats.resourceCount,NodesChecked: runStats.nodesChecked,GuestsChecked: runStats.guestsChecked,@@ -2047,6 +2253,15 @@ func (p *PatrolService) runPatrol(ctx context.Context) {Status: status,}+ if scope != nil {+ runRecord.ScopeResourceIDs = scope.ResourceIDs+ runRecord.ScopeResourceTypes = scope.ResourceTypes+ runRecord.ScopeDepth = scope.Depth.String()+ runRecord.ScopeContext = scope.Context+ runRecord.AlertID = scope.AlertID+ runRecord.FindingID = scope.FindingID+ }+// Add AI analysis details if availableif runStats.aiAnalysis != nil {runRecord.AIAnalysis = runStats.aiAnalysis.Response@@ -2795,12 +3010,19 @@ func (p *PatrolService) parseAndResolveFindings(response string, findings []*FinfindingMap[f.ID] = f}+ p.mu.RLock()+ resolveUnified := p.unifiedFindingResolver+ p.mu.RUnlock()+// Resolve the findings the AI indicatedresolvedCount := 0for _, item := range parsed.Resolve {if f, exists := findingMap[item.ID]; exists {if p.findings.Resolve(f.ID, true) {resolvedCount+++ if resolveUnified != nil {+ resolveUnified(f.ID)+ }log.Info().Str("finding_id", f.ID).Str("resource", f.ResourceName).@@ -2853,7 +3075,7 @@ func (p *PatrolService) reviewAndResolveAlerts(ctx context.Context, state modelsresolvedCount := 0- // Pass nil for aiService if LLM is not allowed (forces heuristics-only)+ // Pass nil for aiService if LLM is not allowed (use heuristic checks only).aiSvc := aiServiceif !llmAllowed {aiSvc = nil@@ -3142,6 +3364,13 @@ func (p *PatrolService) ResolveFinding(findingID string, resolutionNote string)return fmt.Errorf("failed to resolve finding: %s", findingID)}+ p.mu.RLock()+ resolveUnified := p.unifiedFindingResolver+ p.mu.RUnlock()+ if resolveUnified != nil {+ resolveUnified(findingID)+ }+log.Info().Str("finding_id", findingID).Str("resolution_note", resolutionNote).@@ -3240,7 +3469,7 @@ func (p *PatrolService) ForcePatrol(ctx context.Context, deep bool) {if ctx != nil {runCtx = context.WithoutCancel(ctx)}- go p.runPatrol(runCtx)+ go p.runPatrolWithTrigger(runCtx, TriggerReasonManual, nil)}// analyzePBSInstance checks a PBS backup server for issues@@ -3882,12 +4111,8 @@ func cleanThinkingTokens(content string) string {return strings.TrimSpace(content)}-// runAIAnalysis uses the LLM to analyze infrastructure and identify issues+// runAIAnalysis uses the LLM to analyze infrastructure and identify issues.func (p *PatrolService) runAIAnalysis(ctx context.Context, state models.StateSnapshot) (*AIAnalysisResult, error) {- if p.aiService == nil {- return nil, fmt.Errorf("Pulse Patrol service not available")- }-// Build enriched infrastructure context with trends and predictions// Falls back to basic summary if metrics history is not availablesummary := p.buildEnrichedContext(state)@@ -3896,6 +4121,27 @@ func (p *PatrolService) runAIAnalysis(ctx context.Context, state models.StateSna}prompt := p.buildPatrolPrompt(summary)+ return p.runAIAnalysisWithPrompt(ctx, state, prompt)+}++// runScopedAIAnalysis uses the LLM to analyze a scoped subset of resources.+func (p *PatrolService) runScopedAIAnalysis(ctx context.Context, state models.StateSnapshot, scope PatrolScope) (*AIAnalysisResult, error) {+ summary := p.buildEnrichedContext(state)+ if summary == "" {+ return nil, nil+ }++ prompt := p.buildPatrolPromptForScope(summary, scope)+ return p.runAIAnalysisWithPrompt(ctx, state, prompt)+}++func (p *PatrolService) runAIAnalysisWithPrompt(ctx context.Context, state models.StateSnapshot, prompt string) (*AIAnalysisResult, error) {+ if p.aiService == nil {+ return nil, fmt.Errorf("Pulse Patrol service not available")+ }+ if strings.TrimSpace(prompt) == "" {+ return nil, nil+ }log.Debug().Msg("AI Patrol: Sending infrastructure to LLM for analysis")@@ -4485,9 +4731,9 @@ func convertToContextMetricsMap(metricsMap map[string][]MetricPoint) map[string]return result}-// buildPatrolPrompt creates the prompt for AI analysis-// Includes user feedback context to prevent re-raising dismissed findings-func (p *PatrolService) buildPatrolPrompt(summary string) string {+// buildPatrolPromptWithResources creates the prompt for AI analysis.+// Includes user feedback context to prevent re-raising dismissed findings.+func (p *PatrolService) buildPatrolPromptWithResources(summary string, resourceIDs []string) string {// Get user feedback context (dismissed/snoozed findings)feedbackContext := p.findings.GetDismissedForContext()@@ -4495,25 +4741,27 @@ func (p *PatrolService) buildPatrolPrompt(summary string) string {var knowledgeContext stringvar infraContext stringvar incidentContext string- var discoveryContext stringp.mu.RLock()knowledgeStore := p.knowledgeStoreincidentStore := p.incidentStore- discoveryStore := p.discoveryStorep.mu.RUnlock()if knowledgeStore != nil {- knowledgeContext = knowledgeStore.FormatAllForContext()- infraContext = knowledgeStore.GetInfrastructureContext()+ if len(resourceIDs) > 0 {+ knowledgeContext = knowledgeStore.FormatForContextForResources(resourceIDs)+ } else {+ knowledgeContext = knowledgeStore.FormatAllForContext()+ }+ // GetInfrastructureContext now includes discovery via the discoveryContextProvider,+ // so we don't need to call servicediscovery.FormatForAIContext separately+ if len(resourceIDs) > 0 {+ infraContext = knowledgeStore.GetInfrastructureContextForResources(resourceIDs)+ } else {+ infraContext = knowledgeStore.GetInfrastructureContext()+ }}if incidentStore != nil {incidentContext = incidentStore.FormatForPatrol(8)}- // Get AI discovery context (deep-scanned service info)- if discoveryStore != nil {- if discoveries, err := discoveryStore.List(); err == nil && len(discoveries) > 0 {- discoveryContext = aidiscovery.FormatForAIContext(discoveries)- }- }basePrompt := fmt.Sprintf(`Please perform a comprehensive analysis of the following infrastructure and identify any issues, potential problems, or optimization opportunities.@@ -4556,12 +4804,6 @@ IMPORTANT: When proposing remediation commands, use the CLI access method shown`)}- // Append deep AI discovery context (service details, versions, config paths, ports)- if discoveryContext != "" {- contextAdditions.WriteString("\n\n")- contextAdditions.WriteString(discoveryContext)- }-// Append user feedback context (dismissed/snoozed findings)if feedbackContext != "" {contextAdditions.WriteString("\n\n")@@ -4626,6 +4868,40 @@ Only report NEW issues or issues where the severity has clearly escalated.`)return basePrompt}+// buildPatrolPrompt creates the prompt for AI analysis using full discovery context.+func (p *PatrolService) buildPatrolPrompt(summary string) string {+ return p.buildPatrolPromptWithResources(summary, nil)+}++// buildPatrolPromptForScope creates the prompt for AI analysis scoped to specific resources.+func (p *PatrolService) buildPatrolPromptForScope(summary string, scope PatrolScope) string {+ prompt := p.buildPatrolPromptWithResources(summary, scope.ResourceIDs)++ var scopeContext strings.Builder+ scopeContext.WriteString("This patrol run is scoped. Focus ONLY on the resources and context below unless you detect a direct dependency.\n")+ if scope.Reason != "" {+ scopeContext.WriteString(fmt.Sprintf("- Trigger: %s\n", scope.Reason))+ }+ if scope.Context != "" {+ scopeContext.WriteString(fmt.Sprintf("- Trigger context: %s\n", scope.Context))+ }+ if len(scope.ResourceIDs) > 0 {+ scopeContext.WriteString(fmt.Sprintf("- Resource IDs: %s\n", strings.Join(scope.ResourceIDs, ", ")))+ }+ if len(scope.ResourceTypes) > 0 {+ scopeContext.WriteString(fmt.Sprintf("- Resource types: %s\n", strings.Join(scope.ResourceTypes, ", ")))+ }+ if scope.AlertID != "" {+ scopeContext.WriteString(fmt.Sprintf("- Alert ID: %s\n", scope.AlertID))+ }+ if scope.FindingID != "" {+ scopeContext.WriteString(fmt.Sprintf("- Finding ID: %s\n", scope.FindingID))+ }+ scopeContext.WriteString(fmt.Sprintf("- Depth: %s\n", scope.Depth.String()))++ return prompt + "\n\n## PATROL SCOPE\n" + scopeContext.String()+}+// recordEvent records an event in the correlation detector if it's significantfunc (p *PatrolService) recordEvent(resourceID, resourceName, resourceType string, eventType CorrelationEventType, value float64) {p.mu.RLock()@@ -5022,15 +5298,10 @@ func (p *PatrolService) TriggerPatrolForAlert(alert *alerts.Alert) {triggerManager := p.triggerManagerp.mu.RUnlock()+ resourceType := inferResourceType(alert.Type, alert.Metadata)+if triggerManager != nil {- scope := PatrolScope{- ResourceIDs: []string{alert.ResourceID},- Depth: PatrolDepthQuick,- Reason: TriggerReasonAlertFired,- Context: "Alert: " + alert.Type,- Priority: 80,- AlertID: alert.ID,- }+ scope := AlertTriggeredPatrolScope(alert.ID, alert.ResourceID, resourceType, alert.Type)if triggerManager.TriggerPatrol(scope) {log.Debug().Str("alert_id", alert.ID).Msg("Queued alert-triggered patrol via trigger manager")} else {@@ -5073,14 +5344,8 @@ func (p *PatrolService) runTargetedPatrol(ctx context.Context, alert *alerts.AleStr("resource_id", alert.ResourceID).Msg("Running targeted AI patrol for alert")- scope := PatrolScope{- ResourceIDs: []string{alert.ResourceID},- Depth: PatrolDepthQuick,- Reason: TriggerReasonAlertFired,- Context: "Alert: " + alert.Type,- Priority: 80,- AlertID: alert.ID,- }+ resourceType := inferResourceType(alert.Type, alert.Metadata)+ scope := AlertTriggeredPatrolScope(alert.ID, alert.ResourceID, resourceType, alert.Type)p.TriggerScopedPatrol(ctx, scope)}diff --git a/internal/ai/patrol_coverage_test.go b/internal/ai/patrol_coverage_test.goindex a366ede10d..9cfea7d31d 100644--- a/internal/ai/patrol_coverage_test.go+++ b/internal/ai/patrol_coverage_test.go@@ -148,10 +148,9 @@ func TestPatrolService_Setters_Coverage(t *testing.T) {}}-// TestPatrol_RunHeuristicAnalysis_Coverage tests logic branches in heuristic analysis-func TestPatrol_RunHeuristicAnalysis_Coverage(t *testing.T) {- // Heuristic analysis relies on state and thresholds.- // We can set thresholds low to trigger heuristics without AI.+// TestPatrol_RunPatrol_AIRequired verifies patrol skips analysis when AI is unavailable.+func TestPatrol_RunPatrol_AIRequired(t *testing.T) {+ // Populate state with high-usage resources to prove heuristics are not used.stateProvider := &mockStateProvider{state: models.StateSnapshot{@@ -170,7 +169,7 @@ func TestPatrol_RunHeuristicAnalysis_Coverage(t *testing.T) {ps := NewPatrolService(nil, stateProvider)- // Set low thresholds to ensure triggers+ // Set low thresholds that would trigger heuristic findings if they still ran.provider := &mockThresholdProvider{nodeCPU: 50,nodeMemory: 50,@@ -180,18 +179,6 @@ func TestPatrol_RunHeuristicAnalysis_Coverage(t *testing.T) {}ps.SetThresholdProvider(provider)- // runHeuristics is private, but called by runPatrol.- // However, without AI service, runPatrol might skip or return early?- // check runPatrol implementation:- // if p.aiService == nil ... skipping patrol-- // So we typically need AI service for part of it.- // But `Start()` checks AI enabled.- // Let's create an AI service that is enabled but mock provider returns error or dummy,- // to see if heuristics run BEFORE AI?- // Looking at patrol.go (not visible fully), typically heuristics might run as part of analysis.- // Generally, heuristic findings are added to `findings`.-// If runPatrol requires AI service, we provide one.svc := NewService(nil, nil)@@ -212,7 +199,7 @@ func TestPatrol_RunHeuristicAnalysis_Coverage(t *testing.T) {// Link themps.aiService = svc- // Disable AI patrol feature to force heuristic analysis+ // Disable AI patrol feature to force patrol to block (AI-only).licenseChecker := &mockLicenseStore{features: map[string]bool{"ai_patrol": false, // explicitly false@@ -225,15 +212,17 @@ func TestPatrol_RunHeuristicAnalysis_Coverage(t *testing.T) {ctx := context.Background()ps.runPatrol(ctx)- // Check if heuristics generated findings- // With low thresholds and high usage in state, we expect findings+ // No findings should be generated when AI is unavailable.findings := ps.GetFindings().GetActive(FindingSeverityWarning)- // We expect at least one finding (CPU, Memory, or Storage)- if len(findings) == 0 {- // Try Info severity (maybe watch/heuristic produces lower severity?)- findings = ps.GetFindings().GetActive(FindingSeverityInfo)- if len(findings) == 0 {- t.Error("Expected findings from heuristic analysis")- }+ if len(findings) > 0 {+ t.Errorf("Expected no findings when AI patrol is unavailable, got %d", len(findings))+ }++ status := ps.GetStatus()+ if status.BlockedReason == "" {+ t.Error("Expected patrol to report a blocked reason when AI patrol is unavailable")+ }+ if status.BlockedAt == nil {+ t.Error("Expected patrol to report blocked_at when AI patrol is unavailable")}}diff --git a/internal/ai/patrol_history_persistence.go b/internal/ai/patrol_history_persistence.goindex e3bb358675..7f6b3fbd66 100644--- a/internal/ai/patrol_history_persistence.go+++ b/internal/ai/patrol_history_persistence.go@@ -35,30 +35,37 @@ func (a *PatrolHistoryPersistenceAdapter) SavePatrolRunHistory(runs []PatrolRunRdurationMs = int64(r.Duration / time.Millisecond)}records[i] = config.PatrolRunRecord{- ID: r.ID,- StartedAt: r.StartedAt,- CompletedAt: r.CompletedAt,- DurationMs: durationMs,- Type: r.Type,- ResourcesChecked: r.ResourcesChecked,- NodesChecked: r.NodesChecked,- GuestsChecked: r.GuestsChecked,- DockerChecked: r.DockerChecked,- StorageChecked: r.StorageChecked,- HostsChecked: r.HostsChecked,- PBSChecked: r.PBSChecked,- KubernetesChecked: r.KubernetesChecked,- NewFindings: r.NewFindings,- ExistingFindings: r.ExistingFindings,- ResolvedFindings: r.ResolvedFindings,- AutoFixCount: r.AutoFixCount,- FindingsSummary: r.FindingsSummary,- FindingIDs: r.FindingIDs,- ErrorCount: r.ErrorCount,- Status: r.Status,- AIAnalysis: r.AIAnalysis,- InputTokens: r.InputTokens,- OutputTokens: r.OutputTokens,+ ID: r.ID,+ StartedAt: r.StartedAt,+ CompletedAt: r.CompletedAt,+ DurationMs: durationMs,+ Type: r.Type,+ TriggerReason: r.TriggerReason,+ ScopeResourceIDs: r.ScopeResourceIDs,+ ScopeResourceTypes: r.ScopeResourceTypes,+ ScopeDepth: r.ScopeDepth,+ ScopeContext: r.ScopeContext,+ AlertID: r.AlertID,+ FindingID: r.FindingID,+ ResourcesChecked: r.ResourcesChecked,+ NodesChecked: r.NodesChecked,+ GuestsChecked: r.GuestsChecked,+ DockerChecked: r.DockerChecked,+ StorageChecked: r.StorageChecked,+ HostsChecked: r.HostsChecked,+ PBSChecked: r.PBSChecked,+ KubernetesChecked: r.KubernetesChecked,+ NewFindings: r.NewFindings,+ ExistingFindings: r.ExistingFindings,+ ResolvedFindings: r.ResolvedFindings,+ AutoFixCount: r.AutoFixCount,+ FindingsSummary: r.FindingsSummary,+ FindingIDs: r.FindingIDs,+ ErrorCount: r.ErrorCount,+ Status: r.Status,+ AIAnalysis: r.AIAnalysis,+ InputTokens: r.InputTokens,+ OutputTokens: r.OutputTokens,}}return a.config.SavePatrolRunHistory(records)@@ -75,31 +82,38 @@ func (a *PatrolHistoryPersistenceAdapter) LoadPatrolRunHistory() ([]PatrolRunRecruns := make([]PatrolRunRecord, len(data.Runs))for i, r := range data.Runs {runs[i] = PatrolRunRecord{- ID: r.ID,- StartedAt: r.StartedAt,- CompletedAt: r.CompletedAt,- Duration: time.Duration(r.DurationMs) * time.Millisecond, // Convert milliseconds to nanoseconds- DurationMs: r.DurationMs,- Type: r.Type,- ResourcesChecked: r.ResourcesChecked,- NodesChecked: r.NodesChecked,- GuestsChecked: r.GuestsChecked,- DockerChecked: r.DockerChecked,- StorageChecked: r.StorageChecked,- HostsChecked: r.HostsChecked,- PBSChecked: r.PBSChecked,- KubernetesChecked: r.KubernetesChecked,- NewFindings: r.NewFindings,- ExistingFindings: r.ExistingFindings,- ResolvedFindings: r.ResolvedFindings,- AutoFixCount: r.AutoFixCount,- FindingsSummary: r.FindingsSummary,- FindingIDs: r.FindingIDs,- ErrorCount: r.ErrorCount,- Status: r.Status,- AIAnalysis: r.AIAnalysis,- InputTokens: r.InputTokens,- OutputTokens: r.OutputTokens,+ ID: r.ID,+ StartedAt: r.StartedAt,+ CompletedAt: r.CompletedAt,+ Duration: time.Duration(r.DurationMs) * time.Millisecond, // Convert milliseconds to nanoseconds+ DurationMs: r.DurationMs,+ Type: r.Type,+ TriggerReason: r.TriggerReason,+ ScopeResourceIDs: r.ScopeResourceIDs,+ ScopeResourceTypes: r.ScopeResourceTypes,+ ScopeDepth: r.ScopeDepth,+ ScopeContext: r.ScopeContext,+ AlertID: r.AlertID,+ FindingID: r.FindingID,+ ResourcesChecked: r.ResourcesChecked,+ NodesChecked: r.NodesChecked,+ GuestsChecked: r.GuestsChecked,+ DockerChecked: r.DockerChecked,+ StorageChecked: r.StorageChecked,+ HostsChecked: r.HostsChecked,+ PBSChecked: r.PBSChecked,+ KubernetesChecked: r.KubernetesChecked,+ NewFindings: r.NewFindings,+ ExistingFindings: r.ExistingFindings,+ ResolvedFindings: r.ResolvedFindings,+ AutoFixCount: r.AutoFixCount,+ FindingsSummary: r.FindingsSummary,+ FindingIDs: r.FindingIDs,+ ErrorCount: r.ErrorCount,+ Status: r.Status,+ AIAnalysis: r.AIAnalysis,+ InputTokens: r.InputTokens,+ OutputTokens: r.OutputTokens,}}return runs, nildiff --git a/internal/ai/patrol_triggers.go b/internal/ai/patrol_triggers.goindex a10254e9bb..1ee4e215e9 100644--- a/internal/ai/patrol_triggers.go+++ b/internal/ai/patrol_triggers.go@@ -425,9 +425,12 @@ func slicesEqual(a, b []string) bool {if len(a) != len(b) {return false}- if len(a) <= 1 {+ if len(a) == 0 {return true}+ if len(a) == 1 {+ return a[0] == b[0]+ }aSorted := append([]string(nil), a...)bSorted := append([]string(nil), b...)sort.Strings(aSorted)diff --git a/internal/ai/service.go b/internal/ai/service.goindex 5a730f6555..26e8cbe4fc 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -23,11 +23,11 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/knowledge""github.com/rcourtman/pulse-go-rewrite/internal/ai/memory""github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"- "github.com/rcourtman/pulse-go-rewrite/internal/aidiscovery""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/infradiscovery""github.com/rcourtman/pulse-go-rewrite/internal/license""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery""github.com/rcourtman/pulse-go-rewrite/internal/types""github.com/rs/zerolog/log")@@ -125,10 +125,10 @@ type Service struct {infraDiscoveryService *infradiscovery.Service// AI-powered deep discovery store - detailed service analysis with commands- aiDiscoveryStore *aidiscovery.Store+ discoveryStore *servicediscovery.Store// AI-powered deep discovery service - runs commands and AI analysis- aiDiscoveryService *aidiscovery.Service+ discoveryService *servicediscovery.Service// Alert-triggered analysis - token-efficient real-time AI insightsalertTriggeredAnalyzer *AlertTriggeredAnalyzer@@ -158,7 +158,7 @@ type modelsCache struct {func NewService(persistence *config.ConfigPersistence, agentServer AgentServer) *Service {// Initialize knowledge storevar knowledgeStore *knowledge.Store- var aiDiscoveryStore *aidiscovery.Store+ var discoveryStore *servicediscovery.StorecostStore := cost.NewStore(cost.DefaultMaxDays)if persistence != nil {var err error@@ -169,20 +169,20 @@ func NewService(persistence *config.ConfigPersistence, agentServer AgentServer)if err := costStore.SetPersistence(NewCostPersistenceAdapter(persistence)); err != nil {log.Warn().Err(err).Msg("Failed to initialize AI usage cost store")}- // Initialize AI discovery store for deep infrastructure discovery- aiDiscoveryStore, err = aidiscovery.NewStore(persistence.DataDir())+ // Initialize discovery store for deep infrastructure discovery+ discoveryStore, err = servicediscovery.NewStore(persistence.DataDir())if err != nil {- log.Warn().Err(err).Msg("Failed to initialize AI discovery store")+ log.Warn().Err(err).Msg("Failed to initialize discovery store")}}return &Service{- persistence: persistence,- agentServer: agentServer,- policy: agentexec.DefaultPolicy(),- knowledgeStore: knowledgeStore,- aiDiscoveryStore: aiDiscoveryStore,- costStore: costStore,+ persistence: persistence,+ agentServer: agentServer,+ policy: agentexec.DefaultPolicy(),+ knowledgeStore: knowledgeStore,+ discoveryStore: discoveryStore,+ costStore: costStore,limits: executionLimits{chatSlots: make(chan struct{}, 4),patrolSlots: make(chan struct{}, 1),@@ -260,9 +260,9 @@ func (s *Service) SetStateProvider(sp StateProvider) {if s.incidentStore != nil {s.patrolService.SetIncidentStore(s.incidentStore)}- // Connect AI discovery store for deep infrastructure context- if s.aiDiscoveryStore != nil {- s.patrolService.SetDiscoveryStore(s.aiDiscoveryStore)+ // Connect discovery store for deep infrastructure context+ if s.discoveryStore != nil {+ s.patrolService.SetDiscoveryStore(s.discoveryStore)}}@@ -283,9 +283,9 @@ func (s *Service) SetStateProvider(sp StateProvider) {// Initialize AI-powered deep discovery service if not already done// This runs read-only commands on resources and uses AI to understand services- if s.aiDiscoveryService == nil && sp != nil && s.aiDiscoveryStore != nil {+ if s.discoveryService == nil && sp != nil && s.discoveryStore != nil {// Create command executor adapter (wraps agentexec.Server)- var cmdExecutor aidiscovery.CommandExecutor+ var cmdExecutor servicediscovery.CommandExecutorif agentSrv, ok := s.agentServer.(*agentexec.Server); ok {cmdExecutor = newDiscoveryCommandAdapter(agentSrv)}@@ -294,25 +294,25 @@ func (s *Service) SetStateProvider(sp StateProvider) {stateAdapter := newDiscoveryStateAdapter(sp)// Create deep scanner- scanner := aidiscovery.NewDeepScanner(cmdExecutor)+ scanner := servicediscovery.NewDeepScanner(cmdExecutor)// Create the discovery service with config-driven settings- discoveryCfg := aidiscovery.DefaultConfig()+ discoveryCfg := servicediscovery.DefaultConfig()if s.cfg != nil {discoveryCfg.Interval = s.cfg.GetDiscoveryInterval()}- s.aiDiscoveryService = aidiscovery.NewService(- s.aiDiscoveryStore,+ s.discoveryService = servicediscovery.NewService(+ s.discoveryStore,scanner,stateAdapter,discoveryCfg,)- s.aiDiscoveryService.SetAIAnalyzer(s)+ s.discoveryService.SetAIAnalyzer(s)// Start background discovery if enabled and interval is setif s.cfg != nil && s.cfg.IsDiscoveryEnabled() && s.cfg.GetDiscoveryInterval() > 0 {- s.aiDiscoveryService.Start(context.Background())+ s.discoveryService.Start(context.Background())log.Info().Dur("interval", s.cfg.GetDiscoveryInterval()).Msg("AI-powered deep discovery service started with automatic scanning")@@ -515,36 +515,36 @@ func (s *Service) SetIncidentStore(store *memory.IncidentStore) {}}-// SetAIDiscoveryStore sets the AI discovery store for infrastructure context-func (s *Service) SetAIDiscoveryStore(store *aidiscovery.Store) {+// SetDiscoveryStore sets the discovery store for infrastructure context+func (s *Service) SetDiscoveryStore(store *servicediscovery.Store) {s.mu.Lock()defer s.mu.Unlock()- s.aiDiscoveryStore = store+ s.discoveryStore = storeif s.patrolService != nil {s.patrolService.SetDiscoveryStore(store)}- log.Info().Msg("AI Service: AI discovery store set for infrastructure context")+ log.Info().Msg("AI Service: Discovery store set for infrastructure context")}-// GetAIDiscoveryStore returns the AI discovery store-func (s *Service) GetAIDiscoveryStore() *aidiscovery.Store {+// GetDiscoveryStore returns the discovery store+func (s *Service) GetDiscoveryStore() *servicediscovery.Store {s.mu.RLock()defer s.mu.RUnlock()- return s.aiDiscoveryStore+ return s.discoveryStore}-// GetAIDiscoveryService returns the AI discovery service for triggering scans-func (s *Service) GetAIDiscoveryService() *aidiscovery.Service {+// GetDiscoveryService returns the discovery service for triggering scans+func (s *Service) GetDiscoveryService() *servicediscovery.Service {s.mu.RLock()defer s.mu.RUnlock()- return s.aiDiscoveryService+ return s.discoveryService}// updateDiscoverySettings updates the discovery service based on config changes// Note: caller must NOT hold s.mu lockfunc (s *Service) updateDiscoverySettings(cfg *config.AIConfig) {- if s.aiDiscoveryService == nil || cfg == nil {+ if s.discoveryService == nil || cfg == nil {return}@@ -553,15 +553,15 @@ func (s *Service) updateDiscoverySettings(cfg *config.AIConfig) {if enabled && interval > 0 {// Update interval and ensure service is running- s.aiDiscoveryService.SetInterval(interval)- s.aiDiscoveryService.Start(context.Background())+ s.discoveryService.SetInterval(interval)+ s.discoveryService.Start(context.Background())log.Info().Bool("enabled", enabled).Dur("interval", interval).Msg("Discovery service updated: automatic scanning enabled")} else {// Stop background scanning (manual mode)- s.aiDiscoveryService.Stop()+ s.discoveryService.Stop()log.Info().Bool("enabled", enabled).Msg("Discovery service updated: manual mode (background scanning stopped)")@@ -3211,144 +3211,45 @@ func (s *Service) RunCommand(ctx context.Context, req RunCommandRequest) (*RunCo// buildSystemPrompt creates the system prompt based on the request contextfunc (s *Service) buildSystemPrompt(req ExecuteRequest) string {- prompt := `You are Pulse's diagnostic assistant - a built-in tool for investigating Proxmox, Docker, and Kubernetes homelab issues.--## Response Style-- Be DIRECT and CONCISE. No greetings, no "I'll help you", no "Let me check"-- Report findings, not process. Don't narrate what you're doing-- NO emojis, NO markdown tables, NO excessive formatting-- Use simple lists only when showing multiple items-- Final response should be 2-4 sentences summarizing findings and any actions taken-- When you perform cleanup/fixes, report: what was done + the result (e.g., "Freed 6GB. Disk now at 81%.")--## When Investigating-- Execute commands silently in the background-- Only show the conclusion, not every command run-- If something fails, briefly state what and why--## Command Approval System-Pulse has a command approval policy that protects against accidental damage:-- **Safe commands** (read-only: ls, df, cat, ps, etc.) execute immediately-- **Potentially destructive commands** (rm, service restart, apt install, etc.) require approval unless autonomous mode is enabled-- **Blocked commands** are never executed-- When approval is required, the user will see the command and can approve or reject it--When you need to run a potentially destructive command:-1. Execute it normally - Pulse will handle the approval flow-2. If a command is blocked or needs approval, you'll get feedback-3. Continue with other work while waiting for approval, or explain what the command will do--Do NOT say things like:-- "I need your permission to..."-- "Would you like me to run...?"-- "This is destructive, are you sure?"--Instead, just execute the command. Pulse's approval system will handle user confirmation for risky operations.--## Response Format-BAD: "I'll check that for you. Let me run some commands..."-GOOD: State findings directly.--BAD: "Would you like me to run rm -rf...?"-GOOD: Execute the command. User will approve/reject via Pulse.--BAD: Tables, headers, bullet-heavy summaries-GOOD: Plain prose, 2-4 sentences.--## ACTION BIAS - AVOID INVESTIGATION LOOPS-When the user asks you to DO something (install, fix, update, configure), ACT IMMEDIATELY:-- Don't extensively investigate before acting. Run 1-2 diagnostic commands max, then DO the thing.-- Don't explain what you're about to do - just do it.-- If the command needs approval, Pulse will queue it. You don't need to ask separately.-- If the first approach fails, try the next most obvious approach. Don't stop to report.-- Complete the task END TO END. If asked to "install and run X", you're not done until X is running.--INVESTIGATION ANTI-PATTERNS TO AVOID:-- Running 10+ diagnostic commands before taking action-- Explaining each step before doing it-- Stopping to report partial progress-- Asking "would you like me to proceed?" (Pulse handles approval automatically)-- Checking version, checking config, checking service, checking ports, checking this, checking that... JUST ACT.--GOOD PATTERN for "install X and make sure it's running":-1. Download/install X (1 command)-2. Start X (1 command)-3. Verify X is running (1 command)-4. Report: "Installed X vN.N. Service is running on port NNNN."--BAD PATTERN:-1. Check current version... 2. Check if installed... 3. Check service status... 4. Check config file...-5. Check another config... 6. Try to enable something... 7. Check if it worked... 8. Read a script...-9. Check yet another file... [user: "do it"] 10. Still investigating... [user: "DO IT"]---## Using Context Data-Pulse provides real metrics in "Current Metrics and State". Use this data directly - don't ask users to check things you already know.+ prompt := `You are Pulse's diagnostic assistant for Proxmox, Docker, and Kubernetes homelabs.++## Command Approval+Pulse has a built-in approval system:+- Safe commands (read-only: ls, df, cat, ps) execute immediately+- Destructive commands (rm, service restart, apt install) require user approval+- Blocked commands are never executed+Execute commands normally - Pulse handles the approval flow automatically.## Command Execution- run_on_host=true: Run on PVE/Docker host (pct, qm, vzdump, docker commands)- run_on_host=false: Run inside the container/VM-- target_host: ALWAYS set this when using run_on_host=true! Use the node/hostname from target context-- Execute commands to investigate, don't just explain what commands to run--## CRITICAL: Command Routing with target_host-When running commands that require a specific host (pct, qm, docker, vzdump), you MUST specify target_host to route correctly.+- target_host: Required when using run_on_host=true - use the node name from contextExample for LXC 106 on node 'minipc':-- To run 'df -h' inside the container: run_command(command="df -h", run_on_host=false)-- To run 'pct exec 106 -- df -h' on the host: run_command(command="pct exec 106 -- df -h", run_on_host=true, target_host="minipc")--Always check the target's context for the 'node' or 'PVE Node' field and pass it as target_host.-If you don't specify target_host when run_on_host=true, the command may route to the wrong host!--Rules:-1. Look at the target context for 'node', 'guest_node', or 'PVE Node' field-2. When running pct/qm commands: set run_on_host=true AND target_host=<node>-3. When running commands inside the guest: just set run_on_host=false (no target_host needed)-4. Error "Configuration file does not exist" means wrong host - check target_host--## Infrastructure Architecture - LXC Management-Pulse manages LXC containers agentlessly from the PVE host.-- DO NOT check for a Pulse agent process or service inside an LXC. It does not exist.-- Use run_command with run_on_host=false to execute commands inside the LXC. Pulse handles the routing.-- For pct commands, always use run_on_host=true and set target_host to the container's node.--## URL Discovery Feature-When asked to find the web URL for a guest/container/host, or when you discover a web service:--1. **Inspect for web servers**: Check for listening ports (ss -tlnp), running services (nginx, apache, node, etc.)-2. **Get the IP address**: Use 'hostname -I' or 'ip addr' to find the IP-3. **Test the URL**: Use fetch_url to verify the service is responding-4. **Save the URL**: Use set_resource_url tool to save it to Pulse--Common discovery commands:-- Check listening ports: ss -tlnp | grep LISTEN-- Check nginx: systemctl status nginx && grep -r 'listen' /etc/nginx/-- Check running processes: ps aux | grep -E 'node|python|java|nginx|apache|httpd'-- Get IP: hostname -I | awk '{print $1}'--**CRITICAL: resource_id format for set_resource_url**-The resource_id MUST be in the canonical format: {instance}:{node}:{vmid} (uses COLONS, not dashes)-- Example for VMID 201 on node "minipc" in instance "delly": resource_id = "delly:minipc:201"-- Example for VMID 101 on node "delly" in instance "delly": resource_id = "delly:delly:101"-- The instance name is typically the cluster name for PVE clusters-- Always check which NODE the guest is on (visible in the target_host or context)--When working across multiple nodes, use the correct instance:node:vmid format for each guest.--## Installing/Updating Pulse Itself-If asked to install or update Pulse itself, use the official install script. DO NOT investigate configs/services first.-Quick install/update command (x86_64 Linux):-` + "`" + `curl -sSL https://raw.githubusercontent.com/rcourtman/Pulse/main/install.sh | bash` + "`" + `--To install a specific version:-` + "`" + `curl -sSL https://raw.githubusercontent.com/rcourtman/Pulse/main/install.sh | bash -s -- --version vX.Y.Z` + "`" + `--After install, enable and start the service:-` + "`" + `systemctl enable pulse && systemctl start pulse` + "`" + `--The latest version can be found at: https://api.github.com/repos/rcourtman/Pulse/releases/latest-This is a 3-command job. Don't over-investigate.`+- Inside container: run_command(command="df -h", run_on_host=false)+- On host: run_command(command="pct exec 106 -- df -h", run_on_host=true, target_host="minipc")++If you get "Configuration file does not exist" - wrong host, check target_host.++## LXC Management+Pulse manages LXC containers agentlessly - there is no Pulse process inside containers.+- run_on_host=false: Pulse routes commands into the LXC via the PVE host+- run_on_host=true + target_host: Runs pct/qm commands on the PVE host directly++## URL Discovery+When finding web URLs for resources:+1. Check listening ports: ss -tlnp | grep LISTEN+2. Get IP: hostname -I | awk '{print $1}'+3. Test with fetch_url to verify+4. Save with set_resource_url tool++resource_id format: {instance}:{node}:{vmid} (colons, not dashes)+Example: "delly:minipc:201" for VMID 201 on node minipc in instance delly++## Installing/Updating Pulse+curl -sSL https://raw.githubusercontent.com/rcourtman/Pulse/main/install.sh | bash+After: systemctl enable pulse && systemctl start pulse+Latest version: https://api.github.com/repos/rcourtman/Pulse/releases/latest`// Add custom context from AI settings (user's infrastructure description)s.mu.RLock()diff --git a/internal/ai/unified/bridge.go b/internal/ai/unified/bridge.goindex 8e0ba842df..49594b72fa 100644--- a/internal/ai/unified/bridge.go+++ b/internal/ai/unified/bridge.go@@ -43,7 +43,7 @@ type AlertProvider interface {}// PatrolTriggerFunc is called to trigger a mini-patrol for a resource-type PatrolTriggerFunc func(resourceID, reason string)+type PatrolTriggerFunc func(resourceID, resourceType, reason, alertType string)// AIEnhancementFunc is called to request AI enhancement of a findingtype AIEnhancementFunc func(findingID string) error@@ -200,7 +200,7 @@ func (b *AlertBridge) handleNewAlert(alert AlertAdapter) {// Trigger mini-patrol for the resourceif triggerPatrol && patrolFn != nil {- go patrolFn(finding.ResourceID, "alert_fired")+ go patrolFn(finding.ResourceID, finding.ResourceType, "alert_fired", finding.AlertType)}// Schedule AI enhancement@@ -236,7 +236,7 @@ func (b *AlertBridge) handleAlertResolved(alertID string) {// Trigger verification patrolif triggerPatrol && patrolFn != nil && finding != nil {- go patrolFn(finding.ResourceID, "alert_cleared")+ go patrolFn(finding.ResourceID, finding.ResourceType, "alert_cleared", finding.AlertType)}}}diff --git a/internal/ai/unified/bridge_test.go b/internal/ai/unified/bridge_test.goindex 044309039e..9e8989cc44 100644--- a/internal/ai/unified/bridge_test.go+++ b/internal/ai/unified/bridge_test.go@@ -76,7 +76,7 @@ func TestAlertBridge_HandleNewAlertAndEnhance(t *testing.T) {bridge.running = truepatrolCh := make(chan string, 1)- bridge.SetPatrolTrigger(func(resourceID, reason string) {+ bridge.SetPatrolTrigger(func(resourceID, resourceType, reason, alertType string) {patrolCh <- reason})@@ -124,7 +124,7 @@ func TestAlertBridge_HandleAlertResolved(t *testing.T) {bridge.running = truepatrolCh := make(chan string, 1)- bridge.SetPatrolTrigger(func(resourceID, reason string) {+ bridge.SetPatrolTrigger(func(resourceID, resourceType, reason, alertType string) {patrolCh <- reason})diff --git a/internal/ai/unified/setup.go b/internal/ai/unified/setup.goindex 406044543e..481b3990c7 100644--- a/internal/ai/unified/setup.go+++ b/internal/ai/unified/setup.go@@ -42,7 +42,7 @@ type SetupResult struct {// result, err := unified.Setup(unified.SetupConfig{// DataDir: dataPath,// AlertManager: alertManager,-// PatrolTriggerFunc: func(resourceID, reason string) { patrol.Trigger(resourceID, reason) },+// PatrolTriggerFunc: func(resourceID, resourceType, reason, alertType string) { patrol.Trigger(resourceID, reason) },// AutoEnhance: true,// TriggerPatrolOnAlert: true,// })diff --git a/internal/ai/unified/setup_test.go b/internal/ai/unified/setup_test.goindex a3e9f22487..36c42dae68 100644--- a/internal/ai/unified/setup_test.go+++ b/internal/ai/unified/setup_test.go@@ -32,7 +32,7 @@ func TestQuickSetup(t *testing.T) {func TestSetupWithPatrol(t *testing.T) {manager := alerts.NewManager()- result, err := SetupWithPatrol(manager, t.TempDir(), func(resourceID, reason string) {})+ result, err := SetupWithPatrol(manager, t.TempDir(), func(resourceID, resourceType, reason, alertType string) {})if err != nil {t.Fatalf("unexpected error: %v", err)}