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.

Hydrate Assistant handoff resource timeline context

rcourtman05f47560de0d
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 7635555e44..c40b2e05e1 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -185,11 +185,15 @@ runtime cost control, and shared AI transport surfaces.
references may persist as session model-context metadata for follow-up turns,
but they remain references only; each turn must rehydrate them from the
current canonical unified-resource model before action validation can use
- them. The runtime may also persist structured pending-action and approval
- references from the same investigation record as model-context metadata, but
- those references are review context only: they must not include raw command
- text, must not grant approval or execution authority, and must route any
- operator decision back through the governed approval/remediation flow. When
+ them. Assistant runtime may also hydrate recent changes for those handoff
+ resources from the canonical unified-resource timeline as model-only context
+ on each turn, but those timeline facts remain read-only explanation context
+ and do not grant action authority. The runtime may also persist structured
+ pending-action and approval references from the same investigation record as
+ model-context metadata, but those references are review context only: they
+ must not include raw command text, must not grant approval or execution
+ authority, and must route any operator decision back through the governed
+ approval/remediation flow. When
those references include an approval ID, Assistant runtime may refresh a
current status snapshot from the canonical approval store on each turn, but
it must enforce org scoping and still omit the approval command payload.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index bb638964a0..fa077a5cd3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -756,16 +756,19 @@ the canonical monitored-system blocked payload.
affect session-scoped action validation. If stored for follow-up turns, they
remain model-context references rather than saved user text or action
authority, and the runtime must re-resolve them against current canonical
- resources before use. The backend may also carry structured pending-action
- and approval references from the investigation record into chat execution,
- but those references must omit raw proposed-fix commands, remain model-only
- review context, and leave approval/execution authority with the governed
- approval and remediation APIs. Chat execution may refresh approval status
- snapshots for those references from the canonical approval store, but that
- snapshot is read-only, org-scoped, and must not expose or infer the raw
- command. Frontend handoff briefings must derive from the same shared
- investigation payload rather than inventing a second finding-context
- transport shape.
+ resources before use. Chat execution may also hydrate recent changes for
+ those handoff resources from the canonical unified-resource timeline, but the
+ resulting context is read-only, model-only explanation data and must not
+ become saved user text or action authority. The backend may also carry
+ structured pending-action and approval references from the investigation
+ record into chat execution, but those references must omit raw proposed-fix
+ commands, remain model-only review context, and leave approval/execution
+ authority with the governed approval and remediation APIs. Chat execution may
+ refresh approval status snapshots for those references from the canonical
+ approval store, but that snapshot is read-only, org-scoped, and must not
+ expose or infer the raw command. Frontend handoff briefings must derive from
+ the same shared investigation payload rather than inventing a second
+ finding-context transport shape.
7. Keep Patrol summary payload consumers aligned on one assessment hierarchy: transport-driven Patrol summary surfaces may show supporting counts and outcomes, but the canonical assessment and verification states must remain singular and not be repeated as a second compact verdict strip
8. Keep Patrol verification and activity facts unified on one transport-backed secondary status area: when frontend consumers combine Patrol status payloads (`runtime_state`, `last_patrol_at`, `last_activity_at`, `trigger_status`) with run-history transport, the latest run result, activity mix, scoped-trigger state, and circuit-breaker context must read as one supporting explanation beneath the primary assessment instead of being re-expanded into a separate full-width status strip plus duplicate summary layers
and the main Patrol page composition boundary, so once that governed
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 3fd8fab41f..2a656f3592 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -108,7 +108,10 @@ Patrol-specific presentation helpers.
governed approval/remediation surfaces. Assistant may refresh the referenced
approval's current status for review, but Patrol presentation must still keep
command payloads inside governed approval/remediation context rather than
- rendering them as handoff copy.
+ rendering them as handoff copy. Assistant may also enrich that same handoff
+ with recent canonical resource-timeline changes for explanation, but Patrol
+ must keep the visible finding and drawer briefing tied to the shared
+ investigation payload rather than forking a Patrol-local timeline summary.
## Current State
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 2f9a1eacc7..595d25c80b 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1018,6 +1018,12 @@ The same surfaces now also render recent changes through the shared
`frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx`
card, so canonical timeline wording and ordering stay governed by one
frontend feed instead of separate page-local loops.
+Assistant finding handoffs are part of that same timeline contract: when the AI
+runtime needs recent changes for product-originated handoff resources, it should
+read the canonical unified-resource timeline and `FormatResourceRecentChangesContext`
+rather than rebuilding recent-change wording or querying Patrol-local change
+detectors first. Those handoff timeline entries remain read-only explanation
+context, not action authority.
The unified-resource detail drawer now also routes resource-tag presentation
through the shared `frontend-modern/src/components/shared/TagBadges.tsx`
primitive instead of importing a workload-local badge helper into the
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index d776453132..6bd40d2b4a 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -524,6 +524,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist refreshed handoff action status")
}
}
+ handoffContext = mergeHandoffResourceTimelineContext(handoffContext, handoffResources, s.actionAuditStore, time.Now())
handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)
injectHandoffContextIntoLatestUserMessage(messages, handoffContext)
@@ -852,6 +853,80 @@ func mergeHandoffActionContext(handoffContext string, handoffActions []HandoffAc
}
}
+func mergeHandoffResourceTimelineContext(handoffContext string, handoffResources []HandoffResource, store unifiedresources.ResourceStore, now time.Time) string {
+ timelineContext := buildHandoffResourceTimelineContext(handoffResources, store, now)
+ switch {
+ case strings.TrimSpace(handoffContext) == "":
+ return timelineContext
+ case timelineContext == "":
+ return strings.TrimSpace(handoffContext)
+ default:
+ return strings.TrimSpace(handoffContext) + "\n\n" + timelineContext
+ }
+}
+
+func buildHandoffResourceTimelineContext(handoffResources []HandoffResource, store unifiedresources.ResourceStore, now time.Time) string {
+ resources := normalizeHandoffResources(handoffResources)
+ if len(resources) == 0 || store == nil {
+ return ""
+ }
+ if now.IsZero() {
+ now = time.Now()
+ }
+
+ const (
+ perResourceLimit = 5
+ totalLimit = 8
+ )
+ since := now.Add(-24 * time.Hour)
+ changes := make([]unifiedresources.ResourceChange, 0, len(resources)*perResourceLimit)
+ seen := make(map[string]struct{})
+ for _, resource := range resources {
+ resourceID := strings.TrimSpace(resource.ID)
+ if resourceID == "" {
+ continue
+ }
+ recent, err := store.GetRecentChangesFiltered(resourceID, since, perResourceLimit, unifiedresources.ResourceChangeFilters{IncludeRelated: true})
+ if err != nil {
+ log.Debug().
+ Err(err).
+ Str("resource_id", resourceID).
+ Msg("[ChatService] Failed to load handoff resource timeline")
+ continue
+ }
+ for _, change := range recent {
+ key := handoffResourceTimelineChangeKey(change)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ changes = append(changes, change)
+ }
+ }
+ if len(changes) == 0 {
+ return ""
+ }
+ sort.SliceStable(changes, func(i, j int) bool {
+ return changes[i].ObservedAt.After(changes[j].ObservedAt)
+ })
+ if len(changes) > totalLimit {
+ changes = changes[:totalLimit]
+ }
+
+ contextText := strings.TrimSpace(unifiedresources.FormatResourceRecentChangesContext(changes, true, "###"))
+ if contextText == "" {
+ return ""
+ }
+ return contextText + "\nTimeline Boundary: Recent changes are read-only canonical resource timeline context; they are not approval or execution authority."
+}
+
+func handoffResourceTimelineChangeKey(change unifiedresources.ResourceChange) string {
+ if id := strings.TrimSpace(change.ID); id != "" {
+ return id
+ }
+ return strings.ToLower(strings.TrimSpace(change.ResourceID) + "\x00" + string(change.Kind) + "\x00" + change.ObservedAt.UTC().Format(time.RFC3339Nano))
+}
+
func buildHandoffActionContext(handoffActions []HandoffAction) string {
actions := normalizeHandoffActions(handoffActions)
if len(actions) == 0 {
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index e23decd5b2..9e667bb759 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -134,6 +134,21 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {
if err != nil {
t.Fatalf("failed to create session store: %v", err)
}
+ timelineStore := unifiedresources.NewMemoryStore()
+ if err := timelineStore.RecordChange(unifiedresources.ResourceChange{
+ ID: "change-123",
+ ResourceID: "vm-100",
+ ObservedAt: time.Now().Add(-10 * time.Minute),
+ Kind: unifiedresources.ChangeStateTransition,
+ From: "running",
+ To: "degraded",
+ SourceType: unifiedresources.SourcePulseDiff,
+ SourceAdapter: unifiedresources.AdapterProxmox,
+ Confidence: unifiedresources.ConfidenceHigh,
+ Reason: "CPU saturation detected after backup job",
+ }); err != nil {
+ t.Fatalf("RecordChange failed: %v", err)
+ }
executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
var capturedMessages []providers.Message
@@ -154,18 +169,25 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {
loop := NewAgenticLoop(provider, executor, "system")
svc := &Service{
- cfg: &config.AIConfig{ChatModel: "openai:test"},
- sessions: store,
- executor: executor,
- agenticLoop: loop,
- provider: provider,
- started: true,
+ cfg: &config.AIConfig{ChatModel: "openai:test"},
+ sessions: store,
+ executor: executor,
+ agenticLoop: loop,
+ provider: provider,
+ started: true,
+ actionAuditStore: timelineStore,
}
req := ExecuteRequest{
SessionID: "sess-handoff",
Prompt: "What happened?",
HandoffContext: "[Finding Context]\nID: finding-123\nConclusion: CPU saturated after backup.",
+ HandoffResources: []HandoffResource{{
+ ID: "vm-100",
+ Name: "web-server",
+ Type: "vm",
+ Node: "pve-1",
+ }},
HandoffActions: []HandoffAction{{
FindingID: "finding-123",
RecordID: "record-123",
@@ -200,6 +222,9 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {
if strings.Contains(stored[0].Content, "[Action Context]") {
t.Fatalf("stored user message should not include action context: %q", stored[0].Content)
}
+ if strings.Contains(stored[0].Content, "Recent Changes Across Infrastructure") {
+ t.Fatalf("stored user message should not include timeline context: %q", stored[0].Content)
+ }
if len(capturedMessages) == 0 {
t.Fatal("expected provider messages")
@@ -220,6 +245,15 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {
if !strings.Contains(modelUserContent, "Pending Action Approval Status: pending") {
t.Fatalf("model user content missing approval status: %q", modelUserContent)
}
+ if !strings.Contains(modelUserContent, "### Recent Changes Across Infrastructure") {
+ t.Fatalf("model user content missing timeline context: %q", modelUserContent)
+ }
+ if !strings.Contains(modelUserContent, "vm-100: **State transition** running") {
+ t.Fatalf("model user content missing canonical timeline summary: %q", modelUserContent)
+ }
+ if !strings.Contains(modelUserContent, "Timeline Boundary: Recent changes are read-only canonical resource timeline context") {
+ t.Fatalf("model user content missing timeline boundary: %q", modelUserContent)
+ }
if strings.Contains(modelUserContent, "systemctl restart workload.service") {
t.Fatalf("model user content must not infer raw command text: %q", modelUserContent)
}
@@ -242,6 +276,21 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi
if err != nil {
t.Fatalf("failed to create session store: %v", err)
}
+ timelineStore := unifiedresources.NewMemoryStore()
+ if err := timelineStore.RecordChange(unifiedresources.ResourceChange{
+ ID: "change-followup",
+ ResourceID: "vm-100",
+ ObservedAt: time.Now().Add(-5 * time.Minute),
+ Kind: unifiedresources.ChangeConfigUpdate,
+ From: "backup-window",
+ To: "backup-window+cpu-spike",
+ SourceType: unifiedresources.SourcePulseDiff,
+ SourceAdapter: unifiedresources.AdapterProxmox,
+ Confidence: unifiedresources.ConfidenceHigh,
+ Reason: "backup job changed workload pressure",
+ }); err != nil {
+ t.Fatalf("RecordChange failed: %v", err)
+ }
executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
var capturedRequests [][]providers.Message
@@ -262,12 +311,13 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi
loop := NewAgenticLoop(provider, executor, "system")
svc := &Service{
- cfg: &config.AIConfig{ChatModel: "openai:test"},
- sessions: store,
- executor: executor,
- agenticLoop: loop,
- provider: provider,
- started: true,
+ cfg: &config.AIConfig{ChatModel: "openai:test"},
+ sessions: store,
+ executor: executor,
+ agenticLoop: loop,
+ provider: provider,
+ started: true,
+ actionAuditStore: timelineStore,
}
handoffContext := "[Finding Context]\nID: finding-123\nConclusion: CPU saturated after backup."
@@ -288,6 +338,12 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi
SessionID: "sess-handoff-followup",
Prompt: "What happened?",
HandoffContext: handoffContext,
+ HandoffResources: []HandoffResource{{
+ ID: "vm-100",
+ Name: "web-server",
+ Type: "vm",
+ Node: "pve-1",
+ }},
HandoffActions: handoffActions,
}
if err := svc.ExecuteStream(context.Background(), firstReq, func(StreamEvent) {}); err != nil {
@@ -322,6 +378,9 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi
if strings.Contains(content, "[Action Context]") {
t.Fatalf("stored user message should not include action context: %q", content)
}
+ if strings.Contains(content, "Recent Changes Across Infrastructure") {
+ t.Fatalf("stored user message should not include timeline context: %q", content)
+ }
}
if storedUserMessages[0] != "What happened?" || storedUserMessages[1] != "What should I do next?" {
t.Fatalf("stored user messages = %#v, want clean prompts", storedUserMessages)
@@ -346,6 +405,9 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi
if !strings.Contains(firstModelUserContent, "Pending Action Approval Status: pending") {
t.Fatalf("first provider turn missing approval status: %q", firstModelUserContent)
}
+ if !strings.Contains(firstModelUserContent, "### Recent Changes Across Infrastructure") {
+ t.Fatalf("first provider turn missing timeline context: %q", firstModelUserContent)
+ }
secondModelUserContent := latestProviderUserContent(t, capturedRequests[1])
if !strings.Contains(secondModelUserContent, "[Finding Context]") {
t.Fatalf("follow-up provider turn missing stored handoff context: %q", secondModelUserContent)
@@ -362,11 +424,63 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi
if !strings.Contains(secondModelUserContent, "Pending Action Approval Status: pending") {
t.Fatalf("follow-up provider turn missing refreshed approval status: %q", secondModelUserContent)
}
+ if !strings.Contains(secondModelUserContent, "### Recent Changes Across Infrastructure") {
+ t.Fatalf("follow-up provider turn missing stored resource timeline context: %q", secondModelUserContent)
+ }
if strings.Contains(firstModelUserContent+secondModelUserContent, "systemctl restart workload.service") {
t.Fatalf("provider turns must not include raw command text")
}
}
+func TestBuildHandoffResourceTimelineContextUsesRelatedCanonicalChanges(t *testing.T) {
+ now := time.Now()
+ store := unifiedresources.NewMemoryStore()
+ for _, change := range []unifiedresources.ResourceChange{
+ {
+ ID: "change-direct",
+ ResourceID: "vm-100",
+ ObservedAt: now.Add(-2 * time.Minute),
+ Kind: unifiedresources.ChangeStateTransition,
+ From: "running",
+ To: "degraded",
+ SourceType: unifiedresources.SourcePulseDiff,
+ SourceAdapter: unifiedresources.AdapterProxmox,
+ Confidence: unifiedresources.ConfidenceHigh,
+ RelatedResources: []string{"storage-1"},
+ },
+ {
+ ID: "change-related",
+ ResourceID: "storage-1",
+ ObservedAt: now.Add(-1 * time.Minute),
+ Kind: unifiedresources.ChangeActivity,
+ To: "backup completed",
+ SourceType: unifiedresources.SourcePlatformEvent,
+ SourceAdapter: unifiedresources.AdapterProxmox,
+ Confidence: unifiedresources.ConfidenceHigh,
+ RelatedResources: []string{"vm-100"},
+ },
+ } {
+ if err := store.RecordChange(change); err != nil {
+ t.Fatalf("RecordChange(%s) failed: %v", change.ID, err)
+ }
+ }
+
+ contextText := buildHandoffResourceTimelineContext([]HandoffResource{{
+ ID: "vm-100",
+ Name: "web-server",
+ Type: "vm",
+ }}, store, now)
+ if !strings.Contains(contextText, "vm-100: **State transition** running") {
+ t.Fatalf("timeline context missing direct change: %q", contextText)
+ }
+ if !strings.Contains(contextText, "storage-1: **Activity**") {
+ t.Fatalf("timeline context missing related change: %q", contextText)
+ }
+ if strings.Contains(contextText, "Approval ID") {
+ t.Fatalf("timeline context should not include approval metadata: %q", contextText)
+ }
+}
+
func TestRefreshHandoffActionApprovalStatusRejectsCrossOrgApproval(t *testing.T) {
installTestApprovalStore(t, &approval.ApprovalRequest{
ID: "approval-cross-org",
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index c467bb2feb..3e07d8f7d9 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -167,9 +167,11 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
"sessions.SetModelHandoffActions(session.ID, handoffActions)",
"sessions.GetModelHandoffActions(session.ID)",
"refreshHandoffActionApprovalStatus(handoffActions, s.orgID)",
+ "mergeHandoffResourceTimelineContext(handoffContext, handoffResources, s.actionAuditStore, time.Now())",
"handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)",
"s.hydrateHandoffResources(session.ID, handoffResources, sessions, unifiedResourceProvider)",
"injectHandoffContextIntoLatestUserMessage(messages, handoffContext)",
+ "Timeline Boundary",
"Approval Status",
"Action Boundary",
"User message: ",