Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Normalize API-backed AI read routing hints
rcourtman984bc7c6368a
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 14bafaa161..17229f9b43 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -227,6 +227,15 @@ event, task, metrics-history, and snapshot-tree context for VMware-backedresources must stay reachable through those same shared read/query surfacesand canonical resource links rather than through a VMware-only AI tool orprovider-local incident adapter.+That same shared read/query rule also governs AI prompt hints and prefetch+summaries in `internal/ai/chat/service.go` and+`internal/ai/chat/context_prefetch.go`: API-backed read-only resources such as+VMware-backed `agent` / `vm` / `storage` and TrueNAS-backed host/storage+resources must not inherit synthetic `target_host` log-routing hints from+agent-routed platforms. Shared AI context should carry canonical+`resource_id` guidance for those resources, and `pulse_read action=logs` may+only be suggested when the runtime has an explicit native resource read path+such as supported TrueNAS `app-container` logs.That same VMware AI rule also now includes mention resolution. FrontendAssistant mention payloads for VMware-backed `agent`, `vm`, `storage`, andcanonical `app-container` resources must preserve the shared unified resourcediff --git a/internal/ai/chat/context_prefetch.go b/internal/ai/chat/context_prefetch.goindex 898b9dcf68..15cd2908f9 100644--- a/internal/ai/chat/context_prefetch.go+++ b/internal/ai/chat/context_prefetch.go@@ -17,6 +17,7 @@ type ResourceMention struct {ResourceType string // "vm", "system-container", "app-container", "agent", "node"ResourceID stringTargetID string+ Adapter stringMatchedText string // The actual text that matchedPolicy *unifiedresources.ResourcePolicyAISafeSummary string@@ -231,6 +232,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceType: "vm",ResourceID: resourceID,TargetID: targetID,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -267,6 +269,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceType: "system-container",ResourceID: resourceID,TargetID: targetID,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -328,6 +331,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceType: "app-container",ResourceID: container.ContainerID(),TargetID: hostID,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -362,6 +366,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceType: "storage",ResourceID: firstNonEmptyTrimmed(strings.TrimSpace(storage.SourceID()), mentionResourceIDFromResolved("storage", resolved.Resource)),TargetID: firstNonEmptyTrimmed(strings.TrimSpace(storage.Node()), strings.TrimSpace(storage.Instance()), mentionTargetIDFromResolved("storage", resolved.Resource)),+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -424,6 +429,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceType: "agent",ResourceID: hostID,TargetID: hostID,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: hostname,Policy: policy,AISafeSummary: aiSafeSummary,@@ -580,6 +586,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceType: "vm",ResourceID: vmID,TargetID: node,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: sm.Name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -602,6 +609,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceType: "system-container",ResourceID: vmID,TargetID: node,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: sm.Name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -644,6 +652,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceType: "app-container",ResourceID: containerID,TargetID: hostID,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: sm.Name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -664,6 +673,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceType: "storage",ResourceID: resourceID,TargetID: targetID,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: sm.Name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -695,6 +705,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceType: "agent",ResourceID: hostID,TargetID: hostID,+ Adapter: mentionAdapterFromResolved(resolved.Resource),MatchedText: sm.Name,Policy: policy,AISafeSummary: aiSafeSummary,@@ -1032,8 +1043,10 @@ func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention, diskey := fmt.Sprintf("%s:%s:%s", tools.CanonicalDiscoveryResourceType(mention.ResourceType), mention.TargetID, mention.ResourceID)discovery, hasDiscovery := discoveryMap[key]+ hint := readRoutingHintForMention(mention)+// Docker containers get special treatment - show the full routing chain- if tools.CanonicalDiscoveryResourceType(mention.ResourceType) == "app-container" {+ if mentionUsesDockerRouting(mention) {sb.WriteString(fmt.Sprintf("## %s (Docker container)\n", mention.Name))// Show the full routing chain unambiguously@@ -1097,7 +1110,7 @@ func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention, dis}}- if hasDiscovery {+ if hasDiscovery && hint.mode == readRoutingTargetHost {// Command routingif discovery.Hostname != "" {sb.WriteString(fmt.Sprintf("target_host: \"%s\"\n", discovery.Hostname))@@ -1170,11 +1183,24 @@ 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 resourceRequiresReadOnlyGuidance(mention.ResourceType, mention.SupportsControl) {- sb.WriteString("Use pulse_query or pulse_read only — do NOT call pulse_control or pulse_discovery.\n")- } else {- sb.WriteString("Proceed directly with pulse_control — do NOT call pulse_discovery.\n")+ switch hint.mode {+ case readRoutingNativeResource, readRoutingQueryOnly:+ if hint.ref != "" {+ sb.WriteString(fmt.Sprintf("resource_id: \"%s\"\n", hint.ref))+ }+ if instruction := hint.prefetchInstruction(); instruction != "" {+ sb.WriteString(instruction + "\n")+ }+ default:+ targetHost := firstNonEmptyTrimmed(hint.ref, mention.Name)+ if targetHost != "" {+ sb.WriteString(fmt.Sprintf("target_host: \"%s\"\n", targetHost))+ }+ if resourceRequiresReadOnlyGuidance(mention.ResourceType, mention.SupportsControl) {+ sb.WriteString("Use pulse_query or pulse_read only — do NOT call pulse_control or 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.goindex b3aa1d6ba6..aa8aa8b782 100644--- a/internal/ai/chat/context_prefetch_additional_test.go+++ b/internal/ai/chat/context_prefetch_additional_test.go@@ -545,6 +545,7 @@ func TestContextPrefetcher_FormatContextSummary_VMwareGuestStaysReadOnly(t *testResourceID: "vm-201",TargetID: "esxi-01.lab.local",TargetHost: "esxi-01.lab.local",+ Adapter: "vmware-vsphere",UnifiedResourceID: "vmware-vm-1",SupportsControl: false,}}, nil)@@ -555,8 +556,14 @@ func TestContextPrefetcher_FormatContextSummary_VMwareGuestStaysReadOnly(t *testif 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)+ if strings.Contains(summary, "target_host:") {+ t.Fatalf("expected VMware guest summary to avoid target_host routing, got %q", summary)+ }+ if !strings.Contains(summary, "resource_id: \"app-01\"") {+ t.Fatalf("expected VMware guest summary to expose canonical resource_id routing, got %q", summary)+ }+ if !strings.Contains(summary, "Use pulse_query action=get resource_id=\"app-01\"") {+ t.Fatalf("expected VMware summary to direct the assistant to pulse_query, got %q", summary)}}@@ -569,6 +576,7 @@ func TestContextPrefetcher_FormatContextSummary_VMwareHostAndStorageStayReadOnlyResourceType: "agent",ResourceID: "vc-1:host:host-101",TargetID: "vc-1:host:host-101",+ Adapter: "vmware-vsphere",UnifiedResourceID: "vmware-host-1",SupportsControl: false,},@@ -577,6 +585,7 @@ func TestContextPrefetcher_FormatContextSummary_VMwareHostAndStorageStayReadOnlyResourceType: "storage",ResourceID: "vmware-datastore-1",TargetID: "Lab VC",+ Adapter: "vmware-vsphere",UnifiedResourceID: "vmware-datastore-1",SupportsControl: false,},@@ -585,8 +594,42 @@ func TestContextPrefetcher_FormatContextSummary_VMwareHostAndStorageStayReadOnlyif strings.Contains(summary, "Proceed directly with pulse_control") {t.Fatalf("expected VMware host and datastore summary to avoid control instructions, got %q", summary)}- if got := strings.Count(summary, "Use pulse_query or pulse_read only"); got != 2 {- t.Fatalf("expected read-only guidance for VMware host and datastore, got count=%d summary=%q", got, summary)+ if strings.Contains(summary, "target_host:") {+ t.Fatalf("expected VMware host and datastore summary to avoid target_host routing, got %q", summary)+ }+ if got := strings.Count(summary, "Use pulse_query action=get resource_id="); got != 2 {+ t.Fatalf("expected resource_id-based read guidance for VMware host and datastore, got count=%d summary=%q", got, summary)+ }+}++func TestContextPrefetcher_FormatContextSummary_TrueNASAppUsesNativeResourceReadPath(t *testing.T) {+ prefetcher := NewContextPrefetcher(newTestReadState(models.StateSnapshot{}), nil)++ summary := prefetcher.formatContextSummary([]ResourceMention{{+ Name: "Nextcloud",+ ResourceType: "app-container",+ ResourceID: "app-container:truenas-main:nextcloud",+ TargetID: "truenas-main",+ TargetHost: "truenas-main",+ Adapter: "truenas",+ UnifiedResourceID: "app-container:truenas-main:nextcloud",+ SupportsControl: true,+ }}, nil)++ if strings.Contains(summary, "Docker container") {+ t.Fatalf("expected native TrueNAS app summary to avoid Docker wording, got %q", summary)+ }+ if strings.Contains(summary, "pulse_docker") {+ t.Fatalf("expected native TrueNAS app summary to avoid pulse_docker guidance, got %q", summary)+ }+ if strings.Contains(summary, "target_host:") {+ t.Fatalf("expected native TrueNAS app summary to avoid target_host routing, got %q", summary)+ }+ if !strings.Contains(summary, "resource_id: \"Nextcloud\"") {+ t.Fatalf("expected native TrueNAS app summary to expose resource_id routing, got %q", summary)+ }+ if !strings.Contains(summary, "pulse_read action=logs resource_id=\"Nextcloud\"") {+ t.Fatalf("expected native TrueNAS app summary to expose native log routing, got %q", summary)}}diff --git a/internal/ai/chat/read_routing_hints.go b/internal/ai/chat/read_routing_hints.gonew file mode 100644index 0000000000..ad1bc8282d--- /dev/null+++ b/internal/ai/chat/read_routing_hints.go@@ -0,0 +1,163 @@+package chat++import (+ "fmt"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++type readRoutingMode string++const (+ readRoutingNone readRoutingMode = ""+ readRoutingTargetHost readRoutingMode = "target_host"+ readRoutingNativeResource readRoutingMode = "native_resource"+ readRoutingQueryOnly readRoutingMode = "query_only"+)++type readRoutingHint struct {+ mode readRoutingMode+ ref string+}++func buildReadRoutingHint(kind, adapter, targetHost, displayName, resourceID string) readRoutingHint {+ canonicalKind := tools.CanonicalDiscoveryResourceType(kind)+ adapter = strings.ToLower(strings.TrimSpace(adapter))+ targetHost = strings.TrimSpace(targetHost)+ resourceRef := firstNonEmptyTrimmed(displayName, resourceID)++ switch {+ case canonicalKind == "app-container" && adapter == "truenas":+ return readRoutingHint{mode: readRoutingNativeResource, ref: resourceRef}+ case isQueryOnlyAPIBackedReadResource(canonicalKind, adapter):+ return readRoutingHint{mode: readRoutingQueryOnly, ref: resourceRef}+ case targetHost != "":+ return readRoutingHint{mode: readRoutingTargetHost, ref: targetHost}+ case resourceRef != "":+ return readRoutingHint{mode: readRoutingTargetHost, ref: resourceRef}+ }++ return readRoutingHint{}+}++func readRoutingHintForMention(mention ResourceMention) readRoutingHint {+ resourceRef := firstNonEmptyTrimmed(mention.Name, mention.UnifiedResourceID, mention.ResourceID)+ return buildReadRoutingHint(mention.ResourceType, mention.Adapter, mention.TargetHost, resourceRef, mention.ResourceID)+}++func readRoutingHintForResolvedResource(kind, adapter, targetHost, displayName, resourceID string) readRoutingHint {+ return buildReadRoutingHint(kind, adapter, targetHost, displayName, resourceID)+}++func (h readRoutingHint) targetHintSuffix() string {+ switch h.mode {+ case readRoutingTargetHost:+ if h.ref != "" {+ return fmt.Sprintf(" Use target_host=\"%s\".", h.ref)+ }+ case readRoutingNativeResource, readRoutingQueryOnly:+ if h.ref != "" {+ return fmt.Sprintf(" Use resource_id=\"%s\".", h.ref)+ }+ }+ return ""+}++func (h readRoutingHint) recentLogsInstruction(resourceLabel string) string {+ switch h.mode {+ case readRoutingTargetHost:+ if h.ref == "" {+ return ""+ }+ return fmt.Sprintf("Instruction: Show logs for %s (last 50 lines). Use pulse_read action=logs target_host=\"%s\" lines=50.", resourceLabel, h.ref)+ case readRoutingNativeResource:+ if h.ref == "" {+ return ""+ }+ return fmt.Sprintf("Instruction: Show logs for %s (last 50 lines). Use pulse_read action=logs resource_id=\"%s\" lines=50.", resourceLabel, h.ref)+ case readRoutingQueryOnly:+ if h.ref == "" {+ return ""+ }+ return fmt.Sprintf("Instruction: %s does not support shared log reads. Use pulse_query action=get resource_id=\"%s\" to inspect current status, alerts, recent activity, and metrics instead.", resourceLabel, h.ref)+ default:+ return ""+ }+}++func (h readRoutingHint) prefetchInstruction() string {+ switch h.mode {+ case readRoutingNativeResource:+ if h.ref == "" {+ return "Native API-backed app. Use shared resource_id-based reads instead of Docker-style target routing."+ }+ return fmt.Sprintf("Native API-backed app. Use pulse_read action=logs resource_id=\"%s\" or pulse_query action=config resource_id=\"%s\". Do NOT use pulse_discovery or target_host.", h.ref, h.ref)+ case readRoutingQueryOnly:+ if h.ref == "" {+ return "API-backed read-only resource. Use pulse_query get/search on the shared resource identity. Do NOT use target_host, pulse_control, or pulse_discovery."+ }+ return fmt.Sprintf("API-backed read-only resource. Use pulse_query action=get resource_id=\"%s\" for status, alerts, recent activity, and metrics. Do NOT use target_host, pulse_control, or pulse_discovery.", h.ref)+ default:+ return ""+ }+}++func mentionUsesDockerRouting(mention ResourceMention) bool {+ if tools.CanonicalDiscoveryResourceType(mention.ResourceType) != "app-container" {+ return false+ }+ if strings.EqualFold(strings.TrimSpace(mention.Adapter), "truenas") {+ return false+ }+ return mention.DockerHostType != "" || mention.DockerHostName != "" || len(mention.BindMounts) > 0+}++func isQueryOnlyAPIBackedReadResource(kind, adapter string) bool {+ switch strings.ToLower(strings.TrimSpace(adapter)) {+ case "vmware-vsphere":+ switch kind {+ case "agent", "vm", "storage":+ return true+ }+ case "truenas":+ switch kind {+ case "agent", "storage", "physical-disk":+ return true+ }+ }+ return false+}++func mentionAdapterFromResolved(resource *unifiedresources.Resource) string {+ if resource == nil {+ return ""+ }++ switch {+ case resource.TrueNAS != nil || resourceHasTagCaseInsensitive(*resource, "truenas"):+ return "truenas"+ case resource.VMware != nil:+ return "vmware-vsphere"+ case resource.Proxmox != nil:+ return "proxmox"+ case resource.Docker != nil:+ return "docker"+ case resource.Agent != nil && resource.Agent.CommandsEnabled:+ return "direct"+ case resource.Agent != nil && strings.TrimSpace(resource.Agent.Platform) != "":+ return strings.ToLower(strings.TrimSpace(resource.Agent.Platform))+ default:+ return ""+ }+}++func resourceHasTagCaseInsensitive(resource unifiedresources.Resource, needle string) bool {+ for _, tag := range resource.Tags {+ if strings.EqualFold(strings.TrimSpace(tag), needle) {+ return true+ }+ }+ return false+}diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 35a6a32dfe..48d2ce3aad 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -1529,18 +1529,8 @@ func (s *Service) injectRecentContextIfNeeded(prompt, sessionID string, messagesif primaryName == "" {primaryName = primary}- targetHint := ""- if primaryKind == "app-container" && strings.EqualFold(strings.TrimSpace(primaryAdapter), "truenas") {- target := primaryName- if target == "" {- target = primaryResourceID- }- if target != "" {- targetHint = fmt.Sprintf(" Use resource_id=\"%s\".", target)- }- } else if primaryTarget != "" {- targetHint = fmt.Sprintf(" Use target_host=\"%s\".", primaryTarget)- }+ readHint := readRoutingHintForResolvedResource(primaryKind, primaryAdapter, primaryTarget, primaryName, primaryResourceID)+ targetHint := readHint.targetHintSuffix()summary := fmt.Sprintf("Context: The most recently referenced resource is %s. If the user says \"it/its/that\", assume they mean this resource unless they specify otherwise. Do not ask for clarification unless the user names a different resource.%s", primary, targetHint)if len(lines) > 1 {others := strings.Join(lines[1:], "\n")@@ -1549,17 +1539,12 @@ func (s *Service) injectRecentContextIfNeeded(prompt, sessionID string, messageslowerPrompt := strings.ToLower(prompt)if strings.Contains(lowerPrompt, "log") || strings.Contains(lowerPrompt, "journal") {- rewrite := fmt.Sprintf("Show logs for %s (last 50 lines).", primaryName)- if primaryKind == "app-container" && strings.EqualFold(strings.TrimSpace(primaryAdapter), "truenas") {- target := primaryName- if target == "" {- target = primaryResourceID- }- summary += fmt.Sprintf("\nInstruction: %s Use pulse_read action=logs resource_id=\"%s\" lines=50.", rewrite, target)- } else if primaryTarget != "" {- summary += fmt.Sprintf("\nInstruction: %s Use pulse_read action=logs target_host=\"%s\" lines=50.", rewrite, primaryTarget)- } else {- summary += fmt.Sprintf("\nInstruction: %s Use pulse_read action=logs target_host=\"%s\" lines=50.", rewrite, primaryName)+ instructionTarget := primaryName+ if instructionTarget == "" {+ instructionTarget = primary+ }+ if instruction := readHint.recentLogsInstruction(instructionTarget); instruction != "" {+ summary += "\n" + instruction}}diff --git a/internal/ai/chat/service_recent_context_test.go b/internal/ai/chat/service_recent_context_test.goindex b8bddcde32..eae8a3362c 100644--- a/internal/ai/chat/service_recent_context_test.go+++ b/internal/ai/chat/service_recent_context_test.go@@ -165,3 +165,42 @@ func TestInjectRecentContextIfNeeded_UsesResourceIDHintForTrueNASAppLogs(t *testt.Fatalf("expected resource-targeted log instruction, got: %s", content)}}++func TestInjectRecentContextIfNeeded_UsesQueryResourceIDHintForVMwareLogs(t *testing.T) {+ store, err := NewSessionStore(t.TempDir())+ if err != nil {+ t.Fatalf("failed to create session store: %v", err)+ }+ session, err := store.Create()+ if err != nil {+ t.Fatalf("failed to create session: %v", err)+ }++ resolved := store.GetResolvedContext(session.ID)+ resource := &ResolvedResource{+ ResourceID: "agent:vc-1:host:host-101",+ Name: "esxi-01.lab.local",+ Kind: "agent",+ Node: "Lab VC",+ Adapter: "vmware-vsphere",+ }+ resolved.AddResourceWithExplicitAccess(resource.Name, resource)++ messages := []Message{{Role: "user", Content: "show its logs"}}+ service := &Service{}+ service.injectRecentContextIfNeeded("show its logs", session.ID, messages, store)++ content := messages[0].Content+ if !strings.Contains(content, "Use resource_id=\"esxi-01.lab.local\".") {+ t.Fatalf("expected resource_id hint, got: %s", content)+ }+ if strings.Contains(content, "target_host=\"esxi-01.lab.local\"") {+ t.Fatalf("expected VMware recent context to avoid target_host log routing, got: %s", content)+ }+ if !strings.Contains(content, "does not support shared log reads") {+ t.Fatalf("expected VMware log limitation guidance, got: %s", content)+ }+ if !strings.Contains(content, "Use pulse_query action=get resource_id=\"esxi-01.lab.local\"") {+ t.Fatalf("expected VMware recent context to redirect to pulse_query, got: %s", content)+ }+}