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
Centralize memory change formatting
rcourtman2523b6237935
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 5222b7eb35..251e056716 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -146,7 +146,9 @@ timeline when it assembles rich resource or incident context. Recent-changecontext should come from the shared resource store first so AI prompts reflectthe same change record that powers the resource API, with patrol-local changedetectors only serving as fallback coverage when the canonical store is not-available.+available. When that patrol-local fallback is used, it must render through the+shared memory change presentation helper so the same heading, scope prefix, and+change-type labels are reused instead of being rebuilt ad hoc in AI-local code.Resource-only incident context should follow the same rule: if an alerttimeline is absent, the incident prompt path should fall back to the canonicalunified-resource timeline rather than depending only on patrol-local change@@ -234,6 +236,10 @@ Those backend AI and Patrol change summaries should derive their canonicallabels and provenance fragments from`internal/unifiedresources/change_presentation.go`, so the resource-modelsemantics are shared before any surface-specific markdown styling is applied.+The patrol-local recent-change fallback itself should derive its section layout+and change labels from `internal/ai/memory/presentation.go`, so detector-based+fallbacks stay consistent across AI runtime entry points when the canonical+resource timeline is unavailable.The per-resource intelligence payload returned from`/api/ai/intelligence?resource_id=...` should also include the canonical`recent_changes` history so UI and API consumers can read the same timelinediff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 56c45d7e85..f11e2d2053 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 alsorender the canonical recent changes section before any patrol-local changedetector fallback so the prompt surface stays aligned with the sharedunified-resource timeline.+When that detector fallback is used, the Patrol runtime must render recent+changes through the shared memory presentation helper so the same heading,+resource prefixing, and change labels are reused across the Patrol and AI+fallback paths.Those same Patrol-owned prompt contexts now also surface a canonicalresource-graph section from unified-resource relationships, so edge labels,directionality, and provenance stay aligned with the shared graph modeldiff --git a/internal/ai/coverage_increase_test.go b/internal/ai/coverage_increase_test.goindex 5baa8915b0..8cdd122444 100644--- a/internal/ai/coverage_increase_test.go+++ b/internal/ai/coverage_increase_test.go@@ -563,6 +563,23 @@ func TestService_BuildResourceGraphContext_UsesCanonicalReadState(t *testing.T)}}+func TestService_BuildRecentResourceChangesContext_FallsBackToMemoryFormatter(t *testing.T) {+ s := &Service{}+ ps := NewPatrolService(nil, nil)+ cd := NewChangeDetector(ChangeDetectorConfig{MaxChanges: 10})+ cd.DetectChanges([]ResourceSnapshot{+ {ID: "res-fallback", Name: "fallback-resource", Type: "vm", Status: "running", SnapshotTime: time.Now()},+ })+ ps.SetChangeDetector(cd)+ s.patrolService = ps++ got := s.buildRecentResourceChangesContext("res-fallback")+ want := memory.FormatRecentChangesContext(cd.GetChangesForResource("res-fallback", 5), false, "###")+ if got != want {+ t.Fatalf("expected fallback recent-resource-changes context to use shared memory formatter:\nwant %q\n got %q", want, got)+ }+}+type mockIncidentStore struct {}diff --git a/internal/ai/intelligence.go b/internal/ai/intelligence.goindex 36ce8fd659..6dd7c61621 100644--- a/internal/ai/intelligence.go+++ b/internal/ai/intelligence.go@@ -535,64 +535,7 @@ func (i *Intelligence) buildRecentChangesContext(resourceID string, resourceTimeif len(recent) == 0 {return ""}- return formatMemoryRecentChangesContext(recent, includeResourcePrefix)-}--func formatMemoryRecentChangesContext(changes []memory.Change, includeResourcePrefix bool) string {- if len(changes) == 0 {- return ""- }-- heading := "\n## Recent Changes"- if includeResourcePrefix {- heading = "\n## Recent Changes Across Infrastructure"- }-- lines := []string{heading, "What changed recently:"}- for _, change := range changes {- entry := fmt.Sprintf("**%s** %s", formatMemoryChangeTypeLabel(change.ChangeType), change.Description)- if includeResourcePrefix {- scope := strings.TrimSpace(change.ResourceID)- if scope == "" {- scope = strings.TrimSpace(change.ResourceName)- }- if scope == "" {- scope = "resource"- }- if resourceType := strings.TrimSpace(change.ResourceType); resourceType != "" && !strings.Contains(scope, resourceType) {- scope = fmt.Sprintf("%s (%s)", scope, resourceType)- }- entry = fmt.Sprintf("%s: %s", scope, entry)- }- ago := time.Since(change.DetectedAt).Truncate(time.Minute)- lines = append(lines, fmt.Sprintf("- %s (%s ago)", entry, formatDuration(ago)))- }- return strings.Join(lines, "\n")-}--func formatMemoryChangeTypeLabel(changeType memory.ChangeType) string {- switch changeType {- case memory.ChangeCreated:- return "Created"- case memory.ChangeDeleted:- return "Deleted"- case memory.ChangeConfig:- return "Config update"- case memory.ChangeStatus:- return "Status change"- case memory.ChangeMigrated:- return "Migration"- case memory.ChangeRestarted:- return "Restart"- case memory.ChangeBackedUp:- return "Backup"- default:- raw := strings.TrimSpace(strings.ReplaceAll(string(changeType), "_", " "))- if raw == "" {- return "Change"- }- return strings.ToUpper(raw[:1]) + raw[1:]- }+ return memory.FormatRecentChangesContext(recent, includeResourcePrefix, "##")}// RecordLearning saves a learning to the knowledge store after a fixdiff --git a/internal/ai/intelligence_test.go b/internal/ai/intelligence_test.goindex da6e84d69a..00b163500b 100644--- a/internal/ai/intelligence_test.go+++ b/internal/ai/intelligence_test.go@@ -485,6 +485,20 @@ func TestIntelligence_BuildRecentChangesContext_UsesCanonicalSectionFormatter(t}}+func TestIntelligence_BuildRecentChangesContext_FallsBackToMemoryFormatter(t *testing.T) {+ intel := NewIntelligence(IntelligenceConfig{})+ changes := memory.NewChangeDetector(memory.ChangeDetectorConfig{MaxChanges: 10})+ changes.DetectChanges([]memory.ResourceSnapshot{+ {ID: "vm-302", Name: "fallback-vm", Type: "vm", Status: "running", SnapshotTime: time.Now()},+ })++ ctx := intel.buildRecentChangesContext("vm-302", nil, changes, true, 5)+ want := memory.FormatRecentChangesContext(changes.GetChangesForResource("vm-302", 5), true, "##")+ if ctx != want {+ t.Fatalf("expected fallback recent-changes context to use shared memory formatter:\nwant %q\n got %q", want, ctx)+ }+}+func TestIntelligence_CreatePredictionFinding_LowSeverity(t *testing.T) {intel := NewIntelligence(IntelligenceConfig{})diff --git a/internal/ai/memory/presentation.go b/internal/ai/memory/presentation.gonew file mode 100644index 0000000000..97081012a4--- /dev/null+++ b/internal/ai/memory/presentation.go@@ -0,0 +1,73 @@+package memory++import (+ "fmt"+ "strings"+ "time"+)++// ChangeTypeLabel returns the canonical human-readable label for a detected+// memory change type.+func ChangeTypeLabel(changeType ChangeType) string {+ switch changeType {+ case ChangeCreated:+ return "Created"+ case ChangeDeleted:+ return "Deleted"+ case ChangeConfig:+ return "Config update"+ case ChangeStatus:+ return "Status change"+ case ChangeMigrated:+ return "Migration"+ case ChangeRestarted:+ return "Restart"+ case ChangeBackedUp:+ return "Backup"+ default:+ raw := strings.TrimSpace(strings.ReplaceAll(string(changeType), "_", " "))+ if raw == "" {+ return "Change"+ }+ return strings.ToUpper(raw[:1]) + raw[1:]+ }+}++// FormatRecentChangesContext returns the canonical markdown section for recent+// memory changes used in AI prompts and summaries.+func FormatRecentChangesContext(changes []Change, includeResourcePrefix bool, headingLevel string) string {+ if len(changes) == 0 {+ return ""+ }++ headingLevel = strings.TrimSpace(headingLevel)+ if headingLevel == "" {+ headingLevel = "##"+ }++ heading := fmt.Sprintf("\n%s Recent Changes", headingLevel)+ if includeResourcePrefix {+ heading = fmt.Sprintf("\n%s Recent Changes Across Infrastructure", headingLevel)+ }++ lines := []string{heading, "What changed recently:"}+ for _, change := range changes {+ entry := fmt.Sprintf("**%s** %s", ChangeTypeLabel(change.ChangeType), change.Description)+ if includeResourcePrefix {+ scope := strings.TrimSpace(change.ResourceID)+ if scope == "" {+ scope = strings.TrimSpace(change.ResourceName)+ }+ if scope == "" {+ scope = "resource"+ }+ if resourceType := strings.TrimSpace(change.ResourceType); resourceType != "" && !strings.Contains(scope, resourceType) {+ scope = fmt.Sprintf("%s (%s)", scope, resourceType)+ }+ entry = fmt.Sprintf("%s: %s", scope, entry)+ }+ ago := time.Since(change.DetectedAt).Truncate(time.Minute)+ lines = append(lines, fmt.Sprintf("- %s (%s ago)", entry, formatDuration(ago)))+ }+ return strings.Join(lines, "\n")+}diff --git a/internal/ai/memory/presentation_test.go b/internal/ai/memory/presentation_test.gonew file mode 100644index 0000000000..d6b7240b5d--- /dev/null+++ b/internal/ai/memory/presentation_test.go@@ -0,0 +1,66 @@+package memory++import (+ "strings"+ "testing"+ "time"+)++func TestChangeTypeLabel(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ kind ChangeType+ want string+ }{+ {name: "created", kind: ChangeCreated, want: "Created"},+ {name: "deleted", kind: ChangeDeleted, want: "Deleted"},+ {name: "restart", kind: ChangeRestarted, want: "Restart"},+ {name: "fallback", kind: ChangeType("custom_type"), want: "Custom type"},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := ChangeTypeLabel(tc.kind); got != tc.want {+ t.Fatalf("ChangeTypeLabel(%q) = %q, want %q", tc.kind, got, tc.want)+ }+ })+ }+}++func TestFormatRecentChangesContext(t *testing.T) {+ t.Parallel()++ now := time.Now()+ changes := []Change{+ {+ ResourceID: "res-1",+ ResourceType: "vm",+ ResourceName: "web-01",+ ChangeType: ChangeRestarted,+ Description: "restarted after maintenance",+ DetectedAt: now.Add(-90 * time.Minute),+ },+ {+ ResourceName: "cache-1",+ ResourceType: "container",+ ChangeType: ChangeConfig,+ Description: "adjusted memory limit",+ DetectedAt: now.Add(-30 * time.Minute),+ },+ }++ got := FormatRecentChangesContext(changes, true, "###")+ for _, want := range []string{+ "### Recent Changes Across Infrastructure",+ "res-1 (vm): **Restart** restarted after maintenance (1 hour ago)",+ "cache-1 (container): **Config update** adjusted memory limit (30 minutes ago)",+ } {+ if !strings.Contains(got, want) {+ t.Fatalf("FormatRecentChangesContext output %q does not contain %q", got, want)+ }+ }+}diff --git a/internal/ai/service.go b/internal/ai/service.goindex eeb5115d99..4c5c7429a9 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -4604,19 +4604,10 @@ func (s *Service) buildRecentResourceChangesContext(resourceID string) string {if len(changes) == 0 {return ""}-- var changeInfo []string- for _, c := range changes {- if len(changeInfo) >= 3 {- break- }- ago := time.Since(c.DetectedAt).Truncate(time.Minute)- changeInfo = append(changeInfo, fmt.Sprintf("**%s** %s (%s ago)", c.ChangeType, c.Description, ago))- }- if len(changeInfo) == 0 {- return ""+ if len(changes) > 3 {+ changes = changes[:3]}- return "\n\n### Recent Changes\n" + strings.Join(changeInfo, "\n")+ return memory.FormatRecentChangesContext(changes, false, "###")}type canonicalResourceGetter interface {