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
Persist Assistant handoff action references
rcourtman5c8070c58283
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 1381e3211b..7b9b1b9048 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -360,7 +360,11 @@ profile and assignment columns, but embedded table framing must route throughcontext for a Patrol finding, including same-session metadata retained forfollow-up turns and any resolved-resource scope hydrated from that finding,is also not agent lifecycle state and must not be used as enrollment- evidence, command-websocket identity, or installer authority.+ evidence, command-websocket identity, or installer authority. Structured+ Assistant handoff action references from the same Patrol finding remain+ AI/runtime review metadata only; lifecycle code must not treat approval IDs,+ fix IDs, risk, or target-resource labels from that handoff as agent command+ grants, enrollment proof, or auto-approval policy.The same isolation rule applies to CSRF token-store behavior in`internal/api/csrf_store.go`: lifecycle-adjacent browser flows may rely onthe shared API/security layer to keep parallel replacement-token retriesdiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 6d4ce83e00..af264d032a 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -185,8 +185,13 @@ 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 thecurrent canonical unified-resource model before action validation can use- them. Proposed-fix command text must stay out of both the persisted chat- message and the model-only handoff context, and command payloads remain+ 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.+ Proposed-fix command text must stay out of both the persisted chat message+ and the model-only handoff context, and command payloads remainapproval-context data, not conversational copy.The Assistant drawer may also render an attached context briefing for thathandoff, but the briefing is runtime context visibility only: it must notdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex b8627952bf..40c7c4245c 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -756,9 +756,13 @@ the canonical monitored-system blocked payload.affect session-scoped action validation. If stored for follow-up turns, theyremain model-context references rather than saved user text or actionauthority, and the runtime must re-resolve them against current canonical- resources before use. Frontend handoff briefings must derive from the same- shared investigation payload rather than inventing a second finding-context- transport shape.+ 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. 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 strip8. 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 layersand the main Patrol page composition boundary, so once that governeddiff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 765400e05c..203b607e30 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -101,7 +101,11 @@ Patrol-specific presentation helpers.must flow through the governed Patrol investigation-context helpers. Thosehelpers also own the Assistant drawer briefing content for Patrol records,including the rule that proposed-fix commands are summarized by count only- and never rendered as raw command text in the handoff surface.+ and never rendered as raw command text in the handoff surface. When Patrol+ hands a pending fix or approval into Assistant, the shared handoff may retain+ only structured action references such as approval ID, fix ID, risk, target,+ and resource identity; approval and execution authority stays with the+ governed approval/remediation surfaces.## Current Statediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex d8ea50cd2d..24278c33d1 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -416,7 +416,11 @@ bypass the API fail-closed execution gate.unchanged. If the same handoff seeds Assistant resolved-resource scope, thatscope remains AI/runtime action-validation context only and still cannotbecome backup freshness, restore eligibility, or storage-local recovery- authority.+ authority. Structured action or approval references carried by that handoff+ are also adjacent AI/runtime review metadata only; storage and recovery+ surfaces must not reinterpret approval IDs, fix IDs, risk, or target labels+ as restore support, backup freshness, recovery execution authority, or a+ storage-local approval bypass.That same adjacent `internal/api/` boundary still carries Patrol-runexecution identity. Storage and recovery may observe shared Patroltransport through `internal/api/chat_service_adapter.go`, but they must notdiff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 6d907d4568..97fa2eb4cf 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -450,6 +450,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbachandoffContext := strings.TrimSpace(req.HandoffContext)handoffResources := normalizeHandoffResources(req.HandoffResources)+ handoffActions := normalizeHandoffActions(req.HandoffActions)if handoffContext != "" {if err := sessions.SetModelHandoffContext(session.ID, handoffContext); err != nil {log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff context")@@ -457,6 +458,9 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacif err := sessions.SetModelHandoffResources(session.ID, handoffResources); err != nil {log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff resources")}+ if err := sessions.SetModelHandoffActions(session.ID, handoffActions); err != nil {+ log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff actions")+ }} else {if len(handoffResources) > 0 {if err := sessions.SetModelHandoffResources(session.ID, handoffResources); err != nil {@@ -470,6 +474,18 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbachandoffResources = storedHandoffResources}}+ if len(handoffActions) > 0 {+ if err := sessions.SetModelHandoffActions(session.ID, handoffActions); err != nil {+ log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff actions")+ }+ } else {+ storedHandoffActions, err := sessions.GetModelHandoffActions(session.ID)+ if err != nil {+ log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to load model handoff actions")+ } else {+ handoffActions = storedHandoffActions+ }+ }storedHandoffContext, err := sessions.GetModelHandoffContext(session.ID)if err != nil {log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to load model handoff context")@@ -501,6 +517,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacInt("message_count", len(messages)).Msg("[ChatService] Got messages, calling agentic loop")+ handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)injectHandoffContextIntoLatestUserMessage(messages, handoffContext)// Determine which model/loop to use for this request.@@ -816,6 +833,82 @@ func injectHandoffContextIntoLatestUserMessage(messages []Message, handoffContex}}+func mergeHandoffActionContext(handoffContext string, handoffActions []HandoffAction) string {+ actionContext := buildHandoffActionContext(handoffActions)+ switch {+ case strings.TrimSpace(handoffContext) == "":+ return actionContext+ case actionContext == "":+ return strings.TrimSpace(handoffContext)+ default:+ return strings.TrimSpace(handoffContext) + "\n\n" + actionContext+ }+}++func buildHandoffActionContext(handoffActions []HandoffAction) string {+ actions := normalizeHandoffActions(handoffActions)+ if len(actions) == 0 {+ return ""+ }++ var b strings.Builder+ b.WriteString("[Action Context]")+ for idx, action := range actions {+ label := "Pending Action"+ if len(actions) > 1 {+ label = fmt.Sprintf("Pending Action %d", idx+1)+ }+ appendHandoffActionLine(&b, label+" Finding ID", action.FindingID)+ appendHandoffActionLine(&b, label+" Record ID", action.RecordID)+ appendHandoffActionLine(&b, label+" Approval ID", action.ApprovalID)+ appendHandoffActionLine(&b, label+" Fix ID", action.FixID)+ appendHandoffActionLine(&b, label+" Proposed Fix", action.Description)+ appendHandoffActionLine(&b, label+" Risk", action.RiskLevel)+ if action.Destructive {+ appendHandoffActionLine(&b, label+" Destructive", "true")+ }+ appendHandoffActionLine(&b, label+" Target Host", action.TargetHost)+ appendHandoffActionLine(&b, label+" Target Resource", formatHandoffActionResource(action))+ }+ appendHandoffActionLine(&b, "Action Boundary", "Review and approval must stay in governed approval/remediation flows; this reference is not command authority and must not be used to infer raw command text.")+ return strings.TrimSpace(b.String())+}++func appendHandoffActionLine(b *strings.Builder, label, value string) {+ value = strings.TrimSpace(value)+ if value == "" {+ return+ }+ if b.Len() > 0 {+ b.WriteByte('\n')+ }+ b.WriteString(label)+ b.WriteString(": ")+ b.WriteString(value)+}++func formatHandoffActionResource(action HandoffAction) string {+ resourceName := strings.TrimSpace(action.TargetResourceName)+ resourceType := strings.TrimSpace(action.TargetResourceType)+ resourceID := strings.TrimSpace(action.TargetResourceID)+ node := strings.TrimSpace(action.TargetNode)++ parts := make([]string, 0, 4)+ if resourceName != "" {+ parts = append(parts, resourceName)+ }+ if resourceType != "" {+ parts = append(parts, resourceType)+ }+ if resourceID != "" {+ parts = append(parts, resourceID)+ }+ if node != "" {+ parts = append(parts, "node "+node)+ }+ return strings.Join(parts, " / ")+}+func (s *Service) hydrateHandoffResources(sessionID string, handoffResources []HandoffResource, sessions *SessionStore, provider tools.UnifiedResourceProvider) {if len(handoffResources) == 0 || sessions == nil || provider == nil {returndiff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.goindex f3f8f424db..7238dd9d9e 100644--- a/internal/ai/chat/service_execute_additional_test.go+++ b/internal/ai/chat/service_execute_additional_test.go@@ -132,6 +132,19 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {SessionID: "sess-handoff",Prompt: "What happened?",HandoffContext: "[Finding Context]\nID: finding-123\nConclusion: CPU saturated after backup.",+ HandoffActions: []HandoffAction{{+ FindingID: "finding-123",+ RecordID: "record-123",+ ApprovalID: "approval-123",+ FixID: "fix-123",+ Description: "Restart the workload service",+ RiskLevel: "medium",+ TargetHost: "pve-1",+ TargetResourceID: "vm-100",+ TargetResourceName: "web-server",+ TargetResourceType: "vm",+ TargetNode: "pve-1",+ }},}if err := svc.ExecuteStream(context.Background(), req, func(StreamEvent) {}); err != nil {t.Fatalf("ExecuteStream failed: %v", err)@@ -150,6 +163,9 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {if strings.Contains(stored[0].Content, "[Finding Context]") {t.Fatalf("stored user message should not include handoff context: %q", stored[0].Content)}+ if strings.Contains(stored[0].Content, "[Action Context]") {+ t.Fatalf("stored user message should not include action context: %q", stored[0].Content)+ }if len(capturedMessages) == 0 {t.Fatal("expected provider messages")@@ -161,6 +177,15 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {if !strings.Contains(modelUserContent, "User message: What happened?") {t.Fatalf("model user content missing clean user message: %q", modelUserContent)}+ if !strings.Contains(modelUserContent, "[Action Context]") {+ t.Fatalf("model user content missing action context: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Pending Action Approval ID: approval-123") {+ t.Fatalf("model user content missing approval reference: %q", modelUserContent)+ }+ if strings.Contains(modelUserContent, "systemctl restart workload.service") {+ t.Fatalf("model user content must not infer raw command text: %q", modelUserContent)+ }}func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testing.T) {@@ -198,10 +223,24 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi}handoffContext := "[Finding Context]\nID: finding-123\nConclusion: CPU saturated after backup."+ handoffActions := []HandoffAction{{+ FindingID: "finding-123",+ RecordID: "record-123",+ ApprovalID: "approval-123",+ FixID: "fix-123",+ Description: "Restart the workload service",+ RiskLevel: "medium",+ TargetHost: "pve-1",+ TargetResourceID: "vm-100",+ TargetResourceName: "web-server",+ TargetResourceType: "vm",+ TargetNode: "pve-1",+ }}firstReq := ExecuteRequest{SessionID: "sess-handoff-followup",Prompt: "What happened?",HandoffContext: handoffContext,+ HandoffActions: handoffActions,}if err := svc.ExecuteStream(context.Background(), firstReq, func(StreamEvent) {}); err != nil {t.Fatalf("first ExecuteStream failed: %v", err)@@ -232,6 +271,9 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testiif strings.Contains(content, "[Finding Context]") {t.Fatalf("stored user message should not include handoff context: %q", content)}+ if strings.Contains(content, "[Action Context]") {+ t.Fatalf("stored user message should not include action 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)@@ -247,6 +289,12 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testiif !strings.Contains(firstModelUserContent, "User message: What happened?") {t.Fatalf("first provider turn missing clean user message: %q", firstModelUserContent)}+ if !strings.Contains(firstModelUserContent, "[Action Context]") {+ t.Fatalf("first provider turn missing action context: %q", firstModelUserContent)+ }+ if !strings.Contains(firstModelUserContent, "Pending Action Approval ID: approval-123") {+ t.Fatalf("first provider turn missing approval reference: %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)@@ -254,6 +302,15 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testiif !strings.Contains(secondModelUserContent, "User message: What should I do next?") {t.Fatalf("follow-up provider turn missing clean user message: %q", secondModelUserContent)}+ if !strings.Contains(secondModelUserContent, "[Action Context]") {+ t.Fatalf("follow-up provider turn missing stored action context: %q", secondModelUserContent)+ }+ if !strings.Contains(secondModelUserContent, "Pending Action Approval ID: approval-123") {+ t.Fatalf("follow-up provider turn missing stored approval reference: %q", secondModelUserContent)+ }+ if strings.Contains(firstModelUserContent+secondModelUserContent, "systemctl restart workload.service") {+ t.Fatalf("provider turns must not include raw command text")+ }}func TestService_ExecuteStream_HandoffResourceHydratesResolvedContext(t *testing.T) {diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.goindex b2a08f106b..62531aa6f8 100644--- a/internal/ai/chat/session.go+++ b/internal/ai/chat/session.go@@ -53,6 +53,7 @@ type sessionData struct {type sessionModelContext struct {HandoffContext string `json:"handoff_context,omitempty"`HandoffResources []HandoffResource `json:"handoff_resources,omitempty"`+ HandoffActions []HandoffAction `json:"handoff_actions,omitempty"`UpdatedAt time.Time `json:"updated_at,omitempty"`}@@ -84,6 +85,50 @@ func normalizeHandoffResources(resources []HandoffResource) []HandoffResource {return normalized}+func normalizeHandoffActions(actions []HandoffAction) []HandoffAction {+ if len(actions) == 0 {+ return nil+ }++ normalized := make([]HandoffAction, 0, len(actions))+ seen := make(map[string]struct{}, len(actions))+ for _, action := range actions {+ action.FindingID = strings.TrimSpace(action.FindingID)+ action.RecordID = strings.TrimSpace(action.RecordID)+ action.ApprovalID = strings.TrimSpace(action.ApprovalID)+ action.FixID = strings.TrimSpace(action.FixID)+ action.Description = strings.TrimSpace(action.Description)+ action.RiskLevel = strings.TrimSpace(action.RiskLevel)+ action.TargetHost = strings.TrimSpace(action.TargetHost)+ action.TargetResourceID = strings.TrimSpace(action.TargetResourceID)+ action.TargetResourceName = strings.TrimSpace(action.TargetResourceName)+ action.TargetResourceType = strings.TrimSpace(action.TargetResourceType)+ action.TargetNode = strings.TrimSpace(action.TargetNode)+ if action.ApprovalID == "" && action.FixID == "" && action.Description == "" && action.FindingID == "" {+ continue+ }+ key := strings.ToLower(action.FindingID + "\x00" + action.RecordID + "\x00" + action.ApprovalID + "\x00" + action.FixID + "\x00" + action.Description + "\x00" + action.TargetResourceID + "\x00" + action.TargetHost)+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ normalized = append(normalized, action)+ }+ if len(normalized) == 0 {+ return nil+ }+ return normalized+}++func modelContextEmpty(modelContext *sessionModelContext) bool {+ if modelContext == nil {+ return true+ }+ return strings.TrimSpace(modelContext.HandoffContext) == "" &&+ len(normalizeHandoffResources(modelContext.HandoffResources)) == 0 &&+ len(normalizeHandoffActions(modelContext.HandoffActions)) == 0+}+const maxSessionIDLength = 128// NewSessionStore creates a new session store@@ -379,7 +424,35 @@ func (s *SessionStore) SetModelHandoffResources(id string, handoffResources []Ha}data.ModelContext.HandoffResources = resourcesdata.ModelContext.UpdatedAt = now- if strings.TrimSpace(data.ModelContext.HandoffContext) == "" && len(data.ModelContext.HandoffResources) == 0 {+ if modelContextEmpty(data.ModelContext) {+ data.ModelContext = nil+ }+ data.UpdatedAt = now++ return s.writeSession(*data)+}++// SetModelHandoffActions stores product-originated pending action references+// for future turns. These references are not executable authority and must not+// contain raw command text.+func (s *SessionStore) SetModelHandoffActions(id string, handoffActions []HandoffAction) error {+ actions := normalizeHandoffActions(handoffActions)++ s.mu.Lock()+ defer s.mu.Unlock()++ data, err := s.readSession(id)+ if err != nil {+ return err+ }++ now := time.Now()+ if data.ModelContext == nil {+ data.ModelContext = &sessionModelContext{}+ }+ data.ModelContext.HandoffActions = actions+ data.ModelContext.UpdatedAt = now+ if modelContextEmpty(data.ModelContext) {data.ModelContext = nil}data.UpdatedAt = now@@ -419,13 +492,28 @@ func (s *SessionStore) GetModelHandoffResources(id string) ([]HandoffResource, ereturn normalizeHandoffResources(data.ModelContext.HandoffResources), nil}+// GetModelHandoffActions returns stored product-originated pending action+// references for a session. Callers must treat them as review context only.+func (s *SessionStore) GetModelHandoffActions(id string) ([]HandoffAction, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ data, err := s.readSession(id)+ if err != nil {+ return nil, err+ }+ if data.ModelContext == nil {+ return nil, nil+ }+ return normalizeHandoffActions(data.ModelContext.HandoffActions), nil+}+func (s *SessionStore) clearModelHandoffContextLocked(id string) error {data, err := s.readSession(id)if err != nil {return err}- if data.ModelContext == nil ||- (strings.TrimSpace(data.ModelContext.HandoffContext) == "" && len(normalizeHandoffResources(data.ModelContext.HandoffResources)) == 0) {+ if modelContextEmpty(data.ModelContext) {return nil}diff --git a/internal/ai/chat/session_additional_test.go b/internal/ai/chat/session_additional_test.goindex d5d55f6b86..52a2c87ef8 100644--- a/internal/ai/chat/session_additional_test.go+++ b/internal/ai/chat/session_additional_test.go@@ -90,6 +90,63 @@ func TestSessionStore_ModelHandoffContextLifecycle(t *testing.T) {t.Fatalf("handoff resource = %#v, want normalized VM", gotResources[0])}+ handoffActions := []HandoffAction{+ {+ FindingID: " finding-123 ",+ RecordID: " record-123 ",+ ApprovalID: " approval-123 ",+ FixID: " fix-123 ",+ Description: " Restart the workload service ",+ RiskLevel: " medium ",+ Destructive: true,+ TargetHost: " pve-1 ",+ TargetResourceID: " vm-100 ",+ TargetResourceName: " web-server ",+ TargetResourceType: " vm ",+ TargetNode: " pve-1 ",+ },+ {+ FindingID: "finding-123",+ RecordID: "record-123",+ ApprovalID: "approval-123",+ FixID: "fix-123",+ Description: "Restart the workload service",+ RiskLevel: "medium",+ Destructive: true,+ TargetHost: "pve-1",+ TargetResourceID: "vm-100",+ TargetResourceName: "web-server",+ TargetResourceType: "vm",+ TargetNode: "pve-1",+ },+ }+ if err := store.SetModelHandoffActions(session.ID, handoffActions); err != nil {+ t.Fatalf("SetModelHandoffActions failed: %v", err)+ }+ gotActions, err := store.GetModelHandoffActions(session.ID)+ if err != nil {+ t.Fatalf("GetModelHandoffActions failed: %v", err)+ }+ if len(gotActions) != 1 {+ t.Fatalf("handoff actions = %#v, want one normalized action", gotActions)+ }+ if gotActions[0] != (HandoffAction{+ FindingID: "finding-123",+ RecordID: "record-123",+ ApprovalID: "approval-123",+ FixID: "fix-123",+ Description: "Restart the workload service",+ RiskLevel: "medium",+ Destructive: true,+ TargetHost: "pve-1",+ TargetResourceID: "vm-100",+ TargetResourceName: "web-server",+ TargetResourceType: "vm",+ TargetNode: "pve-1",+ }) {+ t.Fatalf("handoff action = %#v, want normalized pending action", gotActions[0])+ }+reloadedStore, err := NewSessionStore(filepath.Dir(store.dataDir))if err != nil {t.Fatalf("failed to reload session store: %v", err)@@ -101,6 +158,13 @@ func TestSessionStore_ModelHandoffContextLifecycle(t *testing.T) {if len(reloadedResources) != 1 || reloadedResources[0].ID != "vm-100" {t.Fatalf("reloaded handoff resources = %#v, want persisted VM reference", reloadedResources)}+ reloadedActions, err := reloadedStore.GetModelHandoffActions(session.ID)+ if err != nil {+ t.Fatalf("GetModelHandoffActions after reload failed: %v", err)+ }+ if len(reloadedActions) != 1 || reloadedActions[0].ApprovalID != "approval-123" {+ t.Fatalf("reloaded handoff actions = %#v, want persisted approval reference", reloadedActions)+ }if err := store.SetModelHandoffResources(session.ID, nil); err != nil {t.Fatalf("SetModelHandoffResources clear failed: %v", err)@@ -119,9 +183,36 @@ func TestSessionStore_ModelHandoffContextLifecycle(t *testing.T) {if got != strings.TrimSpace(handoffContext) {t.Fatalf("handoff context after resource clear = %q, want retained context", got)}+ gotActions, err = store.GetModelHandoffActions(session.ID)+ if err != nil {+ t.Fatalf("GetModelHandoffActions after resource clear failed: %v", err)+ }+ if len(gotActions) != 1 {+ t.Fatalf("expected resource clear to retain handoff actions, got %#v", gotActions)+ }+ if err := store.SetModelHandoffActions(session.ID, nil); err != nil {+ t.Fatalf("SetModelHandoffActions clear failed: %v", err)+ }+ gotActions, err = store.GetModelHandoffActions(session.ID)+ if err != nil {+ t.Fatalf("GetModelHandoffActions after action clear failed: %v", err)+ }+ if len(gotActions) != 0 {+ t.Fatalf("handoff actions after action clear = %#v, want empty", gotActions)+ }+ got, err = store.GetModelHandoffContext(session.ID)+ if err != nil {+ t.Fatalf("GetModelHandoffContext after action clear failed: %v", err)+ }+ if got != strings.TrimSpace(handoffContext) {+ t.Fatalf("handoff context after action clear = %q, want retained context", got)+ }if err := store.SetModelHandoffResources(session.ID, handoffResources); err != nil {t.Fatalf("SetModelHandoffResources restore failed: %v", err)}+ if err := store.SetModelHandoffActions(session.ID, handoffActions); err != nil {+ t.Fatalf("SetModelHandoffActions restore failed: %v", err)+ }if err := store.AddMessage(session.ID, Message{Role: "user", Content: "What happened?"}); err != nil {t.Fatalf("AddMessage failed: %v", err)@@ -149,6 +240,13 @@ func TestSessionStore_ModelHandoffContextLifecycle(t *testing.T) {if len(gotResources) != 1 {t.Fatalf("expected keep-pinned context clear to retain handoff resources, got %#v", gotResources)}+ gotActions, err = store.GetModelHandoffActions(session.ID)+ if err != nil {+ t.Fatalf("GetModelHandoffActions after keep-pinned clear failed: %v", err)+ }+ if len(gotActions) != 1 {+ t.Fatalf("expected keep-pinned context clear to retain handoff actions, got %#v", gotActions)+ }store.ClearSessionState(session.ID, false)got, err = store.GetModelHandoffContext(session.ID)@@ -165,6 +263,13 @@ func TestSessionStore_ModelHandoffContextLifecycle(t *testing.T) {if len(gotResources) != 0 {t.Fatalf("handoff resources after full clear = %#v, want empty", gotResources)}+ gotActions, err = store.GetModelHandoffActions(session.ID)+ if err != nil {+ t.Fatalf("GetModelHandoffActions after full clear failed: %v", err)+ }+ if len(gotActions) != 0 {+ t.Fatalf("handoff actions after full clear = %#v, want empty", gotActions)+ }}func TestSessionStore_ResolvedContextLifecycle(t *testing.T) {diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.goindex 9f9e2fabca..ffa0c2f034 100644--- a/internal/ai/chat/types.go+++ b/internal/ai/chat/types.go@@ -100,6 +100,24 @@ type HandoffResource struct {Node string `json:"node,omitempty"`}+// HandoffAction represents a product-originated pending action reference.+// It is context for review only: it carries no command text and grants no+// authority to approve, execute, or replay a remediation.+type HandoffAction struct {+ FindingID string `json:"finding_id,omitempty"`+ RecordID string `json:"record_id,omitempty"`+ ApprovalID string `json:"approval_id,omitempty"`+ FixID string `json:"fix_id,omitempty"`+ Description string `json:"description,omitempty"`+ RiskLevel string `json:"risk_level,omitempty"`+ Destructive bool `json:"destructive,omitempty"`+ TargetHost string `json:"target_host,omitempty"`+ TargetResourceID string `json:"target_resource_id,omitempty"`+ TargetResourceName string `json:"target_resource_name,omitempty"`+ TargetResourceType string `json:"target_resource_type,omitempty"`+ TargetNode string `json:"target_node,omitempty"`+}+// ExecuteRequest represents a chat execution requesttype ExecuteRequest struct {Prompt string `json:"prompt"`@@ -109,6 +127,7 @@ type ExecuteRequest struct {FindingID string `json:"finding_id,omitempty"` // Pre-populate finding context for "Discuss" flowHandoffContext string `json:"handoff_context,omitempty"` // Model-only context for scoped handoffs; not persisted as user-authored text.HandoffResources []HandoffResource `json:"handoff_resources,omitempty"` // Product-originated resources to seed governed session validation.+ HandoffActions []HandoffAction `json:"handoff_actions,omitempty"` // Product-originated approval/action references for model-only review context.MaxTurns int `json:"max_turns,omitempty"` // Override max agentic turns (0 = use default)AutonomousMode *bool `json:"autonomous_mode,omitempty"` // Per-request autonomous override (nil = use service default)}diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex 0ae6d4fab1..30339a0240 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -904,6 +904,41 @@ func buildUnifiedFindingHandoffResources(f *unified.UnifiedFinding) []chat.Handoreturn resources}+func buildUnifiedFindingHandoffActions(f *unified.UnifiedFinding) []chat.HandoffAction {+ if f == nil || f.InvestigationRecord == nil {+ return nil+ }++ rec := f.InvestigationRecord+ if strings.TrimSpace(rec.ApprovalID) == "" && rec.ProposedFix == nil {+ return nil+ }++ action := chat.HandoffAction{+ FindingID: f.ID,+ RecordID: rec.ID,+ ApprovalID: rec.ApprovalID,+ TargetResourceID: rec.Subject.ResourceID,+ TargetResourceName: rec.Subject.ResourceName,+ TargetResourceType: rec.Subject.ResourceType,+ TargetNode: rec.Subject.Node,+ }+ if rec.ProposedFix != nil {+ action.FixID = rec.ProposedFix.ID+ action.Description = rec.ProposedFix.Description+ action.RiskLevel = rec.ProposedFix.RiskLevel+ action.Destructive = rec.ProposedFix.Destructive+ action.TargetHost = rec.ProposedFix.TargetHost+ }++ if strings.TrimSpace(action.ApprovalID) == "" &&+ strings.TrimSpace(action.FixID) == "" &&+ strings.TrimSpace(action.Description) == "" {+ return nil+ }+ return []chat.HandoffAction{action}+}+func formatChatResource(name, resourceType string) string {name = strings.TrimSpace(name)resourceType = strings.TrimSpace(resourceType)@@ -1139,12 +1174,14 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {// as the user's authored prompt, so conversation history stays readable.handoffContext := ""var handoffResources []chat.HandoffResource+ var handoffActions []chat.HandoffActionif req.FindingID != "" {store := h.GetUnifiedStoreForOrg(GetOrgID(ctx))if store != nil {if f := store.Get(req.FindingID); f != nil {handoffContext = buildUnifiedFindingChatContext(f)handoffResources = buildUnifiedFindingHandoffResources(f)+ handoffActions = buildUnifiedFindingHandoffActions(f)}}}@@ -1159,6 +1196,7 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {FindingID: req.FindingID,HandoffContext: handoffContext,HandoffResources: handoffResources,+ HandoffActions: handoffActions,AutonomousMode: req.AutonomousMode,}, func(event chat.StreamEvent) {if event.Type == "done" {diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.goindex d5dfd22045..3e92a59385 100644--- a/internal/api/ai_handler_test.go+++ b/internal/api/ai_handler_test.go@@ -3,6 +3,7 @@ package apiimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest""path/filepath"@@ -607,6 +608,7 @@ func TestHandleChat_IncludesInvestigationRecordContext(t *testing.T) {RiskLevel: "medium",TargetHost: "pve-1",Rationale: "The process is wedged after backup IO pressure.",+ Destructive: true,},Verification: []string{"CPU returned below 50%"},ToolsUsed: []string{"metrics.history", "ssh.exec"},@@ -642,6 +644,21 @@ func TestHandleChat_IncludesInvestigationRecordContext(t *testing.T) {Type: "vm",Node: "pve-1",}}, reqArg.HandoffResources)+ assert.Equal(t, []chat.HandoffAction{{+ FindingID: "finding-123",+ RecordID: "investigation-123",+ ApprovalID: "approval-123",+ FixID: "fix-123",+ Description: "Restart the workload service",+ RiskLevel: "medium",+ Destructive: true,+ TargetHost: "pve-1",+ TargetResourceID: "vm-100",+ TargetResourceName: "web-server",+ TargetResourceType: "vm",+ TargetNode: "pve-1",+ }}, reqArg.HandoffActions)+ assert.NotContains(t, fmt.Sprintf("%#v", reqArg.HandoffActions), "systemctl restart workload.service")})body := `{"prompt":"What happened?","finding_id":"finding-123"}`diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 9c9c356bcb..fbb3006611 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -142,9 +142,11 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {for _, required := range []string{"handoffContext = buildUnifiedFindingChatContext(f)","handoffResources = buildUnifiedFindingHandoffResources(f)",+ "handoffActions = buildUnifiedFindingHandoffActions(f)","Prompt:","HandoffContext:","HandoffResources: handoffResources",+ "HandoffActions: handoffActions",} {if !strings.Contains(handlerText, required) {t.Fatalf("ai_handler.go must preserve model-only finding handoff contract: missing %q", required)@@ -162,8 +164,12 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {"sessions.GetModelHandoffContext(session.ID)","sessions.SetModelHandoffResources(session.ID, handoffResources)","sessions.GetModelHandoffResources(session.ID)",+ "sessions.SetModelHandoffActions(session.ID, handoffActions)",+ "sessions.GetModelHandoffActions(session.ID)",+ "handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)","s.hydrateHandoffResources(session.ID, handoffResources, sessions, unifiedResourceProvider)","injectHandoffContextIntoLatestUserMessage(messages, handoffContext)",+ "Action Boundary","User message: ",} {if !strings.Contains(chatServiceText, required) {@@ -179,6 +185,9 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {"SetModelHandoffResources","GetModelHandoffResources","HandoffResources []HandoffResource",+ "SetModelHandoffActions",+ "GetModelHandoffActions",+ "HandoffActions []HandoffAction",} {if !strings.Contains(chatSessionText, required) {t.Fatalf("chat session store must persist model-only handoff metadata outside messages: missing %q", required)@@ -189,6 +198,8 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {for _, required := range []string{"type HandoffResource struct","HandoffResources []HandoffResource",+ "type HandoffAction struct",+ "HandoffActions []HandoffAction",} {if !strings.Contains(chatTypesText, required) {t.Fatalf("chat request must carry structured handoff resource scope outside messages: missing %q", required)