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 API handlers for AI and discovery endpoints
rcourtman9dcd859056a2
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex 7e68d51faa..cd3fbe6386 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -49,6 +49,8 @@ type AIService interface {SetMetricsHistory(provider chat.MCPMetricsHistoryProvider)SetAgentProfileManager(manager chat.AgentProfileManager)SetStorageProvider(provider chat.MCPStorageProvider)+ SetStorageConfigProvider(provider chat.MCPStorageConfigProvider)+ SetGuestConfigProvider(provider chat.MCPGuestConfigProvider)SetBackupProvider(provider chat.MCPBackupProvider)SetDiskHealthProvider(provider chat.MCPDiskHealthProvider)SetUpdatesProvider(provider chat.MCPUpdatesProvider)@@ -859,6 +861,20 @@ func (h *AIHandler) SetStorageProvider(provider chat.MCPStorageProvider) {}}+// SetStorageConfigProvider sets the storage config provider for MCP tools+func (h *AIHandler) SetStorageConfigProvider(provider chat.MCPStorageConfigProvider) {+ if h.legacyService != nil {+ h.legacyService.SetStorageConfigProvider(provider)+ }+}++// SetGuestConfigProvider sets the guest config provider for MCP tools+func (h *AIHandler) SetGuestConfigProvider(provider chat.MCPGuestConfigProvider) {+ if h.legacyService != nil {+ h.legacyService.SetGuestConfigProvider(provider)+ }+}+// SetBackupProvider sets the backup provider for MCP toolsfunc (h *AIHandler) SetBackupProvider(provider chat.MCPBackupProvider) {if h.legacyService != nil {diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.goindex 2b3671ab74..ccb9a870a1 100644--- a/internal/api/ai_handler_test.go+++ b/internal/api/ai_handler_test.go@@ -125,6 +125,12 @@ func (m *MockAIService) SetMetricsHistory(provider chat.MCPMetricsHistoryProvide}func (m *MockAIService) SetBackupProvider(provider chat.MCPBackupProvider) { m.Called(provider) }func (m *MockAIService) SetStorageProvider(provider chat.MCPStorageProvider) { m.Called(provider) }+func (m *MockAIService) SetStorageConfigProvider(provider chat.MCPStorageConfigProvider) {+ m.Called(provider)+}+func (m *MockAIService) SetGuestConfigProvider(provider chat.MCPGuestConfigProvider) {+ m.Called(provider)+}func (m *MockAIService) SetDiskHealthProvider(provider chat.MCPDiskHealthProvider) {m.Called(provider)}@@ -144,6 +150,9 @@ func (m *MockAIService) SetEventCorrelatorProvider(provider chat.EventCorrelatorm.Called(provider)}func (m *MockAIService) SetTopologyProvider(provider chat.TopologyProvider) { m.Called(provider) }+func (m *MockAIService) SetDiscoveryProvider(provider chat.MCPDiscoveryProvider) {+ m.Called(provider)+}func (m *MockAIService) UpdateControlSettings(cfg *config.AIConfig) { m.Called(cfg) }func (m *MockAIService) GetBaseURL() string {diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 4f8a9faff4..775c981e6b 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -30,11 +30,11 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/proxmox""github.com/rcourtman/pulse-go-rewrite/internal/ai/remediation""github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"- "github.com/rcourtman/pulse-go-rewrite/internal/aidiscovery""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/license""github.com/rcourtman/pulse-go-rewrite/internal/metrics""github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery""github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rs/zerolog/log")@@ -85,8 +85,8 @@ type AISettingsHandler struct {investigationStores map[string]*investigation.Store // Investigation stores per orginvestigationMu sync.RWMutex- // AI Discovery store for deep infrastructure discovery- aiDiscoveryStore *aidiscovery.Store+ // Discovery store for deep infrastructure discovery+ discoveryStore *servicediscovery.Store}// NewAISettingsHandler creates a new AI settings handler@@ -193,8 +193,8 @@ func (h *AISettingsHandler) GetAIService(ctx context.Context) *ai.Service {if h.correlationDetector != nil {svc.SetCorrelationDetector(h.correlationDetector)}- if h.aiDiscoveryStore != nil {- svc.SetAIDiscoveryStore(h.aiDiscoveryStore)+ if h.discoveryStore != nil {+ svc.SetDiscoveryStore(h.discoveryStore)}// Set license checker if handler available@@ -534,24 +534,24 @@ func (h *AISettingsHandler) GetUnifiedStore() *unified.UnifiedStore {return h.unifiedStore}-// SetAIDiscoveryStore sets the AI discovery store for deep infrastructure discovery-func (h *AISettingsHandler) SetAIDiscoveryStore(store *aidiscovery.Store) {- h.aiDiscoveryStore = store+// SetDiscoveryStore sets the discovery store for deep infrastructure discovery+func (h *AISettingsHandler) SetDiscoveryStore(store *servicediscovery.Store) {+ h.discoveryStore = store// Also set on legacy service if it existsif h.legacyAIService != nil {- h.legacyAIService.SetAIDiscoveryStore(store)+ h.legacyAIService.SetDiscoveryStore(store)}// Set on all existing tenant servicesh.aiServicesMu.RLock()defer h.aiServicesMu.RUnlock()for _, svc := range h.aiServices {- svc.SetAIDiscoveryStore(store)+ svc.SetDiscoveryStore(store)}}-// GetAIDiscoveryStore returns the AI discovery store-func (h *AISettingsHandler) GetAIDiscoveryStore() *aidiscovery.Store {- return h.aiDiscoveryStore+// GetDiscoveryStore returns the discovery store+func (h *AISettingsHandler) GetDiscoveryStore() *servicediscovery.Store {+ return h.discoveryStore}// SetAlertBridge sets the alert bridge@@ -750,7 +750,6 @@ func (h *AISettingsHandler) setupInvestigationOrchestrator(orgID string, svc *aiif cfg != nil {invConfig.MaxTurns = cfg.GetPatrolInvestigationBudget()invConfig.Timeout = cfg.GetPatrolInvestigationTimeout()- invConfig.CriticalRequireApproval = cfg.ShouldCriticalRequireApproval()}// Create orchestrator@@ -766,10 +765,36 @@ func (h *AISettingsHandler) setupInvestigationOrchestrator(orgID string, svc *ai// The chatAdapter implements both ChatService and CommandExecutor interfacesorchestrator.SetCommandExecutor(chatAdapter)+ // Set autonomy level provider for re-checking before fix execution+ // This handles cases where user changes autonomy level during an investigation+ orchestrator.SetAutonomyLevelProvider(&autonomyLevelProviderAdapter{svc: svc})+// Set infrastructure context provider for CLI access information// This enables investigations to know where services run (Docker, systemd, native)// and propose correct commands (e.g., 'docker exec pbs proxmox-backup-manager ...')if knowledgeStore := svc.GetKnowledgeStore(); knowledgeStore != nil {+ // Wire up discovery context to the knowledge store+ // This unifies deep-scanned discovery data with legacy knowledge notes+ if discoveryService := svc.GetDiscoveryService(); discoveryService != nil {+ knowledgeStore.SetDiscoveryContextProvider(func() string {+ discoveries, err := discoveryService.ListDiscoveries()+ if err != nil || len(discoveries) == 0 {+ return ""+ }+ return servicediscovery.FormatForAIContext(discoveries)+ })+ knowledgeStore.SetDiscoveryContextProviderForResources(func(resourceIDs []string) string {+ if len(resourceIDs) == 0 {+ return ""+ }+ discoveries, err := discoveryService.ListDiscoveries()+ if err != nil || len(discoveries) == 0 {+ return ""+ }+ filtered := servicediscovery.FilterDiscoveriesByResourceIDs(discoveries, resourceIDs)+ return servicediscovery.FormatForAIContext(filtered)+ })+ }orchestrator.SetInfrastructureContextProvider(knowledgeStore)}@@ -805,6 +830,33 @@ func (w *findingsStoreWrapper) UpdateInvestigation(id, sessionID, status, outcomreturn w.store.UpdateInvestigation(id, sessionID, status, outcome, lastInvestigatedAt, attempts)}+// autonomyLevelProviderAdapter provides current autonomy level from config for re-checking before fix execution+type autonomyLevelProviderAdapter struct {+ svc *ai.Service+}++func (a *autonomyLevelProviderAdapter) GetCurrentAutonomyLevel() string {+ if a.svc == nil {+ return config.PatrolAutonomyMonitor+ }+ cfg := a.svc.GetConfig()+ if cfg == nil {+ return config.PatrolAutonomyMonitor+ }+ return cfg.GetPatrolAutonomyLevel()+}++func (a *autonomyLevelProviderAdapter) IsFullModeUnlocked() bool {+ if a.svc == nil {+ return false+ }+ cfg := a.svc.GetConfig()+ if cfg == nil {+ return false+ }+ return cfg.PatrolFullModeUnlocked+}+// AISettingsResponse is returned by GET /api/settings/ai// API keys are masked for securitytype AISettingsResponse struct {@@ -846,8 +898,8 @@ type AISettingsResponse struct {// Infrastructure control settingsControlLevel string `json:"control_level"` // "read_only", "controlled", "autonomous"ProtectedGuests []string `json:"protected_guests,omitempty"` // VMIDs/names that AI cannot control- // AI Discovery settings- DiscoveryEnabled bool `json:"discovery_enabled"` // true if AI discovery is enabled+ // Discovery settings+ DiscoveryEnabled bool `json:"discovery_enabled"` // true if discovery is enabledDiscoveryIntervalHours int `json:"discovery_interval_hours,omitempty"` // Hours between auto-scans (0 = manual only)}@@ -891,8 +943,8 @@ type AISettingsUpdateRequest struct {// Infrastructure control settingsControlLevel *string `json:"control_level,omitempty"` // "read_only", "controlled", "autonomous"ProtectedGuests []string `json:"protected_guests,omitempty"` // VMIDs/names that AI cannot control (nil = don't update, empty = clear)- // AI Discovery settings- DiscoveryEnabled *bool `json:"discovery_enabled,omitempty"` // Enable AI discovery+ // Discovery settings+ DiscoveryEnabled *bool `json:"discovery_enabled,omitempty"` // Enable discoveryDiscoveryIntervalHours *int `json:"discovery_interval_hours,omitempty"` // Hours between auto-scans (0 = manual only)}@@ -3024,6 +3076,8 @@ type PatrolStatusResponse struct {Healthy bool `json:"healthy"`IntervalMs int64 `json:"interval_ms"` // Patrol interval in millisecondsFixedCount int `json:"fixed_count"` // Number of issues auto-fixed by Patrol+ BlockedReason string `json:"blocked_reason,omitempty"`+ BlockedAt *time.Time `json:"blocked_at,omitempty"`// License status for Pro feature gatingLicenseRequired bool `json:"license_required"` // True if Pro license needed for full featuresLicenseStatus string `json:"license_status"` // "active", "expired", "grace_period", "none"@@ -3084,6 +3138,8 @@ func (h *AISettingsHandler) HandleGetPatrolStatus(w http.ResponseWriter, r *httpHealthy: status.Healthy,IntervalMs: status.IntervalMs,FixedCount: fixedCount,+ BlockedReason: status.BlockedReason,+ BlockedAt: status.BlockedAt,LicenseRequired: !hasPatrolFeature,LicenseStatus: licenseStatus,}@@ -5217,12 +5273,22 @@ func truncateForLog(s string, maxLen int) string {return s[:maxLen] + "..."}-// PatrolAutonomySettings represents the patrol autonomy configuration+// PatrolAutonomySettings represents the patrol autonomy configuration for API requests+// Uses pointer for FullModeUnlocked to distinguish "not sent" from "sent as false"type PatrolAutonomySettings struct {- AutonomyLevel string `json:"autonomy_level"` // "monitor", "approval", "full"- InvestigationBudget int `json:"investigation_budget"` // Max turns per investigation (5-30)- InvestigationTimeoutSec int `json:"investigation_timeout_sec"` // Max seconds per investigation (60-1800)- CriticalRequireApproval bool `json:"critical_require_approval"` // Critical findings always require approval+ AutonomyLevel string `json:"autonomy_level"` // "monitor", "approval", "assisted", "full"+ FullModeUnlocked *bool `json:"full_mode_unlocked,omitempty"` // User has acknowledged Full mode risks (nil = preserve existing)+ InvestigationBudget int `json:"investigation_budget"` // Max turns per investigation (5-30)+ InvestigationTimeoutSec int `json:"investigation_timeout_sec"` // Max seconds per investigation (60-1800)+}++// PatrolAutonomyResponse represents the patrol autonomy configuration for API responses+// Uses plain bool for FullModeUnlocked since responses always include the actual value+type PatrolAutonomyResponse struct {+ AutonomyLevel string `json:"autonomy_level"`+ FullModeUnlocked bool `json:"full_mode_unlocked"`+ InvestigationBudget int `json:"investigation_budget"`+ InvestigationTimeoutSec int `json:"investigation_timeout_sec"`}// HandleGetPatrolAutonomy returns the current patrol autonomy settings (GET /api/ai/patrol/autonomy)@@ -5239,11 +5305,11 @@ func (h *AISettingsHandler) HandleGetPatrolAutonomy(w http.ResponseWriter, r *htreturn}- settings := PatrolAutonomySettings{+ settings := PatrolAutonomyResponse{AutonomyLevel: cfg.GetPatrolAutonomyLevel(),+ FullModeUnlocked: cfg.PatrolFullModeUnlocked,InvestigationBudget: cfg.GetPatrolInvestigationBudget(),InvestigationTimeoutSec: int(cfg.GetPatrolInvestigationTimeout().Seconds()),- CriticalRequireApproval: cfg.ShouldCriticalRequireApproval(),}w.Header().Set("Content-Type", "application/json")@@ -5266,7 +5332,7 @@ func (h *AISettingsHandler) HandleUpdatePatrolAutonomy(w http.ResponseWriter, r// Validate autonomy levelif !config.IsValidPatrolAutonomyLevel(req.AutonomyLevel) {writeErrorResponse(w, http.StatusBadRequest, "invalid_autonomy_level",- fmt.Sprintf("Invalid autonomy level: %s. Must be 'monitor', 'approval', 'full', or 'autonomous'", req.AutonomyLevel), nil)+ fmt.Sprintf("Invalid autonomy level: %s. Must be 'monitor', 'approval', 'assisted', or 'full'", req.AutonomyLevel), nil)return}@@ -5293,11 +5359,33 @@ func (h *AISettingsHandler) HandleUpdatePatrolAutonomy(w http.ResponseWriter, rreturn}- // Update config- cfg.PatrolAutonomyLevel = req.AutonomyLevel+ // Determine effective unlock value: use request value if provided, else preserve existing+ effectiveUnlocked := cfg.PatrolFullModeUnlocked+ if req.FullModeUnlocked != nil {+ effectiveUnlocked = *req.FullModeUnlocked+ }++ // Handle auto-downgrade FIRST: if turning off unlock while currently in full mode AND+ // request still asks for "full", downgrade to assisted. If user explicitly requested a+ // lower level (monitor, approval, assisted), honor that instead.+ finalAutonomyLevel := req.AutonomyLevel+ currentLevel := cfg.GetPatrolAutonomyLevel() // Use getter to handle legacy "autonomous" migration+ if !effectiveUnlocked && currentLevel == config.PatrolAutonomyFull && req.AutonomyLevel == config.PatrolAutonomyFull {+ finalAutonomyLevel = config.PatrolAutonomyAssisted+ }++ // Validate the FINAL level: can't use "full" mode unless unlocked+ if finalAutonomyLevel == config.PatrolAutonomyFull && !effectiveUnlocked {+ writeErrorResponse(w, http.StatusForbidden, "full_mode_locked",+ "Full mode requires acknowledgment. Enable 'full_mode_unlocked' first.", nil)+ return+ }++ // Now safe to update config (all validation passed)+ cfg.PatrolFullModeUnlocked = effectiveUnlocked+ cfg.PatrolAutonomyLevel = finalAutonomyLevelcfg.PatrolInvestigationBudget = req.InvestigationBudgetcfg.PatrolInvestigationTimeoutSec = req.InvestigationTimeoutSec- cfg.PatrolCriticalRequireApproval = req.CriticalRequireApproval// Save config via persistence layerif err := h.getPersistence(r.Context()).SaveAIConfig(*cfg); err != nil {@@ -5312,16 +5400,22 @@ func (h *AISettingsHandler) HandleUpdatePatrolAutonomy(w http.ResponseWriter, rfmt.Sprintf("Config saved but failed to reload: %v", err))}- // Log audit event+ // Log audit event with actual saved valuesusername := getAuthUsername(h.getConfig(r.Context()), r)LogAuditEvent("patrol_autonomy_updated", username, GetClientIP(r), r.URL.Path, true,- fmt.Sprintf("Updated patrol autonomy: level=%s, budget=%d, timeout=%ds",- req.AutonomyLevel, req.InvestigationBudget, req.InvestigationTimeoutSec))+ fmt.Sprintf("Updated patrol autonomy: level=%s, unlocked=%v, budget=%d, timeout=%ds",+ finalAutonomyLevel, effectiveUnlocked, req.InvestigationBudget, req.InvestigationTimeoutSec))+ // Return actual saved values (may differ from request due to auto-downgrade)w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(map[string]interface{}{- "success": true,- "settings": req,+ "success": true,+ "settings": map[string]interface{}{+ "autonomy_level": finalAutonomyLevel,+ "full_mode_unlocked": effectiveUnlocked,+ "investigation_budget": req.InvestigationBudget,+ "investigation_timeout_sec": req.InvestigationTimeoutSec,+ },})}@@ -5529,7 +5623,7 @@ func (h *AISettingsHandler) HandleReinvestigateFinding(w http.ResponseWriter, rautonomyLevel := cfg.GetPatrolAutonomyLevel()if autonomyLevel == config.PatrolAutonomyMonitor {writeErrorResponse(w, http.StatusBadRequest, "autonomy_disabled",- "Patrol autonomy is set to 'monitor' mode. Enable 'approval' or 'full' mode to investigate findings.", nil)+ "Patrol autonomy is set to 'monitor' mode. Enable 'approval', 'assisted', or 'full' mode to investigate findings.", nil)return}diff --git a/internal/api/ai_handlers_investigation_additional_test.go b/internal/api/ai_handlers_investigation_additional_test.goindex 29cba8754e..0ff1253dea 100644--- a/internal/api/ai_handlers_investigation_additional_test.go+++ b/internal/api/ai_handlers_investigation_additional_test.go@@ -231,7 +231,6 @@ func TestHandlePatrolAutonomyGetAndUpdate(t *testing.T) {aiCfg.PatrolAutonomyLevel = config.PatrolAutonomyApprovalaiCfg.PatrolInvestigationBudget = 8aiCfg.PatrolInvestigationTimeoutSec = 120- aiCfg.PatrolCriticalRequireApproval = trueif err := persistence.SaveAIConfig(*aiCfg); err != nil {t.Fatalf("SaveAIConfig: %v", err)}@@ -256,9 +255,9 @@ func TestHandlePatrolAutonomyGetAndUpdate(t *testing.T) {update := PatrolAutonomySettings{AutonomyLevel: config.PatrolAutonomyFull,+ FullModeUnlocked: func() *bool { v := true; return &v }(),InvestigationBudget: 3,InvestigationTimeoutSec: 10,- CriticalRequireApproval: false,}body, _ := json.Marshal(update)updateReq := httptest.NewRequest(http.MethodPut, "/api/ai/patrol/autonomy", strings.NewReader(string(body)))@@ -277,6 +276,9 @@ func TestHandlePatrolAutonomyGetAndUpdate(t *testing.T) {if settings["autonomy_level"] != config.PatrolAutonomyFull {t.Fatalf("unexpected autonomy level %v", settings["autonomy_level"])}+ if settings["full_mode_unlocked"] != true {+ t.Fatalf("expected full_mode_unlocked true, got %v", settings["full_mode_unlocked"])+ }if settings["investigation_budget"].(float64) != 5 {t.Fatalf("expected clamped budget to 5, got %v", settings["investigation_budget"])}@@ -288,7 +290,7 @@ func TestHandlePatrolAutonomyGetAndUpdate(t *testing.T) {if err != nil {t.Fatalf("LoadAIConfig: %v", err)}- if loaded.PatrolAutonomyLevel != config.PatrolAutonomyFull || loaded.PatrolInvestigationBudget != 5 || loaded.PatrolInvestigationTimeoutSec != 60 {+ if loaded.PatrolAutonomyLevel != config.PatrolAutonomyFull || !loaded.PatrolFullModeUnlocked || loaded.PatrolInvestigationBudget != 5 || loaded.PatrolInvestigationTimeoutSec != 60 {t.Fatalf("unexpected persisted settings: %+v", loaded)}}diff --git a/internal/api/aidiscovery_handlers.go b/internal/api/aidiscovery_handlers.godeleted file mode 100644index 6718cddee6..0000000000--- a/internal/api/aidiscovery_handlers.go+++ /dev/null@@ -1,349 +0,0 @@-package api--import (- "encoding/json"- "net/http"- "strings"-- "github.com/rcourtman/pulse-go-rewrite/internal/aidiscovery"- "github.com/rs/zerolog/log"-)--// AIDiscoveryHandlers handles AI-powered infrastructure discovery endpoints.-type AIDiscoveryHandlers struct {- service *aidiscovery.Service-}--// NewAIDiscoveryHandlers creates new AI discovery handlers.-func NewAIDiscoveryHandlers(service *aidiscovery.Service) *AIDiscoveryHandlers {- return &AIDiscoveryHandlers{- service: service,- }-}--// SetService sets the discovery service (used for late initialization after routes are registered).-func (h *AIDiscoveryHandlers) SetService(service *aidiscovery.Service) {- h.service = service-}--// writeDiscoveryJSON writes a JSON response.-func writeDiscoveryJSON(w http.ResponseWriter, data any) {- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(data)-}--// writeDiscoveryError writes a JSON error response.-func writeDiscoveryError(w http.ResponseWriter, statusCode int, message string) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(statusCode)- json.NewEncoder(w).Encode(map[string]any{- "error": true,- "message": message,- })-}--// HandleListDiscoveries handles GET /api/aidiscovery-func (h *AIDiscoveryHandlers) HandleListDiscoveries(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- discoveries, err := h.service.ListDiscoveries()- if err != nil {- log.Error().Err(err).Msg("Failed to list discoveries")- writeDiscoveryError(w, http.StatusInternalServerError, "Failed to list discoveries")- return- }-- // Convert to summaries for list view- summaries := make([]aidiscovery.DiscoverySummary, 0, len(discoveries))- for _, d := range discoveries {- summaries = append(summaries, d.ToSummary())- }-- writeDiscoveryJSON(w, map[string]any{- "discoveries": summaries,- "total": len(summaries),- })-}--// HandleGetDiscovery handles GET /api/aidiscovery/{type}/{host}/{id}-func (h *AIDiscoveryHandlers) HandleGetDiscovery(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- // Parse path: /api/aidiscovery/{type}/{host}/{id}- path := strings.TrimPrefix(r.URL.Path, "/api/aidiscovery/")- parts := strings.SplitN(path, "/", 3)- if len(parts) < 3 {- writeDiscoveryError(w, http.StatusBadRequest, "Invalid path: expected /api/aidiscovery/{type}/{host}/{id}")- return- }-- resourceType := aidiscovery.ResourceType(parts[0])- hostID := parts[1]- resourceID := parts[2]-- discovery, err := h.service.GetDiscoveryByResource(resourceType, hostID, resourceID)- if err != nil {- log.Error().Err(err).Str("type", string(resourceType)).Str("host", hostID).Str("id", resourceID).Msg("Failed to get discovery")- writeDiscoveryError(w, http.StatusInternalServerError, "Failed to get discovery")- return- }-- if discovery == nil {- writeDiscoveryError(w, http.StatusNotFound, "Discovery not found")- return- }-- writeDiscoveryJSON(w, discovery)-}--// HandleTriggerDiscovery handles POST /api/aidiscovery/{type}/{host}/{id}-func (h *AIDiscoveryHandlers) HandleTriggerDiscovery(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- // Parse path- path := strings.TrimPrefix(r.URL.Path, "/api/aidiscovery/")- parts := strings.SplitN(path, "/", 3)- if len(parts) < 3 {- writeDiscoveryError(w, http.StatusBadRequest, "Invalid path: expected /api/aidiscovery/{type}/{host}/{id}")- return- }-- resourceType := aidiscovery.ResourceType(parts[0])- hostID := parts[1]- resourceID := parts[2]-- // Parse optional request body for force flag and hostname- var reqBody struct {- Force bool `json:"force"`- Hostname string `json:"hostname"`- }- if r.Body != nil {- _ = json.NewDecoder(r.Body).Decode(&reqBody)- }-- // Build discovery request- req := aidiscovery.DiscoveryRequest{- ResourceType: resourceType,- ResourceID: resourceID,- HostID: hostID,- Hostname: reqBody.Hostname,- Force: reqBody.Force,- }-- // If hostname not provided, try to use hostID- if req.Hostname == "" {- req.Hostname = hostID- }-- discovery, err := h.service.DiscoverResource(r.Context(), req)- if err != nil {- log.Error().Err(err).- Str("type", string(resourceType)).- Str("host", hostID).- Str("id", resourceID).- Msg("Failed to trigger discovery")- writeDiscoveryError(w, http.StatusInternalServerError, "Discovery failed: "+err.Error())- return- }-- writeDiscoveryJSON(w, discovery)-}--// HandleUpdateNotes handles PUT /api/aidiscovery/{type}/{host}/{id}/notes-func (h *AIDiscoveryHandlers) HandleUpdateNotes(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- // Parse path- path := strings.TrimPrefix(r.URL.Path, "/api/aidiscovery/")- path = strings.TrimSuffix(path, "/notes")- parts := strings.SplitN(path, "/", 3)- if len(parts) < 3 {- writeDiscoveryError(w, http.StatusBadRequest, "Invalid path")- return- }-- resourceType := aidiscovery.ResourceType(parts[0])- hostID := parts[1]- resourceID := parts[2]-- // Build the full ID- id := aidiscovery.MakeResourceID(resourceType, hostID, resourceID)-- // Parse request body- var req aidiscovery.UpdateNotesRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- writeDiscoveryError(w, http.StatusBadRequest, "Invalid request body")- return- }-- if err := h.service.UpdateNotes(id, req.UserNotes, req.UserSecrets); err != nil {- log.Error().Err(err).Str("id", id).Msg("Failed to update notes")- writeDiscoveryError(w, http.StatusInternalServerError, "Failed to update notes: "+err.Error())- return- }-- // Return updated discovery- discovery, err := h.service.GetDiscovery(id)- if err != nil {- writeDiscoveryError(w, http.StatusInternalServerError, "Notes updated but failed to fetch result")- return- }-- writeDiscoveryJSON(w, discovery)-}--// HandleDeleteDiscovery handles DELETE /api/aidiscovery/{type}/{host}/{id}-func (h *AIDiscoveryHandlers) HandleDeleteDiscovery(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- // Parse path- path := strings.TrimPrefix(r.URL.Path, "/api/aidiscovery/")- parts := strings.SplitN(path, "/", 3)- if len(parts) < 3 {- writeDiscoveryError(w, http.StatusBadRequest, "Invalid path")- return- }-- resourceType := aidiscovery.ResourceType(parts[0])- hostID := parts[1]- resourceID := parts[2]-- id := aidiscovery.MakeResourceID(resourceType, hostID, resourceID)-- if err := h.service.DeleteDiscovery(id); err != nil {- log.Error().Err(err).Str("id", id).Msg("Failed to delete discovery")- writeDiscoveryError(w, http.StatusInternalServerError, "Failed to delete discovery")- return- }-- writeDiscoveryJSON(w, map[string]any{"success": true, "id": id})-}--// HandleGetProgress handles GET /api/aidiscovery/{type}/{host}/{id}/progress-func (h *AIDiscoveryHandlers) HandleGetProgress(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- // Parse path- path := strings.TrimPrefix(r.URL.Path, "/api/aidiscovery/")- path = strings.TrimSuffix(path, "/progress")- parts := strings.SplitN(path, "/", 3)- if len(parts) < 3 {- writeDiscoveryError(w, http.StatusBadRequest, "Invalid path")- return- }-- resourceType := aidiscovery.ResourceType(parts[0])- hostID := parts[1]- resourceID := parts[2]-- id := aidiscovery.MakeResourceID(resourceType, hostID, resourceID)-- progress := h.service.GetProgress(id)- if progress == nil {- // Not currently scanning - check if we have a discovery- discovery, err := h.service.GetDiscovery(id)- if err == nil && discovery != nil {- writeDiscoveryJSON(w, map[string]any{- "status": "completed",- "resource_id": id,- "updated_at": discovery.UpdatedAt,- })- return- }-- writeDiscoveryJSON(w, map[string]any{- "status": "not_started",- "resource_id": id,- })- return- }-- writeDiscoveryJSON(w, progress)-}--// HandleGetStatus handles GET /api/aidiscovery/status-func (h *AIDiscoveryHandlers) HandleGetStatus(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- writeDiscoveryJSON(w, h.service.GetStatus())-}--// HandleListByType handles GET /api/aidiscovery/type/{type}-func (h *AIDiscoveryHandlers) HandleListByType(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- // Parse path- path := strings.TrimPrefix(r.URL.Path, "/api/aidiscovery/type/")- resourceType := aidiscovery.ResourceType(path)-- discoveries, err := h.service.ListDiscoveriesByType(resourceType)- if err != nil {- log.Error().Err(err).Str("type", string(resourceType)).Msg("Failed to list discoveries by type")- writeDiscoveryError(w, http.StatusInternalServerError, "Failed to list discoveries")- return- }-- summaries := make([]aidiscovery.DiscoverySummary, 0, len(discoveries))- for _, d := range discoveries {- summaries = append(summaries, d.ToSummary())- }-- writeDiscoveryJSON(w, map[string]any{- "discoveries": summaries,- "total": len(summaries),- "type": resourceType,- })-}--// HandleListByHost handles GET /api/aidiscovery/host/{host}-func (h *AIDiscoveryHandlers) HandleListByHost(w http.ResponseWriter, r *http.Request) {- if h.service == nil {- writeDiscoveryError(w, http.StatusServiceUnavailable, "AI discovery service not configured")- return- }-- // Parse path- hostID := strings.TrimPrefix(r.URL.Path, "/api/aidiscovery/host/")-- discoveries, err := h.service.ListDiscoveriesByHost(hostID)- if err != nil {- log.Error().Err(err).Str("host", hostID).Msg("Failed to list discoveries by host")- writeDiscoveryError(w, http.StatusInternalServerError, "Failed to list discoveries")- return- }-- summaries := make([]aidiscovery.DiscoverySummary, 0, len(discoveries))- for _, d := range discoveries {- summaries = append(summaries, d.ToSummary())- }-- writeDiscoveryJSON(w, map[string]any{- "discoveries": summaries,- "total": len(summaries),- "host": hostID,- })-}diff --git a/internal/api/discovery_handlers.go b/internal/api/discovery_handlers.gonew file mode 100644index 0000000000..9ddc9d9452--- /dev/null+++ b/internal/api/discovery_handlers.go@@ -0,0 +1,494 @@+package api++import (+ "encoding/json"+ "net/http"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery"+ "github.com/rs/zerolog/log"+)++// Note: adminBypassEnabled() is defined in auth.go++// DiscoveryHandlers handles AI-powered infrastructure discovery endpoints.+type DiscoveryHandlers struct {+ service *servicediscovery.Service+ config *config.Config // For admin status checks+}++// NewDiscoveryHandlers creates new discovery handlers.+func NewDiscoveryHandlers(service *servicediscovery.Service, cfg *config.Config) *DiscoveryHandlers {+ return &DiscoveryHandlers{+ service: service,+ config: cfg,+ }+}++// SetService sets the discovery service (used for late initialization after routes are registered).+func (h *DiscoveryHandlers) SetService(service *servicediscovery.Service) {+ h.service = service+}++// writeDiscoveryJSON writes a JSON response.+func writeDiscoveryJSON(w http.ResponseWriter, data any) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(data)+}++// writeDiscoveryError writes a JSON error response.+func writeDiscoveryError(w http.ResponseWriter, statusCode int, message string) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(statusCode)+ json.NewEncoder(w).Encode(map[string]any{+ "error": true,+ "message": message,+ })+}++// isAdminRequest checks if the current request is from an admin user.+// In Pulse, all authenticated users have admin privileges except non-admin+// proxy auth users. This method checks all authentication methods.+func (h *DiscoveryHandlers) isAdminRequest(r *http.Request) bool {+ // Dev mode bypass - treat all requests as admin when enabled+ if adminBypassEnabled() {+ return true+ }++ if h.config == nil {+ return false // Default to non-admin if no config+ }++ // 1. If using proxy auth, check the admin role+ if h.config.ProxyAuthSecret != "" {+ if valid, _, isAdmin := CheckProxyAuth(h.config, r); valid {+ return isAdmin+ }+ return false+ }++ // 2. Check for basic auth (Pulse single-user admin credential)+ if _, _, ok := r.BasicAuth(); ok {+ return true+ }++ // 3. Check for valid session cookie (OIDC/SAML sessions)+ if cookie, err := r.Cookie("pulse_session"); err == nil && cookie.Value != "" {+ if ValidateSession(cookie.Value) {+ return true // Valid session = admin+ }+ }++ // 4. Check for valid API token (read-only check, safe under RLock)+ if token := r.Header.Get("X-API-Token"); token != "" {+ config.Mu.RLock()+ ok := h.config.IsValidAPIToken(token)+ config.Mu.RUnlock()+ if ok {+ return true // Valid API token = admin+ }+ }++ return false+}++// redactSensitiveFields removes sensitive data from a discovery for non-admin users.+// This creates a copy to avoid modifying the original.+func redactSensitiveFields(d *servicediscovery.ResourceDiscovery) *servicediscovery.ResourceDiscovery {+ if d == nil {+ return nil+ }+ // Create a shallow copy+ redacted := *d+ // Redact sensitive fields+ redacted.UserSecrets = nil // Never expose to non-admins+ redacted.RawCommandOutput = nil // May contain sensitive output+ return &redacted+}++// HandleListDiscoveries handles GET /api/discovery+func (h *DiscoveryHandlers) HandleListDiscoveries(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ discoveries, err := h.service.ListDiscoveries()+ if err != nil {+ log.Error().Err(err).Msg("Failed to list discoveries")+ writeDiscoveryError(w, http.StatusInternalServerError, "Failed to list discoveries")+ return+ }++ // Convert to summaries for list view+ summaries := make([]servicediscovery.DiscoverySummary, 0, len(discoveries))+ for _, d := range discoveries {+ summaries = append(summaries, d.ToSummary())+ }++ writeDiscoveryJSON(w, map[string]any{+ "discoveries": summaries,+ "total": len(summaries),+ })+}++// HandleGetDiscovery handles GET /api/discovery/{type}/{host}/{id}+func (h *DiscoveryHandlers) HandleGetDiscovery(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Parse path: /api/discovery/{type}/{host}/{id}+ path := strings.TrimPrefix(r.URL.Path, "/api/discovery/")+ parts := strings.SplitN(path, "/", 3)+ if len(parts) < 3 {+ writeDiscoveryError(w, http.StatusBadRequest, "Invalid path: expected /api/discovery/{type}/{host}/{id}")+ return+ }++ resourceType := servicediscovery.ResourceType(parts[0])+ hostID := parts[1]+ resourceID := parts[2]++ discovery, err := h.service.GetDiscoveryByResource(resourceType, hostID, resourceID)+ if err != nil {+ log.Error().Err(err).Str("type", string(resourceType)).Str("host", hostID).Str("id", resourceID).Msg("Failed to get discovery")+ writeDiscoveryError(w, http.StatusInternalServerError, "Failed to get discovery")+ return+ }++ if discovery == nil {+ writeDiscoveryError(w, http.StatusNotFound, "Discovery not found")+ return+ }++ // Redact sensitive fields for non-admin users+ if !h.isAdminRequest(r) {+ discovery = redactSensitiveFields(discovery)+ }++ writeDiscoveryJSON(w, discovery)+}++// HandleTriggerDiscovery handles POST /api/discovery/{type}/{host}/{id}+func (h *DiscoveryHandlers) HandleTriggerDiscovery(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Parse path+ path := strings.TrimPrefix(r.URL.Path, "/api/discovery/")+ parts := strings.SplitN(path, "/", 3)+ if len(parts) < 3 {+ writeDiscoveryError(w, http.StatusBadRequest, "Invalid path: expected /api/discovery/{type}/{host}/{id}")+ return+ }++ resourceType := servicediscovery.ResourceType(parts[0])+ hostID := parts[1]+ resourceID := parts[2]++ // Parse optional request body for force flag and hostname+ var reqBody struct {+ Force bool `json:"force"`+ Hostname string `json:"hostname"`+ }+ if r.Body != nil {+ _ = json.NewDecoder(r.Body).Decode(&reqBody)+ }++ // Build discovery request+ req := servicediscovery.DiscoveryRequest{+ ResourceType: resourceType,+ ResourceID: resourceID,+ HostID: hostID,+ Hostname: reqBody.Hostname,+ Force: reqBody.Force,+ }++ // If hostname not provided, try to use hostID+ if req.Hostname == "" {+ req.Hostname = hostID+ }++ discovery, err := h.service.DiscoverResource(r.Context(), req)+ if err != nil {+ log.Error().Err(err).+ Str("type", string(resourceType)).+ Str("host", hostID).+ Str("id", resourceID).+ Msg("Failed to trigger discovery")+ writeDiscoveryError(w, http.StatusInternalServerError, "Discovery failed: "+err.Error())+ return+ }++ // Redact sensitive fields for non-admin users+ if !h.isAdminRequest(r) {+ discovery = redactSensitiveFields(discovery)+ }++ writeDiscoveryJSON(w, discovery)+}++// HandleUpdateNotes handles PUT /api/discovery/{type}/{host}/{id}/notes+func (h *DiscoveryHandlers) HandleUpdateNotes(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Parse path+ path := strings.TrimPrefix(r.URL.Path, "/api/discovery/")+ path = strings.TrimSuffix(path, "/notes")+ parts := strings.SplitN(path, "/", 3)+ if len(parts) < 3 {+ writeDiscoveryError(w, http.StatusBadRequest, "Invalid path")+ return+ }++ resourceType := servicediscovery.ResourceType(parts[0])+ hostID := parts[1]+ resourceID := parts[2]++ // Build the full ID+ id := servicediscovery.MakeResourceID(resourceType, hostID, resourceID)++ // Parse request body+ var req servicediscovery.UpdateNotesRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeDiscoveryError(w, http.StatusBadRequest, "Invalid request body")+ return+ }++ // Only admins can set user_secrets (contains sensitive data like API tokens)+ isAdmin := h.isAdminRequest(r)+ if !isAdmin && len(req.UserSecrets) > 0 {+ writeDiscoveryError(w, http.StatusForbidden, "Only admins can set user_secrets")+ return+ }++ if err := h.service.UpdateNotes(id, req.UserNotes, req.UserSecrets); err != nil {+ log.Error().Err(err).Str("id", id).Msg("Failed to update notes")+ writeDiscoveryError(w, http.StatusInternalServerError, "Failed to update notes: "+err.Error())+ return+ }++ // Return updated discovery+ discovery, err := h.service.GetDiscovery(id)+ if err != nil {+ writeDiscoveryError(w, http.StatusInternalServerError, "Notes updated but failed to fetch result")+ return+ }++ // Redact sensitive fields for non-admin users+ if !isAdmin {+ discovery = redactSensitiveFields(discovery)+ }++ writeDiscoveryJSON(w, discovery)+}++// HandleDeleteDiscovery handles DELETE /api/discovery/{type}/{host}/{id}+func (h *DiscoveryHandlers) HandleDeleteDiscovery(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Parse path+ path := strings.TrimPrefix(r.URL.Path, "/api/discovery/")+ parts := strings.SplitN(path, "/", 3)+ if len(parts) < 3 {+ writeDiscoveryError(w, http.StatusBadRequest, "Invalid path")+ return+ }++ resourceType := servicediscovery.ResourceType(parts[0])+ hostID := parts[1]+ resourceID := parts[2]++ id := servicediscovery.MakeResourceID(resourceType, hostID, resourceID)++ if err := h.service.DeleteDiscovery(id); err != nil {+ log.Error().Err(err).Str("id", id).Msg("Failed to delete discovery")+ writeDiscoveryError(w, http.StatusInternalServerError, "Failed to delete discovery")+ return+ }++ writeDiscoveryJSON(w, map[string]any{"success": true, "id": id})+}++// HandleGetProgress handles GET /api/discovery/{type}/{host}/{id}/progress+func (h *DiscoveryHandlers) HandleGetProgress(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Parse path+ path := strings.TrimPrefix(r.URL.Path, "/api/discovery/")+ path = strings.TrimSuffix(path, "/progress")+ parts := strings.SplitN(path, "/", 3)+ if len(parts) < 3 {+ writeDiscoveryError(w, http.StatusBadRequest, "Invalid path")+ return+ }++ resourceType := servicediscovery.ResourceType(parts[0])+ hostID := parts[1]+ resourceID := parts[2]++ id := servicediscovery.MakeResourceID(resourceType, hostID, resourceID)++ progress := h.service.GetProgress(id)+ if progress == nil {+ // Not currently scanning - check if we have a discovery+ discovery, err := h.service.GetDiscovery(id)+ if err == nil && discovery != nil {+ // Return completed status with all fields for frontend compatibility+ writeDiscoveryJSON(w, map[string]any{+ "resource_id": id,+ "status": "completed",+ "current_step": "",+ "total_steps": 0,+ "completed_steps": 0,+ "started_at": discovery.DiscoveredAt,+ "updated_at": discovery.UpdatedAt,+ })+ return+ }++ // Return not_started status with all fields for frontend compatibility+ writeDiscoveryJSON(w, map[string]any{+ "resource_id": id,+ "status": "not_started",+ "current_step": "",+ "total_steps": 0,+ "completed_steps": 0,+ "started_at": "",+ })+ return+ }++ writeDiscoveryJSON(w, progress)+}++// HandleGetStatus handles GET /api/discovery/status+func (h *DiscoveryHandlers) HandleGetStatus(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ status := h.service.GetStatus()++ // Add fingerprint change/stale stats+ changedCount, _ := h.service.GetChangedResourceCount()+ staleCount, _ := h.service.GetStaleResourceCount()++ status["changed_count"] = changedCount // Containers with changed fingerprints+ status["stale_count"] = staleCount // Discoveries > 30 days old++ writeDiscoveryJSON(w, status)+}++// HandleUpdateSettings handles PUT /api/discovery/settings+// Allows updating discovery settings like the staleness threshold.+func (h *DiscoveryHandlers) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Require admin privileges+ if !h.isAdminRequest(r) {+ writeDiscoveryError(w, http.StatusForbidden, "Admin privileges required")+ return+ }++ var req struct {+ MaxDiscoveryAgeDays int `json:"max_discovery_age_days"` // Days before rediscovery+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeDiscoveryError(w, http.StatusBadRequest, "Invalid request body")+ return+ }++ // Update settings+ if req.MaxDiscoveryAgeDays > 0 {+ h.service.SetMaxDiscoveryAge(time.Duration(req.MaxDiscoveryAgeDays) * 24 * time.Hour)+ log.Info().Int("days", req.MaxDiscoveryAgeDays).Msg("Max discovery age updated via API")+ }++ // Return updated status+ status := h.service.GetStatus()+ changedCount, _ := h.service.GetChangedResourceCount()+ staleCount, _ := h.service.GetStaleResourceCount()+ status["changed_count"] = changedCount+ status["stale_count"] = staleCount++ writeDiscoveryJSON(w, status)+}++// HandleListByType handles GET /api/discovery/type/{type}+func (h *DiscoveryHandlers) HandleListByType(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Parse path+ path := strings.TrimPrefix(r.URL.Path, "/api/discovery/type/")+ resourceType := servicediscovery.ResourceType(path)++ discoveries, err := h.service.ListDiscoveriesByType(resourceType)+ if err != nil {+ log.Error().Err(err).Str("type", string(resourceType)).Msg("Failed to list discoveries by type")+ writeDiscoveryError(w, http.StatusInternalServerError, "Failed to list discoveries")+ return+ }++ summaries := make([]servicediscovery.DiscoverySummary, 0, len(discoveries))+ for _, d := range discoveries {+ summaries = append(summaries, d.ToSummary())+ }++ writeDiscoveryJSON(w, map[string]any{+ "discoveries": summaries,+ "total": len(summaries),+ "type": resourceType,+ })+}++// HandleListByHost handles GET /api/discovery/host/{host}+func (h *DiscoveryHandlers) HandleListByHost(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ // Parse path+ hostID := strings.TrimPrefix(r.URL.Path, "/api/discovery/host/")++ discoveries, err := h.service.ListDiscoveriesByHost(hostID)+ if err != nil {+ log.Error().Err(err).Str("host", hostID).Msg("Failed to list discoveries by host")+ writeDiscoveryError(w, http.StatusInternalServerError, "Failed to list discoveries")+ return+ }++ summaries := make([]servicediscovery.DiscoverySummary, 0, len(discoveries))+ for _, d := range discoveries {+ summaries = append(summaries, d.ToSummary())+ }++ writeDiscoveryJSON(w, map[string]any{+ "discoveries": summaries,+ "total": len(summaries),+ "host": hostID,+ })+}diff --git a/internal/api/router.go b/internal/api/router.goindex c41e46953a..2767dd52ff 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -37,13 +37,13 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/remediation""github.com/rcourtman/pulse-go-rewrite/internal/ai/tools""github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"- "github.com/rcourtman/pulse-go-rewrite/internal/aidiscovery""github.com/rcourtman/pulse-go-rewrite/internal/alerts""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/license""github.com/rcourtman/pulse-go-rewrite/internal/metrics""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery""github.com/rcourtman/pulse-go-rewrite/internal/system""github.com/rcourtman/pulse-go-rewrite/internal/updates""github.com/rcourtman/pulse-go-rewrite/internal/utils"@@ -68,7 +68,7 @@ type Router struct {systemSettingsHandler *SystemSettingsHandleraiSettingsHandler *AISettingsHandleraiHandler *AIHandler // AI chat handler- aiDiscoveryHandlers *AIDiscoveryHandlers+ discoveryHandlers *DiscoveryHandlersresourceHandlers *ResourceHandlersreportingHandlers *ReportingHandlersconfigProfileHandler *ConfigProfileHandler@@ -288,6 +288,7 @@ func (r *Router) setupRoutes() {r.mux.HandleFunc("/api/agents/kubernetes/clusters/", RequireAdmin(r.config, RequireScope(config.ScopeKubernetesManage, r.kubernetesAgentHandlers.HandleClusterActions)))r.mux.HandleFunc("/api/version", r.handleVersion)r.mux.HandleFunc("/api/storage/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleStorage)))+ r.mux.HandleFunc("/api/storage/config", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleStorageConfig)))r.mux.HandleFunc("/api/storage-charts", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleStorageCharts)))r.mux.HandleFunc("/api/charts", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleCharts)))r.mux.HandleFunc("/api/metrics-store/stats", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleMetricsStoreStats)))@@ -1271,8 +1272,8 @@ func (r *Router) setupRoutes() {r.aiHandler = NewAIHandler(r.multiTenant, r.mtMonitor, r.agentExecServer)// AI-powered infrastructure discovery handlers- // Note: The actual service is wired up later via SetAIDiscoveryService- r.aiDiscoveryHandlers = NewAIDiscoveryHandlers(nil)+ // Note: The actual service is wired up later via SetDiscoveryService+ r.discoveryHandlers = NewDiscoveryHandlers(nil, r.config)// Wire license checker for Pro feature gating (AI Patrol, Alert Analysis, Auto-Fix)r.aiSettingsHandler.SetLicenseHandlers(r.licenseHandlers)@@ -1503,11 +1504,12 @@ func (r *Router) setupRoutes() {r.mux.HandleFunc("/api/ai/question/", RequireAuth(r.config, r.routeQuestions))// AI-powered infrastructure discovery endpoints- r.mux.HandleFunc("/api/aidiscovery", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.aiDiscoveryHandlers.HandleListDiscoveries)))- r.mux.HandleFunc("/api/aidiscovery/status", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.aiDiscoveryHandlers.HandleGetStatus)))- r.mux.HandleFunc("/api/aidiscovery/type/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.aiDiscoveryHandlers.HandleListByType)))- r.mux.HandleFunc("/api/aidiscovery/host/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.aiDiscoveryHandlers.HandleListByHost)))- r.mux.HandleFunc("/api/aidiscovery/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {+ r.mux.HandleFunc("/api/discovery", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleListDiscoveries)))+ r.mux.HandleFunc("/api/discovery/status", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleGetStatus)))+ r.mux.HandleFunc("/api/discovery/settings", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, r.discoveryHandlers.HandleUpdateSettings)))+ r.mux.HandleFunc("/api/discovery/type/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleListByType)))+ r.mux.HandleFunc("/api/discovery/host/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleListByHost)))+ r.mux.HandleFunc("/api/discovery/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {path := req.URL.Pathswitch req.Method {case http.MethodGet:@@ -1515,21 +1517,21 @@ func (r *Router) setupRoutes() {return}if strings.HasSuffix(path, "/progress") {- r.aiDiscoveryHandlers.HandleGetProgress(w, req)+ r.discoveryHandlers.HandleGetProgress(w, req)} else {- r.aiDiscoveryHandlers.HandleGetDiscovery(w, req)+ r.discoveryHandlers.HandleGetDiscovery(w, req)}case http.MethodPost:if !ensureScope(w, req, config.ScopeMonitoringWrite) {return}- r.aiDiscoveryHandlers.HandleTriggerDiscovery(w, req)+ r.discoveryHandlers.HandleTriggerDiscovery(w, req)case http.MethodPut:if !ensureScope(w, req, config.ScopeMonitoringWrite) {return}if strings.HasSuffix(path, "/notes") {- r.aiDiscoveryHandlers.HandleUpdateNotes(w, req)+ r.discoveryHandlers.HandleUpdateNotes(w, req)} else {http.Error(w, "Not found", http.StatusNotFound)}@@ -1537,7 +1539,7 @@ func (r *Router) setupRoutes() {if !ensureScope(w, req, config.ScopeMonitoringWrite) {return}- r.aiDiscoveryHandlers.HandleDeleteDiscovery(w, req)+ r.discoveryHandlers.HandleDeleteDiscovery(w, req)default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -1923,11 +1925,33 @@ func (r *Router) SetConfig(cfg *config.Config) {}}-// SetAIDiscoveryService sets the AI discovery service for the router.-func (r *Router) SetAIDiscoveryService(svc *aidiscovery.Service) {- if r.aiDiscoveryHandlers != nil {- r.aiDiscoveryHandlers.SetService(svc)+// SetDiscoveryService sets the discovery service for the router.+func (r *Router) SetDiscoveryService(svc *servicediscovery.Service) {+ if r.discoveryHandlers != nil {+ r.discoveryHandlers.SetService(svc)}++ // Wire up WebSocket hub for progress broadcasting+ if svc != nil && r.wsHub != nil {+ svc.SetWSHub(&wsHubAdapter{hub: r.wsHub})+ log.Info().Msg("Discovery: WebSocket hub wired for progress broadcasting")+ }+}++// wsHubAdapter adapts websocket.Hub to the servicediscovery.WSBroadcaster interface.+type wsHubAdapter struct {+ hub *websocket.Hub+}++// BroadcastDiscoveryProgress broadcasts discovery progress to all WebSocket clients.+func (a *wsHubAdapter) BroadcastDiscoveryProgress(progress *servicediscovery.DiscoveryProgress) {+ if a.hub == nil || progress == nil {+ return+ }+ a.hub.BroadcastMessage(websocket.Message{+ Type: "ai_discovery_progress",+ Data: progress,+ })}// StartPatrol starts the AI patrol service for background infrastructure monitoring@@ -2098,6 +2122,9 @@ func (r *Router) StartPatrol(ctx context.Context) {_, isNew := unifiedStore.AddFromAI(uf)return isNew})+ patrol.SetUnifiedFindingResolver(func(findingID string) {+ unifiedStore.Resolve(findingID)+ })log.Info().Msg("AI Intelligence: Patrol findings wired to unified store")// Sync existing findings from persistence to the unified store@@ -2143,13 +2170,13 @@ func (r *Router) StartPatrol(ctx context.Context) {// Finally start the actual patrol loopr.aiSettingsHandler.StartPatrol(ctx)- // Wire up AI discovery service to the handlers- // This enables the /api/aidiscovery endpoints to trigger discovery scans+ // Wire up discovery service to the handlers+ // This enables the /api/discovery endpoints to trigger discovery scansaiService := r.aiSettingsHandler.GetAIService(ctx)if aiService != nil {- if discoveryService := aiService.GetAIDiscoveryService(); discoveryService != nil {- r.SetAIDiscoveryService(discoveryService)- log.Info().Msg("AI Discovery: Service wired to API handlers")+ if discoveryService := aiService.GetDiscoveryService(); discoveryService != nil {+ r.SetDiscoveryService(discoveryService)+ log.Info().Msg("Discovery: Service wired to API handlers")}}}@@ -2229,12 +2256,51 @@ func (r *Router) initializeAIIntelligenceServices(ctx context.Context, dataDir s// Set patrol trigger function (triggers mini-patrol on alert events)patrol := r.aiSettingsHandler.GetAIService(ctx).GetPatrolService()if patrol != nil {- alertBridge.SetPatrolTrigger(func(resourceID, reason string) {+ alertBridge.SetPatrolTrigger(func(resourceID, resourceType, reason, alertType string) {+ scope := ai.PatrolScope{+ ResourceIDs: []string{resourceID},+ ResourceTypes: []string{resourceType},+ Depth: ai.PatrolDepthQuick,+ Context: "Alert bridge: " + reason,+ Priority: 50,+ }+ switch reason {+ case "alert_fired":+ scope.Reason = ai.TriggerReasonAlertFired+ scope.Priority = 80+ if alertType != "" {+ scope.Context = "Alert: " + alertType+ }+ case "alert_cleared":+ scope.Reason = ai.TriggerReasonAlertCleared+ scope.Priority = 40+ if alertType != "" {+ scope.Context = "Alert cleared: " + alertType+ }+ default:+ scope.Reason = ai.TriggerReasonManual+ }+log.Debug().Str("resource_id", resourceID).Str("reason", reason).Msg("Alert bridge: Triggering mini-patrol")- // Could trigger a targeted patrol here in future+ if triggerManager := r.aiSettingsHandler.GetTriggerManager(); triggerManager != nil {+ if triggerManager.TriggerPatrol(scope) {+ log.Debug().+ Str("resource_id", resourceID).+ Str("reason", reason).+ Msg("Alert bridge: Queued patrol via trigger manager")+ } else {+ log.Warn().+ Str("resource_id", resourceID).+ Str("reason", reason).+ Msg("Alert bridge: Patrol trigger rejected by trigger manager")+ }+ return+ }++ patrol.TriggerScopedPatrol(context.Background(), scope)})}@@ -2497,6 +2563,16 @@ func (r *Router) wireAIChatProviders() {service.SetStorageProvider(storageAdapter)log.Debug().Msg("AI chat: Storage provider wired")}+ storageConfigAdapter := tools.NewStorageConfigMCPAdapter(r.monitor)+ if storageConfigAdapter != nil {+ service.SetStorageConfigProvider(storageConfigAdapter)+ log.Debug().Msg("AI chat: Storage config provider wired")+ }+ guestConfigAdapter := tools.NewGuestConfigMCPAdapter(r.monitor)+ if guestConfigAdapter != nil {+ service.SetGuestConfigProvider(guestConfigAdapter)+ log.Debug().Msg("AI chat: Guest config provider wired")+ }}// Wire backup provider@@ -2626,8 +2702,8 @@ func (r *Router) wireAIChatProviders() {// Wire discovery provider for AI-powered infrastructure discovery (pulse_get_discovery, pulse_list_discoveries)if r.aiSettingsHandler != nil {if aiSvc := r.aiSettingsHandler.GetAIService(context.Background()); aiSvc != nil {- if discoverySvc := aiSvc.GetAIDiscoveryService(); discoverySvc != nil {- adapter := aidiscovery.NewToolsAdapter(discoverySvc)+ if discoverySvc := aiSvc.GetDiscoveryService(); discoverySvc != nil {+ adapter := servicediscovery.NewToolsAdapter(discoverySvc)if adapter != nil {service.SetDiscoveryProvider(tools.NewDiscoveryMCPAdapter(adapter))log.Debug().Msg("AI chat: Discovery provider wired")diff --git a/internal/api/storage_config_handler.go b/internal/api/storage_config_handler.gonew file mode 100644index 0000000000..6e4e551375--- /dev/null+++ b/internal/api/storage_config_handler.go@@ -0,0 +1,126 @@+package api++import (+ "encoding/json"+ "net/http"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"+)++type storageConfigItem struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Instance string `json:"instance,omitempty"`+ Type string `json:"type,omitempty"`+ Content string `json:"content,omitempty"`+ Nodes []string `json:"nodes,omitempty"`+ Path string `json:"path,omitempty"`+ Shared bool `json:"shared"`+ Enabled bool `json:"enabled"`+ Active bool `json:"active"`+}++type storageConfigResponse struct {+ Storages []storageConfigItem `json:"storages,omitempty"`+}++func (r *Router) handleStorageConfig(w http.ResponseWriter, req *http.Request) {+ if req.Method != http.MethodGet {+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only GET method is allowed", nil)+ return+ }++ monitor := r.getTenantMonitor(req.Context())+ if monitor == nil {+ writeErrorResponse(w, http.StatusServiceUnavailable, "not_initialized", "Monitoring service not initialized", nil)+ return+ }++ query := req.URL.Query()+ instance := strings.TrimSpace(query.Get("instance"))+ storageID := strings.TrimSpace(query.Get("storage_id"))+ node := strings.TrimSpace(query.Get("node"))++ configs, err := monitor.GetStorageConfig(req.Context(), instance)+ if err != nil {+ writeErrorResponse(w, http.StatusServiceUnavailable, "storage_config_unavailable", err.Error(), nil)+ return+ }++ response := storageConfigResponse{Storages: []storageConfigItem{}}+ seen := make(map[string]bool)++ for inst, storages := range configs {+ for _, storage := range storages {+ if storageID != "" && !strings.EqualFold(storage.Storage, storageID) {+ continue+ }++ nodes := parseStorageConfigNodes(storage)+ if node != "" && !storageConfigMatchesNode(nodes, node) {+ continue+ }++ key := inst + ":" + storage.Storage+ if seen[key] {+ continue+ }+ seen[key] = true++ response.Storages = append(response.Storages, storageConfigItem{+ ID: storage.Storage,+ Name: storage.Storage,+ Instance: inst,+ Type: storage.Type,+ Content: storage.Content,+ Nodes: nodes,+ Path: storage.Path,+ Shared: storage.Shared == 1,+ Enabled: storage.Enabled == 1,+ Active: storage.Active == 1,+ })+ }+ }++ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(response); err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "encoding_error", "Failed to encode response", nil)+ }+}++func parseStorageConfigNodes(storage proxmox.Storage) []string {+ nodes := strings.TrimSpace(storage.Nodes)+ if nodes == "" {+ return nil+ }++ parts := strings.Split(nodes, ",")+ result := make([]string, 0, len(parts))+ for _, part := range parts {+ node := strings.TrimSpace(part)+ if node == "" {+ continue+ }+ result = append(result, node)+ }+ if len(result) == 0 {+ return nil+ }+ return result+}++func storageConfigMatchesNode(nodes []string, filter string) bool {+ if filter == "" {+ return true+ }+ if len(nodes) == 0 {+ return true+ }+ for _, node := range nodes {+ if strings.EqualFold(node, filter) {+ return true+ }+ }+ return false+}