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): expose canonical truenas resources to pulse query

rcourtmana6c03860692f
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 3a634fb772..1126d1fb31 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -266,6 +266,16 @@ canonical `policy` and `ai_safe_summary` fields derived from unified resources,
and deterministic knowledge extraction must prefer those governed summaries
when policy redaction covers aliases, hostnames, or platform IDs instead of
persisting raw resource labels into cached AI facts.
+That same `pulse_query` boundary now also owns canonical resource coverage for
+API-backed platforms such as TrueNAS. The runtime must expose canonical
+`system`, `app-container`, `storage-pool`, and `physical-disk` views through
+the shared unified-resource model instead of falling back to Proxmox- or
+Docker-local enumerations when a platform projects onto canonical host,
+storage, disk, or workload contracts.
+Unified AI context should follow the same rule: storage summaries may mention
+canonical storage pools and physical disks that need attention, but must not
+mislabel lower-topology storage resources such as TrueNAS datasets as
+top-level pools.
That same requirement includes `pulse_query action=config`: guest-config
payloads must carry canonical resource policy metadata, and config-fact
extraction must not persist raw guest hostnames when governed redaction covers
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 374ecd9f25..8c2e753149 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -180,6 +180,12 @@ provider-local host surface. API-backed `reporting.realtime` telemetry must
project onto that same canonical `agent` contract as live metrics and metrics
targets, using the shared `agent:<id>` in-memory key and `agent` history store
path instead of adding a TrueNAS-only host history lane.
+AI discovery and query surfaces now follow the same rule. Assistant runtime
+paths such as `pulse_query` and unified AI context must expose TrueNAS-backed
+canonical `agent`, `app-container`, `storage`, and `physical-disk` resources
+through those shared contracts, filtering dataset-topology storage children
+out of any `storage-pool` presentation instead of inventing TrueNAS-local
+assistant types or mislabeling datasets as pools.
The canonical resource timeline now also owns durable incident-response facts
that materially changed resource investigation state. `ResourceChange` kinds
such as `alert_fired`, `alert_acknowledged`, `alert_unacknowledged`,
diff --git a/internal/ai/resource_context.go b/internal/ai/resource_context.go
index d876a03587..49debfd829 100644
--- a/internal/ai/resource_context.go
+++ b/internal/ai/resource_context.go
@@ -360,6 +360,88 @@ func (s *Service) buildUnifiedResourceContextForModel(destinationModel string) s
}
}
+ storagePools := make([]unifiedresources.Resource, 0)
+ for _, resource := range unifiedresources.RefreshCanonicalMetadataSlice(urp.GetByType(unifiedresources.ResourceTypeStorage)) {
+ if resource.Storage != nil && strings.EqualFold(strings.TrimSpace(resource.Storage.Topology), "dataset") {
+ continue
+ }
+ storagePools = append(storagePools, resource)
+ }
+ physicalDisks := unifiedresources.RefreshCanonicalMetadataSlice(urp.GetByType(unifiedresources.ResourceTypePhysicalDisk))
+ if len(storagePools) > 0 || len(physicalDisks) > 0 {
+ sections = append(sections, "\n### Storage")
+
+ if len(storagePools) > 0 {
+ sort.Slice(storagePools, func(i, j int) bool {
+ return strings.ToLower(unifiedresources.ResourceDisplayName(storagePools[i])) < strings.ToLower(unifiedresources.ResourceDisplayName(storagePools[j]))
+ })
+ sections = append(sections, "\n**Storage Pools:**")
+ for _, pool := range storagePools {
+ diskPercent := 0.0
+ if pool.Metrics != nil {
+ diskPercent = unifiedMetricPercent(pool.Metrics.Disk)
+ }
+
+ poolType := ""
+ if pool.Storage != nil && strings.TrimSpace(pool.Storage.Type) != "" {
+ poolType = pool.Storage.Type
+ }
+ usage := ""
+ if diskPercent > 0 {
+ usage = fmt.Sprintf(", Usage: %.1f%%", diskPercent)
+ }
+ typeLabel := ""
+ if poolType != "" {
+ typeLabel = fmt.Sprintf(" (%s)", poolType)
+ }
+
+ sections = append(sections, fmt.Sprintf("- **%s**%s%s [%s]",
+ unifiedresources.ResourcePolicyLabel(pool.Name, pool.AISafeSummary, pool.Policy), typeLabel, usage, pool.Status))
+ }
+ }
+
+ if len(physicalDisks) > 0 {
+ attention := make([]unifiedresources.Resource, 0)
+ for _, disk := range physicalDisks {
+ health := ""
+ temperature := 0
+ if disk.PhysicalDisk != nil {
+ health = strings.ToUpper(strings.TrimSpace(disk.PhysicalDisk.Health))
+ temperature = disk.PhysicalDisk.Temperature
+ }
+ if disk.Status != unifiedresources.StatusOnline || (health != "" && health != "PASSED" && health != "UNKNOWN") || temperature >= 50 {
+ attention = append(attention, disk)
+ }
+ }
+
+ if len(attention) > 0 {
+ sort.Slice(attention, func(i, j int) bool {
+ return strings.ToLower(unifiedresources.ResourceDisplayName(attention[i])) < strings.ToLower(unifiedresources.ResourceDisplayName(attention[j]))
+ })
+ sections = append(sections, "\n**Physical Disks Needing Attention:**")
+ for _, disk := range attention {
+ health := ""
+ temperature := ""
+ if disk.PhysicalDisk != nil {
+ if value := strings.TrimSpace(disk.PhysicalDisk.Health); value != "" {
+ health = value
+ }
+ if disk.PhysicalDisk.Temperature > 0 {
+ temperature = fmt.Sprintf(", Temp: %dC", disk.PhysicalDisk.Temperature)
+ }
+ }
+ healthSummary := ""
+ if health != "" {
+ healthSummary = fmt.Sprintf(" (%s)", health)
+ }
+
+ sections = append(sections, fmt.Sprintf("- **%s**%s%s [%s]",
+ unifiedresources.ResourcePolicyLabel(disk.Name, disk.AISafeSummary, disk.Policy), healthSummary, temperature, disk.Status))
+ }
+ }
+ }
+ }
+
activeAlerts := make([]AlertInfo, 0)
if ap != nil {
activeAlerts = ap.GetActiveAlerts()
diff --git a/internal/ai/resource_context_test.go b/internal/ai/resource_context_test.go
index 4c6c26ad6c..5e0256fdc8 100644
--- a/internal/ai/resource_context_test.go
+++ b/internal/ai/resource_context_test.go
@@ -573,6 +573,18 @@ func TestBuildUnifiedResourceContextIncludesTrueNASResources(t *testing.T) {
if !strings.Contains(got, "TrueNAS Systems") {
t.Fatalf("expected context to include TrueNAS section, got %q", got)
}
+ if !strings.Contains(got, "### Storage") {
+ t.Fatalf("expected context to include storage section, got %q", got)
+ }
+ if !strings.Contains(got, "Storage Pools") {
+ t.Fatalf("expected context to include storage pools section, got %q", got)
+ }
+ if !strings.Contains(got, "Physical Disks Needing Attention") {
+ t.Fatalf("expected context to include disk attention section, got %q", got)
+ }
+ if strings.Contains(got, "tank/apps") {
+ t.Fatalf("expected storage pool section to exclude dataset names, got %q", got)
+ }
if !strings.Contains(got, "agent resource; status warning; sources truenas") {
t.Fatalf("expected context to include governed truenas summary, got %q", got)
}
diff --git a/internal/ai/tools/data_types.go b/internal/ai/tools/data_types.go
index efdd7d94d1..9a2181ae0f 100644
--- a/internal/ai/tools/data_types.go
+++ b/internal/ai/tools/data_types.go
@@ -156,10 +156,14 @@ type FeatureFlags struct {
// InfrastructureResponse is returned by pulse_list_infrastructure
type InfrastructureResponse struct {
+ Systems []SystemSummary `json:"systems"`
Nodes []NodeSummary `json:"nodes"`
VMs []VMSummary `json:"vms"`
Containers []ContainerSummary `json:"containers"`
+ AppContainers []AppContainerSummary `json:"app_containers"`
DockerHosts []DockerHostSummary `json:"docker_hosts"`
+ StoragePools []StoragePoolSummary `json:"storage_pools"`
+ PhysicalDisks []PhysicalDiskSummary `json:"physical_disks"`
K8sClusters []K8sClusterSummary `json:"k8s_clusters"`
K8sNodes []K8sNodeSummary `json:"k8s_nodes"`
K8sPods []K8sPodSummary `json:"k8s_pods"`
@@ -173,6 +177,9 @@ func EmptyInfrastructureResponse() InfrastructureResponse {
}
func (r InfrastructureResponse) NormalizeCollections() InfrastructureResponse {
+ if r.Systems == nil {
+ r.Systems = []SystemSummary{}
+ }
if r.Nodes == nil {
r.Nodes = []NodeSummary{}
}
@@ -182,9 +189,18 @@ func (r InfrastructureResponse) NormalizeCollections() InfrastructureResponse {
if r.Containers == nil {
r.Containers = []ContainerSummary{}
}
+ if r.AppContainers == nil {
+ r.AppContainers = []AppContainerSummary{}
+ }
if r.DockerHosts == nil {
r.DockerHosts = []DockerHostSummary{}
}
+ if r.StoragePools == nil {
+ r.StoragePools = []StoragePoolSummary{}
+ }
+ if r.PhysicalDisks == nil {
+ r.PhysicalDisks = []PhysicalDiskSummary{}
+ }
if r.K8sClusters == nil {
r.K8sClusters = []K8sClusterSummary{}
}
@@ -229,11 +245,26 @@ type ResourceMatch struct {
Node string `json:"node,omitempty"` // Hypervisor node this resource is on
NodeHasAgent bool `json:"node_has_agent,omitempty"` // True if the node has a connected agent
Host string `json:"host,omitempty"` // Docker host for docker containers
+ Platform string `json:"platform,omitempty"`
VMID int `json:"vmid,omitempty"`
Image string `json:"image,omitempty"`
AgentConnected bool `json:"agent_connected,omitempty"` // True if this specific resource has a connected agent
}
+// SystemSummary is a summarized infrastructure system for list responses.
+type SystemSummary struct {
+ GovernedResourceMetadata
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Platform string `json:"platform,omitempty"`
+ ChildCount int `json:"child_count,omitempty"`
+ AgentConnected bool `json:"agent_connected,omitempty"`
+ CPU float64 `json:"cpu_percent,omitempty"`
+ Memory float64 `json:"memory_percent,omitempty"`
+ Disk float64 `json:"disk_percent,omitempty"`
+}
+
// NodeSummary is a summarized node for list responses
type NodeSummary struct {
GovernedResourceMetadata
@@ -293,6 +324,21 @@ type DockerContainerSummary struct {
Health string `json:"health,omitempty"`
}
+// AppContainerSummary is a summarized canonical app container for list responses.
+type AppContainerSummary struct {
+ GovernedResourceMetadata
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Host string `json:"host,omitempty"`
+ Platform string `json:"platform,omitempty"`
+ Image string `json:"image,omitempty"`
+ Health string `json:"health,omitempty"`
+ CPU float64 `json:"cpu_percent,omitempty"`
+ Memory float64 `json:"memory_percent,omitempty"`
+ Disk float64 `json:"disk_percent,omitempty"`
+}
+
// K8sClusterSummary is a summarized Kubernetes cluster for list responses
type K8sClusterSummary struct {
GovernedResourceMetadata
@@ -346,10 +392,14 @@ type K8sDeploymentSummary struct {
// TotalCounts for infrastructure response
type TotalCounts struct {
+ Systems int `json:"systems"`
Nodes int `json:"nodes"`
VMs int `json:"vms"`
Containers int `json:"containers"`
+ AppContainers int `json:"app_containers"`
DockerHosts int `json:"docker_hosts"`
+ StoragePools int `json:"storage_pools"`
+ PhysicalDisks int `json:"physical_disks"`
K8sClusters int `json:"k8s_clusters"`
K8sNodes int `json:"k8s_nodes"`
K8sPods int `json:"k8s_pods"`
@@ -613,6 +663,7 @@ type ResourceResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
+ Platform string `json:"platform,omitempty"`
Node string `json:"node,omitempty"`
Host string `json:"host,omitempty"`
CPU ResourceCPU `json:"cpu"`
diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.go
index b56151e12c..0a3225d07c 100644
--- a/internal/ai/tools/tools_query.go
+++ b/internal/ai/tools/tools_query.go
@@ -2006,7 +2006,7 @@ func (e *PulseToolExecutor) registerQueryTools() {
e.registry.Register(RegisteredTool{
Definition: Tool{
Name: "pulse_query",
- Description: `Query and search infrastructure resources. Start here to find resources by name. Actions: search, get, config, topology, list, health.`,
+ Description: `Query and search canonical infrastructure resources. Start here to discover systems, workloads, storage, and disks by name. Actions: search, get, config, topology, list, health.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
@@ -2021,8 +2021,8 @@ func (e *PulseToolExecutor) registerQueryTools() {
},
"resource_type": {
Type: "string",
- Description: "Resource type: 'vm', 'system-container', 'app-container', 'node' (for action: get, config, search)",
- Enum: []string{"vm", "system-container", "app-container", "node"},
+ Description: "Resource type. For get: 'system', 'vm', 'system-container', 'app-container'. For config: 'vm' or 'system-container'. For search: use type or resource_type with canonical values.",
+ Enum: []string{"system", "vm", "system-container", "app-container", "node", "docker-host", "storage-pool", "physical-disk"},
},
"resource_id": {
Type: "string",
@@ -2030,8 +2030,8 @@ func (e *PulseToolExecutor) registerQueryTools() {
},
"type": {
Type: "string",
- Description: "Filter by type (for action: list): 'nodes', 'vms', 'system-containers', 'app-containers', 'kubernetes', 'k8s-clusters', 'k8s-nodes', 'k8s-pods', 'k8s-deployments'",
- Enum: []string{"nodes", "vms", "system-containers", "app-containers", "kubernetes", "k8s-clusters", "k8s-nodes", "k8s-pods", "k8s-deployments"},
+ Description: "Filter by type (for action: list/search): 'systems', 'nodes', 'vms', 'system-containers', 'app-containers', 'docker-hosts', 'storage-pools', 'physical-disks', 'kubernetes', 'k8s-clusters', 'k8s-nodes', 'k8s-pods', 'k8s-deployments'",
+ Enum: []string{"systems", "nodes", "vms", "system-containers", "app-containers", "docker-hosts", "storage-pools", "physical-disks", "kubernetes", "k8s-clusters", "k8s-nodes", "k8s-pods", "k8s-deployments"},
},
"status": {
Type: "string",
@@ -2114,6 +2114,8 @@ func canonicalQueryResourceType(resourceType string) string {
func canonicalQueryListType(filterType string) string {
switch strings.ToLower(strings.TrimSpace(filterType)) {
+ case "system":
+ return "systems"
case "node":
return "nodes"
case "vm":
@@ -2122,6 +2124,12 @@ func canonicalQueryListType(filterType string) string {
return "system-containers"
case "app-container":
return "app-containers"
+ case "docker-host":
+ return "docker-hosts"
+ case "storage-pool":
+ return "storage-pools"
+ case "physical-disk":
+ return "physical-disks"
case "k8s-cluster", "k8s-clusters":
return "k8s-clusters"
case "k8s-node", "k8s-nodes":
@@ -2146,10 +2154,18 @@ func canonicalQueryTopologyInclude(include string) string {
func canonicalQuerySearchType(typeFilter string) string {
switch strings.ToLower(strings.TrimSpace(typeFilter)) {
+ case "systems":
+ return "system"
case "system-containers":
return "system-container"
case "app-containers":
return "app-container"
+ case "docker-hosts":
+ return "docker-host"
+ case "storage-pools":
+ return "storage-pool"
+ case "physical-disks":
+ return "physical-disk"
case "docker-host":
return "docker-host"
default:
@@ -2205,6 +2221,253 @@ func governedQueryMetadataFromResolvedResource(resource *unifiedresources.Resour
}
}
+func metricPercent(value *unifiedresources.MetricValue) float64 {
+ if value == nil {
+ return 0
+ }
+ return value.Percent
+}
+
+func metricUsedGB(value *unifiedresources.MetricValue) float64 {
+ if value == nil || value.Used == nil {
+ return 0
+ }
+ return float64(*value.Used) / (1024 * 1024 * 1024)
+}
+
+func metricTotalGB(value *unifiedresources.MetricValue) float64 {
+ if value == nil || value.Total == nil {
+ return 0
+ }
+ return float64(*value.Total) / (1024 * 1024 * 1024)
+}
+
+func canonicalResourcePlatform(resource unifiedresources.Resource) string {
+ switch {
+ case resource.TrueNAS != nil || resourceHasTag(resource, "truenas"):
+ return "truenas"
+ case resource.Proxmox != nil:
+ return "proxmox"
+ case resource.Docker != nil:
+ return "docker"
+ case resource.Agent != nil && strings.TrimSpace(resource.Agent.Platform) != "":
+ return strings.ToLower(strings.TrimSpace(resource.Agent.Platform))
+ default:
+ return ""
+ }
+}
+
+func resourceHasTag(resource unifiedresources.Resource, needle string) bool {
+ for _, tag := range resource.Tags {
+ if strings.EqualFold(strings.TrimSpace(tag), needle) {
+ return true
+ }
+ }
+ return false
+}
+
+func resourceDisplayName(resource unifiedresources.Resource) string {
+ if name := unifiedresources.ResourceDisplayName(resource); name != "" {
+ return name
+ }
+ return strings.TrimSpace(resource.Name)
+}
+
+func resourceHostCandidates(resource unifiedresources.Resource) []string {
+ candidates := []string{resourceDisplayName(resource)}
+ if resource.Agent != nil {
+ candidates = append(candidates, strings.TrimSpace(resource.Agent.Hostname))
+ }
+ if resource.TrueNAS != nil {
+ candidates = append(candidates, strings.TrimSpace(resource.TrueNAS.Hostname))
+ }
+ if resource.Docker != nil {
+ candidates = append(candidates, strings.TrimSpace(resource.Docker.Hostname))
+ }
+ if resource.Proxmox != nil {
+ candidates = append(candidates, strings.TrimSpace(resource.Proxmox.NodeName))
+ }
+ candidates = append(candidates, resource.Identity.Hostnames...)
+ return candidates
+}
+
+func resourceAgentConnected(resource unifiedresources.Resource, connected map[string]bool) bool {
+ for _, candidate := range resourceHostCandidates(resource) {
+ key := strings.TrimSpace(candidate)
+ if key == "" {
+ continue
+ }
+ if connected[key] {
+ return true
+ }
+ }
+ return false
+}
+
+func canonicalAppContainerID(resource unifiedresources.Resource) string {
+ if resource.Docker != nil && strings.TrimSpace(resource.Docker.ContainerID) != "" {
+ return strings.TrimSpace(resource.Docker.ContainerID)
+ }
+ return strings.TrimSpace(resource.ID)
+}
+
+func canonicalAppContainerState(resource unifiedresources.Resource) string {
+ if resource.Docker != nil && strings.TrimSpace(resource.Docker.ContainerState) != "" {
+ return strings.TrimSpace(resource.Docker.ContainerState)
+ }
+ return string(resource.Status)
+}
+
+func canonicalAppContainerHost(resource unifiedresources.Resource) string {
+ if host := strings.TrimSpace(resource.ParentName); host != "" {
+ return host
+ }
+ for _, candidate := range resource.Identity.Hostnames {
+ if strings.TrimSpace(candidate) != "" {
+ return strings.TrimSpace(candidate)
+ }
+ }
+ return ""
+}
+
+func canonicalSystemSummaryFromResource(resource unifiedresources.Resource, connected map[string]bool) SystemSummary {
+ return SystemSummary{
+ ID: strings.TrimSpace(resource.ID),
+ Name: resourceDisplayName(resource),
+ Status: string(resource.Status),
+ Platform: canonicalResourcePlatform(resource),
+ ChildCount: resource.ChildCount,
+ AgentConnected: resourceAgentConnected(resource, connected),
+ CPU: metricPercent(resourceMetric(resource, "cpu")),
+ Memory: metricPercent(resourceMetric(resource, "memory")),
+ Disk: metricPercent(resourceMetric(resource, "disk")),
+ }
+}
+
+func canonicalAppContainerSummaryFromResource(resource unifiedresources.Resource) AppContainerSummary {
+ health := ""
+ image := ""
+ if resource.Docker != nil {
+ health = strings.TrimSpace(resource.Docker.Health)
+ image = strings.TrimSpace(resource.Docker.Image)
+ }
+ return AppContainerSummary{
+ ID: canonicalAppContainerID(resource),
+ Name: resourceDisplayName(resource),
+ Status: canonicalAppContainerState(resource),
+ Host: canonicalAppContainerHost(resource),
+ Platform: canonicalResourcePlatform(resource),
+ Image: image,
+ Health: health,
+ CPU: metricPercent(resourceMetric(resource, "cpu")),
+ Memory: metricPercent(resourceMetric(resource, "memory")),
+ Disk: metricPercent(resourceMetric(resource, "disk")),
+ }
+}
+
+func canonicalStoragePoolResources(provider UnifiedResourceProvider) []unifiedresources.Resource {
+ if provider == nil {
+ return []unifiedresources.Resource{}
+ }
+
+ storagePoolResources := make([]unifiedresources.Resource, 0)
+ for _, resource := range sortedResourcesByName(provider.GetByType(unifiedresources.ResourceTypeStorage)) {
+ if resource.Storage != nil && strings.EqualFold(strings.TrimSpace(resource.Storage.Topology), "dataset") {
+ continue
+ }
+ storagePoolResources = append(storagePoolResources, resource)
+ }
+ return storagePoolResources
+}
+
+func canonicalPhysicalDiskHost(resource unifiedresources.Resource) string {
+ for _, candidate := range resource.Identity.Hostnames {
+ if candidate = strings.TrimSpace(candidate); candidate != "" {
+ return candidate
+ }
+ }
+ return strings.TrimSpace(resource.ParentName)
+}
+
+func physicalDiskSummaryFromResource(resource unifiedresources.Resource) PhysicalDiskSummary {
+ pd := resource.PhysicalDisk
+ summary := PhysicalDiskSummary{
+ ID: resource.ID,
+ Node: canonicalPhysicalDiskHost(resource),
+ DevPath: "",
+ Model: "",
+ Serial: "",
+ WWN: "",
+ Type: "",
+ SizeBytes: 0,
+ Health: "",
+ Used: "",
+ LastChecked: resource.LastSeen,
+ }
+ if pd == nil {
+ return summary
+ }
+ summary.DevPath = pd.DevPath
+ summary.Model = pd.Model
+ summary.Serial = pd.Serial
+ summary.WWN = pd.WWN
+ summary.Type = pd.DiskType
+ summary.SizeBytes = pd.SizeBytes
+ summary.Health = pd.Health
+ summary.Used = pd.Used
+ if pd.Wearout >= 0 {
+ wearout := pd.Wearout
+ summary.Wearout = &wearout
+ }
+ if pd.Temperature > 0 {
+ temp := pd.Temperature
+ summary.Temperature = &temp
+ }
+ if pd.RPM > 0 {
+ rpm := pd.RPM
+ summary.RPM = &rpm
+ }
+ return summary
+}
+
+func resourceMetric(resource unifiedresources.Resource, kind string) *unifiedresources.MetricValue {
+ if resource.Metrics == nil {
+ return nil
+ }
+ switch kind {
+ case "cpu":
+ return resource.Metrics.CPU
+ case "memory":
+ return resource.Metrics.Memory
+ case "disk":
+ return resource.Metrics.Disk
+ default:
+ return nil
+ }
+}
+
+func sortedResourcesByName(resources []unifiedresources.Resource) []unifiedresources.Resource {
+ sorted := append([]unifiedresources.Resource(nil), resources...)
+ sort.Slice(sorted, func(i, j int) bool {
+ return strings.ToLower(resourceDisplayName(sorted[i])) < strings.ToLower(resourceDisplayName(sorted[j]))
+ })
+ return sorted
+}
+
+func matchesCanonicalResourceID(resource unifiedresources.Resource, resourceID string) bool {
+ resourceID = strings.TrimSpace(resourceID)
+ if resourceID == "" {
+ return false
+ }
+ if strings.EqualFold(strings.TrimSpace(resource.ID), resourceID) {
+ return true
+ }
+ if strings.EqualFold(resourceDisplayName(resource), resourceID) {
+ return true
+ }
+ return false
+}
+
// executeQuery routes to the appropriate query handler based on action
func (e *PulseToolExecutor) executeQuery(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
action, _ := args["action"].(string)
@@ -2277,17 +2540,44 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args ma
}
}
+ systemResources := []unifiedresources.Resource{}
+ appContainerResources := []unifiedresources.Resource{}
+ storagePoolResources := []unifiedresources.Resource{}
+ physicalDiskResources := []unifiedresources.Resource{}
+ if e.unifiedResourceProvider != nil {
+ systemResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAgent))
+ appContainerResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAppContainer))
+ physicalDiskResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypePhysicalDisk))
+ storagePoolResources = canonicalStoragePoolResources(e.unifiedResourceProvider)
+ }
+
response := EmptyInfrastructureResponse()
response.Total = TotalCounts{
+ Systems: len(systemResources),
Nodes: len(rs.Nodes()),
VMs: len(rs.VMs()),
Containers: len(rs.Containers()),
+ AppContainers: len(appContainerResources),
DockerHosts: len(rs.DockerHosts()),
+ StoragePools: len(storagePoolResources),
+ PhysicalDisks: len(physicalDiskResources),
K8sClusters: len(rs.K8sClusters()),
K8sNodes: len(rs.K8sNodes()),
K8sPods: len(rs.Pods()),
K8sDeployments: len(rs.K8sDeployments()),
}
+ if response.Total.Systems == 0 {
+ response.Total.Systems = len(rs.Nodes()) + len(rs.Hosts()) + len(rs.DockerHosts())
+ }
+ if response.Total.AppContainers == 0 {
+ response.Total.AppContainers = len(rs.DockerContainers())
+ }
+ if response.Total.StoragePools == 0 {
+ response.Total.StoragePools = len(rs.StoragePools())
+ }
+ if response.Total.PhysicalDisks == 0 {
+ response.Total.PhysicalDisks = len(rs.PhysicalDisks())
+ }
totalMatches := 0
@@ -2313,6 +2603,39 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args ma
podCountByCluster[normalizeClusterKey(pod.ClusterName())]++
}
+ dockerHostsByID := make(map[string]*unifiedresources.DockerHostView)
+ for _, host := range rs.DockerHosts() {
+ if host == nil {
+ continue
+ }
+ dockerHostsByID[host.ID()] = host
+ }
+
+ // Systems
+ if filterType == "" || filterType == "systems" {
+ count := 0
+ for _, resource := range systemResources {
+ if !statusMatchesFilter(string(resource.Status), filterStatus) {
+ continue
+ }
+ if count < offset {
+ count++
+ continue
+ }
+ if len(response.Systems) >= limit {
+ count++
+ continue
+ }
+ summary := canonicalSystemSummaryFromResource(resource, connectedAgentHostnames)
+ summary.GovernedResourceMetadata = governance.Resolve(resourceDisplayName(resource), resource.ID)
+ response.Systems = append(response.Systems, summary)
+ count++
+ }
+ if filterType == "systems" {
+ totalMatches = count
+ }
+ }
+
// Nodes
if filterType == "" || filterType == "nodes" {
count := 0
@@ -2403,8 +2726,82 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args ma
}
}
- // Docker hosts
+ // App containers
if filterType == "" || filterType == "app-containers" {
+ count := 0
+ for _, resource := range appContainerResources {
+ status := canonicalAppContainerState(resource)
+ if !statusMatchesFilter(status, filterStatus) {
+ continue
+ }
+ if count < offset {
+ count++
+ continue
+ }
+ if len(response.AppContainers) >= limit {
+ count++
+ continue
+ }
+
+ summary := canonicalAppContainerSummaryFromResource(resource)
+ summary.GovernedResourceMetadata = governance.Resolve(resourceDisplayName(resource), resource.ID, canonicalAppContainerID(resource))
+ response.AppContainers = append(response.AppContainers, summary)
+ count++
+ }
+ if len(appContainerResources) == 0 {
+ for _, container := range rs.DockerContainers() {
+ if container == nil {
+ continue
+ }
+ state := strings.TrimSpace(container.ContainerState())
+ if state == "" {
+ state = string(container.Status())
+ }
+ if !statusMatchesFilter(state, filterStatus) {
+ continue
+ }
+ if count < offset {
+ count++
+ continue
+ }
+ if len(response.AppContainers) >= limit {
+ count++
+ continue
+ }
+
+ hostName := ""
+ if host := dockerHostsByID[strings.TrimSpace(container.ParentID())]; host != nil {
+ hostName = strings.TrimSpace(host.Hostname())
+ if hostName == "" {
+ hostName = strings.TrimSpace(host.Name())
+ }
+ }
+ containerID := strings.TrimSpace(container.ContainerID())
+ if containerID == "" {
+ containerID = strings.TrimSpace(container.ID())
+ }
+ response.AppContainers = append(response.AppContainers, AppContainerSummary{
+ GovernedResourceMetadata: governance.Resolve(container.Name(), container.ID(), containerID),
+ ID: containerID,
+ Name: container.Name(),
+ Status: state,
+ Host: hostName,
+ Platform: "docker",
+ Image: container.Image(),
+ Health: container.Health(),
+ CPU: container.CPUPercent(),
+ Memory: container.MemoryPercent(),
+ })
+ count++
+ }
+ }
+ if filterType == "app-containers" {
+ totalMatches = count
+ }
+ }
+
+ // Docker hosts
+ if filterType == "" || filterType == "docker-hosts" {
containersByHost := make(map[string][]*unifiedresources.DockerContainerView)
for _, container := range rs.DockerContainers() {
if container == nil {
@@ -2470,7 +2867,53 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args ma
response.DockerHosts = append(response.DockerHosts, dockerHost)
count++
}
- if filterType == "app-containers" {
+ if filterType == "docker-hosts" {
+ totalMatches = count
+ }
+ }
+
+ // Storage pools
+ if filterType == "" || filterType == "storage-pools" {
+ count := 0
+ for _, resource := range storagePoolResources {
+ if !statusMatchesFilter(string(resource.Status), filterStatus) {
+ continue
+ }
+ if count < offset {
+ count++
+ continue
+ }
+ if len(response.StoragePools) >= limit {
+ count++
+ continue
+ }
+ response.StoragePools = append(response.StoragePools, storagePoolSummaryFromResource(resource))
+ count++
+ }
+ if filterType == "storage-pools" {
+ totalMatches = count
+ }
+ }
+
+ // Physical disks
+ if filterType == "" || filterType == "physical-disks" {
+ count := 0
+ for _, resource := range physicalDiskResources {
+ if !statusMatchesFilter(string(resource.Status), filterStatus) {
+ continue
+ }
+ if count < offset {
+ count++
+ continue
+ }
+ if len(response.PhysicalDisks) >= limit {
+ count++
+ continue
+ }
+ response.PhysicalDisks = append(response.PhysicalDisks, physicalDiskSummaryFromResource(resource))
+ count++
+ }
+ if filterType == "physical-disks" {
totalMatches = count
}
}
@@ -3151,6 +3594,52 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
governance := newGovernedQueryMetadataResolver(rs)
switch resourceType {
+ case "system":
+ if e.unifiedResourceProvider != nil {
+ for _, resource := range e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAgent) {
+ if !matchesCanonicalResourceID(resource, resourceID) {
+ continue
+ }
+ response := EmptyResourceResponse()
+ response.GovernedResourceMetadata = governance.Resolve(resourceDisplayName(resource), resource.ID)
+ response.Type = "system"
+ response.ID = strings.TrimSpace(resource.ID)
+ response.Name = resourceDisplayName(resource)
+ response.Status = string(resource.Status)
+ response.Platform = canonicalResourcePlatform(resource)
+ response.CPU = ResourceCPU{
+ Percent: metricPercent(resourceMetric(resource, "cpu")),
+ }
+ response.Memory = ResourceMemory{
+ Percent: metricPercent(resourceMetric(resource, "memory")),
+ UsedGB: metricUsedGB(resourceMetric(resource, "memory")),
+ TotalGB: metricTotalGB(resourceMetric(resource, "memory")),
+ }
+ if diskMetric := resourceMetric(resource, "disk"); diskMetric != nil {
+ response.Disk = &ResourceDisk{
+ Percent: metricPercent(diskMetric),
+ UsedGB: metricUsedGB(diskMetric),
+ TotalGB: metricTotalGB(diskMetric),
+ }
+ }
+ response.Tags = append([]string{}, resource.Tags...)
+ if resource.Agent != nil {
+ response.OS = strings.TrimSpace(resource.Agent.OSName)
+ response.Host = strings.TrimSpace(resource.Agent.Hostname)
+ response.CPU.Cores = resource.Agent.CPUCount
+ }
+ if response.Host == "" && resource.TrueNAS != nil {
+ response.Host = strings.TrimSpace(resource.TrueNAS.Hostname)
+ }
+ return NewJSONResult(response.NormalizeCollections()), nil
+ }
+ }
+ return NewJSONResult(map[string]interface{}{
+ "error": "not_found",
+ "resource_id": resourceID,
+ "type": "system",
+ }), nil
+
case "vm":
for _, vm := range rs.VMs() {
if fmt.Sprintf("%d", vm.VMID()) == resourceID || vm.Name() == resourceID || vm.ID() == resourceID {
@@ -3262,6 +3751,121 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
}), nil
case "app-container":
+ if e.unifiedResourceProvider != nil {
+ for _, resource := range e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAppContainer) {
+ containerID := canonicalAppContainerID(resource)
+ if !strings.EqualFold(containerID, strings.TrimSpace(resourceID)) &&
+ !strings.EqualFold(resourceDisplayName(resource), strings.TrimSpace(resourceID)) &&
+ !strings.EqualFold(strings.TrimSpace(resource.ID), strings.TrimSpace(resourceID)) &&
+ !strings.HasPrefix(strings.ToLower(containerID), strings.ToLower(strings.TrimSpace(resourceID))) {
+ continue
+ }
+
+ response := EmptyResourceResponse()
+ response.GovernedResourceMetadata = governance.Resolve(resourceDisplayName(resource), resource.ID, containerID)
+ response.Type = "app-container"
+ response.ID = containerID
+ response.Name = resourceDisplayName(resource)
+ response.Status = canonicalAppContainerState(resource)
+ response.Platform = canonicalResourcePlatform(resource)
+ response.Host = canonicalAppContainerHost(resource)
+ response.CPU = ResourceCPU{
+ Percent: metricPercent(resourceMetric(resource, "cpu")),
+ }
+ response.Memory = ResourceMemory{
+ Percent: metricPercent(resourceMetric(resource, "memory")),
+ UsedGB: metricUsedGB(resourceMetric(resource, "memory")),
+ TotalGB: metricTotalGB(resourceMetric(resource, "memory")),
+ }
+ if diskMetric := resourceMetric(resource, "disk"); diskMetric != nil {
+ response.Disk = &ResourceDisk{
+ Percent: metricPercent(diskMetric),
+ UsedGB: metricUsedGB(diskMetric),
+ TotalGB: metricTotalGB(diskMetric),
+ }
+ }
+ response.Tags = append([]string{}, resource.Tags...)
+ if resource.Docker != nil {
+ response.Image = strings.TrimSpace(resource.Docker.Image)
+ response.Health = strings.TrimSpace(resource.Docker.Health)
+ response.RestartCount = resource.Docker.RestartCount
+ response.Labels = resource.Docker.Labels
+ if update := resource.Docker.UpdateStatus; update != nil && update.UpdateAvailable {
+ response.UpdateAvailable = true
+ }
+ for _, p := range resource.Docker.Ports {
+ response.Ports = append(response.Ports, PortInfo{
+ Private: p.PrivatePort,
+ Public: p.PublicPort,
+ Protocol: p.Protocol,
+ IP: p.IP,
+ })
+ }
+ for _, n := range resource.Docker.Networks {
+ addresses := make([]string, 0, 2)
+ if n.IPv4 != "" {
+ addresses = append(addresses, n.IPv4)
+ }
+ if n.IPv6 != "" {
+ addresses = append(addresses, n.IPv6)
+ }
+ response.Networks = append(response.Networks, NetworkInfo{
+ Name: n.Name,
+ Addresses: addresses,
+ })
+ }
+ for _, m := range resource.Docker.Mounts {
+ response.Mounts = append(response.Mounts, MountInfo{
+ Source: m.Source,
+ Destination: m.Destination,
+ ReadWrite: !strings.EqualFold(strings.TrimSpace(m.Mode), "ro"),
+ })
+ }
+ }
+
+ if response.Platform == "docker" {
+ hostUID := ""
+ if resource.ParentID != nil {
+ hostUID = strings.TrimSpace(*resource.ParentID)
+ }
+ hostName := response.Host
+ if hostUID == "" {
+ hostUID = hostName
+ }
+ if hostName == "" {
+ hostName = hostUID
+ }
+ executorID := hostName
+ if executorID == "" {
+ executorID = hostUID
+ }
+ aliases := []string{response.Name, containerID, strings.TrimSpace(resource.ID)}
+ if len(containerID) > 12 {
+ aliases = append(aliases, containerID[:12])
+ }
+ e.registerResolvedResourceWithExplicitAccess(ResourceRegistration{
+ Kind: "app-container",
+ ProviderUID: containerID,
+ Name: response.Name,
+ Aliases: aliases,
+ HostUID: hostUID,
+ HostName: hostName,
+ LocationChain: []string{
+ "docker-host:" + hostName,
+ "docker:" + response.Name,
+ },
+ Executors: []ExecutorRegistration{{
+ ExecutorID: executorID,
+ Adapter: "docker",
+ Actions: []string{"query", "get", "logs", "exec", "restart", "stop", "start"},
+ Priority: 10,
+ }},
+ })
+ }
+ return NewJSONResult(response.NormalizeCollections()), nil
+ }
+ }
+
dockerHostsByID := make(map[string]*unifiedresources.DockerHostView)
for _, host := range rs.DockerHosts() {
if host == nil {
@@ -3407,7 +4011,7 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
}), nil
default:
- return NewErrorResult(fmt.Errorf("invalid resource_type: %s. Use 'vm', 'system-container', or 'app-container'", resourceTypeRaw)), nil
+ return NewErrorResult(fmt.Errorf("invalid resource_type: %s. Use 'system', 'vm', 'system-container', or 'app-container'", resourceTypeRaw)), nil
}
}
@@ -3669,14 +4273,17 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
allowedTypes := map[string]bool{
"": true,
+ "system": true,
"node": true,
"vm": true,
"system-container": true,
"app-container": true,
"docker-host": true,
+ "storage-pool": true,
+ "physical-disk": true,
}
if !allowedTypes[typeFilter] {
- return NewErrorResult(fmt.Errorf("invalid type: %s. Use node, vm, system-container, app-container, or docker-host", typeFilter)), nil
+ return NewErrorResult(fmt.Errorf("invalid type: %s. Use system, node, vm, system-container, app-container, docker-host, storage-pool, or physical-disk", typeFilter)), nil
}
// normalizeForSearch replaces common separators with spaces and splits at
@@ -3751,6 +4358,17 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
dockerHostsByID[host.ID()] = host
}
+ systemResources := []unifiedresources.Resource{}
+ appContainerResources := []unifiedresources.Resource{}
+ storagePoolResources := []unifiedresources.Resource{}
+ physicalDiskResources := []unifiedresources.Resource{}
+ if e.unifiedResourceProvider != nil {
+ systemResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAgent))
+ appContainerResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAppContainer))
+ physicalDiskResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypePhysicalDisk))
+ storagePoolResources = canonicalStoragePoolResources(e.unifiedResourceProvider)
+ }
+
// Build a set of connected agent hostnames for quick lookup
connectedAgentHostnames := make(map[string]bool)
if e.agentServer != nil {
@@ -3775,6 +4393,28 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
total++
}
+ if typeFilter == "" || typeFilter == "system" {
+ for _, resource := range systemResources {
+ status := string(resource.Status)
+ if !statusMatchesFilter(status, statusFilter) {
+ continue
+ }
+ candidates := append(resourceHostCandidates(resource), resource.ID, canonicalResourcePlatform(resource))
+ if !matchesQuery(queryLower, candidates...) {
+ continue
+ }
+ addMatch(ResourceMatch{
+ GovernedResourceMetadata: governance.Resolve(resourceDisplayName(resource), resource.ID),
+ Type: "system",
+ ID: resource.ID,
+ Name: resourceDisplayName(resource),
+ Status: status,
+ Platform: canonicalResourcePlatform(resource),
+ AgentConnected: resourceAgentConnected(resource, connectedAgentHostnames),
+ })
+ }
+ }
+
if typeFilter == "" || typeFilter == "node" {
for _, node := range rs.Nodes() {
status := string(node.Status())
@@ -3889,6 +4529,49 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
}
if typeFilter == "" || typeFilter == "app-container" {
+ for _, resource := range appContainerResources {
+ status := canonicalAppContainerState(resource)
+ if !statusMatchesFilter(status, statusFilter) {
+ continue
+ }
+
+ containerID := canonicalAppContainerID(resource)
+ candidates := []string{
+ resourceDisplayName(resource),
+ resource.ID,
+ containerID,
+ canonicalAppContainerHost(resource),
+ canonicalResourcePlatform(resource),
+ }
+ if resource.Docker != nil {
+ candidates = append(candidates, resource.Docker.Image)
+ for key, value := range resource.Docker.Labels {
+ candidates = append(candidates, key, value)
+ }
+ for _, network := range resource.Docker.Networks {
+ candidates = append(candidates, network.IPv4, network.IPv6, network.Name)
+ }
+ }
+ candidates = append(candidates, resource.Tags...)
+ if !matchesQuery(queryLower, candidates...) {
+ continue
+ }
+
+ summary := canonicalAppContainerSummaryFromResource(resource)
+ addMatch(ResourceMatch{
+ GovernedResourceMetadata: governance.Resolve(resourceDisplayName(resource), resource.ID, containerID),
+ Type: "app-container",
+ ID: summary.ID,
+ Name: summary.Name,
+ Status: summary.Status,
+ Host: summary.Host,
+ Platform: summary.Platform,
+ Image: summary.Image,
+ })
+ }
+ }
+
+ if (typeFilter == "" || typeFilter == "app-container") && len(appContainerResources) == 0 {
for _, container := range rs.DockerContainers() {
if container == nil {
continue
@@ -3941,6 +4624,71 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
}
}
+ if typeFilter == "" || typeFilter == "storage-pool" {
+ for _, resource := range storagePoolResources {
+ status := string(resource.Status)
+ if !statusMatchesFilter(status, statusFilter) {
+ continue
+ }
+ candidates := []string{
+ resourceDisplayName(resource),
+ resource.ID,
+ canonicalResourcePlatform(resource),
+ }
+ if resource.Storage != nil {
+ candidates = append(candidates, resource.Storage.Type, resource.Storage.Content, resource.Storage.Path)
+ }
+ candidates = append(candidates, resource.Tags...)
+ if !matchesQuery(queryLower, candidates...) {
+ continue
+ }
+ addMatch(ResourceMatch{
+ GovernedResourceMetadata: governance.Resolve(resourceDisplayName(resource), resource.ID),
+ Type: "storage-pool",
+ ID: resource.ID,
+ Name: resourceDisplayName(resource),
+ Status: status,
+ Host: strings.TrimSpace(resource.ParentName),
+ Platform: canonicalResourcePlatform(resource),
+ })
+ }
+ }
+
+ if typeFilter == "" || typeFilter == "physical-disk" {
+ for _, resource := range physicalDiskResources {
+ status := string(resource.Status)
+ if !statusMatchesFilter(status, statusFilter) {
+ continue
+ }
+ summary := physicalDiskSummaryFromResource(resource)
+ candidates := []string{
+ resourceDisplayName(resource),
+ resource.ID,
+ summary.DevPath,
+ summary.Model,
+ summary.Serial,
+ summary.WWN,
+ summary.Type,
+ summary.Node,
+ strings.TrimSpace(resource.ParentName),
+ canonicalResourcePlatform(resource),
+ }
+ candidates = append(candidates, resource.Tags...)
+ if !matchesQuery(queryLower, candidates...) {
+ continue
+ }
+ addMatch(ResourceMatch{
+ GovernedResourceMetadata: governance.Resolve(resourceDisplayName(resource), resource.ID, summary.Serial, summary.DevPath),
+ Type: "physical-disk",
+ ID: resource.ID,
+ Name: resourceDisplayName(resource),
+ Status: status,
+ Host: summary.Node,
+ Platform: canonicalResourcePlatform(resource),
+ })
+ }
+ }
+
response := EmptyResourceSearchResponse()
response.Query = query
response.Matches = matches
@@ -3960,6 +4708,15 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
var reg ResourceRegistration
switch match.Type {
+ case "system":
+ reg = ResourceRegistration{
+ Kind: "system",
+ ProviderUID: match.ID,
+ Name: match.Name,
+ Aliases: []string{match.Name, match.ID},
+ HostUID: match.ID,
+ HostName: match.Name,
+ }
case "node":
reg = ResourceRegistration{
Kind: "node",
@@ -4029,19 +4786,39 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
}
case "app-container":
reg = ResourceRegistration{
- Kind: "app-container",
- ProviderUID: match.ID, // Docker container ID
- Name: match.Name,
- Aliases: []string{match.Name, match.ID},
- HostUID: match.Host,
- HostName: match.Host,
- LocationChain: []string{"docker-host:" + match.Host, "docker:" + match.Name},
- Executors: []ExecutorRegistration{{
+ Kind: "app-container",
+ ProviderUID: match.ID, // Stable container/app provider ID
+ Name: match.Name,
+ Aliases: []string{match.Name, match.ID},
+ HostUID: match.Host,
+ HostName: match.Host,
+ }
+ if match.Platform == "docker" {
+ reg.LocationChain = []string{"docker-host:" + match.Host, "docker:" + match.Name}
+ reg.Executors = []ExecutorRegistration{{
ExecutorID: match.Host,
Adapter: "docker",
Actions: []string{"query", "get", "logs", "exec", "restart", "stop", "start"},
Priority: 10,
- }},
+ }}
+ }
+ case "storage-pool":
+ reg = ResourceRegistration{
+ Kind: "storage-pool",
+ ProviderUID: match.ID,
+ Name: match.Name,
+ Aliases: []string{match.Name, match.ID},
+ HostUID: match.Host,
+ HostName: match.Host,
+ }
+ case "physical-disk":
+ reg = ResourceRegistration{
+ Kind: "physical-disk",
+ ProviderUID: match.ID,
+ Name: match.Name,
+ Aliases: []string{match.Name, match.ID},
+ HostUID: match.Host,
+ HostName: match.Host,
}
default:
continue // Skip unknown types
diff --git a/internal/ai/tools/tools_query_test.go b/internal/ai/tools/tools_query_test.go
index a9bedb0f5c..ae3f31c76c 100644
--- a/internal/ai/tools/tools_query_test.go
+++ b/internal/ai/tools/tools_query_test.go
@@ -8,6 +8,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/truenas"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
@@ -232,6 +233,32 @@ func (m *mockGuestConfigProvider) GetGuestConfig(guestType, instance, node strin
return m.config, nil
}
+type registryUnifiedQueryProvider struct {
+ *unifiedresources.ResourceRegistry
+}
+
+func (p *registryUnifiedQueryProvider) GetByType(t unifiedresources.ResourceType) []unifiedresources.Resource {
+ return p.ListByType(t)
+}
+
+func newTrueNASUnifiedQueryProvider(t *testing.T) *registryUnifiedQueryProvider {
+ t.Helper()
+
+ previous := truenas.IsFeatureEnabled()
+ truenas.SetFeatureEnabled(true)
+ t.Cleanup(func() {
+ truenas.SetFeatureEnabled(previous)
+ })
+
+ registry := unifiedresources.NewRegistry(nil)
+ records := truenas.NewDefaultProvider().Records()
+ if len(records) == 0 {
+ t.Fatal("expected TrueNAS fixture records")
+ }
+ registry.IngestRecords(unifiedresources.SourceTrueNAS, records)
+ return &registryUnifiedQueryProvider{ResourceRegistry: registry}
+}
+
func TestCanonicalQueryListType_StrictV6Tokens(t *testing.T) {
if got := canonicalQueryListType("k8s-pods"); got != "k8s-pods" {
t.Fatalf("canonicalQueryListType(k8s-pods) = %q, want k8s-pods", got)
@@ -242,6 +269,15 @@ func TestCanonicalQueryListType_StrictV6Tokens(t *testing.T) {
if got := canonicalQueryListType("kubernetes-clusters"); got != "kubernetes-clusters" {
t.Fatalf("canonicalQueryListType(kubernetes-clusters) = %q, want kubernetes-clusters", got)
}
+ if got := canonicalQueryListType("system"); got != "systems" {
+ t.Fatalf("canonicalQueryListType(system) = %q, want systems", got)
+ }
+ if got := canonicalQueryListType("storage-pool"); got != "storage-pools" {
+ t.Fatalf("canonicalQueryListType(storage-pool) = %q, want storage-pools", got)
+ }
+ if got := canonicalQueryListType("physical-disk"); got != "physical-disks" {
+ t.Fatalf("canonicalQueryListType(physical-disk) = %q, want physical-disks", got)
+ }
}
func TestCanonicalQueryTopologyInclude_StrictV6Tokens(t *testing.T) {
@@ -263,6 +299,15 @@ func TestCanonicalQuerySearchType_StrictV6Tokens(t *testing.T) {
if got := canonicalQuerySearchType("docker_host"); got != "docker_host" {
t.Fatalf("canonicalQuerySearchType(docker_host) = %q, want docker_host", got)
}
+ if got := canonicalQuerySearchType("systems"); got != "system" {
+ t.Fatalf("canonicalQuerySearchType(systems) = %q, want system", got)
+ }
+ if got := canonicalQuerySearchType("storage-pools"); got != "storage-pool" {
+ t.Fatalf("canonicalQuerySearchType(storage-pools) = %q, want storage-pool", got)
+ }
+ if got := canonicalQuerySearchType("physical-disks"); got != "physical-disk" {
+ t.Fatalf("canonicalQuerySearchType(physical-disks) = %q, want physical-disk", got)
+ }
}
func TestCanonicalQueryHelpers_DoNotTranslateLegacyAliases(t *testing.T) {
@@ -700,6 +745,163 @@ func TestExecuteGetResource(t *testing.T) {
}
}
+func TestExecuteQuery_UsesCanonicalTrueNASUnifiedResources(t *testing.T) {
+ provider := newTrueNASUnifiedQueryProvider(t)
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ })
+
+ listSystems, err := executor.executeListInfrastructure(context.Background(), map[string]interface{}{
+ "type": "systems",
+ })
+ if err != nil {
+ t.Fatalf("list systems: unexpected error: %v", err)
+ }
+ var systemsResp InfrastructureResponse
+ if err := json.Unmarshal([]byte(listSystems.Content[0].Text), &systemsResp); err != nil {
+ t.Fatalf("decode systems response: %v", err)
+ }
+ if len(systemsResp.Systems) != 1 {
+ t.Fatalf("expected one TrueNAS system, got %+v", systemsResp.Systems)
+ }
+ if systemsResp.Systems[0].Platform != "truenas" || systemsResp.Systems[0].Name != "truenas-main" {
+ t.Fatalf("unexpected system summary: %+v", systemsResp.Systems[0])
+ }
+
+ listApps, err := executor.executeListInfrastructure(context.Background(), map[string]interface{}{
+ "type": "app-containers",
+ })
+ if err != nil {
+ t.Fatalf("list app containers: unexpected error: %v", err)
+ }
+ var appsResp InfrastructureResponse
+ if err := json.Unmarshal([]byte(listApps.Content[0].Text), &appsResp); err != nil {
+ t.Fatalf("decode app container response: %v", err)
+ }
+ if len(appsResp.AppContainers) == 0 {
+ t.Fatal("expected canonical app containers from TrueNAS fixtures")
+ }
+ foundNextcloud := false
+ for _, app := range appsResp.AppContainers {
+ if app.Name != "Nextcloud" {
+ continue
+ }
+ foundNextcloud = true
+ if app.Platform != "truenas" || app.Host != "truenas-main" || app.ID != "nextcloud" {
+ t.Fatalf("unexpected Nextcloud summary: %+v", app)
+ }
+ }
+ if !foundNextcloud {
+ t.Fatalf("expected Nextcloud in app containers, got %+v", appsResp.AppContainers)
+ }
+
+ listPools, err := executor.executeListInfrastructure(context.Background(), map[string]interface{}{
+ "type": "storage-pools",
+ })
+ if err != nil {
+ t.Fatalf("list storage pools: unexpected error: %v", err)
+ }
+ var poolsResp InfrastructureResponse
+ if err := json.Unmarshal([]byte(listPools.Content[0].Text), &poolsResp); err != nil {
+ t.Fatalf("decode storage pools response: %v", err)
+ }
+ if len(poolsResp.StoragePools) != 3 {
+ t.Fatalf("expected only top-level pools, got %+v", poolsResp.StoragePools)
+ }
+ for _, pool := range poolsResp.StoragePools {
+ if strings.Contains(pool.Name, "/") {
+ t.Fatalf("expected storage-pools list to exclude datasets, got %+v", poolsResp.StoragePools)
+ }
+ }
+
+ listDisks, err := executor.executeListInfrastructure(context.Background(), map[string]interface{}{
+ "type": "physical-disks",
+ })
+ if err != nil {
+ t.Fatalf("list physical disks: unexpected error: %v", err)
+ }
+ var disksResp InfrastructureResponse
+ if err := json.Unmarshal([]byte(listDisks.Content[0].Text), &disksResp); err != nil {
+ t.Fatalf("decode physical disks response: %v", err)
+ }
+ if len(disksResp.PhysicalDisks) == 0 {
+ t.Fatal("expected physical disks from TrueNAS fixtures")
+ }
+ foundHotDisk := false
+ for _, disk := range disksResp.PhysicalDisks {
+ if disk.DevPath != "/dev/sdc" {
+ continue
+ }
+ foundHotDisk = true
+ if disk.Node != "truenas-main" || disk.Health == "" {
+ t.Fatalf("unexpected canonical disk summary: %+v", disk)
+ }
+ }
+ if !foundHotDisk {
+ t.Fatalf("expected sdc disk in list response, got %+v", disksResp.PhysicalDisks)
+ }
+
+ searchPool, err := executor.executeSearchResources(context.Background(), map[string]interface{}{
+ "query": "archive",
+ "type": "storage-pool",
+ })
+ if err != nil {
+ t.Fatalf("search storage pools: unexpected error: %v", err)
+ }
+ var searchResp ResourceSearchResponse
+ if err := json.Unmarshal([]byte(searchPool.Content[0].Text), &searchResp); err != nil {
+ t.Fatalf("decode storage-pool search response: %v", err)
+ }
+ if len(searchResp.Matches) != 1 || searchResp.Matches[0].Type != "storage-pool" || searchResp.Matches[0].Name != "archive" || searchResp.Matches[0].Platform != "truenas" {
+ t.Fatalf("unexpected storage-pool search response: %+v", searchResp.Matches)
+ }
+
+ searchDisk, err := executor.executeSearchResources(context.Background(), map[string]interface{}{
+ "query": "sdc",
+ "type": "physical-disk",
+ })
+ if err != nil {
+ t.Fatalf("search physical disks: unexpected error: %v", err)
+ }
+ searchResp = ResourceSearchResponse{}
+ if err := json.Unmarshal([]byte(searchDisk.Content[0].Text), &searchResp); err != nil {
+ t.Fatalf("decode physical-disk search response: %v", err)
+ }
+ if len(searchResp.Matches) != 1 || searchResp.Matches[0].Type != "physical-disk" || searchResp.Matches[0].Platform != "truenas" || searchResp.Matches[0].Host != "truenas-main" {
+ t.Fatalf("unexpected physical-disk search response: %+v", searchResp.Matches)
+ }
+
+ getSystem, err := executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "system",
+ "resource_id": "truenas-main",
+ })
+ if err != nil {
+ t.Fatalf("get system: unexpected error: %v", err)
+ }
+ var systemRes ResourceResponse
+ if err := json.Unmarshal([]byte(getSystem.Content[0].Text), &systemRes); err != nil {
+ t.Fatalf("decode system resource: %v", err)
+ }
+ if systemRes.Type != "system" || systemRes.Platform != "truenas" || systemRes.Host != "truenas-main" {
+ t.Fatalf("unexpected canonical system resource: %+v", systemRes)
+ }
+
+ getApp, err := executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "app-container",
+ "resource_id": "nextcloud",
+ })
+ if err != nil {
+ t.Fatalf("get app-container: unexpected error: %v", err)
+ }
+ var appRes ResourceResponse
+ if err := json.Unmarshal([]byte(getApp.Content[0].Text), &appRes); err != nil {
+ t.Fatalf("decode app resource: %v", err)
+ }
+ if appRes.Type != "app-container" || appRes.Name != "Nextcloud" || appRes.Platform != "truenas" || appRes.Host != "truenas-main" {
+ t.Fatalf("unexpected canonical app resource: %+v", appRes)
+ }
+}
+
func TestExecuteQuerySurfacesIncludeGovernedMetadata(t *testing.T) {
state := models.StateSnapshot{
Nodes: []models.Node{
@@ -936,11 +1138,11 @@ func TestExecuteListInfrastructurePaginationAndDockerFilter(t *testing.T) {
if err := json.Unmarshal([]byte(result.Content[0].Text), &dockerResp); err != nil {
t.Fatalf("decode docker response: %v", err)
}
- if len(dockerResp.DockerHosts) != 1 || dockerResp.DockerHosts[0].Hostname != "dock1" {
- t.Fatalf("unexpected docker hosts: %+v", dockerResp.DockerHosts)
+ if len(dockerResp.AppContainers) != 1 || dockerResp.AppContainers[0].Name != "app" {
+ t.Fatalf("unexpected app containers: %+v", dockerResp.AppContainers)
}
- if len(dockerResp.DockerHosts[0].Containers) != 1 || dockerResp.DockerHosts[0].Containers[0].State != "running" {
- t.Fatalf("unexpected docker containers: %+v", dockerResp.DockerHosts[0].Containers)
+ if dockerResp.AppContainers[0].Host != "dock1" || dockerResp.AppContainers[0].Status != "running" || dockerResp.AppContainers[0].Platform != "docker" {
+ t.Fatalf("unexpected app container summary: %+v", dockerResp.AppContainers[0])
}
}
@@ -1131,7 +1333,7 @@ func TestInfrastructureResponse_UsesCanonicalEmptyCollections(t *testing.T) {
t.Fatalf("decode empty infrastructure response: %v", err)
}
- for _, key := range []string{"nodes", "vms", "containers", "docker_hosts", "k8s_clusters", "k8s_nodes", "k8s_pods", "k8s_deployments"} {
+ for _, key := range []string{"systems", "nodes", "vms", "containers", "app_containers", "docker_hosts", "storage_pools", "physical_disks", "k8s_clusters", "k8s_nodes", "k8s_pods", "k8s_deployments"} {
values, ok := decoded[key].([]any)
if !ok || len(values) != 0 {
t.Fatalf("expected %s to serialize as an empty array, got %T (%v)", key, decoded[key], decoded[key])