Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(ai): add extractors for all tool actions and fix predict/extract key mismatches

rcourtman50ecd62ae66a
diff --git a/internal/ai/chat/knowledge_extractor.go b/internal/ai/chat/knowledge_extractor.go
index a134ed82e0..b564d336df 100644
--- a/internal/ai/chat/knowledge_extractor.go
+++ b/internal/ai/chat/knowledge_extractor.go
@@ -35,8 +35,16 @@ func ExtractFacts(toolName string, toolInput map[string]interface{}, resultText
return extractMetricsFacts(toolInput, resultText)
case "pulse_alerts":
return extractAlertsFacts(toolInput, resultText)
+ case "pulse_docker":
+ return extractDockerFacts(toolInput, resultText)
+ case "pulse_kubernetes":
+ return extractKubernetesFacts(toolInput, resultText)
+ case "pulse_pmg":
+ return extractPMGFacts(toolInput, resultText)
case "patrol_report_finding":
return extractFindingFacts(toolInput, resultText)
+ case "patrol_get_findings":
+ return extractPatrolGetFindingsFacts(resultText)
default:
log.Debug().Str("tool", toolName).Msg("[KnowledgeExtractor] No extractor for tool")
return nil
@@ -119,10 +127,15 @@ func extractQueryGetFacts(input map[string]interface{}, resultText string) []Fac
if node == "" {
node = resource.Host
}
- id := resource.ID
- if id == "" && resource.VMID > 0 {
+ // Prefer VMID (numeric) over composite ID (which may contain node prefix like "delly:minipc:100")
+ id := ""
+ if resource.VMID > 0 {
id = fmt.Sprintf("%d", resource.VMID)
}
+ if id == "" {
+ // Fall back to resource_id from tool input (user-provided, e.g. "100")
+ id = strFromMap(input, "resource_id")
+ }
if id == "" {
id = resource.Name
}
@@ -147,11 +160,25 @@ func extractQueryGetFacts(input map[string]interface{}, resultText string) []Fac
return nil
}
- return []FactEntry{{
+ value := strings.Join(parts, ", ")
+
+ facts := []FactEntry{{
Category: FactCategoryResource,
Key: key,
- Value: strings.Join(parts, ", "),
+ Value: value,
}}
+
+ // Secondary fact with predictable key for gate matching
+ resourceID := strFromMap(input, "resource_id")
+ if resourceID != "" {
+ facts = append(facts, FactEntry{
+ Category: FactCategoryResource,
+ Key: fmt.Sprintf("query:get:%s:cached", resourceID),
+ Value: truncateValue(value),
+ })
+ }
+
+ return facts
}
func extractQuerySearchFacts(input map[string]interface{}, resultText string) []FactEntry {
@@ -468,11 +495,25 @@ func extractQueryConfigFacts(input map[string]interface{}, resultText string) []
return nil
}
- return []FactEntry{{
+ facts := []FactEntry{{
Category: FactCategoryResource,
Key: fmt.Sprintf("config:%s:%s", resp.Node, id),
Value: truncateValue(strings.Join(parts, ", ")),
}}
+
+ // Secondary fact with predictable key for gate matching.
+ // The model often omits "node" from the tool input, so config:{node}:{id}
+ // can't be predicted. This key uses just the resource_id.
+ resourceID := strFromMap(input, "resource_id")
+ if resourceID != "" {
+ facts = append(facts, FactEntry{
+ Category: FactCategoryResource,
+ Key: fmt.Sprintf("config:%s:cached", resourceID),
+ Value: truncateValue(strings.Join(parts, ", ")),
+ })
+ }
+
+ return facts
}
// categoryForPredictedKey infers the FactCategory from a predicted key prefix.
@@ -481,7 +522,11 @@ func categoryForPredictedKey(key string) FactCategory {
switch {
case strings.HasPrefix(key, "storage:") || strings.HasPrefix(key, "disk_health:") ||
strings.HasPrefix(key, "raid:") || strings.HasPrefix(key, "backups:") ||
- strings.HasPrefix(key, "physical_disks:"):
+ strings.HasPrefix(key, "physical_disks:") || strings.HasPrefix(key, "ceph:") ||
+ strings.HasPrefix(key, "ceph_details:") || strings.HasPrefix(key, "snapshots:") ||
+ strings.HasPrefix(key, "replication:") || strings.HasPrefix(key, "pbs_jobs:") ||
+ strings.HasPrefix(key, "resource_disks:") || strings.HasPrefix(key, "backup_tasks:") ||
+ strings.HasPrefix(key, "backup:"):
return FactCategoryStorage
case strings.HasPrefix(key, "metrics:") || strings.HasPrefix(key, "baseline:") ||
strings.HasPrefix(key, "baselines:") || strings.HasPrefix(key, "temperatures:"):
@@ -492,9 +537,12 @@ func categoryForPredictedKey(key string) FactCategory {
return FactCategoryDiscovery
case strings.HasPrefix(key, "topology:") || strings.HasPrefix(key, "health:") ||
strings.HasPrefix(key, "search:") || strings.HasPrefix(key, "query:") ||
- strings.HasPrefix(key, "inventory:") || strings.HasPrefix(key, "config:"):
+ strings.HasPrefix(key, "inventory:") || strings.HasPrefix(key, "config:") ||
+ strings.HasPrefix(key, "docker_") || strings.HasPrefix(key, "k8s_") ||
+ strings.HasPrefix(key, "pmg:") || strings.HasPrefix(key, "pmg_"):
return FactCategoryResource
- case strings.HasPrefix(key, "finding:") || strings.HasPrefix(key, "findings:"):
+ case strings.HasPrefix(key, "finding:") || strings.HasPrefix(key, "findings:") ||
+ strings.HasPrefix(key, "patrol_findings:"):
return FactCategoryFinding
case strings.HasPrefix(key, "alert:") || strings.HasPrefix(key, "alerts:"):
return FactCategoryAlert
@@ -522,6 +570,18 @@ func extractStorageFacts(input map[string]interface{}, resultText string) []Fact
return extractStorageRAIDFacts(resultText)
case "backups":
return extractStorageBackupsFacts(resultText)
+ case "ceph":
+ return extractCephFacts(resultText)
+ case "ceph_details":
+ return extractCephDetailsFacts(resultText)
+ case "snapshots":
+ return extractSnapshotsFacts(resultText)
+ case "replication":
+ return extractReplicationFacts(resultText)
+ case "pbs_jobs":
+ return extractPBSJobsFacts(resultText)
+ case "resource_disks":
+ return extractResourceDisksFacts(resultText)
default:
log.Debug().Str("tool", "pulse_storage").Str("action", action).
Msg("[KnowledgeExtractor] No extractor for action")
@@ -589,23 +649,46 @@ func extractStoragePoolFacts(resultText string) []FactEntry {
func extractBackupTaskFacts(resultText string) []FactEntry {
// BackupTasksListResponse — direct JSON, no wrapper
+ // Note: vmid is an int in the API response (can be 0 for cluster-level tasks)
var resp struct {
Tasks []struct {
- VMID string `json:"vmid"`
+ VMID int `json:"vmid"`
Node string `json:"node"`
Status string `json:"status"`
StartTime string `json:"start_time"`
Error string `json:"error"`
} `json:"tasks"`
+ Total int `json:"total"`
}
if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
return nil
}
- var facts []FactEntry
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Tasks)
+ }
+
+ // Count failures — status is case-insensitive
+ failed := 0
for _, task := range resp.Tasks {
- // Only record failures
- if task.Status == "ok" || task.Status == "success" || task.Status == "" {
+ s := strings.ToUpper(task.Status)
+ if s != "OK" && s != "SUCCESS" && s != "" {
+ failed++
+ }
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "backup_tasks:queried",
+ Value: fmt.Sprintf("%d tasks, %d failed", total, failed),
+ }
+
+ facts := []FactEntry{markerFact}
+ for _, task := range resp.Tasks {
+ // Only record failures as individual facts
+ s := strings.ToUpper(task.Status)
+ if s == "OK" || s == "SUCCESS" || s == "" {
continue
}
var parts []string
@@ -616,9 +699,10 @@ func extractBackupTaskFacts(resultText string) []FactEntry {
if task.Error != "" {
parts = append(parts, "error="+task.Error)
}
+ vmidStr := fmt.Sprintf("%d", task.VMID)
facts = append(facts, FactEntry{
Category: FactCategoryStorage,
- Key: fmt.Sprintf("backup:%s:%s", task.VMID, task.Node),
+ Key: fmt.Sprintf("backup:%s:%s", vmidStr, task.Node),
Value: truncateValue(strings.Join(parts, ", ")),
})
}
@@ -1100,35 +1184,29 @@ func extractAlertsFacts(input map[string]interface{}, resultText string) []FactE
}
func extractAlertsFindingsFacts(resultText string) []FactEntry {
+ // Response format: {"active": [...], "counts": {"active": N, "dismissed": N}}
var resp struct {
- Findings []struct {
+ Active []struct {
Key string `json:"key"`
Severity string `json:"severity"`
Title string `json:"title"`
- Status string `json:"status"`
ResourceID string `json:"resource_id"`
- } `json:"findings"`
+ } `json:"active"`
+ Counts struct {
+ Active int `json:"active"`
+ Dismissed int `json:"dismissed"`
+ } `json:"counts"`
}
if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
return nil
}
- if len(resp.Findings) == 0 {
+ active := resp.Counts.Active
+ dismissed := resp.Counts.Dismissed
+ if active == 0 && dismissed == 0 && len(resp.Active) == 0 {
return nil
}
- // Count by status
- active := 0
- dismissed := 0
- for _, f := range resp.Findings {
- switch strings.ToLower(f.Status) {
- case "dismissed", "resolved":
- dismissed++
- default:
- active++
- }
- }
-
var facts []FactEntry
facts = append(facts, FactEntry{
Category: FactCategoryFinding,
@@ -1138,10 +1216,10 @@ func extractAlertsFindingsFacts(resultText string) []FactEntry {
// Per-finding facts (cap at 5)
limit := 5
- if len(resp.Findings) < limit {
- limit = len(resp.Findings)
+ if len(resp.Active) < limit {
+ limit = len(resp.Active)
}
- for _, f := range resp.Findings[:limit] {
+ for _, f := range resp.Active[:limit] {
if f.Key == "" {
continue
}
@@ -1156,9 +1234,15 @@ func extractAlertsFindingsFacts(resultText string) []FactEntry {
parts = append(parts, "(resource="+f.ResourceID+")")
}
if len(parts) > 0 {
+ // Include resource_id in key to avoid upsert collisions when multiple
+ // findings share the same key (e.g. two "backup-failed" for different resources)
+ factKey := fmt.Sprintf("finding:%s", f.Key)
+ if f.ResourceID != "" {
+ factKey = fmt.Sprintf("finding:%s:%s", f.Key, f.ResourceID)
+ }
facts = append(facts, FactEntry{
Category: FactCategoryFinding,
- Key: fmt.Sprintf("finding:%s", f.Key),
+ Key: factKey,
Value: truncateValue(strings.Join(parts, ": ")),
})
}
@@ -1261,203 +1345,906 @@ func extractFindingFacts(input map[string]interface{}, resultText string) []Fact
}}
}
-// PredictFactKeys returns the KA fact keys that this tool call would produce,
-// based solely on the tool input (without needing the result).
-// Used by the gate to check if we already have facts for this call.
-// Returns nil if the key can't be predicted from input alone.
-func PredictFactKeys(toolName string, toolInput map[string]interface{}) []string {
- switch toolName {
- case "pulse_query":
- action := strFromMap(toolInput, "action")
- if action == "" {
- action = strFromMap(toolInput, "type")
- }
- switch action {
- case "topology":
- return []string{"topology:summary"}
- case "health":
- return []string{"health:connections"}
- case "get":
- // Can't predict: success key depends on response (type:node:id:status)
- // Negative facts (not-found) are stored by the extractor directly.
- return nil
- case "search":
- query := strFromMap(toolInput, "query")
- if query == "" {
- query = strFromMap(toolInput, "search")
- }
- if query != "" {
- return []string{fmt.Sprintf("search:%s:summary", query)}
- }
- case "list":
- return []string{"inventory:summary"}
- case "config":
- resourceID := strFromMap(toolInput, "resource_id")
- node := strFromMap(toolInput, "node")
- if resourceID != "" && node != "" {
- return []string{fmt.Sprintf("config:%s:%s", node, resourceID)}
- }
- }
- case "pulse_discovery":
- host := strFromMap(toolInput, "host_id")
- if host == "" {
- host = strFromMap(toolInput, "host")
- }
- id := strFromMap(toolInput, "resource_id")
- if host != "" && id != "" {
- return []string{fmt.Sprintf("discovery:%s:%s", host, id)}
- }
- case "pulse_read", "pulse_run_command":
- host := strFromMap(toolInput, "target_host")
- if host == "" {
- host = strFromMap(toolInput, "host")
- }
- cmdPrefix := buildExecKeyCmd(toolInput)
- if host != "" && cmdPrefix != "" {
- return []string{fmt.Sprintf("exec:%s:%s", host, cmdPrefix)}
- }
- case "pulse_storage":
- action := strFromMap(toolInput, "action")
- if action == "" {
- action = strFromMap(toolInput, "type")
- }
- switch action {
- case "pools":
- return []string{"storage:pools:queried"}
- case "disk_health":
- return []string{"disk_health:queried"}
- case "raid":
- return []string{"raid:queried"}
- case "backups":
- return []string{"backups:queried"}
- }
- case "pulse_metrics":
- action := strFromMap(toolInput, "action")
- if action == "" {
- action = strFromMap(toolInput, "type")
- }
- switch action {
- case "performance":
- resourceID := strFromMap(toolInput, "resource_id")
- if resourceID != "" {
- return []string{fmt.Sprintf("metrics:%s", resourceID)}
- }
- case "baselines":
- resourceID := strFromMap(toolInput, "resource_id")
- if resourceID != "" {
- return []string{fmt.Sprintf("baseline:%s", resourceID)}
- }
- return []string{"baselines:queried"}
- case "disks":
- return []string{"physical_disks:queried"}
- case "temperatures":
- return []string{"temperatures:queried"}
- }
- case "pulse_alerts":
- action := strFromMap(toolInput, "action")
- if action == "" {
- action = strFromMap(toolInput, "type")
- }
- switch action {
- case "findings":
- return []string{"findings:overview"}
- case "list":
- return []string{"alerts:overview"}
- }
+// --- pulse_docker ---
+
+func extractDockerFacts(input map[string]interface{}, resultText string) []FactEntry {
+ action := strFromMap(input, "action")
+ if action == "" {
+ action = strFromMap(input, "type")
}
- return nil
-}
-// --- pulse_metrics: temperatures ---
+ switch action {
+ case "services":
+ return extractDockerServicesFacts(resultText)
+ case "updates":
+ return extractDockerUpdatesFacts(resultText)
+ case "swarm":
+ return extractDockerSwarmFacts(resultText)
+ case "tasks":
+ return extractDockerTasksFacts(resultText)
+ default:
+ log.Debug().Str("tool", "pulse_docker").Str("action", action).
+ Msg("[KnowledgeExtractor] No extractor for action")
+ return nil
+ }
+}
-func extractMetricsTemperaturesFacts(resultText string) []FactEntry {
- var hosts []struct {
- Hostname string `json:"hostname"`
- CPUTemps map[string]float64 `json:"cpu_temps"`
- DiskTemps map[string]float64 `json:"disk_temps"`
+func extractDockerServicesFacts(resultText string) []FactEntry {
+ var resp struct {
+ Host string `json:"host"`
+ Services []struct {
+ Name string `json:"name"`
+ Mode string `json:"mode"`
+ DesiredTasks int `json:"desired_tasks"`
+ RunningTasks int `json:"running_tasks"`
+ UpdateStatus string `json:"update_status"`
+ } `json:"services"`
+ Total int `json:"total"`
}
- if err := json.Unmarshal([]byte(resultText), &hosts); err != nil {
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
return nil
}
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Services)
+ }
+
markerFact := FactEntry{
- Category: FactCategoryMetrics,
- Key: "temperatures:queried",
- Value: fmt.Sprintf("%d hosts", len(hosts)),
+ Category: FactCategoryResource,
+ Key: "docker_services:queried",
+ Value: fmt.Sprintf("%d services", total),
}
- if len(hosts) == 0 {
+
+ if total == 0 {
return []FactEntry{markerFact}
}
- facts := []FactEntry{markerFact}
- for _, h := range hosts {
- if h.Hostname == "" {
- continue
- }
- var maxCPU float64
- for _, t := range h.CPUTemps {
- if t > maxCPU {
- maxCPU = t
- }
- }
- var maxDisk float64
- for _, t := range h.DiskTemps {
- if t > maxDisk {
- maxDisk = t
- }
- }
- var parts []string
- if maxCPU > 0 {
- parts = append(parts, fmt.Sprintf("cpu_max=%.0f°C", maxCPU))
+ // Count healthy vs unhealthy
+ healthy := 0
+ for _, s := range resp.Services {
+ if s.RunningTasks >= s.DesiredTasks {
+ healthy++
}
- if maxDisk > 0 {
- parts = append(parts, fmt.Sprintf("disk_max=%.0f°C", maxDisk))
- }
- if len(parts) == 0 {
- continue
- }
- facts = append(facts, FactEntry{
- Category: FactCategoryMetrics,
- Key: fmt.Sprintf("temperatures:%s", h.Hostname),
- Value: truncateValue(strings.Join(parts, ", ")),
- })
}
- return facts
-}
-// --- pulse_storage: raid ---
+ summaryValue := fmt.Sprintf("%d services, %d healthy, %d degraded", total, healthy, total-healthy)
-func extractStorageRAIDFacts(resultText string) []FactEntry {
+ return []FactEntry{markerFact, {
+ Category: FactCategoryResource,
+ Key: "docker_services:summary",
+ Value: truncateValue(summaryValue),
+ }}
+}
+
+func extractDockerUpdatesFacts(resultText string) []FactEntry {
var resp struct {
- Hosts []struct {
- Hostname string `json:"hostname"`
- Arrays []struct {
- Device string `json:"device"`
- Level string `json:"level"`
- State string `json:"state"`
- FailedDevices int `json:"failed_devices"`
- TotalDevices int `json:"total_devices"`
- } `json:"arrays"`
- } `json:"hosts"`
+ Updates []struct {
+ ContainerName string `json:"container_name"`
+ UpdateAvailable bool `json:"update_available"`
+ Error string `json:"error"`
+ } `json:"updates"`
+ Total int `json:"total"`
}
if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
return nil
}
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Updates)
+ }
+
+ available := 0
+ for _, u := range resp.Updates {
+ if u.UpdateAvailable {
+ available++
+ }
+ }
+
markerFact := FactEntry{
- Category: FactCategoryStorage,
- Key: "raid:queried",
- Value: fmt.Sprintf("%d hosts", len(resp.Hosts)),
+ Category: FactCategoryResource,
+ Key: "docker_updates:queried",
+ Value: fmt.Sprintf("%d containers, %d updates available", total, available),
}
- if len(resp.Hosts) == 0 {
- return []FactEntry{markerFact}
+
+ return []FactEntry{markerFact}
+}
+
+func extractDockerSwarmFacts(resultText string) []FactEntry {
+ var resp struct {
+ Host string `json:"host"`
+ Status struct {
+ NodeRole string `json:"node_role"`
+ LocalState string `json:"local_state"`
+ ControlAvailable bool `json:"control_available"`
+ ClusterName string `json:"cluster_name"`
+ Error string `json:"error"`
+ } `json:"status"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
}
- facts := []FactEntry{markerFact}
- for _, h := range resp.Hosts {
- if h.Hostname == "" {
- continue
- }
+ host := resp.Host
+ s := resp.Status
+
+ var parts []string
+ if s.NodeRole != "" {
+ parts = append(parts, "role="+s.NodeRole)
+ }
+ if s.LocalState != "" {
+ parts = append(parts, "state="+s.LocalState)
+ }
+ if s.ControlAvailable {
+ parts = append(parts, "manager")
+ }
+ if s.Error != "" {
+ parts = append(parts, "error="+s.Error)
+ }
+
+ if len(parts) == 0 {
+ return nil
+ }
+
+ if host != "" {
+ parts = append(parts, "host="+host)
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "docker_swarm:status",
+ Value: truncateValue(strings.Join(parts, ", ")),
+ }}
+}
+
+func extractDockerTasksFacts(resultText string) []FactEntry {
+ var resp struct {
+ Host string `json:"host"`
+ Service string `json:"service"`
+ Tasks []struct {
+ CurrentState string `json:"current_state"`
+ Error string `json:"error"`
+ } `json:"tasks"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Tasks)
+ }
+
+ running := 0
+ failed := 0
+ for _, t := range resp.Tasks {
+ switch strings.ToLower(t.CurrentState) {
+ case "running":
+ running++
+ case "failed", "rejected":
+ failed++
+ }
+ }
+
+ value := fmt.Sprintf("%d tasks, %d running, %d failed", total, running, failed)
+ if resp.Service != "" {
+ value = fmt.Sprintf("service=%s, %s", resp.Service, value)
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "docker_tasks:queried",
+ Value: truncateValue(value),
+ }}
+}
+
+// --- pulse_kubernetes ---
+
+func extractKubernetesFacts(input map[string]interface{}, resultText string) []FactEntry {
+ action := strFromMap(input, "action")
+ if action == "" {
+ action = strFromMap(input, "type")
+ }
+
+ switch action {
+ case "clusters":
+ return extractK8sClustersFacts(resultText)
+ case "nodes":
+ return extractK8sNodesFacts(resultText)
+ case "pods":
+ return extractK8sPodsFacts(resultText)
+ case "deployments":
+ return extractK8sDeploymentsFacts(resultText)
+ default:
+ log.Debug().Str("tool", "pulse_kubernetes").Str("action", action).
+ Msg("[KnowledgeExtractor] No extractor for action")
+ return nil
+ }
+}
+
+func extractK8sClustersFacts(resultText string) []FactEntry {
+ var resp struct {
+ Clusters []struct {
+ Name string `json:"name"`
+ DisplayName string `json:"display_name"`
+ Status string `json:"status"`
+ NodeCount int `json:"node_count"`
+ PodCount int `json:"pod_count"`
+ ReadyNodes int `json:"ready_nodes"`
+ } `json:"clusters"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Clusters)
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryResource,
+ Key: "k8s_clusters:queried",
+ Value: fmt.Sprintf("%d clusters", total),
+ }
+
+ if total == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ limit := 5
+ if len(resp.Clusters) < limit {
+ limit = len(resp.Clusters)
+ }
+ for _, c := range resp.Clusters[:limit] {
+ name := c.DisplayName
+ if name == "" {
+ name = c.Name
+ }
+ if name == "" {
+ continue
+ }
+ value := fmt.Sprintf("%s, %d nodes (%d ready), %d pods",
+ c.Status, c.NodeCount, c.ReadyNodes, c.PodCount)
+ facts = append(facts, FactEntry{
+ Category: FactCategoryResource,
+ Key: fmt.Sprintf("k8s_cluster:%s", name),
+ Value: truncateValue(value),
+ })
+ }
+ return facts
+}
+
+func extractK8sNodesFacts(resultText string) []FactEntry {
+ var resp struct {
+ Cluster string `json:"cluster"`
+ Nodes []struct {
+ Name string `json:"name"`
+ Ready bool `json:"ready"`
+ Roles []string `json:"roles"`
+ } `json:"nodes"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Nodes)
+ }
+
+ ready := 0
+ for _, n := range resp.Nodes {
+ if n.Ready {
+ ready++
+ }
+ }
+
+ value := fmt.Sprintf("%d nodes, %d ready, %d not ready", total, ready, total-ready)
+ if resp.Cluster != "" {
+ value = fmt.Sprintf("cluster=%s, %s", resp.Cluster, value)
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "k8s_nodes:queried",
+ Value: truncateValue(value),
+ }}
+}
+
+func extractK8sPodsFacts(resultText string) []FactEntry {
+ var resp struct {
+ Cluster string `json:"cluster"`
+ Pods []struct {
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Phase string `json:"phase"`
+ Restarts int `json:"restarts"`
+ } `json:"pods"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Pods)
+ }
+
+ // Count by phase
+ phaseCounts := make(map[string]int)
+ crashLoop := 0
+ for _, p := range resp.Pods {
+ phase := p.Phase
+ if phase == "" {
+ phase = "Unknown"
+ }
+ phaseCounts[phase]++
+ if p.Restarts > 5 {
+ crashLoop++
+ }
+ }
+
+ var parts []string
+ if resp.Cluster != "" {
+ parts = append(parts, "cluster="+resp.Cluster)
+ }
+ parts = append(parts, fmt.Sprintf("%d pods", total))
+ for phase, count := range phaseCounts {
+ parts = append(parts, fmt.Sprintf("%d %s", count, phase))
+ }
+ if crashLoop > 0 {
+ parts = append(parts, fmt.Sprintf("%d high-restart", crashLoop))
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "k8s_pods:queried",
+ Value: truncateValue(strings.Join(parts, ", ")),
+ }}
+}
+
+func extractK8sDeploymentsFacts(resultText string) []FactEntry {
+ var resp struct {
+ Cluster string `json:"cluster"`
+ Deployments []struct {
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ DesiredReplicas int32 `json:"desired_replicas"`
+ ReadyReplicas int32 `json:"ready_replicas"`
+ AvailableReplicas int32 `json:"available_replicas"`
+ } `json:"deployments"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Deployments)
+ }
+
+ healthy := 0
+ degraded := 0
+ for _, d := range resp.Deployments {
+ if d.ReadyReplicas >= d.DesiredReplicas {
+ healthy++
+ } else {
+ degraded++
+ }
+ }
+
+ value := fmt.Sprintf("%d deployments, %d healthy, %d degraded", total, healthy, degraded)
+ if resp.Cluster != "" {
+ value = fmt.Sprintf("cluster=%s, %s", resp.Cluster, value)
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "k8s_deployments:queried",
+ Value: truncateValue(value),
+ }}
+}
+
+// --- pulse_pmg ---
+
+func extractPMGFacts(input map[string]interface{}, resultText string) []FactEntry {
+ action := strFromMap(input, "action")
+ if action == "" {
+ action = strFromMap(input, "type")
+ }
+
+ switch action {
+ case "status":
+ return extractPMGStatusFacts(resultText)
+ case "mail_stats":
+ return extractPMGMailStatsFacts(resultText)
+ case "queues":
+ return extractPMGQueuesFacts(resultText)
+ case "spam":
+ return extractPMGSpamFacts(resultText)
+ default:
+ log.Debug().Str("tool", "pulse_pmg").Str("action", action).
+ Msg("[KnowledgeExtractor] No extractor for action")
+ return nil
+ }
+}
+
+func extractPMGStatusFacts(resultText string) []FactEntry {
+ var resp struct {
+ Instances []struct {
+ Name string `json:"name"`
+ Host string `json:"host"`
+ Status string `json:"status"`
+ Version string `json:"version"`
+ } `json:"instances"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Instances)
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryResource,
+ Key: "pmg:queried",
+ Value: fmt.Sprintf("%d instances", total),
+ }
+
+ if total == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ for _, inst := range resp.Instances {
+ name := inst.Name
+ if name == "" {
+ name = inst.Host
+ }
+ if name == "" {
+ continue
+ }
+ var parts []string
+ if inst.Status != "" {
+ parts = append(parts, inst.Status)
+ }
+ if inst.Version != "" {
+ parts = append(parts, "v"+inst.Version)
+ }
+ if len(parts) == 0 {
+ continue
+ }
+ facts = append(facts, FactEntry{
+ Category: FactCategoryResource,
+ Key: fmt.Sprintf("pmg:%s", name),
+ Value: truncateValue(strings.Join(parts, ", ")),
+ })
+ }
+ return facts
+}
+
+func extractPMGMailStatsFacts(resultText string) []FactEntry {
+ var resp struct {
+ Instance string `json:"instance"`
+ Stats struct {
+ TotalIn float64 `json:"total_in"`
+ TotalOut float64 `json:"total_out"`
+ SpamIn float64 `json:"spam_in"`
+ VirusIn float64 `json:"virus_in"`
+ } `json:"stats"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ s := resp.Stats
+ value := fmt.Sprintf("in=%.0f out=%.0f spam=%.0f virus=%.0f",
+ s.TotalIn, s.TotalOut, s.SpamIn, s.VirusIn)
+ if resp.Instance != "" {
+ value = resp.Instance + ": " + value
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "pmg_mail_stats:queried",
+ Value: truncateValue(value),
+ }}
+}
+
+func extractPMGQueuesFacts(resultText string) []FactEntry {
+ var resp struct {
+ Instance string `json:"instance"`
+ Queues []struct {
+ Node string `json:"node"`
+ Active int `json:"active"`
+ Deferred int `json:"deferred"`
+ Total int `json:"total"`
+ } `json:"queues"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ totalQueued := 0
+ totalDeferred := 0
+ for _, q := range resp.Queues {
+ totalQueued += q.Total
+ totalDeferred += q.Deferred
+ }
+
+ value := fmt.Sprintf("%d nodes, %d queued, %d deferred",
+ len(resp.Queues), totalQueued, totalDeferred)
+ if resp.Instance != "" {
+ value = resp.Instance + ": " + value
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "pmg_queues:queried",
+ Value: truncateValue(value),
+ }}
+}
+
+func extractPMGSpamFacts(resultText string) []FactEntry {
+ var resp struct {
+ Instance string `json:"instance"`
+ Quarantine struct {
+ Spam int `json:"spam"`
+ Virus int `json:"virus"`
+ Total int `json:"total"`
+ } `json:"quarantine"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ q := resp.Quarantine
+ value := fmt.Sprintf("quarantine: %d total (%d spam, %d virus)", q.Total, q.Spam, q.Virus)
+ if resp.Instance != "" {
+ value = resp.Instance + ": " + value
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "pmg_spam:queried",
+ Value: truncateValue(value),
+ }}
+}
+
+// --- patrol_get_findings ---
+
+func extractPatrolGetFindingsFacts(resultText string) []FactEntry {
+ var resp struct {
+ OK bool `json:"ok"`
+ Count int `json:"count"`
+ Findings []struct {
+ Key string `json:"key"`
+ Severity string `json:"severity"`
+ Title string `json:"title"`
+ ResourceID string `json:"resource_id"`
+ } `json:"findings"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Count
+ if total == 0 {
+ total = len(resp.Findings)
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryFinding,
+ Key: "patrol_findings:queried",
+ Value: fmt.Sprintf("%d findings", total),
+ }
+
+ if total == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ // Count by severity
+ severityCounts := make(map[string]int)
+ for _, f := range resp.Findings {
+ sev := f.Severity
+ if sev == "" {
+ sev = "unknown"
+ }
+ severityCounts[sev]++
+ }
+
+ var parts []string
+ parts = append(parts, fmt.Sprintf("%d total", total))
+ for sev, count := range severityCounts {
+ parts = append(parts, fmt.Sprintf("%d %s", count, sev))
+ }
+
+ facts := []FactEntry{markerFact, {
+ Category: FactCategoryFinding,
+ Key: "patrol_findings:summary",
+ Value: truncateValue(strings.Join(parts, ", ")),
+ }}
+
+ return facts
+}
+
+// PredictFactKeys returns the KA fact keys that this tool call would produce,
+// based solely on the tool input (without needing the result).
+// Used by the gate to check if we already have facts for this call.
+// Returns nil if the key can't be predicted from input alone.
+func PredictFactKeys(toolName string, toolInput map[string]interface{}) []string {
+ switch toolName {
+ case "pulse_query":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "topology":
+ return []string{"topology:summary"}
+ case "health":
+ return []string{"health:connections"}
+ case "get":
+ resourceID := strFromMap(toolInput, "resource_id")
+ if resourceID != "" {
+ return []string{
+ fmt.Sprintf("query:get:%s:cached", resourceID),
+ fmt.Sprintf("query:get:%s:error", resourceID),
+ }
+ }
+ return nil
+ case "search":
+ query := strFromMap(toolInput, "query")
+ if query == "" {
+ query = strFromMap(toolInput, "search")
+ }
+ if query != "" {
+ return []string{fmt.Sprintf("search:%s:summary", query)}
+ }
+ case "list":
+ return []string{"inventory:summary"}
+ case "config":
+ resourceID := strFromMap(toolInput, "resource_id")
+ if resourceID != "" {
+ // Predict the cached key (always available) + node-specific key if node is provided
+ keys := []string{fmt.Sprintf("config:%s:cached", resourceID)}
+ node := strFromMap(toolInput, "node")
+ if node != "" {
+ keys = append(keys, fmt.Sprintf("config:%s:%s", node, resourceID))
+ }
+ return keys
+ }
+ }
+ case "pulse_discovery":
+ host := strFromMap(toolInput, "host_id")
+ if host == "" {
+ host = strFromMap(toolInput, "host")
+ }
+ id := strFromMap(toolInput, "resource_id")
+ if host != "" && id != "" {
+ return []string{fmt.Sprintf("discovery:%s:%s", host, id)}
+ }
+ case "pulse_read", "pulse_run_command":
+ host := strFromMap(toolInput, "target_host")
+ if host == "" {
+ host = strFromMap(toolInput, "host")
+ }
+ cmdPrefix := buildExecKeyCmd(toolInput)
+ if host != "" && cmdPrefix != "" {
+ return []string{fmt.Sprintf("exec:%s:%s", host, cmdPrefix)}
+ }
+ case "pulse_storage":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "pools":
+ return []string{"storage:pools:queried"}
+ case "disk_health":
+ return []string{"disk_health:queried"}
+ case "raid":
+ return []string{"raid:queried"}
+ case "backups":
+ return []string{"backups:queried"}
+ case "ceph":
+ return []string{"ceph:queried"}
+ case "ceph_details":
+ return []string{"ceph_details:queried"}
+ case "snapshots":
+ return []string{"snapshots:queried"}
+ case "replication":
+ return []string{"replication:queried"}
+ case "pbs_jobs":
+ return []string{"pbs_jobs:queried"}
+ case "resource_disks":
+ return []string{"resource_disks:queried"}
+ case "backup_tasks":
+ return []string{"backup_tasks:queried"}
+ }
+ case "pulse_metrics":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "performance":
+ resourceID := strFromMap(toolInput, "resource_id")
+ if resourceID != "" {
+ return []string{fmt.Sprintf("metrics:%s", resourceID)}
+ }
+ case "baselines":
+ // Always predict the marker key — the extractor emits baselines:queried
+ // regardless of whether resource_id is provided.
+ return []string{"baselines:queried"}
+ case "disks":
+ return []string{"physical_disks:queried"}
+ case "temperatures":
+ return []string{"temperatures:queried"}
+ }
+ case "pulse_alerts":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "findings":
+ return []string{"findings:overview"}
+ case "list":
+ return []string{"alerts:overview"}
+ }
+ case "pulse_docker":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "services":
+ return []string{"docker_services:queried", "docker_services:summary"}
+ case "updates":
+ return []string{"docker_updates:queried"}
+ case "swarm":
+ return []string{"docker_swarm:status"}
+ case "tasks":
+ return []string{"docker_tasks:queried"}
+ }
+ case "pulse_kubernetes":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "clusters":
+ return []string{"k8s_clusters:queried"}
+ case "nodes":
+ return []string{"k8s_nodes:queried"}
+ case "pods":
+ return []string{"k8s_pods:queried"}
+ case "deployments":
+ return []string{"k8s_deployments:queried"}
+ }
+ case "pulse_pmg":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "status":
+ return []string{"pmg:queried"}
+ case "mail_stats":
+ return []string{"pmg_mail_stats:queried"}
+ case "queues":
+ return []string{"pmg_queues:queried"}
+ case "spam":
+ return []string{"pmg_spam:queried"}
+ }
+ case "patrol_get_findings":
+ return []string{"patrol_findings:queried"}
+ }
+ return nil
+}
+
+// --- pulse_metrics: temperatures ---
+
+func extractMetricsTemperaturesFacts(resultText string) []FactEntry {
+ var hosts []struct {
+ Hostname string `json:"hostname"`
+ CPUTemps map[string]float64 `json:"cpu_temps"`
+ DiskTemps map[string]float64 `json:"disk_temps"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &hosts); err != nil {
+ return nil
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryMetrics,
+ Key: "temperatures:queried",
+ Value: fmt.Sprintf("%d hosts", len(hosts)),
+ }
+ if len(hosts) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ for _, h := range hosts {
+ if h.Hostname == "" {
+ continue
+ }
+ var maxCPU float64
+ for _, t := range h.CPUTemps {
+ if t > maxCPU {
+ maxCPU = t
+ }
+ }
+ var maxDisk float64
+ for _, t := range h.DiskTemps {
+ if t > maxDisk {
+ maxDisk = t
+ }
+ }
+ var parts []string
+ if maxCPU > 0 {
+ parts = append(parts, fmt.Sprintf("cpu_max=%.0f°C", maxCPU))
+ }
+ if maxDisk > 0 {
+ parts = append(parts, fmt.Sprintf("disk_max=%.0f°C", maxDisk))
+ }
+ if len(parts) == 0 {
+ continue
+ }
+ facts = append(facts, FactEntry{
+ Category: FactCategoryMetrics,
+ Key: fmt.Sprintf("temperatures:%s", h.Hostname),
+ Value: truncateValue(strings.Join(parts, ", ")),
+ })
+ }
+ return facts
+}
+
+// --- pulse_storage: raid ---
+
+func extractStorageRAIDFacts(resultText string) []FactEntry {
+ var resp struct {
+ Hosts []struct {
+ Hostname string `json:"hostname"`
+ Arrays []struct {
+ Device string `json:"device"`
+ Level string `json:"level"`
+ State string `json:"state"`
+ FailedDevices int `json:"failed_devices"`
+ TotalDevices int `json:"total_devices"`
+ } `json:"arrays"`
+ } `json:"hosts"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "raid:queried",
+ Value: fmt.Sprintf("%d hosts", len(resp.Hosts)),
+ }
+ if len(resp.Hosts) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ for _, h := range resp.Hosts {
+ if h.Hostname == "" {
+ continue
+ }
totalArrays := len(h.Arrays)
degraded := 0
for _, a := range h.Arrays {
@@ -1535,16 +2322,365 @@ func extractStorageBackupsFacts(resultText string) []FactEntry {
return facts
}
+// --- pulse_storage: ceph ---
+
+func extractCephFacts(resultText string) []FactEntry {
+ var clusters []struct {
+ Name string `json:"name"`
+ Health string `json:"health"`
+ Details struct {
+ OSDCount int `json:"osd_count"`
+ OSDsUp int `json:"osds_up"`
+ OSDsDown int `json:"osds_down"`
+ Monitors int `json:"monitors"`
+ UsagePercent float64 `json:"usage_percent"`
+ } `json:"details"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &clusters); err != nil {
+ return nil
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "ceph:queried",
+ Value: fmt.Sprintf("%d clusters", len(clusters)),
+ }
+
+ if len(clusters) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ limit := 5
+ if len(clusters) < limit {
+ limit = len(clusters)
+ }
+ for _, c := range clusters[:limit] {
+ if c.Name == "" {
+ continue
+ }
+ d := c.Details
+ value := fmt.Sprintf("%s, %d OSDs (%d up, %d down), %d monitors, %.0f%% used",
+ c.Health, d.OSDCount, d.OSDsUp, d.OSDsDown, d.Monitors, d.UsagePercent)
+ facts = append(facts, FactEntry{
+ Category: FactCategoryStorage,
+ Key: fmt.Sprintf("ceph:%s", c.Name),
+ Value: truncateValue(value),
+ })
+ }
+ return facts
+}
+
+// --- pulse_storage: ceph_details ---
+
+func extractCephDetailsFacts(resultText string) []FactEntry {
+ var resp struct {
+ Hosts []struct {
+ Hostname string `json:"hostname"`
+ Health struct {
+ Status string `json:"status"`
+ } `json:"health"`
+ OSDMap struct {
+ NumOSDs int `json:"num_osds"`
+ NumUp int `json:"num_up"`
+ NumDown int `json:"num_down"`
+ } `json:"osd_map"`
+ PGMap struct {
+ UsagePercent float64 `json:"usage_percent"`
+ } `json:"pg_map"`
+ Pools []json.RawMessage `json:"pools"`
+ } `json:"hosts"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "ceph_details:queried",
+ Value: fmt.Sprintf("%d hosts", len(resp.Hosts)),
+ }
+
+ if len(resp.Hosts) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ limit := 5
+ if len(resp.Hosts) < limit {
+ limit = len(resp.Hosts)
+ }
+ for _, h := range resp.Hosts[:limit] {
+ if h.Hostname == "" {
+ continue
+ }
+ value := fmt.Sprintf("%s, %d OSDs (%d up), %.0f%% used, %d pools",
+ h.Health.Status, h.OSDMap.NumOSDs, h.OSDMap.NumUp, h.PGMap.UsagePercent, len(h.Pools))
+ facts = append(facts, FactEntry{
+ Category: FactCategoryStorage,
+ Key: fmt.Sprintf("ceph_details:%s", h.Hostname),
+ Value: truncateValue(value),
+ })
+ }
+ return facts
+}
+
+// --- pulse_storage: snapshots ---
+
+func extractSnapshotsFacts(resultText string) []FactEntry {
+ var resp struct {
+ Snapshots []struct {
+ VMID int `json:"vmid"`
+ VMName string `json:"vm_name"`
+ Type string `json:"type"`
+ Node string `json:"node"`
+ SnapshotName string `json:"snapshot_name"`
+ } `json:"snapshots"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Snapshots)
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "snapshots:queried",
+ Value: fmt.Sprintf("%d snapshots", total),
+ }
+
+ if total == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ // Count by guest
+ guestCounts := make(map[string]int)
+ for _, s := range resp.Snapshots {
+ name := s.VMName
+ if name == "" {
+ name = fmt.Sprintf("%d", s.VMID)
+ }
+ guestCounts[name]++
+ }
+
+ var summaryParts []string
+ count := 0
+ for guest, cnt := range guestCounts {
+ if count >= 5 {
+ break
+ }
+ summaryParts = append(summaryParts, fmt.Sprintf("%s: %d", guest, cnt))
+ count++
+ }
+
+ summaryValue := fmt.Sprintf("%d total; %s", total, strings.Join(summaryParts, ", "))
+
+ return []FactEntry{markerFact, {
+ Category: FactCategoryStorage,
+ Key: "snapshots:summary",
+ Value: truncateValue(summaryValue),
+ }}
+}
+
+// --- pulse_storage: replication ---
+
+func extractReplicationFacts(resultText string) []FactEntry {
+ // Response is TEXT-wrapped JSON array
+ var jobs []struct {
+ ID string `json:"id"`
+ GuestID int `json:"guest_id"`
+ GuestName string `json:"guest_name"`
+ SourceNode string `json:"source_node"`
+ TargetNode string `json:"target_node"`
+ Status string `json:"status"`
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &jobs); err != nil {
+ return nil
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "replication:queried",
+ Value: fmt.Sprintf("%d jobs", len(jobs)),
+ }
+
+ if len(jobs) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ errorCount := 0
+ var errorNames []string
+ for _, j := range jobs {
+ if j.Error != "" {
+ errorCount++
+ name := j.GuestName
+ if name == "" {
+ name = fmt.Sprintf("%d", j.GuestID)
+ }
+ errorNames = append(errorNames, name)
+ }
+ }
+
+ var summaryValue string
+ if errorCount == 0 {
+ summaryValue = fmt.Sprintf("%d jobs, all ok", len(jobs))
+ } else {
+ summaryValue = fmt.Sprintf("%d jobs, %d with errors: %s", len(jobs), errorCount, strings.Join(errorNames, ", "))
+ }
+
+ return []FactEntry{markerFact, {
+ Category: FactCategoryStorage,
+ Key: "replication:summary",
+ Value: truncateValue(summaryValue),
+ }}
+}
+
+// --- pulse_storage: pbs_jobs ---
+
+func extractPBSJobsFacts(resultText string) []FactEntry {
+ var resp struct {
+ Instance string `json:"instance"`
+ Jobs []struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Store string `json:"store"`
+ Status string `json:"status"`
+ Error string `json:"error"`
+ } `json:"jobs"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Jobs)
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "pbs_jobs:queried",
+ Value: fmt.Sprintf("%d jobs", total),
+ }
+
+ if total == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ // Count by type and errors
+ typeCounts := make(map[string]int)
+ errorCount := 0
+ for _, j := range resp.Jobs {
+ jType := j.Type
+ if jType == "" {
+ jType = "unknown"
+ }
+ typeCounts[jType]++
+ if j.Error != "" {
+ errorCount++
+ }
+ }
+
+ var typeParts []string
+ for jType, cnt := range typeCounts {
+ typeParts = append(typeParts, fmt.Sprintf("%d %s", cnt, jType))
+ }
+
+ summaryValue := strings.Join(typeParts, ", ")
+ if errorCount > 0 {
+ summaryValue += fmt.Sprintf("; %d with errors", errorCount)
+ }
+
+ return []FactEntry{markerFact, {
+ Category: FactCategoryStorage,
+ Key: "pbs_jobs:summary",
+ Value: truncateValue(summaryValue),
+ }}
+}
+
+// --- pulse_storage: resource_disks ---
+
+func extractResourceDisksFacts(resultText string) []FactEntry {
+ var resp struct {
+ Resources []struct {
+ VMID int `json:"vmid"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Node string `json:"node"`
+ Disks []struct {
+ Mountpoint string `json:"mountpoint"`
+ Usage float64 `json:"usage_percent"`
+ } `json:"disks"`
+ } `json:"resources"`
+ Total int `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ total := resp.Total
+ if total == 0 {
+ total = len(resp.Resources)
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "resource_disks:queried",
+ Value: fmt.Sprintf("%d resources", total),
+ }
+
+ if total == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ totalDisks := 0
+ highUsage := 0
+ for _, r := range resp.Resources {
+ totalDisks += len(r.Disks)
+ for _, d := range r.Disks {
+ if d.Usage > 80 {
+ highUsage++
+ }
+ }
+ }
+
+ summaryValue := fmt.Sprintf("%d resources, %d disks total, %d disks over 80%% usage", total, totalDisks, highUsage)
+
+ return []FactEntry{markerFact, {
+ Category: FactCategoryStorage,
+ Key: "resource_disks:summary",
+ Value: truncateValue(summaryValue),
+ }}
+}
+
// MarkerExpansions maps marker fact keys to the prefix used to find related per-resource facts.
// Used by the gate to enrich marker-based cache hits with actual data.
var MarkerExpansions = map[string]string{
- "storage:pools:queried": "storage:",
- "disk_health:queried": "disk_health:",
- "baselines:queried": "baseline:",
- "physical_disks:queried": "physical_disks:",
- "temperatures:queried": "temperatures:",
- "raid:queried": "raid:",
- "backups:queried": "backups:",
+ "storage:pools:queried": "storage:",
+ "disk_health:queried": "disk_health:",
+ "baselines:queried": "baseline:",
+ "physical_disks:queried": "physical_disks:",
+ "temperatures:queried": "temperatures:",
+ "raid:queried": "raid:",
+ "backups:queried": "backups:",
+ "ceph:queried": "ceph:",
+ "ceph_details:queried": "ceph_details:",
+ "snapshots:queried": "snapshots:",
+ "replication:queried": "replication:",
+ "pbs_jobs:queried": "pbs_jobs:",
+ "resource_disks:queried": "resource_disks:",
+ "backup_tasks:queried": "backup:",
+ "docker_services:queried": "docker_services:",
+ "k8s_clusters:queried": "k8s_cluster:",
+ "pmg:queried": "pmg:",
+ "patrol_findings:queried": "patrol_findings:",
}
// --- helpers ---
diff --git a/internal/ai/chat/knowledge_extractor_test.go b/internal/ai/chat/knowledge_extractor_test.go
index bf849ad0b1..fae16ab1fe 100644
--- a/internal/ai/chat/knowledge_extractor_test.go
+++ b/internal/ai/chat/knowledge_extractor_test.go
@@ -20,21 +20,35 @@ func TestExtractFacts_InvalidJSON(t *testing.T) {
}
func TestExtractFacts_QueryGet(t *testing.T) {
- input := map[string]interface{}{"action": "get", "resource_type": "lxc"}
+ input := map[string]interface{}{"action": "get", "resource_type": "lxc", "resource_id": "106"}
// Actual format from NewJSONResult(ResourceResponse): direct JSON, no wrapper.
// CPU/Memory are nested structs.
result := `{"type":"lxc","name":"postfix-server","status":"running","node":"delly","id":"lxc/106","vmid":106,"cpu":{"percent":2.5,"cores":4},"memory":{"percent":45.0,"used_gb":1.2,"total_gb":4.0}}`
facts := ExtractFacts("pulse_query", input, result)
- require.Len(t, facts, 1)
+ require.Len(t, facts, 2) // primary + cached key
f := facts[0]
assert.Equal(t, FactCategoryResource, f.Category)
- assert.Equal(t, "lxc:delly:lxc/106:status", f.Key)
+ assert.Equal(t, "lxc:delly:106:status", f.Key)
assert.Contains(t, f.Value, "running")
assert.Contains(t, f.Value, "postfix-server")
assert.Contains(t, f.Value, "CPU=2.5%")
assert.Contains(t, f.Value, "Mem=45.0%")
+
+ // Secondary cached fact
+ assert.Equal(t, "query:get:106:cached", facts[1].Key)
+ assert.Equal(t, FactCategoryResource, facts[1].Category)
+}
+
+func TestExtractFacts_QueryGet_NoResourceID(t *testing.T) {
+ // Without resource_id in input, only primary fact should be emitted (no cached key)
+ input := map[string]interface{}{"action": "get", "resource_type": "lxc"}
+ result := `{"type":"lxc","name":"postfix-server","status":"running","node":"delly","id":"lxc/106","vmid":106,"cpu":{"percent":2.5,"cores":4},"memory":{"percent":45.0,"used_gb":1.2,"total_gb":4.0}}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1) // only primary fact
+ assert.Equal(t, "lxc:delly:106:status", facts[0].Key)
}
func TestExtractFacts_QueryGet_NotFound(t *testing.T) {
@@ -132,18 +146,39 @@ func TestExtractFacts_StoragePools(t *testing.T) {
func TestExtractFacts_BackupTasks_OnlyFailures(t *testing.T) {
input := map[string]interface{}{"action": "backup_tasks"}
- result := `{"tasks":[{"vmid":"106","node":"delly","status":"ok"},{"vmid":"200","node":"minipc","status":"failed","start_time":"2024-01-15T03:00","error":"snapshot failed"}]}`
+ result := `{"tasks":[{"vmid":106,"node":"delly","status":"OK"},{"vmid":200,"node":"minipc","status":"failed","start_time":"2024-01-15T03:00","error":"snapshot failed"}],"total":2}`
facts := ExtractFacts("pulse_storage", input, result)
- require.Len(t, facts, 1)
+ require.Len(t, facts, 2) // marker + 1 failure
- f := facts[0]
+ // Marker fact
+ assert.Equal(t, "backup_tasks:queried", facts[0].Key)
+ assert.Equal(t, "2 tasks, 1 failed", facts[0].Value)
+
+ // Failure fact
+ f := facts[1]
assert.Equal(t, FactCategoryStorage, f.Category)
assert.Equal(t, "backup:200:minipc", f.Key)
assert.Contains(t, f.Value, "failed")
assert.Contains(t, f.Value, "snapshot failed")
}
+func TestExtractFacts_BackupTasks_AllOK(t *testing.T) {
+ input := map[string]interface{}{"action": "backup_tasks"}
+ result := `{"tasks":[{"vmid":106,"node":"delly","status":"OK"},{"vmid":200,"node":"minipc","status":"success"}],"total":2}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only (no failures)
+ assert.Equal(t, "backup_tasks:queried", facts[0].Key)
+ assert.Equal(t, "2 tasks, 0 failed", facts[0].Value)
+}
+
+func TestPredictFactKeys_BackupTasks(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "backup_tasks"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "backup_tasks:queried", keys[0])
+}
+
func TestExtractFacts_Discovery(t *testing.T) {
input := map[string]interface{}{"host": "delly", "resource_id": "106"}
result := `{"service_type":"Postfix","hostname":"patrol-signal-test","host_id":"delly","resource_id":"106","ports":[{"port":25},{"port":22}]}`
@@ -272,7 +307,7 @@ func TestPredictFactKeys_Metrics(t *testing.T) {
}
func TestPredictFactKeys_UnpredictableTools(t *testing.T) {
- // pulse_query get/search keys depend on result data
+ // pulse_query get without resource_id / search without query are unpredictable
assert.Nil(t, PredictFactKeys("pulse_query", map[string]interface{}{"action": "get"}))
assert.Nil(t, PredictFactKeys("pulse_query", map[string]interface{}{"action": "search"}))
assert.Nil(t, PredictFactKeys("unknown_tool", nil))
@@ -404,7 +439,8 @@ func TestExtractFacts_QueryHealth_Disconnected(t *testing.T) {
func TestExtractFacts_AlertsFindings(t *testing.T) {
input := map[string]interface{}{"action": "findings"}
- result := `{"findings":[{"key":"high-cpu-vm101","severity":"warning","title":"High CPU on vm101","status":"active","resource_id":"vm101"},{"key":"disk-full-ct200","severity":"critical","title":"Disk full on ct200","status":"active","resource_id":"ct200"},{"key":"old-issue","severity":"info","title":"Old issue","status":"dismissed","resource_id":"ct300"}]}`
+ // Real response format: {"active": [...], "counts": {"active": N, "dismissed": N}}
+ result := `{"active":[{"key":"high-cpu-vm101","severity":"warning","title":"High CPU on vm101","resource_id":"vm101"},{"key":"disk-full-ct200","severity":"critical","title":"Disk full on ct200","resource_id":"ct200"}],"counts":{"active":2,"dismissed":1}}`
facts := ExtractFacts("pulse_alerts", input, result)
require.GreaterOrEqual(t, len(facts), 2) // overview + per-finding
@@ -420,8 +456,8 @@ func TestExtractFacts_AlertsFindings(t *testing.T) {
for _, f := range facts[1:] {
findingKeys = append(findingKeys, f.Key)
}
- assert.Contains(t, findingKeys, "finding:high-cpu-vm101")
- assert.Contains(t, findingKeys, "finding:disk-full-ct200")
+ assert.Contains(t, findingKeys, "finding:high-cpu-vm101:vm101")
+ assert.Contains(t, findingKeys, "finding:disk-full-ct200:ct200")
}
// --- Alerts: List ---
@@ -589,9 +625,10 @@ func TestPredictFactKeys_AlertsList(t *testing.T) {
}
func TestPredictFactKeys_MetricsBaselines(t *testing.T) {
+ // Even with resource_id, predict always returns the marker key
keys := PredictFactKeys("pulse_metrics", map[string]interface{}{"action": "baselines", "resource_id": "vm101"})
require.Len(t, keys, 1)
- assert.Equal(t, "baseline:vm101", keys[0])
+ assert.Equal(t, "baselines:queried", keys[0])
}
func TestPredictFactKeys_MetricsBaselinesGlobal(t *testing.T) {
@@ -827,7 +864,7 @@ func TestExtractFacts_QueryConfig_LXC(t *testing.T) {
result := `{"guest_type":"lxc","vmid":106,"name":"postfix-server","node":"delly","hostname":"postfix","os_type":"ubuntu","onboot":true,"mounts":[{"key":"mp0","mountpoint":"/data"},{"key":"mp1","mountpoint":"/logs"}],"disks":[{"key":"rootfs"}]}`
facts := ExtractFacts("pulse_query", input, result)
- require.Len(t, facts, 1)
+ require.Len(t, facts, 2) // primary + cached key
f := facts[0]
assert.Equal(t, FactCategoryResource, f.Category)
@@ -838,22 +875,26 @@ func TestExtractFacts_QueryConfig_LXC(t *testing.T) {
assert.Contains(t, f.Value, "onboot=yes")
assert.Contains(t, f.Value, "2 mounts")
assert.Contains(t, f.Value, "1 disks")
+
+ // Secondary cached key for gate matching without node
+ assert.Equal(t, "config:106:cached", facts[1].Key)
+ assert.Equal(t, f.Value, facts[1].Value)
}
func TestExtractFacts_QueryConfig_VM(t *testing.T) {
input := map[string]interface{}{"action": "config", "resource_id": "200"}
- onbootFalse := false
- _ = onbootFalse
result := `{"guest_type":"qemu","vmid":200,"name":"win10","node":"minipc","os_type":"win10","onboot":false,"disks":[{"key":"scsi0"},{"key":"scsi1"}]}`
facts := ExtractFacts("pulse_query", input, result)
- require.Len(t, facts, 1)
+ require.Len(t, facts, 2) // primary + cached key
f := facts[0]
assert.Equal(t, "config:minipc:200", f.Key)
assert.Contains(t, f.Value, "qemu")
assert.Contains(t, f.Value, "onboot=no")
assert.Contains(t, f.Value, "2 disks")
+
+ assert.Equal(t, "config:200:cached", facts[1].Key)
}
func TestExtractFacts_QueryConfig_Empty(t *testing.T) {
@@ -870,27 +911,45 @@ func TestPredictFactKeys_QueryConfig(t *testing.T) {
"resource_id": "106",
"node": "delly",
})
- require.Len(t, keys, 1)
- assert.Equal(t, "config:delly:106", keys[0])
+ require.Len(t, keys, 2)
+ assert.Equal(t, "config:106:cached", keys[0])
+ assert.Equal(t, "config:delly:106", keys[1])
}
func TestPredictFactKeys_QueryConfig_NoNode(t *testing.T) {
- // Without node, can't predict exact key
+ // Without node, still predicts the cached key
keys := PredictFactKeys("pulse_query", map[string]interface{}{
"action": "config",
"resource_id": "106",
})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "config:106:cached", keys[0])
+}
+
+func TestPredictFactKeys_QueryConfig_NoResourceID(t *testing.T) {
+ // Without resource_id, can't predict anything
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{
+ "action": "config",
+ })
assert.Nil(t, keys)
}
// --- Change 4: PredictFactKeys for query:get ---
-func TestPredictFactKeys_QueryGet_ReturnsNil(t *testing.T) {
- // get success key depends on response data (type:node:id:status), can't predict
+func TestPredictFactKeys_QueryGet_WithResourceID(t *testing.T) {
keys := PredictFactKeys("pulse_query", map[string]interface{}{
"action": "get",
"resource_id": "106",
})
+ require.Len(t, keys, 2)
+ assert.Equal(t, "query:get:106:cached", keys[0])
+ assert.Equal(t, "query:get:106:error", keys[1])
+}
+
+func TestPredictFactKeys_QueryGet_NoResourceID(t *testing.T) {
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{
+ "action": "get",
+ })
assert.Nil(t, keys)
}
@@ -1016,6 +1075,37 @@ func TestCategoryForPredictedKey(t *testing.T) {
{"findings:overview", FactCategoryFinding},
{"alert:vm101:cpu", FactCategoryAlert},
{"alerts:overview", FactCategoryAlert},
+ {"ceph:queried", FactCategoryStorage},
+ {"ceph:mycluster", FactCategoryStorage},
+ {"ceph_details:queried", FactCategoryStorage},
+ {"ceph_details:host1", FactCategoryStorage},
+ {"snapshots:queried", FactCategoryStorage},
+ {"snapshots:summary", FactCategoryStorage},
+ {"replication:queried", FactCategoryStorage},
+ {"replication:summary", FactCategoryStorage},
+ {"pbs_jobs:queried", FactCategoryStorage},
+ {"pbs_jobs:summary", FactCategoryStorage},
+ {"resource_disks:queried", FactCategoryStorage},
+ {"resource_disks:summary", FactCategoryStorage},
+ {"backup_tasks:queried", FactCategoryStorage},
+ {"backup:200:minipc", FactCategoryStorage},
+ {"docker_services:queried", FactCategoryResource},
+ {"docker_services:summary", FactCategoryResource},
+ {"docker_updates:queried", FactCategoryResource},
+ {"docker_swarm:status", FactCategoryResource},
+ {"docker_tasks:queried", FactCategoryResource},
+ {"k8s_clusters:queried", FactCategoryResource},
+ {"k8s_cluster:mycluster", FactCategoryResource},
+ {"k8s_nodes:queried", FactCategoryResource},
+ {"k8s_pods:queried", FactCategoryResource},
+ {"k8s_deployments:queried", FactCategoryResource},
+ {"pmg:queried", FactCategoryResource},
+ {"pmg:mypmg", FactCategoryResource},
+ {"pmg_mail_stats:queried", FactCategoryResource},
+ {"pmg_queues:queried", FactCategoryResource},
+ {"pmg_spam:queried", FactCategoryResource},
+ {"patrol_findings:queried", FactCategoryFinding},
+ {"patrol_findings:summary", FactCategoryFinding},
{"unknown:key", FactCategoryResource}, // default
}
@@ -1025,3 +1115,809 @@ func TestCategoryForPredictedKey(t *testing.T) {
})
}
}
+
+// --- Storage: Ceph ---
+
+func TestExtractFacts_Ceph(t *testing.T) {
+ input := map[string]interface{}{"action": "ceph"}
+ result := `[{"name":"ceph-main","health":"HEALTH_OK","details":{"osd_count":6,"osds_up":6,"osds_down":0,"monitors":3,"usage_percent":42.5}}]`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2) // marker + 1 cluster
+
+ assert.Equal(t, "ceph:queried", facts[0].Key)
+ assert.Equal(t, "1 clusters", facts[0].Value)
+ assert.Equal(t, FactCategoryStorage, facts[0].Category)
+
+ assert.Equal(t, "ceph:ceph-main", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "HEALTH_OK")
+ assert.Contains(t, facts[1].Value, "6 OSDs")
+ assert.Contains(t, facts[1].Value, "6 up")
+ assert.Contains(t, facts[1].Value, "0 down")
+ assert.Contains(t, facts[1].Value, "3 monitors")
+ assert.Contains(t, facts[1].Value, "42% used")
+}
+
+func TestExtractFacts_Ceph_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "ceph"}
+ result := `[]`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "ceph:queried", facts[0].Key)
+ assert.Equal(t, "0 clusters", facts[0].Value)
+}
+
+func TestPredictFactKeys_Ceph(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "ceph"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "ceph:queried", keys[0])
+}
+
+// --- Storage: Ceph Details ---
+
+func TestExtractFacts_CephDetails(t *testing.T) {
+ input := map[string]interface{}{"action": "ceph_details"}
+ result := `{"hosts":[{"hostname":"node1","health":{"status":"HEALTH_OK"},"osd_map":{"num_osds":4,"num_up":4,"num_down":0},"pg_map":{"usage_percent":35.2},"pools":[{},{}]}],"total":1}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2) // marker + 1 host
+
+ assert.Equal(t, "ceph_details:queried", facts[0].Key)
+ assert.Equal(t, "1 hosts", facts[0].Value)
+ assert.Equal(t, FactCategoryStorage, facts[0].Category)
+
+ assert.Equal(t, "ceph_details:node1", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "HEALTH_OK")
+ assert.Contains(t, facts[1].Value, "4 OSDs")
+ assert.Contains(t, facts[1].Value, "4 up")
+ assert.Contains(t, facts[1].Value, "35% used")
+ assert.Contains(t, facts[1].Value, "2 pools")
+}
+
+func TestExtractFacts_CephDetails_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "ceph_details"}
+ result := `{"hosts":[],"total":0}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "ceph_details:queried", facts[0].Key)
+ assert.Equal(t, "0 hosts", facts[0].Value)
+}
+
+func TestPredictFactKeys_CephDetails(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "ceph_details"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "ceph_details:queried", keys[0])
+}
+
+// --- Storage: Snapshots ---
+
+func TestExtractFacts_Snapshots(t *testing.T) {
+ input := map[string]interface{}{"action": "snapshots"}
+ result := `{"snapshots":[{"vmid":100,"vm_name":"docker","type":"qemu","node":"minipc","snapshot_name":"snap1"},{"vmid":100,"vm_name":"docker","type":"qemu","node":"minipc","snapshot_name":"snap2"},{"vmid":106,"vm_name":"postfix","type":"lxc","node":"delly","snapshot_name":"backup"}],"total":3}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2) // marker + summary
+
+ assert.Equal(t, "snapshots:queried", facts[0].Key)
+ assert.Equal(t, "3 snapshots", facts[0].Value)
+
+ assert.Equal(t, "snapshots:summary", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "3 total")
+}
+
+func TestExtractFacts_Snapshots_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "snapshots"}
+ result := `{"snapshots":[],"total":0}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "snapshots:queried", facts[0].Key)
+ assert.Equal(t, "0 snapshots", facts[0].Value)
+}
+
+func TestPredictFactKeys_Snapshots(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "snapshots"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "snapshots:queried", keys[0])
+}
+
+// --- Storage: Replication ---
+
+func TestExtractFacts_Replication(t *testing.T) {
+ input := map[string]interface{}{"action": "replication"}
+ result := `[{"id":"106-0","guest_id":106,"guest_name":"postfix","source_node":"delly","target_node":"minipc","status":"ok","error":""},{"id":"200-0","guest_id":200,"guest_name":"win10","source_node":"delly","target_node":"minipc","status":"error","error":"connection refused"}]`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2) // marker + summary
+
+ assert.Equal(t, "replication:queried", facts[0].Key)
+ assert.Equal(t, "2 jobs", facts[0].Value)
+
+ assert.Equal(t, "replication:summary", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "2 jobs")
+ assert.Contains(t, facts[1].Value, "1 with errors")
+ assert.Contains(t, facts[1].Value, "win10")
+}
+
+func TestExtractFacts_Replication_AllOK(t *testing.T) {
+ input := map[string]interface{}{"action": "replication"}
+ result := `[{"id":"106-0","guest_id":106,"guest_name":"postfix","source_node":"delly","target_node":"minipc","status":"ok","error":""}]`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2)
+ assert.Contains(t, facts[1].Value, "all ok")
+}
+
+func TestExtractFacts_Replication_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "replication"}
+ result := `[]`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "replication:queried", facts[0].Key)
+ assert.Equal(t, "0 jobs", facts[0].Value)
+}
+
+func TestPredictFactKeys_Replication(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "replication"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "replication:queried", keys[0])
+}
+
+// --- Storage: PBS Jobs ---
+
+func TestExtractFacts_PBSJobs(t *testing.T) {
+ input := map[string]interface{}{"action": "pbs_jobs"}
+ result := `{"instance":"pbs-minipc","jobs":[{"id":"j1","type":"backup","store":"datastore1","status":"ok","error":""},{"id":"j2","type":"backup","store":"datastore1","status":"error","error":"timeout"},{"id":"j3","type":"sync","store":"datastore2","status":"ok","error":""}],"total":3}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2) // marker + summary
+
+ assert.Equal(t, "pbs_jobs:queried", facts[0].Key)
+ assert.Equal(t, "3 jobs", facts[0].Value)
+
+ assert.Equal(t, "pbs_jobs:summary", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "backup")
+ assert.Contains(t, facts[1].Value, "sync")
+ assert.Contains(t, facts[1].Value, "1 with errors")
+}
+
+func TestExtractFacts_PBSJobs_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "pbs_jobs"}
+ result := `{"instance":"pbs-minipc","jobs":[],"total":0}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "pbs_jobs:queried", facts[0].Key)
+ assert.Equal(t, "0 jobs", facts[0].Value)
+}
+
+func TestPredictFactKeys_PBSJobs(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "pbs_jobs"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "pbs_jobs:queried", keys[0])
+}
+
+// --- Storage: Resource Disks ---
+
+func TestExtractFacts_ResourceDisks(t *testing.T) {
+ input := map[string]interface{}{"action": "resource_disks"}
+ result := `{"resources":[{"vmid":106,"name":"postfix","type":"lxc","node":"delly","disks":[{"mountpoint":"/","usage_percent":45.2},{"mountpoint":"/data","usage_percent":85.0}]},{"vmid":200,"name":"win10","type":"qemu","node":"minipc","disks":[{"mountpoint":"C:","usage_percent":92.3}]}],"total":2}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2) // marker + summary
+
+ assert.Equal(t, "resource_disks:queried", facts[0].Key)
+ assert.Equal(t, "2 resources", facts[0].Value)
+
+ assert.Equal(t, "resource_disks:summary", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "2 resources")
+ assert.Contains(t, facts[1].Value, "3 disks total")
+ assert.Contains(t, facts[1].Value, "2 disks over 80%")
+}
+
+func TestExtractFacts_ResourceDisks_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "resource_disks"}
+ result := `{"resources":[],"total":0}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "resource_disks:queried", facts[0].Key)
+ assert.Equal(t, "0 resources", facts[0].Value)
+}
+
+func TestPredictFactKeys_ResourceDisks(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "resource_disks"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "resource_disks:queried", keys[0])
+}
+
+// --- Docker: Services ---
+
+func TestExtractFacts_DockerServices(t *testing.T) {
+ input := map[string]interface{}{"action": "services"}
+ result := `{"host":"delly","services":[{"name":"nginx","mode":"replicated","desired_tasks":3,"running_tasks":3},{"name":"redis","mode":"replicated","desired_tasks":2,"running_tasks":1}],"total":2}`
+
+ facts := ExtractFacts("pulse_docker", input, result)
+ require.Len(t, facts, 2) // marker + summary
+
+ assert.Equal(t, "docker_services:queried", facts[0].Key)
+ assert.Equal(t, "2 services", facts[0].Value)
+ assert.Equal(t, FactCategoryResource, facts[0].Category)
+
+ assert.Equal(t, "docker_services:summary", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "2 services")
+ assert.Contains(t, facts[1].Value, "1 healthy")
+ assert.Contains(t, facts[1].Value, "1 degraded")
+}
+
+func TestExtractFacts_DockerServices_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "services"}
+ result := `{"host":"delly","services":[],"total":0}`
+
+ facts := ExtractFacts("pulse_docker", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "docker_services:queried", facts[0].Key)
+ assert.Equal(t, "0 services", facts[0].Value)
+}
+
+func TestPredictFactKeys_DockerServices(t *testing.T) {
+ keys := PredictFactKeys("pulse_docker", map[string]interface{}{"action": "services"})
+ require.Len(t, keys, 2)
+ assert.Equal(t, "docker_services:queried", keys[0])
+ assert.Equal(t, "docker_services:summary", keys[1])
+}
+
+// --- Docker: Updates ---
+
+func TestExtractFacts_DockerUpdates(t *testing.T) {
+ input := map[string]interface{}{"action": "updates"}
+ result := `{"updates":[{"container_name":"nginx","update_available":true},{"container_name":"redis","update_available":false}],"total":2}`
+
+ facts := ExtractFacts("pulse_docker", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "docker_updates:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "2 containers")
+ assert.Contains(t, facts[0].Value, "1 updates available")
+}
+
+func TestPredictFactKeys_DockerUpdates(t *testing.T) {
+ keys := PredictFactKeys("pulse_docker", map[string]interface{}{"action": "updates"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "docker_updates:queried", keys[0])
+}
+
+// --- Docker: Swarm ---
+
+func TestExtractFacts_DockerSwarm(t *testing.T) {
+ input := map[string]interface{}{"action": "swarm"}
+ result := `{"host":"delly","status":{"node_role":"manager","local_state":"active","control_available":true,"cluster_name":"prod"}}`
+
+ facts := ExtractFacts("pulse_docker", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "docker_swarm:status", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "role=manager")
+ assert.Contains(t, facts[0].Value, "state=active")
+ assert.Contains(t, facts[0].Value, "host=delly")
+}
+
+func TestPredictFactKeys_DockerSwarm(t *testing.T) {
+ keys := PredictFactKeys("pulse_docker", map[string]interface{}{"action": "swarm"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "docker_swarm:status", keys[0])
+}
+
+// --- Docker: Tasks ---
+
+func TestExtractFacts_DockerTasks(t *testing.T) {
+ input := map[string]interface{}{"action": "tasks"}
+ result := `{"host":"delly","service":"nginx","tasks":[{"current_state":"running"},{"current_state":"running"},{"current_state":"failed","error":"OOM killed"}],"total":3}`
+
+ facts := ExtractFacts("pulse_docker", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "docker_tasks:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "service=nginx")
+ assert.Contains(t, facts[0].Value, "3 tasks")
+ assert.Contains(t, facts[0].Value, "2 running")
+ assert.Contains(t, facts[0].Value, "1 failed")
+}
+
+func TestPredictFactKeys_DockerTasks(t *testing.T) {
+ keys := PredictFactKeys("pulse_docker", map[string]interface{}{"action": "tasks"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "docker_tasks:queried", keys[0])
+}
+
+// --- Docker: Unknown action ---
+
+func TestExtractFacts_DockerUnknown(t *testing.T) {
+ input := map[string]interface{}{"action": "control"}
+ result := `some text result`
+
+ facts := ExtractFacts("pulse_docker", input, result)
+ assert.Empty(t, facts) // control is a write action, no extractor
+}
+
+// --- Kubernetes: Clusters ---
+
+func TestExtractFacts_K8sClusters(t *testing.T) {
+ input := map[string]interface{}{"action": "clusters"}
+ result := `{"clusters":[{"name":"prod","display_name":"Production","status":"healthy","node_count":3,"pod_count":42,"ready_nodes":3}],"total":1}`
+
+ facts := ExtractFacts("pulse_kubernetes", input, result)
+ require.Len(t, facts, 2) // marker + 1 cluster
+
+ assert.Equal(t, "k8s_clusters:queried", facts[0].Key)
+ assert.Equal(t, "1 clusters", facts[0].Value)
+
+ assert.Equal(t, "k8s_cluster:Production", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "healthy")
+ assert.Contains(t, facts[1].Value, "3 nodes")
+ assert.Contains(t, facts[1].Value, "3 ready")
+ assert.Contains(t, facts[1].Value, "42 pods")
+}
+
+func TestExtractFacts_K8sClusters_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "clusters"}
+ result := `{"clusters":[],"total":0}`
+
+ facts := ExtractFacts("pulse_kubernetes", input, result)
+ require.Len(t, facts, 1)
+ assert.Equal(t, "k8s_clusters:queried", facts[0].Key)
+ assert.Equal(t, "0 clusters", facts[0].Value)
+}
+
+func TestPredictFactKeys_K8sClusters(t *testing.T) {
+ keys := PredictFactKeys("pulse_kubernetes", map[string]interface{}{"action": "clusters"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "k8s_clusters:queried", keys[0])
+}
+
+// --- Kubernetes: Nodes ---
+
+func TestExtractFacts_K8sNodes(t *testing.T) {
+ input := map[string]interface{}{"action": "nodes"}
+ result := `{"cluster":"prod","nodes":[{"name":"node1","ready":true},{"name":"node2","ready":true},{"name":"node3","ready":false}],"total":3}`
+
+ facts := ExtractFacts("pulse_kubernetes", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "k8s_nodes:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "cluster=prod")
+ assert.Contains(t, facts[0].Value, "3 nodes")
+ assert.Contains(t, facts[0].Value, "2 ready")
+ assert.Contains(t, facts[0].Value, "1 not ready")
+}
+
+func TestPredictFactKeys_K8sNodes(t *testing.T) {
+ keys := PredictFactKeys("pulse_kubernetes", map[string]interface{}{"action": "nodes"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "k8s_nodes:queried", keys[0])
+}
+
+// --- Kubernetes: Pods ---
+
+func TestExtractFacts_K8sPods(t *testing.T) {
+ input := map[string]interface{}{"action": "pods"}
+ result := `{"cluster":"prod","pods":[{"name":"nginx-1","namespace":"default","phase":"Running","restarts":0},{"name":"redis-1","namespace":"default","phase":"Running","restarts":10},{"name":"broken-1","namespace":"test","phase":"CrashLoopBackOff","restarts":0}],"total":3}`
+
+ facts := ExtractFacts("pulse_kubernetes", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "k8s_pods:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "cluster=prod")
+ assert.Contains(t, facts[0].Value, "3 pods")
+ assert.Contains(t, facts[0].Value, "Running")
+ assert.Contains(t, facts[0].Value, "1 high-restart")
+}
+
+func TestPredictFactKeys_K8sPods(t *testing.T) {
+ keys := PredictFactKeys("pulse_kubernetes", map[string]interface{}{"action": "pods"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "k8s_pods:queried", keys[0])
+}
+
+// --- Kubernetes: Deployments ---
+
+func TestExtractFacts_K8sDeployments(t *testing.T) {
+ input := map[string]interface{}{"action": "deployments"}
+ result := `{"cluster":"prod","deployments":[{"name":"nginx","namespace":"default","desired_replicas":3,"ready_replicas":3,"available_replicas":3},{"name":"redis","namespace":"default","desired_replicas":2,"ready_replicas":1,"available_replicas":1}],"total":2}`
+
+ facts := ExtractFacts("pulse_kubernetes", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "k8s_deployments:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "cluster=prod")
+ assert.Contains(t, facts[0].Value, "2 deployments")
+ assert.Contains(t, facts[0].Value, "1 healthy")
+ assert.Contains(t, facts[0].Value, "1 degraded")
+}
+
+func TestPredictFactKeys_K8sDeployments(t *testing.T) {
+ keys := PredictFactKeys("pulse_kubernetes", map[string]interface{}{"action": "deployments"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "k8s_deployments:queried", keys[0])
+}
+
+// --- PMG: Status ---
+
+func TestExtractFacts_PMGStatus(t *testing.T) {
+ input := map[string]interface{}{"action": "status"}
+ result := `{"instances":[{"name":"pmg-main","host":"10.0.0.5","status":"running","version":"8.1.2"}],"total":1}`
+
+ facts := ExtractFacts("pulse_pmg", input, result)
+ require.Len(t, facts, 2) // marker + 1 instance
+
+ assert.Equal(t, "pmg:queried", facts[0].Key)
+ assert.Equal(t, "1 instances", facts[0].Value)
+
+ assert.Equal(t, "pmg:pmg-main", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "running")
+ assert.Contains(t, facts[1].Value, "v8.1.2")
+}
+
+func TestExtractFacts_PMGStatus_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "status"}
+ result := `{"instances":[],"total":0}`
+
+ facts := ExtractFacts("pulse_pmg", input, result)
+ require.Len(t, facts, 1)
+ assert.Equal(t, "pmg:queried", facts[0].Key)
+ assert.Equal(t, "0 instances", facts[0].Value)
+}
+
+func TestPredictFactKeys_PMGStatus(t *testing.T) {
+ keys := PredictFactKeys("pulse_pmg", map[string]interface{}{"action": "status"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "pmg:queried", keys[0])
+}
+
+// --- PMG: Mail Stats ---
+
+func TestExtractFacts_PMGMailStats(t *testing.T) {
+ input := map[string]interface{}{"action": "mail_stats"}
+ result := `{"instance":"pmg-main","stats":{"total_in":1500,"total_out":800,"spam_in":200,"virus_in":5}}`
+
+ facts := ExtractFacts("pulse_pmg", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "pmg_mail_stats:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "pmg-main")
+ assert.Contains(t, facts[0].Value, "in=1500")
+ assert.Contains(t, facts[0].Value, "out=800")
+ assert.Contains(t, facts[0].Value, "spam=200")
+ assert.Contains(t, facts[0].Value, "virus=5")
+}
+
+func TestPredictFactKeys_PMGMailStats(t *testing.T) {
+ keys := PredictFactKeys("pulse_pmg", map[string]interface{}{"action": "mail_stats"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "pmg_mail_stats:queried", keys[0])
+}
+
+// --- PMG: Queues ---
+
+func TestExtractFacts_PMGQueues(t *testing.T) {
+ input := map[string]interface{}{"action": "queues"}
+ result := `{"instance":"pmg-main","queues":[{"node":"pmg1","active":5,"deferred":12,"total":17},{"node":"pmg2","active":2,"deferred":3,"total":5}]}`
+
+ facts := ExtractFacts("pulse_pmg", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "pmg_queues:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "pmg-main")
+ assert.Contains(t, facts[0].Value, "2 nodes")
+ assert.Contains(t, facts[0].Value, "22 queued")
+ assert.Contains(t, facts[0].Value, "15 deferred")
+}
+
+func TestPredictFactKeys_PMGQueues(t *testing.T) {
+ keys := PredictFactKeys("pulse_pmg", map[string]interface{}{"action": "queues"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "pmg_queues:queried", keys[0])
+}
+
+// --- PMG: Spam ---
+
+func TestExtractFacts_PMGSpam(t *testing.T) {
+ input := map[string]interface{}{"action": "spam"}
+ result := `{"instance":"pmg-main","quarantine":{"spam":150,"virus":3,"total":153}}`
+
+ facts := ExtractFacts("pulse_pmg", input, result)
+ require.Len(t, facts, 1)
+
+ assert.Equal(t, "pmg_spam:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "pmg-main")
+ assert.Contains(t, facts[0].Value, "153 total")
+ assert.Contains(t, facts[0].Value, "150 spam")
+ assert.Contains(t, facts[0].Value, "3 virus")
+}
+
+func TestPredictFactKeys_PMGSpam(t *testing.T) {
+ keys := PredictFactKeys("pulse_pmg", map[string]interface{}{"action": "spam"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "pmg_spam:queried", keys[0])
+}
+
+// --- Patrol: Get Findings ---
+
+func TestExtractFacts_PatrolGetFindings(t *testing.T) {
+ result := `{"ok":true,"count":3,"findings":[{"key":"high-cpu","severity":"warning","title":"High CPU","resource_id":"vm101"},{"key":"disk-full","severity":"critical","title":"Disk Full","resource_id":"ct200"},{"key":"low-mem","severity":"warning","title":"Low Memory","resource_id":"vm102"}]}`
+
+ facts := ExtractFacts("patrol_get_findings", nil, result)
+ require.Len(t, facts, 2) // marker + summary
+
+ assert.Equal(t, "patrol_findings:queried", facts[0].Key)
+ assert.Equal(t, "3 findings", facts[0].Value)
+ assert.Equal(t, FactCategoryFinding, facts[0].Category)
+
+ assert.Equal(t, "patrol_findings:summary", facts[1].Key)
+ assert.Contains(t, facts[1].Value, "3 total")
+ assert.Contains(t, facts[1].Value, "warning")
+ assert.Contains(t, facts[1].Value, "critical")
+}
+
+func TestExtractFacts_PatrolGetFindings_Empty(t *testing.T) {
+ result := `{"ok":true,"count":0,"findings":[]}`
+
+ facts := ExtractFacts("patrol_get_findings", nil, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "patrol_findings:queried", facts[0].Key)
+ assert.Equal(t, "0 findings", facts[0].Value)
+}
+
+func TestPredictFactKeys_PatrolGetFindings(t *testing.T) {
+ keys := PredictFactKeys("patrol_get_findings", nil)
+ require.Len(t, keys, 1)
+ assert.Equal(t, "patrol_findings:queried", keys[0])
+}
+
+// --- Roundtrip Consistency: Predict keys must match extracted keys ---
+// This test prevents the class of bug where PredictFactKeys returns keys that
+// don't match what ExtractFacts actually stores — making the gate useless.
+
+func TestPredictExtractRoundtrip(t *testing.T) {
+ // Each entry: tool, input, sample result, description
+ // PredictFactKeys must return at least one key that appears in ExtractFacts output.
+ cases := []struct {
+ name string
+ tool string
+ input map[string]interface{}
+ result string
+ }{
+ {"query:topology", "pulse_query", map[string]interface{}{"action": "topology"},
+ `{"summary":{"total_nodes":1},"proxmox":{"nodes":[{"name":"n1","status":"online"}]}}`},
+ {"query:health", "pulse_query", map[string]interface{}{"action": "health"},
+ `{"connections":[{"instance_id":"n1","connected":true}]}`},
+ {"query:get", "pulse_query", map[string]interface{}{"action": "get", "resource_id": "106"},
+ `{"type":"lxc","name":"test","status":"running","node":"n1","id":"106","vmid":106,"cpu":{"percent":1},"memory":{"percent":50}}`},
+ {"query:get:error", "pulse_query", map[string]interface{}{"action": "get", "resource_id": "999"},
+ `{"error":"not_found","resource_id":"999","type":"vm"}`},
+ {"query:search", "pulse_query", map[string]interface{}{"action": "search", "query": "test"},
+ `{"matches":[{"name":"test","status":"running"}],"total":1}`},
+ {"query:list", "pulse_query", map[string]interface{}{"action": "list"},
+ `{"nodes":[{"name":"n1","status":"online"}],"total":{"nodes":1}}`},
+ {"query:config", "pulse_query", map[string]interface{}{"action": "config", "resource_id": "106", "node": "n1"},
+ `{"guest_type":"lxc","vmid":106,"name":"test","node":"n1"}`},
+ {"query:config:no_node", "pulse_query", map[string]interface{}{"action": "config", "resource_id": "106"},
+ `{"guest_type":"lxc","vmid":106,"name":"test","node":"n1"}`},
+ {"storage:pools", "pulse_storage", map[string]interface{}{"action": "pools"},
+ `{"pools":[{"name":"local","node":"n1","type":"dir","usage_percent":50,"total_gb":100,"used_gb":50}]}`},
+ {"storage:disk_health", "pulse_storage", map[string]interface{}{"action": "disk_health"},
+ `{"hosts":[{"hostname":"n1","smart":[{"device":"/dev/sda","health":"PASSED"}]}]}`},
+ {"storage:raid", "pulse_storage", map[string]interface{}{"action": "raid"},
+ `{"hosts":[{"hostname":"n1","arrays":[{"device":"/dev/md0","state":"clean","failed_devices":0}]}]}`},
+ {"storage:backups", "pulse_storage", map[string]interface{}{"action": "backups"},
+ `{"pbs":[],"pve":[],"pbs_servers":[]}`},
+ {"storage:backup_tasks", "pulse_storage", map[string]interface{}{"action": "backup_tasks"},
+ `{"tasks":[{"vmid":100,"node":"n1","status":"OK"}],"total":1}`},
+ {"storage:ceph", "pulse_storage", map[string]interface{}{"action": "ceph"},
+ `[{"name":"c1","health":"OK","details":{"osd_count":3,"osds_up":3,"osds_down":0,"monitors":1,"usage_percent":30}}]`},
+ {"storage:ceph_details", "pulse_storage", map[string]interface{}{"action": "ceph_details"},
+ `{"hosts":[{"hostname":"n1","health":{"status":"OK"},"osd_map":{"num_osds":3,"num_up":3},"pg_map":{"usage_percent":30},"pools":[]}]}`},
+ {"storage:snapshots", "pulse_storage", map[string]interface{}{"action": "snapshots"},
+ `{"snapshots":[{"vmid":100,"vm_name":"test","snapshot_name":"s1"}],"total":1}`},
+ {"storage:replication", "pulse_storage", map[string]interface{}{"action": "replication"},
+ `[{"id":"1","guest_id":100,"guest_name":"test","status":"ok","error":""}]`},
+ {"storage:pbs_jobs", "pulse_storage", map[string]interface{}{"action": "pbs_jobs"},
+ `{"jobs":[{"id":"j1","type":"backup","status":"ok"}],"total":1}`},
+ {"storage:resource_disks", "pulse_storage", map[string]interface{}{"action": "resource_disks"},
+ `{"resources":[{"vmid":100,"name":"test","disks":[{"mountpoint":"/","usage_percent":50}]}],"total":1}`},
+ {"metrics:performance", "pulse_metrics", map[string]interface{}{"action": "performance", "resource_id": "vm101"},
+ `{"summary":{"vm101":{"avg_cpu":10,"max_cpu":50,"trend":"stable"}}}`},
+ {"metrics:baselines", "pulse_metrics", map[string]interface{}{"action": "baselines"},
+ `{"baselines":{"n1":{"n1:100:cpu":{"mean":5,"std_dev":2,"min":0,"max":20}}}}`},
+ {"metrics:disks", "pulse_metrics", map[string]interface{}{"action": "disks"},
+ `{"disks":[{"host":"n1","device":"/dev/sda","health":"PASSED"}]}`},
+ {"metrics:temperatures", "pulse_metrics", map[string]interface{}{"action": "temperatures"},
+ `[{"hostname":"n1","cpu_temps":{"core0":50},"disk_temps":{}}]`},
+ {"alerts:findings", "pulse_alerts", map[string]interface{}{"action": "findings"},
+ `{"active":[{"key":"k1","severity":"warning","title":"test"}],"counts":{"active":1,"dismissed":0}}`},
+ {"alerts:list", "pulse_alerts", map[string]interface{}{"action": "list"},
+ `{"alerts":[{"resource_name":"vm101","type":"cpu","severity":"warning","value":90,"threshold":80,"status":"active"}]}`},
+ {"docker:services", "pulse_docker", map[string]interface{}{"action": "services"},
+ `{"host":"h1","services":[{"name":"nginx","desired_tasks":2,"running_tasks":2}],"total":1}`},
+ {"docker:updates", "pulse_docker", map[string]interface{}{"action": "updates"},
+ `{"updates":[{"container_name":"nginx","update_available":false}],"total":1}`},
+ {"docker:swarm", "pulse_docker", map[string]interface{}{"action": "swarm"},
+ `{"host":"h1","status":{"node_role":"manager","local_state":"active","control_available":true}}`},
+ {"docker:tasks", "pulse_docker", map[string]interface{}{"action": "tasks"},
+ `{"host":"h1","tasks":[{"current_state":"running"}],"total":1}`},
+ {"k8s:clusters", "pulse_kubernetes", map[string]interface{}{"action": "clusters"},
+ `{"clusters":[{"name":"prod","status":"healthy","node_count":3,"ready_nodes":3,"pod_count":10}],"total":1}`},
+ {"k8s:nodes", "pulse_kubernetes", map[string]interface{}{"action": "nodes"},
+ `{"cluster":"prod","nodes":[{"name":"n1","ready":true}],"total":1}`},
+ {"k8s:pods", "pulse_kubernetes", map[string]interface{}{"action": "pods"},
+ `{"cluster":"prod","pods":[{"name":"p1","phase":"Running"}],"total":1}`},
+ {"k8s:deployments", "pulse_kubernetes", map[string]interface{}{"action": "deployments"},
+ `{"cluster":"prod","deployments":[{"name":"d1","desired_replicas":2,"ready_replicas":2}],"total":1}`},
+ {"pmg:status", "pulse_pmg", map[string]interface{}{"action": "status"},
+ `{"instances":[{"name":"pmg1","status":"running"}],"total":1}`},
+ {"pmg:mail_stats", "pulse_pmg", map[string]interface{}{"action": "mail_stats"},
+ `{"instance":"pmg1","stats":{"total_in":100,"total_out":50,"spam_in":10,"virus_in":1}}`},
+ {"pmg:queues", "pulse_pmg", map[string]interface{}{"action": "queues"},
+ `{"instance":"pmg1","queues":[{"node":"n1","total":5,"deferred":2}]}`},
+ {"pmg:spam", "pulse_pmg", map[string]interface{}{"action": "spam"},
+ `{"instance":"pmg1","quarantine":{"spam":10,"virus":1,"total":11}}`},
+ {"patrol:get_findings", "patrol_get_findings", nil,
+ `{"ok":true,"count":1,"findings":[{"key":"k1","severity":"warning","title":"test"}]}`},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ predictedKeys := PredictFactKeys(tc.tool, tc.input)
+ require.NotNil(t, predictedKeys, "PredictFactKeys should return keys for %s", tc.name)
+
+ extractedFacts := ExtractFacts(tc.tool, tc.input, tc.result)
+ require.NotEmpty(t, extractedFacts, "ExtractFacts should return facts for %s", tc.name)
+
+ // Build set of extracted keys
+ extractedKeys := make(map[string]bool)
+ for _, f := range extractedFacts {
+ extractedKeys[f.Key] = true
+ }
+
+ // At least one predicted key must appear in extracted keys
+ matched := false
+ for _, pk := range predictedKeys {
+ if extractedKeys[pk] {
+ matched = true
+ break
+ }
+ }
+ assert.True(t, matched,
+ "PredictFactKeys %v must match at least one ExtractFacts key %v for %s",
+ predictedKeys, keys(extractedKeys), tc.name)
+ })
+ }
+}
+
+// keys extracts map keys as a slice for readable test output.
+func keys(m map[string]bool) []string {
+ var result []string
+ for k := range m {
+ result = append(result, k)
+ }
+ return result
+}
+
+// --- End-to-end gate flow test ---
+// Simulates the full cycle: extract facts → store in KA → predict → lookup → gate fires.
+// Also validates MarkerExpansion enrichment for marker-based extractors.
+
+func TestGateFlowEndToEnd(t *testing.T) {
+ cases := []struct {
+ name string
+ tool string
+ input map[string]interface{}
+ result string
+ expectEnrich bool // whether MarkerExpansions should add related facts
+ }{
+ {"storage:pools", "pulse_storage", map[string]interface{}{"action": "pools"},
+ `{"pools":[{"name":"local","node":"n1","type":"dir","usage_percent":50,"total_gb":100,"used_gb":50}]}`,
+ true}, // Marker expansion: storage:pools:queried → storage:
+ {"storage:ceph", "pulse_storage", map[string]interface{}{"action": "ceph"},
+ `[{"name":"c1","health":"OK","details":{"osd_count":3,"osds_up":3,"osds_down":0,"monitors":1,"usage_percent":30}}]`,
+ true}, // Marker expansion: ceph:queried → ceph:
+ {"k8s:clusters", "pulse_kubernetes", map[string]interface{}{"action": "clusters"},
+ `{"clusters":[{"name":"prod","status":"healthy","node_count":3,"ready_nodes":3,"pod_count":10}],"total":1}`,
+ true}, // Marker expansion: k8s_clusters:queried → k8s_cluster:
+ {"pmg:status", "pulse_pmg", map[string]interface{}{"action": "status"},
+ `{"instances":[{"name":"pmg1","status":"running"}],"total":1}`,
+ true}, // Marker expansion: pmg:queried → pmg:
+ {"query:get", "pulse_query", map[string]interface{}{"action": "get", "resource_id": "106"},
+ `{"type":"lxc","name":"test","status":"running","node":"n1","id":"106","vmid":106,"cpu":{"percent":1},"memory":{"percent":50}}`,
+ false}, // No marker expansion for query:get:106:cached
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ // Step 1: Extract facts from tool result
+ facts := ExtractFacts(tc.tool, tc.input, tc.result)
+ require.NotEmpty(t, facts, "should extract facts")
+
+ // Step 2: Store facts in KA (as agentic.go does)
+ for _, f := range facts {
+ ka.AddFact(f.Category, f.Key, f.Value)
+ }
+
+ // Step 3: Predict keys (as gate does on second call)
+ predictedKeys := PredictFactKeys(tc.tool, tc.input)
+ require.NotNil(t, predictedKeys, "should predict keys")
+
+ // Step 4: Gate lookup — at least one predicted key should be found
+ var cachedParts []string
+ for _, key := range predictedKeys {
+ if value, found := ka.Lookup(key); found {
+ cachedParts = append(cachedParts, fmt.Sprintf("%s = %s", key, value))
+ }
+ }
+ require.NotEmpty(t, cachedParts, "gate should fire (cached facts found)")
+
+ // Step 5: Enrichment via MarkerExpansions
+ if tc.expectEnrich {
+ enriched := false
+ for _, key := range predictedKeys {
+ if prefix, ok := MarkerExpansions[key]; ok {
+ related := ka.RelatedFacts(prefix)
+ if related != "" {
+ enriched = true
+ // RelatedFacts should not include the marker itself
+ assert.NotContains(t, related, ":queried",
+ "RelatedFacts should exclude marker keys")
+ }
+ }
+ }
+ assert.True(t, enriched, "MarkerExpansion should enrich with related facts")
+ }
+ })
+ }
+}
+
+// --- Negative marker gate test ---
+// Verifies that when ExtractFacts returns nil (text/error response),
+// the negative marker prevents re-execution on the next call.
+
+func TestNegativeMarkerGateFlow(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ tool := "pulse_storage"
+ input := map[string]interface{}{"action": "ceph"}
+ textResult := "No Ceph clusters configured on this system"
+
+ // ExtractFacts should return nil for plain text
+ facts := ExtractFacts(tool, input, textResult)
+ assert.Empty(t, facts)
+
+ // Simulate negative marker storage (as agentic.go does)
+ predictedKeys := PredictFactKeys(tool, input)
+ require.NotEmpty(t, predictedKeys)
+ for _, key := range predictedKeys {
+ if _, found := ka.Lookup(key); !found {
+ cat := categoryForPredictedKey(key)
+ summary := textResult
+ if len(summary) > 120 {
+ summary = summary[:120]
+ }
+ ka.AddFact(cat, key, fmt.Sprintf("checked: %s", summary))
+ }
+ }
+
+ // Now simulate second call — gate should fire
+ predictedKeys2 := PredictFactKeys(tool, input)
+ var cachedParts []string
+ for _, key := range predictedKeys2 {
+ if value, found := ka.Lookup(key); found {
+ cachedParts = append(cachedParts, value)
+ }
+ }
+ require.NotEmpty(t, cachedParts, "gate should fire on second call due to negative marker")
+ assert.Contains(t, cachedParts[0], "checked:", "negative marker value should start with 'checked:'")
+}