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.

Add canonical resource graph context

rcourtman7bb7b16ac5ee
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 3e049dd264..fa8bcc3b05 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -152,6 +152,10 @@ store instead of leaving command execution state in memory-only tool helpers.
Those unified-resource action and export audit records are now also exposed
through the enterprise audit read surface so operators can inspect the
execution trail without reaching into storage internals.
+AI resource and incident context now also surfaces a canonical resource-graph
+section from unified-resource relationships, so relationship wording and edge
+provenance stay aligned with the same shared resource model instead of being
+reconstructed from the drawer or prompt helpers.
The Patrol intelligence seed context now also prefers the canonical
unified-resource timeline before falling back to the patrol-local change
detector, so deterministic patrol context and resource detail context share
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 3dbb0ceaf0..9fbc041b7a 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -81,6 +81,10 @@ Patrol-owned resource and global intelligence prompt contexts should also
render the canonical recent changes section before any patrol-local change
detector fallback so the prompt surface stays aligned with the shared
unified-resource timeline.
+Those same Patrol-owned prompt contexts now also surface a canonical
+resource-graph section from unified-resource relationships, so edge labels,
+directionality, and provenance stay aligned with the shared graph model
+instead of being reconstructed locally.
The Patrol page also now renders the canonical intelligence summary card
through the governed AI client and store, so the visible page summary and the
resource/timeline sections stay aligned on the same shared backend slice.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 31b5ef86de..19634de241 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -97,6 +97,11 @@ kind, source type, source adapter, actor, reason, and related-resource
fragments from `internal/unifiedresources/change_presentation.go`, so the
semantic mapping lives with the resource model instead of being duplicated in
lane-local prompt helpers.
+The backend AI and Patrol graph context renderers now derive their canonical
+relationship labels, direction, provenance, freshness, and metadata flags
+from `internal/unifiedresources/relationship_presentation.go`, so the graph
+semantics live with the resource model instead of being duplicated in prompt
+helpers or drawer-specific markdown.
The change emitter now also classifies canonical restart changes for Docker
and Kubernetes resources when restart counters increase or uptime resets, so
the timeline can distinguish restarts from generic state transitions instead
diff --git a/internal/ai/coverage_increase_test.go b/internal/ai/coverage_increase_test.go
index 96777c80cf..52ad49d6b0 100644
--- a/internal/ai/coverage_increase_test.go
+++ b/internal/ai/coverage_increase_test.go
@@ -467,6 +467,61 @@ func TestService_BuildIncidentContext(t *testing.T) {
}
}
+func TestService_BuildResourceGraphContext_UsesCanonicalReadState(t *testing.T) {
+ now := time.Now()
+ s := NewService(nil, nil)
+ ps := NewPatrolService(nil, nil)
+
+ resourceID := "vm-graph-1"
+ readState := &mockReadState{
+ resources: map[string]*unifiedresources.Resource{
+ resourceID: {
+ ID: resourceID,
+ Type: unifiedresources.ResourceTypeVM,
+ Name: resourceID,
+ Status: unifiedresources.StatusOnline,
+ Relationships: []unifiedresources.ResourceRelationship{
+ {
+ SourceID: resourceID,
+ TargetID: "node-graph-1",
+ Type: unifiedresources.RelRunsOn,
+ Confidence: 0.9,
+ Active: true,
+ Discoverer: "proxmox_adapter",
+ ObservedAt: now.Add(-2 * time.Hour),
+ LastSeenAt: now.Add(-time.Hour),
+ Metadata: map[string]any{"role": "primary"},
+ },
+ },
+ },
+ },
+ }
+
+ s.mu.Lock()
+ s.patrolService = ps
+ s.readState = readState
+ s.mu.Unlock()
+
+ resourceCtx := s.buildEnrichedResourceContext(resourceID, "", nil)
+ if !strings.Contains(resourceCtx, "Resource Graph") {
+ t.Fatalf("expected enriched resource context to include graph section, got %q", resourceCtx)
+ }
+ if !strings.Contains(resourceCtx, "Runs on") {
+ t.Fatalf("expected enriched resource context to include canonical relationship label, got %q", resourceCtx)
+ }
+ if !strings.Contains(resourceCtx, "discoverer proxmox_adapter") {
+ t.Fatalf("expected enriched resource context to include provenance, got %q", resourceCtx)
+ }
+
+ incidentCtx := s.buildIncidentContext(resourceID, "")
+ if !strings.Contains(incidentCtx, "Resource Graph") {
+ t.Fatalf("expected incident context to include graph section, got %q", incidentCtx)
+ }
+ if !strings.Contains(incidentCtx, "Runs on") {
+ t.Fatalf("expected incident context to include canonical relationship label, got %q", incidentCtx)
+ }
+}
+
type mockIncidentStore struct {
}
diff --git a/internal/ai/patrol_ai_intelligence_test.go b/internal/ai/patrol_ai_intelligence_test.go
index a679e33557..f39d757c29 100644
--- a/internal/ai/patrol_ai_intelligence_test.go
+++ b/internal/ai/patrol_ai_intelligence_test.go
@@ -27,6 +27,7 @@ type mockReadState struct {
pbs []*ur.PBSInstanceView
pmg []*ur.PMGInstanceView
k8sClusters []*ur.K8sClusterView
+ resources map[string]*ur.Resource
}
func (m *mockReadState) Nodes() []*ur.NodeView { return m.nodes }
@@ -50,6 +51,17 @@ func (m *mockReadState) Infrastructure() []*ur.InfrastructureView {
return nil
}
+func (m *mockReadState) Get(id string) (*ur.Resource, bool) {
+ if m.resources == nil {
+ return nil, false
+ }
+ resource, ok := m.resources[id]
+ if !ok || resource == nil {
+ return nil, false
+ }
+ return resource, true
+}
+
type precomputeMetricsHistoryProvider struct {
metrics map[string][]models.MetricPoint
storage map[string][]models.MetricPoint
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 2d95a004df..769a36cf71 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -4512,6 +4512,9 @@ func (s *Service) buildIncidentContext(resourceID, alertIdentifier string) strin
if recentChanges := s.buildRecentResourceChangesContext(resourceID); recentChanges != "" {
sections = append(sections, recentChanges)
}
+ if graphContext := s.buildResourceGraphContext(resourceID); graphContext != "" {
+ sections = append(sections, graphContext)
+ }
}
if len(sections) == 0 {
@@ -4620,6 +4623,74 @@ func (s *Service) buildRecentResourceChangesContext(resourceID string) string {
return "\n\n### Recent Changes\n" + strings.Join(changeInfo, "\n")
}
+type canonicalResourceGetter interface {
+ Get(id string) (*unifiedresources.Resource, bool)
+}
+
+func (s *Service) buildResourceGraphContext(resourceID string) string {
+ resourceID = strings.TrimSpace(resourceID)
+ if resourceID == "" {
+ return ""
+ }
+
+ s.mu.RLock()
+ rs := s.readState
+ s.mu.RUnlock()
+
+ if rs == nil {
+ return ""
+ }
+
+ getter, ok := rs.(canonicalResourceGetter)
+ if !ok {
+ return ""
+ }
+
+ resource, ok := getter.Get(resourceID)
+ if !ok || resource == nil || len(resource.Relationships) == 0 {
+ return ""
+ }
+
+ relationshipLimit := len(resource.Relationships)
+ if relationshipLimit > 3 {
+ relationshipLimit = 3
+ }
+ lines := make([]string, 0, relationshipLimit)
+ for _, rel := range resource.Relationships {
+ if len(lines) >= 3 {
+ break
+ }
+ presentation := unifiedresources.DescribeRelationship(rel)
+ parts := []string{
+ fmt.Sprintf("**%s** %s", presentation.TypeLabel, presentation.Direction),
+ }
+ if presentation.StateLabel != "" {
+ parts = append(parts, presentation.StateLabel)
+ }
+ if presentation.Provenance != "" {
+ parts = append(parts, fmt.Sprintf("discoverer %s", presentation.Provenance))
+ }
+ if presentation.Confidence != "" {
+ parts = append(parts, fmt.Sprintf("confidence %s", presentation.Confidence))
+ }
+ if !rel.ObservedAt.IsZero() {
+ parts = append(parts, fmt.Sprintf("observed %s ago", formatDuration(time.Since(rel.ObservedAt).Truncate(time.Minute))))
+ }
+ if !rel.LastSeenAt.IsZero() {
+ parts = append(parts, fmt.Sprintf("last seen %s ago", formatDuration(time.Since(rel.LastSeenAt).Truncate(time.Minute))))
+ }
+ if presentation.HasMetadata {
+ parts = append(parts, "metadata present")
+ }
+ lines = append(lines, strings.Join(parts, "; "))
+ }
+
+ if len(lines) == 0 {
+ return ""
+ }
+ return "\n\n### Resource Graph\n" + strings.Join(lines, "\n")
+}
+
// truncateString truncates a string to maxLen characters
func truncateString(s string, maxLen int) string {
if len(s) <= maxLen {
@@ -4845,6 +4916,11 @@ func (s *Service) buildEnrichedResourceContext(resourceID, _ string, currentMetr
sections = append(sections, recentChanges)
}
+ // Get canonical resource graph context from unified resources.
+ if graphContext := s.buildResourceGraphContext(resourceID); graphContext != "" {
+ sections = append(sections, graphContext)
+ }
+
// Get correlation detector for related resources
correlationDetector := patrol.GetCorrelationDetector()
if correlationDetector != nil {
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 962e7109c7..e619260be8 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -334,6 +334,26 @@ func TestResourceChangePresentationUsesCanonicalLabels(t *testing.T) {
}
}
+func TestResourceGraphContextUsesCanonicalRelationshipPresentation(t *testing.T) {
+ data, err := os.ReadFile(filepath.Join("..", "ai", "service.go"))
+ if err != nil {
+ t.Fatalf("failed to read service.go: %v", err)
+ }
+ source := string(data)
+ requiredSnippets := []string{
+ "func (s *Service) buildResourceGraphContext(resourceID string) string",
+ "if graphContext := s.buildResourceGraphContext(resourceID); graphContext != \"\" {",
+ "unifiedresources.DescribeRelationship(rel)",
+ "### Resource Graph",
+ "type canonicalResourceGetter interface {",
+ }
+ for _, snippet := range requiredSnippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("internal/ai/service.go must pin canonical resource graph presentation snippet %q", snippet)
+ }
+ }
+}
+
func TestResourceFacetCountsAreCanonicalResourceFields(t *testing.T) {
typesData, err := os.ReadFile(filepath.Join("types.go"))
if err != nil {
diff --git a/internal/unifiedresources/relationship_presentation.go b/internal/unifiedresources/relationship_presentation.go
new file mode 100644
index 0000000000..8b0bd17284
--- /dev/null
+++ b/internal/unifiedresources/relationship_presentation.go
@@ -0,0 +1,66 @@
+package unifiedresources
+
+import (
+ "fmt"
+ "strings"
+)
+
+// RelationshipPresentation captures the canonical human-readable fragments for
+// a unified resource relationship.
+type RelationshipPresentation struct {
+ TypeLabel string
+ Direction string
+ Provenance string
+ StateLabel string
+ Confidence string
+ HasMetadata bool
+}
+
+// RelationshipTypeLabel returns the canonical label for a relationship type.
+func RelationshipTypeLabel(t RelationshipType) string {
+ switch t {
+ case RelRunsOn:
+ return "Runs on"
+ case RelDependsOn:
+ return "Depends on"
+ case RelMountedTo:
+ return "Mounted to"
+ case RelExposedBy:
+ return "Exposed by"
+ case RelOwnedBy:
+ return "Owned by"
+ default:
+ raw := strings.TrimSpace(strings.ReplaceAll(string(t), "_", " "))
+ if raw == "" {
+ return "Related to"
+ }
+ return strings.ToUpper(raw[:1]) + raw[1:]
+ }
+}
+
+// DescribeRelationship returns the canonical presentation fragments for a
+// unified resource relationship.
+func DescribeRelationship(rel ResourceRelationship) RelationshipPresentation {
+ presentation := RelationshipPresentation{
+ TypeLabel: RelationshipTypeLabel(rel.Type),
+ Direction: fmt.Sprintf("%s → %s", strings.TrimSpace(rel.SourceID), strings.TrimSpace(rel.TargetID)),
+ }
+
+ if rel.Discoverer != "" {
+ presentation.Provenance = strings.TrimSpace(rel.Discoverer)
+ }
+
+ if rel.Active {
+ presentation.StateLabel = "Active"
+ } else {
+ presentation.StateLabel = "Historical"
+ }
+
+ if rel.Confidence > 0 {
+ presentation.Confidence = fmt.Sprintf("%.0f%%", rel.Confidence*100)
+ }
+
+ presentation.HasMetadata = len(rel.Metadata) > 0
+
+ return presentation
+}
diff --git a/internal/unifiedresources/relationship_presentation_test.go b/internal/unifiedresources/relationship_presentation_test.go
new file mode 100644
index 0000000000..9c02e523b9
--- /dev/null
+++ b/internal/unifiedresources/relationship_presentation_test.go
@@ -0,0 +1,52 @@
+package unifiedresources
+
+import "testing"
+
+func TestRelationshipTypeLabel(t *testing.T) {
+ cases := map[RelationshipType]string{
+ RelRunsOn: "Runs on",
+ RelDependsOn: "Depends on",
+ RelMountedTo: "Mounted to",
+ RelExposedBy: "Exposed by",
+ RelOwnedBy: "Owned by",
+ RelationshipType("custom_link"): "Custom link",
+ RelationshipType(""): "Related to",
+ }
+
+ for relationType, want := range cases {
+ if got := RelationshipTypeLabel(relationType); got != want {
+ t.Fatalf("RelationshipTypeLabel(%q) = %q, want %q", relationType, got, want)
+ }
+ }
+}
+
+func TestDescribeRelationship(t *testing.T) {
+ presentation := DescribeRelationship(ResourceRelationship{
+ SourceID: "node-1",
+ TargetID: "vm-1",
+ Type: RelRunsOn,
+ Confidence: 0.85,
+ Active: false,
+ Discoverer: "docker_adapter",
+ Metadata: map[string]any{"region": "lab"},
+ })
+
+ if presentation.TypeLabel != "Runs on" {
+ t.Fatalf("unexpected type label: %q", presentation.TypeLabel)
+ }
+ if presentation.Direction != "node-1 → vm-1" {
+ t.Fatalf("unexpected direction: %q", presentation.Direction)
+ }
+ if presentation.Provenance != "docker_adapter" {
+ t.Fatalf("unexpected provenance: %q", presentation.Provenance)
+ }
+ if presentation.StateLabel != "Historical" {
+ t.Fatalf("unexpected state label: %q", presentation.StateLabel)
+ }
+ if presentation.Confidence != "85%" {
+ t.Fatalf("unexpected confidence: %q", presentation.Confidence)
+ }
+ if !presentation.HasMetadata {
+ t.Fatalf("expected metadata flag to be set")
+ }
+}