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.

Use canonical resource timelines in AI context

rcourtman749b0c46e558
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index ee117922fe..2cd8b49d4b 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -53,6 +53,7 @@ runtime cost control, and shared AI transport surfaces.
2. Keep AI runtime and shared API proof routing aligned in `registry.json`
3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changes
4. Preserve auditability for outbound model-bound context exports and keep the export record aligned with the prompt boundary that actually reaches the provider
+5. Keep AI resource and incident context aligned with the canonical unified-resource timeline before falling back to patrol-local change detectors
## Current State
@@ -132,6 +133,12 @@ boundary. When the AI service assembles unified-resource context for a model
request, it must record a durable export audit with the active destination
model and governed redaction decision instead of treating the prompt boundary
as a transient formatting step.
+The same AI runtime boundary now also consumes the canonical unified-resource
+timeline when it assembles rich resource or incident context. Recent-change
+context should come from the shared resource store first so AI prompts reflect
+the same change record that powers the resource API, with patrol-local change
+detectors only serving as fallback coverage when the canonical store is not
+available.
The same runtime boundary now also owns durable action execution auditing.
`internal/ai/chat/service.go` initializes the unified-resource audit store on
diff --git a/internal/ai/coverage_increase_test.go b/internal/ai/coverage_increase_test.go
index 9767fd2abc..ad4c3f7f19 100644
--- a/internal/ai/coverage_increase_test.go
+++ b/internal/ai/coverage_increase_test.go
@@ -8,6 +8,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
func TestPatrolService_BroadcastFullChannel(t *testing.T) {
@@ -298,7 +299,52 @@ func TestService_BuildEnrichedResourceContext(t *testing.T) {
t.Error("Expected 'Past 30 days' history in context")
}
- // Case 7: With Change Logic
+ // Case 7: With canonical resource timeline history
+ canonicalStore := unifiedresources.NewMemoryStore()
+ if err := canonicalStore.RecordChange(unifiedresources.ResourceChange{
+ ID: "change-1",
+ ObservedAt: now.Add(-2 * time.Hour),
+ ResourceID: "res1",
+ Kind: unifiedresources.ChangeRestart,
+ From: "running",
+ To: "restarting",
+ SourceType: unifiedresources.SourcePlatformEvent,
+ SourceAdapter: unifiedresources.AdapterProxmox,
+ Confidence: unifiedresources.ConfidenceHigh,
+ Actor: "agent:oncall-helper",
+ RelatedResources: []string{"node-1"},
+ Reason: "Routine restart requested",
+ }); err != nil {
+ t.Fatalf("record canonical resource change: %v", err)
+ }
+ s.mu.Lock()
+ s.orgID = "org-1"
+ s.resourceExportStore = canonicalStore
+ s.resourceExportStoreOrgID = s.orgID
+ s.mu.Unlock()
+
+ ctx = s.buildEnrichedResourceContext("res1", "node", metrics)
+ t.Logf("Enriched context (canonical changes): %s", ctx)
+
+ if !strings.Contains(ctx, "Recent Changes") {
+ t.Error("Expected canonical recent changes section in context")
+ }
+ if !strings.Contains(ctx, "Restart") {
+ t.Error("Expected canonical restart change in context")
+ }
+ if !strings.Contains(ctx, "proxmox_adapter") {
+ t.Error("Expected canonical adapter provenance in context")
+ }
+ if !strings.Contains(ctx, "node-1") {
+ t.Error("Expected canonical related resource in context")
+ }
+
+ s.mu.Lock()
+ s.resourceExportStore = nil
+ s.resourceExportStoreOrgID = ""
+ s.mu.Unlock()
+
+ // Case 8: With Change Logic
cd := NewChangeDetector(memory.ChangeDetectorConfig{})
// Simulate a "created" change
cd.DetectChanges([]memory.ResourceSnapshot{
@@ -324,7 +370,7 @@ func TestService_BuildEnrichedResourceContext(t *testing.T) {
t.Error("Expected creation event in context")
}
- // Case 8: With Correlation Logic
+ // Case 9: With Correlation Logic
// We need correlation package or just use the alias
cord := NewCorrelationDetector(DefaultCorrelationConfig())
// Record an event that should contribute to correlation
diff --git a/internal/ai/service.go b/internal/ai/service.go
index de7df5763b..157a88b3f0 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -4545,6 +4545,68 @@ func extractAlertIdentifier(ctx map[string]interface{}) string {
return ""
}
+func (s *Service) buildRecentResourceChangesContext(resourceID string) string {
+ resourceID = strings.TrimSpace(resourceID)
+ if resourceID == "" {
+ return ""
+ }
+
+ s.mu.RLock()
+ store := s.resourceExportStore
+ orgID := strings.TrimSpace(s.orgID)
+ storeOrgID := strings.TrimSpace(s.resourceExportStoreOrgID)
+ patrol := s.patrolService
+ s.mu.RUnlock()
+
+ if store != nil && (storeOrgID == "" || storeOrgID == orgID) {
+ changes, err := store.GetRecentChanges(resourceID, time.Now().Add(-24*time.Hour), 5)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("resource_id", resourceID).
+ Msg("failed to load canonical resource timeline context")
+ } else if len(changes) > 0 {
+ var changeInfo []string
+ for _, change := range changes {
+ if len(changeInfo) >= 3 {
+ break
+ }
+ changeInfo = append(changeInfo, formatResourceChangeContext(change))
+ }
+ if len(changeInfo) > 0 {
+ return "\n\n### Recent Changes\n" + strings.Join(changeInfo, "\n")
+ }
+ }
+ }
+
+ if patrol == nil {
+ return ""
+ }
+
+ changeDetector := patrol.GetChangeDetector()
+ if changeDetector == nil {
+ return ""
+ }
+
+ changes := changeDetector.GetChangesForResource(resourceID, 5)
+ 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 ""
+ }
+ return "\n\n### Recent Changes\n" + strings.Join(changeInfo, "\n")
+}
+
// truncateString truncates a string to maxLen characters
func truncateString(s string, maxLen int) string {
if len(s) <= maxLen {
@@ -4553,6 +4615,73 @@ func truncateString(s string, maxLen int) string {
return s[:maxLen-3] + "..."
}
+func formatResourceChangeContext(change unifiedresources.ResourceChange) string {
+ label := formatResourceChangeKindLabel(change.Kind)
+ summary := fmt.Sprintf("**%s**", label)
+
+ if from := strings.TrimSpace(change.From); from != "" || strings.TrimSpace(change.To) != "" {
+ to := strings.TrimSpace(change.To)
+ if from == "" {
+ summary += fmt.Sprintf(" → %s", to)
+ } else if to == "" {
+ summary += fmt.Sprintf(" %s →", from)
+ } else {
+ summary += fmt.Sprintf(" %s → %s", from, to)
+ }
+ }
+
+ provenance := make([]string, 0, 2)
+ if sourceType := strings.TrimSpace(string(change.SourceType)); sourceType != "" {
+ provenance = append(provenance, sourceType)
+ }
+ if sourceAdapter := strings.TrimSpace(string(change.SourceAdapter)); sourceAdapter != "" {
+ provenance = append(provenance, sourceAdapter)
+ }
+ if len(provenance) > 0 {
+ summary += fmt.Sprintf(" [%s]", strings.Join(provenance, "/"))
+ }
+
+ if actor := strings.TrimSpace(change.Actor); actor != "" {
+ summary += fmt.Sprintf("; actor %s", actor)
+ }
+ if reason := strings.TrimSpace(change.Reason); reason != "" {
+ summary += fmt.Sprintf("; %s", reason)
+ }
+ if len(change.RelatedResources) > 0 {
+ summary += fmt.Sprintf("; related: %s", strings.Join(change.RelatedResources, ", "))
+ }
+
+ ago := "recently"
+ if !change.ObservedAt.IsZero() {
+ ago = formatDuration(time.Since(change.ObservedAt).Truncate(time.Minute))
+ }
+ summary += fmt.Sprintf(" (%s ago)", ago)
+ return summary
+}
+
+func formatResourceChangeKindLabel(kind unifiedresources.ChangeKind) string {
+ switch kind {
+ case unifiedresources.ChangeStateTransition:
+ return "State transition"
+ case unifiedresources.ChangeRestart:
+ return "Restart"
+ case unifiedresources.ChangeConfigUpdate:
+ return "Config update"
+ case unifiedresources.ChangeAnomaly:
+ return "Metric anomaly"
+ case unifiedresources.ChangeRelationship:
+ return "Relationship change"
+ case unifiedresources.ChangeCapability:
+ return "Capability change"
+ default:
+ raw := strings.TrimSpace(strings.ReplaceAll(string(kind), "_", " "))
+ if raw == "" {
+ return "Change"
+ }
+ return strings.ToUpper(raw[:1]) + raw[1:]
+ }
+}
+
// buildEnrichedResourceContext adds historical intelligence to regular AI chat
// This is what makes Pulse Pro valuable - context that Claude Code can't have:
// - Baseline comparisons ("this is 2x normal")
@@ -4723,22 +4852,8 @@ func (s *Service) buildEnrichedResourceContext(resourceID, _ string, currentMetr
}
// Get change detector for recent changes
- changeDetector := patrol.GetChangeDetector()
- if changeDetector != nil {
- changes := changeDetector.GetChangesForResource(resourceID, 5)
- if len(changes) > 0 {
- var changeInfo []string
- for _, c := range changes {
- if len(changeInfo) >= 3 { // Limit to 3 recent changes
- 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 {
- sections = append(sections, "### Recent Changes\n"+strings.Join(changeInfo, "\n"))
- }
- }
+ if recentChanges := s.buildRecentResourceChangesContext(resourceID); recentChanges != "" {
+ sections = append(sections, recentChanges)
}
// Get correlation detector for related resources