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.

Lock VMware phase-1 exclusion integrity

rcourtmandd5f099cda3d
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index f7cef10c5e..741d541e10 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -205,6 +205,14 @@ canonical resource capabilities and tool routing must stay read-only in phase
1: shared `pulse_read` and `pulse_query` may expose VMware-backed context, but
`pulse_control` must not grow VMware verbs and VMware-backed resources must not
advertise action metadata that implies a supported VMware admin plane.
+That same capability boundary also governs resolved-context enforcement inside
+`internal/ai/chat/context_prefetch.go`, `internal/ai/tools/tools_query.go`, and
+`internal/ai/tools/tools_control.go`. Once the shared runtime has resolved a
+canonical VMware-backed `vm` or `system-container`, Assistant summaries may not
+emit `pulse_control` guest instructions for it, shared resource registrations
+must stay limited to read-side actions, and any attempted `pulse_control`
+restart/stop/shutdown path must fail as a read-only denial instead of falling
+through to legacy guest resolution or provider-local control assumptions.
That same VMware AI rule also includes the investigation path. Alarm, health,
event, task, metrics-history, and snapshot-tree context for VMware-backed
resources must stay reachable through those same shared read/query surfaces
diff --git a/internal/ai/chat/context_prefetch.go b/internal/ai/chat/context_prefetch.go
index bb42bcee45..695646f2b8 100644
--- a/internal/ai/chat/context_prefetch.go
+++ b/internal/ai/chat/context_prefetch.go
@@ -21,6 +21,7 @@ type ResourceMention struct {
Policy *unifiedresources.ResourcePolicy
AISafeSummary string
UnifiedResourceID string
+ SupportsControl bool
// Docker-specific: bind mounts (source -> destination)
BindMounts []MountInfo
// Full routing chain (for Docker containers)
@@ -62,6 +63,20 @@ func resourceMentionGovernance(resource *unifiedresources.Resource) (*unifiedres
return unifiedresources.CanonicalGovernanceMetadata(resource)
}
+func resourceSupportsControl(resourceType string, resource *unifiedresources.Resource) bool {
+ switch tools.CanonicalDiscoveryResourceType(resourceType) {
+ case "vm", "system-container":
+ return resource != nil && resource.Proxmox != nil
+ case "app-container":
+ if resource == nil {
+ return false
+ }
+ return resource.Docker != nil || resource.TrueNAS != nil
+ default:
+ return false
+ }
+}
+
// Prefetch analyzes a user message and proactively gathers relevant context.
// When structuredMentions are provided (from the frontend @ autocomplete), they are used
// directly instead of fuzzy-matching resource names from the message text.
@@ -209,6 +224,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe
Policy: policy,
AISafeSummary: aiSafeSummary,
UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource),
+ SupportsControl: resourceSupportsControl("vm", resolved.Resource),
})
}
}
@@ -244,6 +260,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe
Policy: policy,
AISafeSummary: aiSafeSummary,
UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource),
+ SupportsControl: resourceSupportsControl("system-container", resolved.Resource),
})
}
}
@@ -555,6 +572,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen
AISafeSummary: aiSafeSummary,
UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),
TargetHost: loc.TargetHost,
+ SupportsControl: resourceSupportsControl("vm", resolved.Resource),
})
case "system-container":
@@ -576,6 +594,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen
AISafeSummary: aiSafeSummary,
UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),
TargetHost: loc.TargetHost,
+ SupportsControl: resourceSupportsControl("system-container", resolved.Resource),
})
case "app-container":
@@ -977,7 +996,7 @@ func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention, dis
var sb strings.Builder
sb.WriteString("=== PULSE MONITORING DATA (AUTHORITATIVE) ===\n")
- sb.WriteString("This is verified data from Pulse agents. Canonical resource policy is enforced below.\n")
+ sb.WriteString("This is verified data from Pulse monitoring sources. Canonical resource policy is enforced below.\n")
sb.WriteString(unifiedresources.ResourcePolicyGovernedSummaryPreamble())
sb.WriteString("\n\n")
@@ -1052,10 +1071,15 @@ func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention, dis
sb.WriteString(fmt.Sprintf("## %s\n", mention.Name))
sb.WriteString(fmt.Sprintf("Type: %s | Target: %s\n", mention.ResourceType, mention.TargetID))
- // Include VMID for VMs and system containers — the AI needs this for pulse_control guest operations
+ // Include guest identifier, but only emit control instructions for platforms
+ // that are actually on the shared control surface.
if (mention.ResourceType == "system-container" || mention.ResourceType == "vm") && mention.ResourceID != "" {
sb.WriteString(fmt.Sprintf("VMID: %s\n", mention.ResourceID))
- sb.WriteString(fmt.Sprintf("To control this guest, use: pulse_control type=\"guest\", guest_id=\"%s\", action=\"start|stop|shutdown|restart\"\n", mention.ResourceID))
+ if mention.SupportsControl {
+ sb.WriteString(fmt.Sprintf("To control this guest, use: pulse_control type=\"guest\", guest_id=\"%s\", action=\"start|stop|shutdown|restart\"\n", mention.ResourceID))
+ } else {
+ sb.WriteString("This guest is read-only in Pulse. Do NOT use pulse_control for this resource.\n")
+ }
}
if hasDiscovery {
@@ -1132,7 +1156,9 @@ func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention, dis
} else {
// No discovery - provide basic routing without suggesting discovery calls
sb.WriteString(fmt.Sprintf("target_host: \"%s\"\n", mention.Name))
- if mention.ResourceType == "system-container" || mention.ResourceType == "vm" {
+ if (mention.ResourceType == "system-container" || mention.ResourceType == "vm") && !mention.SupportsControl {
+ sb.WriteString("Use pulse_query or pulse_read only — do NOT call pulse_control or pulse_discovery.\n")
+ } else if mention.ResourceType == "system-container" || mention.ResourceType == "vm" {
sb.WriteString("Proceed directly with pulse_control — do NOT call pulse_discovery.\n")
} else {
sb.WriteString("Proceed directly with pulse_control — do NOT call pulse_discovery.\n")
diff --git a/internal/ai/chat/context_prefetch_additional_test.go b/internal/ai/chat/context_prefetch_additional_test.go
index b50a412a9d..7f4ace5948 100644
--- a/internal/ai/chat/context_prefetch_additional_test.go
+++ b/internal/ai/chat/context_prefetch_additional_test.go
@@ -381,6 +381,9 @@ func TestContextPrefetcher_ResolveStructuredMentions_VMwareCanonicalIDs(t *testi
if mentions[0].ResourceType != "vm" || mentions[0].ResourceID != "vm-201" || mentions[0].TargetID != "esxi-01.lab.local" {
t.Fatalf("expected VMware VM routing coordinates, got %+v", mentions[0])
}
+ if mentions[0].SupportsControl {
+ t.Fatalf("expected VMware VM mention to stay read-only, got %+v", mentions[0])
+ }
if mentions[0].UnifiedResourceID != vmResourceID {
t.Fatalf("expected VMware VM unified resource id, got %+v", mentions[0])
}
@@ -513,6 +516,30 @@ func TestContextPrefetcher_FormatContextSummary(t *testing.T) {
}
}
+func TestContextPrefetcher_FormatContextSummary_VMwareGuestStaysReadOnly(t *testing.T) {
+ prefetcher := NewContextPrefetcher(newTestReadState(models.StateSnapshot{}), nil)
+
+ summary := prefetcher.formatContextSummary([]ResourceMention{{
+ Name: "app-01",
+ ResourceType: "vm",
+ ResourceID: "vm-201",
+ TargetID: "esxi-01.lab.local",
+ TargetHost: "esxi-01.lab.local",
+ UnifiedResourceID: "vmware-vm-1",
+ SupportsControl: false,
+ }}, nil)
+
+ if !strings.Contains(summary, "read-only in Pulse") {
+ t.Fatalf("expected VMware read-only note, got %q", summary)
+ }
+ if strings.Contains(summary, "To control this guest, use: pulse_control") {
+ t.Fatalf("expected VMware summary to avoid guest-control instructions, got %q", summary)
+ }
+ if !strings.Contains(summary, "Use pulse_query or pulse_read only") {
+ t.Fatalf("expected VMware summary to direct the assistant to read-only tools, got %q", summary)
+ }
+}
+
func TestContextPrefetcher_ExtractHelpers(t *testing.T) {
words := extractWords("hello-123 world")
if len(words) != 3 {
diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.go
index 60294e8f7a..cac85213f3 100644
--- a/internal/ai/tools/tools_control.go
+++ b/internal/ai/tools/tools_control.go
@@ -111,11 +111,7 @@ func (e *PulseToolExecutor) executeControlResource(ctx context.Context, args map
return NewErrorResult(fmt.Errorf("resource '%s' has not been discovered in this session. Use pulse_query to find it first", resourceRef)), nil
}
if validation.ErrorMsg != "" {
- log.Warn().
- Str("resource", resourceRef).
- Str("action", action).
- Str("validation_error", validation.ErrorMsg).
- Msg("[ControlResource] Continuing with discovered resource despite validation warning")
+ return NewErrorResult(errors.New(validation.ErrorMsg)), nil
}
resolved := validation.Resource
@@ -530,6 +526,9 @@ func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[st
return NewToolResponseResult(validation.StrictError.ToToolResponse()), nil
}
if validation.ErrorMsg != "" {
+ if validation.Resource != nil {
+ return NewErrorResult(errors.New(validation.ErrorMsg)), nil
+ }
// Soft validation - log warning but allow operation
log.Warn().
Str("guest_id", guestID).
diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.go
index c12ebd49ef..a84fe18f4f 100644
--- a/internal/ai/tools/tools_query.go
+++ b/internal/ai/tools/tools_query.go
@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"sort"
+ "strconv"
"strings"
"sync"
"time"
@@ -2242,10 +2243,22 @@ func metricTotalGB(value *unifiedresources.MetricValue) float64 {
return float64(*value.Total) / (1024 * 1024 * 1024)
}
+func firstNonEmptyString(values ...string) string {
+ for _, value := range values {
+ trimmed := strings.TrimSpace(value)
+ if trimmed != "" {
+ return trimmed
+ }
+ }
+ return ""
+}
+
func canonicalResourcePlatform(resource unifiedresources.Resource) string {
switch {
case resource.TrueNAS != nil || resourceHasTag(resource, "truenas"):
return "truenas"
+ case resource.VMware != nil:
+ return "vmware-vsphere"
case resource.Proxmox != nil:
return "proxmox"
case resource.Docker != nil:
@@ -2361,6 +2374,218 @@ func guestExecutorActions() []string {
return []string{"query", "get", "logs", "console", "exec", "start", "stop", "shutdown", "restart", "delete"}
}
+func readOnlyResourceActions() []string {
+ return []string{"query", "get"}
+}
+
+func canonicalGuestResourceType(kind string) (unifiedresources.ResourceType, bool) {
+ switch strings.TrimSpace(kind) {
+ case "vm":
+ return unifiedresources.ResourceTypeVM, true
+ case "system-container":
+ return unifiedresources.ResourceTypeSystemContainer, true
+ default:
+ return "", false
+ }
+}
+
+func canonicalGuestManagedID(resource unifiedresources.Resource) string {
+ if resource.Proxmox != nil && resource.Proxmox.VMID > 0 {
+ return strconv.Itoa(resource.Proxmox.VMID)
+ }
+ if resource.VMware != nil {
+ return strings.TrimSpace(resource.VMware.ManagedObjectID)
+ }
+ return ""
+}
+
+func canonicalGuestTarget(resource unifiedresources.Resource) string {
+ if resource.Proxmox != nil {
+ return strings.TrimSpace(resource.Proxmox.NodeName)
+ }
+ if resource.VMware != nil {
+ return firstNonEmptyString(
+ resource.VMware.RuntimeHostName,
+ resource.VMware.RuntimeHostID,
+ resource.ParentName,
+ resource.VMware.ConnectionName,
+ )
+ }
+ return strings.TrimSpace(resource.ParentName)
+}
+
+func canonicalGuestSearchCandidates(kind string, resource unifiedresources.Resource) []string {
+ candidates := []string{
+ resourceDisplayName(resource),
+ strings.TrimSpace(resource.ID),
+ }
+ if managedID := canonicalGuestManagedID(resource); managedID != "" {
+ candidates = append(candidates, managedID)
+ }
+ if host := canonicalGuestTarget(resource); host != "" {
+ candidates = append(candidates, host)
+ }
+ candidates = append(candidates, resource.Identity.IPAddresses...)
+ candidates = append(candidates, resource.Tags...)
+
+ if resource.Proxmox != nil && resource.Proxmox.VMID > 0 {
+ vmid := strconv.Itoa(resource.Proxmox.VMID)
+ switch strings.TrimSpace(kind) {
+ case "vm":
+ candidates = append(candidates, "vm"+vmid)
+ case "system-container":
+ candidates = append(candidates, "system-container"+vmid)
+ }
+ }
+
+ return candidates
+}
+
+func canonicalGuestMatchesResourceID(kind, resourceID string, resource unifiedresources.Resource) bool {
+ query := strings.TrimSpace(resourceID)
+ if query == "" {
+ return false
+ }
+ for _, candidate := range canonicalGuestSearchCandidates(kind, resource) {
+ if strings.EqualFold(strings.TrimSpace(candidate), query) {
+ return true
+ }
+ }
+ return false
+}
+
+func findCanonicalGuestResource(provider UnifiedResourceProvider, kind, resourceID string) (unifiedresources.Resource, bool) {
+ if provider == nil {
+ return unifiedresources.Resource{}, false
+ }
+ resourceType, ok := canonicalGuestResourceType(kind)
+ if !ok {
+ return unifiedresources.Resource{}, false
+ }
+ for _, resource := range provider.GetByType(resourceType) {
+ if canonicalGuestMatchesResourceID(kind, resourceID, resource) {
+ return resource, true
+ }
+ }
+ return unifiedresources.Resource{}, false
+}
+
+func canonicalGuestRegistration(kind string, resource unifiedresources.Resource) (ResourceRegistration, bool) {
+ kind = strings.TrimSpace(kind)
+ name := strings.TrimSpace(resourceDisplayName(resource))
+ providerUID := firstNonEmptyString(canonicalGuestManagedID(resource), resource.ID)
+ if kind == "" || name == "" || providerUID == "" {
+ return ResourceRegistration{}, false
+ }
+
+ host := canonicalGuestTarget(resource)
+ aliases := appendUniqueStrings(nil, canonicalGuestSearchCandidates(kind, resource)...)
+ reg := ResourceRegistration{
+ Kind: kind,
+ ProviderUID: providerUID,
+ Name: name,
+ Aliases: aliases,
+ HostUID: host,
+ HostName: host,
+ Node: host,
+ }
+
+ switch kind {
+ case "vm":
+ reg.LocationChain = []string{"agent:" + firstNonEmptyString(host, name), "vm:" + name}
+ case "system-container":
+ reg.LocationChain = []string{"agent:" + firstNonEmptyString(host, name), "system-container:" + name}
+ }
+
+ switch canonicalResourcePlatform(resource) {
+ case "proxmox":
+ if resource.Proxmox == nil || host == "" {
+ return ResourceRegistration{}, false
+ }
+ reg.VMID = resource.Proxmox.VMID
+ reg.HostUID = strings.TrimSpace(resource.Proxmox.NodeName)
+ reg.HostName = strings.TrimSpace(resource.Proxmox.NodeName)
+ reg.Node = strings.TrimSpace(resource.Proxmox.NodeName)
+ adapter := "qm"
+ if kind == "system-container" {
+ adapter = "pct"
+ }
+ reg.Executors = []ExecutorRegistration{{
+ ExecutorID: reg.Node,
+ Adapter: adapter,
+ Actions: guestExecutorActions(),
+ Priority: 10,
+ }}
+ default:
+ executorID := firstNonEmptyString(host, name)
+ reg.Executors = []ExecutorRegistration{{
+ ExecutorID: executorID,
+ Adapter: canonicalResourcePlatform(resource),
+ Actions: readOnlyResourceActions(),
+ Priority: 10,
+ }}
+ }
+
+ return reg, true
+}
+
+func canonicalGuestResponse(kind string, resource unifiedresources.Resource, governance *governedQueryMetadataResolver) ResourceResponse {
+ candidates := append([]string{resourceDisplayName(resource), resource.ID}, canonicalGuestSearchCandidates(kind, resource)...)
+ response := EmptyResourceResponse()
+ response.GovernedResourceMetadata = governance.Resolve(candidates...)
+ response.Type = kind
+ response.ID = firstNonEmptyString(resource.ID, canonicalGuestManagedID(resource))
+ response.Name = resourceDisplayName(resource)
+ response.Status = string(resource.Status)
+ response.Platform = canonicalResourcePlatform(resource)
+ response.Node = canonicalGuestTarget(resource)
+ response.Host = canonicalGuestTarget(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.Proxmox != nil {
+ response.ID = firstNonEmptyString(resource.ID, resource.Proxmox.SourceID)
+ response.Node = strings.TrimSpace(resource.Proxmox.NodeName)
+ response.CPU.Cores = resource.Proxmox.CPUs
+ response.OS = strings.TrimSpace(resource.Proxmox.OSName)
+ if !resource.Proxmox.LastBackup.IsZero() {
+ t := resource.Proxmox.LastBackup
+ response.LastBackup = &t
+ }
+ }
+
+ if resource.VMware != nil {
+ response.ID = firstNonEmptyString(resource.ID, resource.VMware.ManagedObjectID)
+ response.Node = firstNonEmptyString(response.Node, resource.VMware.RuntimeHostName, resource.ParentName)
+ response.Host = firstNonEmptyString(response.Host, resource.VMware.RuntimeHostName, resource.ParentName)
+ if response.CPU.Cores == 0 {
+ response.CPU.Cores = resource.VMware.CPUCount
+ }
+ if response.Memory.TotalGB == 0 && resource.VMware.MemorySizeMiB > 0 {
+ response.Memory.TotalGB = float64(resource.VMware.MemorySizeMiB) / 1024
+ }
+ if response.OS == "" {
+ response.OS = strings.TrimSpace(resource.VMware.GuestOSFamily)
+ }
+ }
+
+ return response.NormalizeCollections()
+}
+
func canonicalAppContainerAdapter(resource unifiedresources.Resource) string {
switch canonicalResourcePlatform(resource) {
case "docker":
@@ -3775,6 +4000,13 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
}), nil
case "vm":
+ if resource, ok := findCanonicalGuestResource(e.unifiedResourceProvider, "vm", resourceID); ok {
+ response := canonicalGuestResponse("vm", resource, governance)
+ if reg, ok := canonicalGuestRegistration("vm", resource); ok {
+ e.registerResolvedResourceWithExplicitAccess(reg)
+ }
+ return NewJSONResult(response), nil
+ }
for _, vm := range rs.VMs() {
if fmt.Sprintf("%d", vm.VMID()) == resourceID || vm.Name() == resourceID || vm.ID() == resourceID {
used := vm.MemoryUsed()
@@ -3830,6 +4062,13 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
}), nil
case "system-container":
+ if resource, ok := findCanonicalGuestResource(e.unifiedResourceProvider, "system-container", resourceID); ok {
+ response := canonicalGuestResponse("system-container", resource, governance)
+ if reg, ok := canonicalGuestRegistration("system-container", resource); ok {
+ e.registerResolvedResourceWithExplicitAccess(reg)
+ }
+ return NewJSONResult(response), nil
+ }
for _, ct := range rs.Containers() {
if fmt.Sprintf("%d", ct.VMID()) == resourceID || ct.Name() == resourceID || ct.ID() == resourceID {
used := ct.MemoryUsed()
@@ -4561,11 +4800,15 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
}
systemResources := []unifiedresources.Resource{}
+ vmResources := []unifiedresources.Resource{}
+ systemContainerResources := []unifiedresources.Resource{}
appContainerResources := []unifiedresources.Resource{}
storagePoolResources := []unifiedresources.Resource{}
physicalDiskResources := []unifiedresources.Resource{}
if e.unifiedResourceProvider != nil {
systemResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAgent))
+ vmResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeVM))
+ systemContainerResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeSystemContainer))
appContainerResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypeAppContainer))
physicalDiskResources = sortedResourcesByName(e.unifiedResourceProvider.GetByType(unifiedresources.ResourceTypePhysicalDisk))
storagePoolResources = canonicalStoragePoolResources(e.unifiedResourceProvider)
@@ -4636,7 +4879,37 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
}
}
- if typeFilter == "" || typeFilter == "vm" {
+ if (typeFilter == "" || typeFilter == "vm") && len(vmResources) > 0 {
+ for _, resource := range vmResources {
+ status := string(resource.Status)
+ if !statusMatchesFilter(status, statusFilter) {
+ continue
+ }
+ candidates := canonicalGuestSearchCandidates("vm", resource)
+ if !matchesQuery(queryLower, candidates...) {
+ continue
+ }
+
+ vmid := 0
+ if resource.Proxmox != nil && resource.Proxmox.VMID > 0 {
+ vmid = resource.Proxmox.VMID
+ }
+ node := canonicalGuestTarget(resource)
+ metadataCandidates := append([]string{resourceDisplayName(resource), resource.ID}, candidates...)
+ addMatch(ResourceMatch{
+ GovernedResourceMetadata: governance.Resolve(metadataCandidates...),
+ Type: "vm",
+ ID: resource.ID,
+ Name: resourceDisplayName(resource),
+ Status: status,
+ Node: node,
+ NodeHasAgent: connectedAgentHostnames[node],
+ Platform: canonicalResourcePlatform(resource),
+ VMID: vmid,
+ AgentConnected: resourceAgentConnected(resource, connectedAgentHostnames),
+ })
+ }
+ } else if typeFilter == "" || typeFilter == "vm" {
for _, vm := range rs.VMs() {
status := string(vm.Status())
if !statusMatchesFilter(status, statusFilter) {
@@ -4659,13 +4932,44 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
Status: status,
Node: vm.Node(),
NodeHasAgent: connectedAgentHostnames[vm.Node()],
+ Platform: "proxmox",
VMID: vm.VMID(),
AgentConnected: connectedAgentHostnames[vm.Name()],
})
}
}
- if typeFilter == "" || typeFilter == "system-container" {
+ if (typeFilter == "" || typeFilter == "system-container") && len(systemContainerResources) > 0 {
+ for _, resource := range systemContainerResources {
+ status := string(resource.Status)
+ if !statusMatchesFilter(status, statusFilter) {
+ continue
+ }
+ candidates := canonicalGuestSearchCandidates("system-container", resource)
+ if !matchesQuery(queryLower, candidates...) {
+ continue
+ }
+
+ vmid := 0
+ if resource.Proxmox != nil && resource.Proxmox.VMID > 0 {
+ vmid = resource.Proxmox.VMID
+ }
+ node := canonicalGuestTarget(resource)
+ metadataCandidates := append([]string{resourceDisplayName(resource), resource.ID}, candidates...)
+ addMatch(ResourceMatch{
+ GovernedResourceMetadata: governance.Resolve(metadataCandidates...),
+ Type: "system-container",
+ ID: resource.ID,
+ Name: resourceDisplayName(resource),
+ Status: status,
+ Node: node,
+ NodeHasAgent: connectedAgentHostnames[node],
+ Platform: canonicalResourcePlatform(resource),
+ VMID: vmid,
+ AgentConnected: resourceAgentConnected(resource, connectedAgentHostnames),
+ })
+ }
+ } else if typeFilter == "" || typeFilter == "system-container" {
for _, ct := range rs.Containers() {
status := string(ct.Status())
if !statusMatchesFilter(status, statusFilter) {
@@ -4688,6 +4992,7 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
Status: status,
Node: ct.Node(),
NodeHasAgent: connectedAgentHostnames[ct.Node()],
+ Platform: "proxmox",
VMID: ct.VMID(),
AgentConnected: connectedAgentHostnames[ct.Name()],
})
@@ -4935,40 +5240,52 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
}},
}
case "vm":
- reg = ResourceRegistration{
- Kind: "vm",
- ProviderUID: fmt.Sprintf("%d", match.VMID),
- Name: match.Name,
- Aliases: []string{match.Name, fmt.Sprintf("%d", match.VMID), match.ID},
- HostUID: match.Node,
- HostName: match.Node,
- VMID: match.VMID,
- Node: match.Node,
- LocationChain: []string{"node:" + match.Node, "vm:" + match.Name},
- Executors: []ExecutorRegistration{{
- ExecutorID: match.Node,
- Adapter: "qm",
- Actions: guestExecutorActions(),
- Priority: 10,
- }},
+ if resource, ok := findCanonicalGuestResource(e.unifiedResourceProvider, "vm", match.ID); ok {
+ reg, _ = canonicalGuestRegistration("vm", resource)
+ } else if resource, ok := findCanonicalGuestResource(e.unifiedResourceProvider, "vm", match.Name); ok {
+ reg, _ = canonicalGuestRegistration("vm", resource)
+ } else {
+ reg = ResourceRegistration{
+ Kind: "vm",
+ ProviderUID: fmt.Sprintf("%d", match.VMID),
+ Name: match.Name,
+ Aliases: []string{match.Name, fmt.Sprintf("%d", match.VMID), match.ID},
+ HostUID: match.Node,
+ HostName: match.Node,
+ VMID: match.VMID,
+ Node: match.Node,
+ LocationChain: []string{"node:" + match.Node, "vm:" + match.Name},
+ Executors: []ExecutorRegistration{{
+ ExecutorID: match.Node,
+ Adapter: "qm",
+ Actions: guestExecutorActions(),
+ Priority: 10,
+ }},
+ }
}
case "system-container":
- reg = ResourceRegistration{
- Kind: "system-container",
- ProviderUID: fmt.Sprintf("%d", match.VMID),
- Name: match.Name,
- Aliases: []string{match.Name, fmt.Sprintf("%d", match.VMID), match.ID},
- HostUID: match.Node,
- HostName: match.Node,
- VMID: match.VMID,
- Node: match.Node,
- LocationChain: []string{"node:" + match.Node, "system-container:" + match.Name},
- Executors: []ExecutorRegistration{{
- ExecutorID: match.Node,
- Adapter: "pct",
- Actions: guestExecutorActions(),
- Priority: 10,
- }},
+ if resource, ok := findCanonicalGuestResource(e.unifiedResourceProvider, "system-container", match.ID); ok {
+ reg, _ = canonicalGuestRegistration("system-container", resource)
+ } else if resource, ok := findCanonicalGuestResource(e.unifiedResourceProvider, "system-container", match.Name); ok {
+ reg, _ = canonicalGuestRegistration("system-container", resource)
+ } else {
+ reg = ResourceRegistration{
+ Kind: "system-container",
+ ProviderUID: fmt.Sprintf("%d", match.VMID),
+ Name: match.Name,
+ Aliases: []string{match.Name, fmt.Sprintf("%d", match.VMID), match.ID},
+ HostUID: match.Node,
+ HostName: match.Node,
+ VMID: match.VMID,
+ Node: match.Node,
+ LocationChain: []string{"node:" + match.Node, "system-container:" + match.Name},
+ Executors: []ExecutorRegistration{{
+ ExecutorID: match.Node,
+ Adapter: "pct",
+ Actions: guestExecutorActions(),
+ Priority: 10,
+ }},
+ }
}
case "docker-host":
reg = ResourceRegistration{
diff --git a/internal/ai/tools/tools_query_test.go b/internal/ai/tools/tools_query_test.go
index a2b9885981..91bed87d8c 100644
--- a/internal/ai/tools/tools_query_test.go
+++ b/internal/ai/tools/tools_query_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
@@ -259,6 +260,60 @@ func newTrueNASUnifiedQueryProvider(t *testing.T) *registryUnifiedQueryProvider
return &registryUnifiedQueryProvider{ResourceRegistry: registry}
}
+func newVMwareUnifiedQueryProvider(t *testing.T) *registryUnifiedQueryProvider {
+ t.Helper()
+
+ now := time.Now().UTC()
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestRecords(unifiedresources.SourceVMware, []unifiedresources.IngestRecord{
+ {
+ SourceID: "vc-1:host:host-101",
+ Resource: unifiedresources.Resource{
+ ID: "vmware-host-1",
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: unifiedresources.StatusOnline,
+ LastSeen: now,
+ UpdatedAt: now,
+ VMware: &unifiedresources.VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ },
+ },
+ Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"esxi-01.lab.local"}},
+ },
+ {
+ SourceID: "vc-1:vm:vm-201",
+ Resource: unifiedresources.Resource{
+ ID: "vmware-vm-1",
+ Type: unifiedresources.ResourceTypeVM,
+ Name: "app-01",
+ Status: unifiedresources.StatusOnline,
+ LastSeen: now,
+ UpdatedAt: now,
+ ParentName: "esxi-01.lab.local",
+ VMware: &unifiedresources.VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "vm-201",
+ EntityType: "vm",
+ RuntimeHostName: "esxi-01.lab.local",
+ GuestOSFamily: "ubuntu64Guest",
+ CPUCount: 4,
+ MemorySizeMiB: 8192,
+ },
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ Hostnames: []string{"app-01"},
+ IPAddresses: []string{"192.0.2.50"},
+ },
+ },
+ })
+ 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)
@@ -939,6 +994,104 @@ func TestExecuteGetResource_RegistersTrueNASAppContainerForCanonicalControl(t *t
}
}
+func TestExecuteGetResource_RegistersVMwareVMAsReadOnly(t *testing.T) {
+ provider := newVMwareUnifiedQueryProvider(t)
+ resolved := &mockResolvedContext{
+ resources: make(map[string]ResolvedResourceInfo),
+ aliases: make(map[string]ResolvedResourceInfo),
+ }
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ ReadState: provider.ResourceRegistry,
+ })
+ executor.SetResolvedContext(resolved)
+
+ result, err := executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ "resource_id": "app-01",
+ })
+ if err != nil {
+ t.Fatalf("get vm: unexpected error: %v", err)
+ }
+
+ var response ResourceResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response.Platform != "vmware-vsphere" {
+ t.Fatalf("expected VMware platform on response, got %+v", response)
+ }
+ if response.Node != "esxi-01.lab.local" {
+ t.Fatalf("expected VMware runtime host in node field, got %+v", response)
+ }
+
+ info, found := resolved.GetResolvedResourceByAlias("app-01")
+ if !found {
+ t.Fatal("expected resolved context to include VMware VM by alias")
+ }
+ if info.GetAdapter() != "vmware-vsphere" {
+ t.Fatalf("expected VMware adapter, got %q", info.GetAdapter())
+ }
+ if got := strings.Join(info.GetAllowedActions(), ","); got != "query,get" && got != "get,query" {
+ t.Fatalf("expected VMware VM to register read-only actions, got %v", info.GetAllowedActions())
+ }
+
+ controlResult, err := executor.executeControl(context.Background(), map[string]interface{}{
+ "type": "resource",
+ "resource_id": "app-01",
+ "action": "restart",
+ })
+ if err != nil {
+ t.Fatalf("executeControl(type=resource): unexpected error: %v", err)
+ }
+ if !controlResult.IsError {
+ t.Fatalf("expected VMware VM restart to be rejected, got %+v", controlResult)
+ }
+ if !strings.Contains(controlResult.Content[0].Text, "not permitted") {
+ t.Fatalf("expected read-only rejection, got %q", controlResult.Content[0].Text)
+ }
+}
+
+func TestExecuteSearchResources_RegistersVMwareVMAsReadOnly(t *testing.T) {
+ provider := newVMwareUnifiedQueryProvider(t)
+ resolved := &mockResolvedContext{
+ resources: make(map[string]ResolvedResourceInfo),
+ aliases: make(map[string]ResolvedResourceInfo),
+ }
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ ReadState: provider.ResourceRegistry,
+ })
+ executor.SetResolvedContext(resolved)
+
+ result, err := executor.executeSearchResources(context.Background(), map[string]interface{}{
+ "query": "app-01",
+ "type": "vm",
+ })
+ if err != nil {
+ t.Fatalf("search vm: unexpected error: %v", err)
+ }
+
+ var response ResourceSearchResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &response); err != nil {
+ t.Fatalf("decode search response: %v", err)
+ }
+ if len(response.Matches) != 1 {
+ t.Fatalf("expected one VMware search match, got %+v", response.Matches)
+ }
+ if response.Matches[0].Platform != "vmware-vsphere" {
+ t.Fatalf("expected VMware platform on search match, got %+v", response.Matches[0])
+ }
+
+ info, found := resolved.GetResolvedResourceByAlias("app-01")
+ if !found {
+ t.Fatal("expected VMware VM search result to register in resolved context")
+ }
+ if got := strings.Join(info.GetAllowedActions(), ","); got != "query,get" && got != "get,query" {
+ t.Fatalf("expected VMware search registration to remain read-only, got %v", info.GetAllowedActions())
+ }
+}
+
func TestExecuteQuerySurfacesIncludeGovernedMetadata(t *testing.T) {
state := models.StateSnapshot{
Nodes: []models.Node{
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index db589ce0e0..3317aadf38 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -53,6 +53,42 @@ func TestRouterRouteInventory(t *testing.T) {
}
}
+func TestRouterRouteInventory_VMwarePhase1ExclusionIntegrity(t *testing.T) {
+ literalRoutes, _, _ := parseRouterRoutes(t)
+ actual := sliceToSet(t, literalRoutes, "router routes")
+
+ forbidden := []string{
+ "/api/vmware/hosts",
+ "/api/vmware/vms",
+ "/api/vmware/datastores",
+ "/api/vmware/events",
+ "/api/vmware/tasks",
+ "/api/vmware/alarms",
+ }
+ for _, route := range forbidden {
+ if _, ok := actual[route]; ok {
+ t.Fatalf("vmware phase-1 exclusion failed: unexpected route %q is registered", route)
+ }
+ }
+
+ var vmwareRoutes []string
+ for route := range actual {
+ if strings.HasPrefix(route, "/api/vmware/") {
+ vmwareRoutes = append(vmwareRoutes, route)
+ }
+ }
+ sort.Strings(vmwareRoutes)
+
+ expected := []string{
+ "/api/vmware/connections",
+ "/api/vmware/connections/",
+ "/api/vmware/connections/test",
+ }
+ if strings.Join(vmwareRoutes, ",") != strings.Join(expected, ",") {
+ t.Fatalf("vmware phase-1 route family drifted: got %v, want %v", vmwareRoutes, expected)
+ }
+}
+
func parseRouterRoutes(t *testing.T) ([]string, []string, []string) {
t.Helper()
diff --git a/tests/integration/tests/41-vmware-phase1-exclusion-integrity.spec.ts b/tests/integration/tests/41-vmware-phase1-exclusion-integrity.spec.ts
new file mode 100644
index 0000000000..68fe4dd913
--- /dev/null
+++ b/tests/integration/tests/41-vmware-phase1-exclusion-integrity.spec.ts
@@ -0,0 +1,180 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { expect, test as base } from '@playwright/test';
+
+import { createAuthenticatedStorageState } from './helpers';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const SCREENSHOT_PATH = '/tmp/vmware-phase1-exclusion-integrity.png';
+const RESOURCE_ID = 'vc-1:vm:vm-201';
+const RESOURCE_ID_ENCODED = encodeURIComponent(RESOURCE_ID);
+
+type WorkerFixtures = {
+ authStorageStatePath: string;
+};
+
+const test = base.extend<{}, WorkerFixtures>({
+ storageState: async ({ authStorageStatePath }, use) => {
+ await use(authStorageStatePath);
+ },
+ authStorageStatePath: [async ({ browser }, use, workerInfo) => {
+ const storageStatePath = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'tmp',
+ 'playwright-auth',
+ `vmware-phase1-exclusion-integrity-${workerInfo.project.name}.json`,
+ );
+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
+ await createAuthenticatedStorageState(browser, storageStatePath);
+ try {
+ await use(storageStatePath);
+ } finally {
+ fs.rmSync(storageStatePath, { force: true });
+ }
+ }, { scope: 'worker' }],
+});
+
+test.describe('VMware phase-1 exclusion integrity', () => {
+ test.setTimeout(180_000);
+
+ test('keeps VMware resources out of recovery and provider-local admin routes', async ({
+ page,
+ }) => {
+ let unexpectedVmwareApiCall: string | null = null;
+ let unexpectedRecoveryApiCall: string | null = null;
+
+ await page.route('**/api/vmware/**', async (route) => {
+ unexpectedVmwareApiCall = route.request().url();
+ await route.abort();
+ });
+
+ await page.route('**/api/recovery/**', async (route) => {
+ unexpectedRecoveryApiCall = route.request().url();
+ await route.abort();
+ });
+
+ await page.route('**/api/resources**', async (route) => {
+ const requestUrl = new URL(route.request().url());
+
+ if (requestUrl.pathname === '/api/resources') {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ data: [
+ {
+ id: RESOURCE_ID,
+ type: 'vm',
+ name: 'app-01.lab.local',
+ displayName: 'App 01',
+ platformId: RESOURCE_ID,
+ platformType: 'vmware-vsphere',
+ sourceType: 'api',
+ sources: ['vmware-vsphere'],
+ status: 'running',
+ lastSeen: '2026-03-30T21:10:00Z',
+ canonicalIdentity: {
+ displayName: 'App 01',
+ hostname: 'app-01.lab.local',
+ platformId: RESOURCE_ID,
+ },
+ vmware: {
+ connectionId: 'vc-1',
+ connectionName: 'Lab VC',
+ vcenterHost: 'vc.lab.local',
+ managedObjectId: 'vm-201',
+ entityType: 'VirtualMachine',
+ overallStatus: 'green',
+ powerState: 'poweredOn',
+ runtimeHostName: 'esxi-01.lab.local',
+ guestOsFamily: 'ubuntu64Guest',
+ snapshotCount: 2,
+ },
+ platformData: {
+ sources: ['vmware-vsphere'],
+ },
+ },
+ ],
+ meta: {
+ page: 1,
+ limit: 100,
+ total: 1,
+ totalPages: 1,
+ },
+ }),
+ });
+ return;
+ }
+
+ if (requestUrl.pathname === `/api/resources/${RESOURCE_ID_ENCODED}/facets`) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ capabilities: [],
+ relationships: [],
+ recentChanges: [],
+ counts: {
+ recentChanges: 0,
+ },
+ }),
+ });
+ return;
+ }
+
+ await route.continue();
+ });
+
+ await page.route('**/api/ai/intelligence**', async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ resource_id: RESOURCE_ID,
+ resource_name: 'App 01',
+ resource_type: 'vm',
+ health: {
+ score: 90,
+ grade: 'A',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Phase-1 VMware context remains read-only.',
+ },
+ dependencies: [],
+ dependents: [],
+ correlations: [],
+ recent_changes: [],
+ note_count: 0,
+ }),
+ });
+ });
+
+ await page.goto(
+ `/infrastructure?source=vmware-vsphere&resource=${encodeURIComponent(RESOURCE_ID)}`,
+ {
+ waitUntil: 'domcontentloaded',
+ },
+ );
+
+ await expect(page.getByTestId('infrastructure-page')).toBeVisible();
+ await expect(page.getByTestId('resource-vmware-details-section')).toContainText(
+ 'Read-only vCenter context',
+ );
+
+ await page.getByRole('button', { name: 'Show access' }).click();
+
+ await expect(page.getByRole('link', { name: /Open related recovery/i })).toHaveCount(0);
+ await expect(page.getByRole('link', { name: /Open in Recovery/i })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: /^Restart$/ })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: /^Stop$/ })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: /^Shutdown$/ })).toHaveCount(0);
+
+ expect(unexpectedVmwareApiCall).toBeNull();
+ expect(unexpectedRecoveryApiCall).toBeNull();
+
+ await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true });
+ });
+});