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
Hydrate Assistant action audit context
rcourtman8d51556d924b
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 95023bd512..2920061bde 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -370,11 +370,12 @@ profile and assignment columns, but embedded table framing must route throughhandoff context remain Patrol/AI review metadata and must not become agentlifecycle state or fleet-control authority. Structured Assistant handoff actionreferences 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. Any approval status snapshot refreshed for- Assistant review remains read-only AI/runtime context and must not become- command-websocket authority or lifecycle execution state.+ only; lifecycle code must not treat approval IDs, action IDs, fix IDs,+ action lifecycle state, risk, or target-resource labels from that handoff as+ agent command grants, enrollment proof, or auto-approval policy. Any approval+ or action-audit status snapshot refreshed for Assistant review remains+ read-only AI/runtime context and must not become command-websocket authority+ or lifecycle execution state.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 83f351410b..aae0e35f06 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -221,6 +221,13 @@ runtime cost control, and shared AI transport surfaces.those references include an approval ID, Assistant runtime may refresh acurrent status snapshot from the canonical approval store on each turn, butit must enforce org scoping and still omit the approval command payload.+ When those references resolve to a governed action plan or action audit,+ Assistant runtime must hydrate the canonical action ID, lifecycle state,+ requester, capability, approval policy, plan expiry, preflight/dry-run+ summary, and terminal success/failure state from the action-audit store+ rather than treating the original approval as the current action truth.+ That action snapshot remains model-only review context and must expose+ lifecycle status rather than raw execution output or command text.Proposed-fix command text must stay out of both the persisted chat messageand the model-only handoff context, and command payloads remainapproval-context data, not conversational copy.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 115df59d30..9df3f1d036 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -789,9 +789,15 @@ the canonical monitored-system blocked payload.governed approval and remediation APIs. Chat execution may refresh approvalstatus snapshots for those references from the canonical approval store, butthat 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.+ command. When the reference resolves to a governed action plan or action+ audit, chat execution must hydrate the canonical action ID, lifecycle state,+ requester, capability, approval policy, plan expiry, preflight/dry-run+ summary, and terminal success/failure state from the action-audit store so+ API consumers do not mistake the original approval snapshot for current+ action truth. That action-audit snapshot remains model-only review context+ and must not expose raw command text or raw execution output. 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 e64fe7f711..7e4b45afed 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -108,12 +108,17 @@ Patrol-specific presentation helpers.governed approval/remediation surfaces. Assistant may refresh the referencedapproval's current status for review, but Patrol presentation must still keepcommand payloads inside governed approval/remediation context rather than- rendering them as handoff copy. Assistant may also enrich that same handoff- with refreshed unified finding and investigation-record state, canonical- resource-policy guidance, canonical resource-relationship context, and recent- canonical resource-timeline changes for explanation; Assistant resolves those- timeline lookups through the current canonical unified-resource model before- falling back to handoff IDs. If the referenced finding is no longer current,+ rendering them as handoff copy. Assistant may also hydrate the referenced+ action plan or action audit so the handoff explains current action lifecycle+ state, requester, capability, approval policy, plan expiry, preflight/dry-run+ posture, and terminal success/failure without treating approval as execution+ authority or exposing raw command/execution payloads. Assistant may also+ enrich that same handoff with refreshed unified finding and+ investigation-record state, canonical resource-policy guidance, canonical+ resource-relationship context, and recent canonical resource-timeline changes+ for explanation; Assistant resolves those timeline lookups through the+ current canonical unified-resource model before falling back to handoff IDs.+ If the referenced finding is no longer current,Assistant must drop the stored handoff instead of continuing from stalePatrol context. Assistant handoff context must also carry the unifiedfinding's current lifecycle and recency facts, including active/resolved/diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 70a25fa370..a1ab2b9093 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -439,6 +439,10 @@ persisted action records must identify the requester, resource, capability,approval policy, preflight dry-run posture, and lifecycle state before they areread through audit APIs, so audit history cannot silently accept an unscoped orunplanned execution record.+Assistant handoff context may hydrate those normalized action-audit facts for+review, but that read is still model-only context: it must remain org-scoped,+must not expose raw command text or raw execution output, and must not grant+approval or execution authority.Action planning and action decision mutations remain privileged runtimecontrol surfaces even though the decision endpoint does not execute thecapability. `POST /api/actions/plan` anddiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 351767fa54..374d8565ef 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -427,12 +427,12 @@ bypass the API fail-closed execution gate.review metadata only. Unified finding lifecycle facts carried by the samehandoff remain Patrol/AI review metadata and must not become backup recency,restore support, or storage-local lifecycle state.- 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. Any refreshed- approval status snapshot in Assistant handoff context is still read-only- AI/runtime context and must not become recovery freshness, restore- eligibility, or storage-local execution state.+ storage and recovery surfaces must not reinterpret approval IDs, action IDs,+ action lifecycle state, fix IDs, risk, or target labels as restore support,+ backup freshness, recovery execution authority, or a storage-local approval+ bypass. Any refreshed approval or action-audit status snapshot in Assistant+ handoff context is still read-only AI/runtime context and must not become+ recovery freshness, restore eligibility, or storage-local execution state.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/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex c70be60008..4d8b6db775 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1550,6 +1550,11 @@ decision-only record or overwriting an already decided action.The enterprise audit API now reads those same unified-resource action andexport records back out, so the durable store is not just a write sink but thecanonical history surface for the control-plane verbs.+Assistant handoff action context must also read current action-plan and+action-audit state from this same store when an approval reference resolves to+a governed action, so chat follow-ups describe the canonical lifecycle record+rather than a stale approval snapshot. That read remains model-only review+context and must not expose raw command text or raw execution output.That same ownership boundary applies to incident-adjacent runtime history:durable backend facts about what changed on a resource belong in`ResourceChange` and the shared unified-resource store, whilediff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 45f98c6789..924d9a7a6a 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -524,7 +524,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacInt("message_count", len(messages)).Msg("[ChatService] Got messages, calling agentic loop")- handoffActions = refreshHandoffActionApprovalStatus(handoffActions, s.orgID)+ handoffActions = refreshHandoffActionStatus(handoffActions, s.orgID, s.actionAuditStore)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 refreshed handoff action status")@@ -1121,9 +1121,9 @@ func buildHandoffActionContext(handoffActions []HandoffAction) string {var b strings.Builderb.WriteString("[Action Context]")for idx, action := range actions {- label := "Pending Action"+ label := "Action Reference"if len(actions) > 1 {- label = fmt.Sprintf("Pending Action %d", idx+1)+ label = fmt.Sprintf("Action Reference %d", idx+1)}appendHandoffContextLine(&b, label+" Finding ID", action.FindingID)appendHandoffContextLine(&b, label+" Record ID", action.RecordID)@@ -1135,6 +1135,20 @@ func buildHandoffActionContext(handoffActions []HandoffAction) string {if action.ApprovalConsumed {appendHandoffContextLine(&b, label+" Approval Consumed", "true")}+ appendHandoffContextLine(&b, label+" Action ID", action.ActionID)+ appendHandoffContextLine(&b, label+" Action State", action.ActionState)+ appendHandoffContextLine(&b, label+" Action Updated At", action.ActionUpdatedAt)+ appendHandoffContextLine(&b, label+" Action Requested By", action.ActionRequestedBy)+ appendHandoffContextLine(&b, label+" Action Capability", action.ActionCapability)+ appendHandoffContextLine(&b, label+" Action Approval Policy", action.ActionApprovalPolicy)+ if action.ActionRequiresApproval {+ appendHandoffContextLine(&b, label+" Action Requires Approval", "true")+ }+ appendHandoffContextLine(&b, label+" Action Plan Expires At", action.ActionPlanExpiresAt)+ appendHandoffContextLine(&b, label+" Action Plan Message", action.ActionPlanMessage)+ appendHandoffContextLine(&b, label+" Action Preflight", action.ActionPreflight)+ appendHandoffContextLine(&b, label+" Action Dry Run Summary", action.ActionDryRunSummary)+ appendHandoffContextLine(&b, label+" Action Result", action.ActionResult)appendHandoffContextLine(&b, label+" Fix ID", action.FixID)appendHandoffContextLine(&b, label+" Proposed Fix", action.Description)appendHandoffContextLine(&b, label+" Risk", action.RiskLevel)@@ -1149,6 +1163,10 @@ func buildHandoffActionContext(handoffActions []HandoffAction) string {}func refreshHandoffActionApprovalStatus(handoffActions []HandoffAction, orgID string) []HandoffAction {+ return refreshHandoffActionStatus(handoffActions, orgID, nil)+}++func refreshHandoffActionStatus(handoffActions []HandoffAction, orgID string, actionStore unifiedresources.ResourceStore) []HandoffAction {actions := normalizeHandoffActions(handoffActions)if len(actions) == 0 {return nil@@ -1157,40 +1175,39 @@ func refreshHandoffActionApprovalStatus(handoffActions []HandoffAction, orgID ststore := approval.GetStore()normalizedOrgID := approval.NormalizeOrgID(orgID)for idx := range actions {- clearHandoffActionApprovalStatus(&actions[idx])+ clearHandoffActionStatus(&actions[idx])approvalID := strings.TrimSpace(actions[idx].ApprovalID)- if approvalID == "" || store == nil {- continue- }- req, ok := store.GetApproval(approvalID)- if !ok || !approval.BelongsToOrg(req, normalizedOrgID) {- continue- }-- actions[idx].ApprovalStatus = string(req.Status)- actions[idx].ApprovalRequestedAt = formatHandoffActionTime(req.RequestedAt)- actions[idx].ApprovalExpiresAt = formatHandoffActionTime(req.ExpiresAt)- if req.DecidedAt != nil {- actions[idx].ApprovalDecidedAt = formatHandoffActionTime(*req.DecidedAt)- }- actions[idx].ApprovalConsumed = req.Consumed- if strings.TrimSpace(actions[idx].RiskLevel) == "" {- actions[idx].RiskLevel = string(req.RiskLevel)- }- if strings.TrimSpace(actions[idx].TargetResourceID) == "" {- actions[idx].TargetResourceID = strings.TrimSpace(req.TargetID)- }- if strings.TrimSpace(actions[idx].TargetResourceName) == "" {- actions[idx].TargetResourceName = strings.TrimSpace(req.TargetName)- }- if strings.TrimSpace(actions[idx].TargetResourceType) == "" {- actions[idx].TargetResourceType = strings.TrimSpace(req.TargetType)+ if approvalID != "" && store != nil {+ req, ok := store.GetApproval(approvalID)+ if ok && approval.BelongsToOrg(req, normalizedOrgID) {+ actions[idx].ApprovalStatus = string(req.Status)+ actions[idx].ApprovalRequestedAt = formatHandoffActionTime(req.RequestedAt)+ actions[idx].ApprovalExpiresAt = formatHandoffActionTime(req.ExpiresAt)+ if req.DecidedAt != nil {+ actions[idx].ApprovalDecidedAt = formatHandoffActionTime(*req.DecidedAt)+ }+ actions[idx].ApprovalConsumed = req.Consumed+ if strings.TrimSpace(actions[idx].RiskLevel) == "" {+ actions[idx].RiskLevel = string(req.RiskLevel)+ }+ if strings.TrimSpace(actions[idx].TargetResourceID) == "" {+ actions[idx].TargetResourceID = strings.TrimSpace(req.TargetID)+ }+ if strings.TrimSpace(actions[idx].TargetResourceName) == "" {+ actions[idx].TargetResourceName = strings.TrimSpace(req.TargetName)+ }+ if strings.TrimSpace(actions[idx].TargetResourceType) == "" {+ actions[idx].TargetResourceType = strings.TrimSpace(req.TargetType)+ }+ hydrateHandoffActionPlan(&actions[idx], req.Plan)+ }}+ hydrateHandoffActionAudit(&actions[idx], actionStore)}return normalizeHandoffActions(actions)}-func clearHandoffActionApprovalStatus(action *HandoffAction) {+func clearHandoffActionStatus(action *HandoffAction) {if action == nil {return}@@ -1199,6 +1216,72 @@ func clearHandoffActionApprovalStatus(action *HandoffAction) {action.ApprovalExpiresAt = ""action.ApprovalDecidedAt = ""action.ApprovalConsumed = false+ action.ActionState = ""+ action.ActionUpdatedAt = ""+ action.ActionRequestedBy = ""+ action.ActionCapability = ""+ action.ActionApprovalPolicy = ""+ action.ActionRequiresApproval = false+ action.ActionPlanExpiresAt = ""+ action.ActionPlanMessage = ""+ action.ActionPreflight = ""+ action.ActionDryRunSummary = ""+ action.ActionResult = ""+}++func hydrateHandoffActionPlan(action *HandoffAction, plan *unifiedresources.ActionPlan) {+ if action == nil || plan == nil {+ return+ }+ if strings.TrimSpace(action.ActionID) == "" {+ action.ActionID = strings.TrimSpace(plan.ActionID)+ }+ action.ActionRequiresApproval = plan.RequiresApproval+ action.ActionApprovalPolicy = strings.TrimSpace(string(plan.ApprovalPolicy))+ action.ActionPlanExpiresAt = formatHandoffActionTime(plan.ExpiresAt)+ action.ActionPlanMessage = strings.TrimSpace(plan.Message)+ if plan.Preflight != nil {+ action.ActionPreflight = strings.TrimSpace(plan.Preflight.IntendedChange)+ action.ActionDryRunSummary = strings.TrimSpace(plan.Preflight.DryRunSummary)+ }+}++func hydrateHandoffActionAudit(action *HandoffAction, store unifiedresources.ResourceStore) {+ if action == nil || store == nil {+ return+ }+ actionID := strings.TrimSpace(action.ActionID)+ if actionID == "" {+ return+ }+ record, ok, err := store.GetActionAudit(actionID)+ if err != nil {+ log.Debug().+ Err(err).+ Str("action_id", actionID).+ Msg("[ChatService] Failed to load handoff action audit")+ return+ }+ if !ok {+ return+ }++ action.ActionID = strings.TrimSpace(record.ID)+ action.ActionState = strings.TrimSpace(string(record.State))+ action.ActionUpdatedAt = formatHandoffActionTime(record.UpdatedAt)+ action.ActionRequestedBy = strings.TrimSpace(record.Request.RequestedBy)+ action.ActionCapability = strings.TrimSpace(record.Request.CapabilityName)+ if strings.TrimSpace(action.TargetResourceID) == "" {+ action.TargetResourceID = strings.TrimSpace(record.Request.ResourceID)+ }+ hydrateHandoffActionPlan(action, &record.Plan)+ if record.Result != nil {+ if record.Result.Success {+ action.ActionResult = "success"+ } else {+ action.ActionResult = "failed"+ }+ }}func formatHandoffActionTime(value time.Time) string {diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.goindex 363d122b7b..0394796ba1 100644--- a/internal/ai/chat/service_execute_additional_test.go+++ b/internal/ai/chat/service_execute_additional_test.go@@ -49,6 +49,63 @@ func installTestApprovalStore(t *testing.T, req *approval.ApprovalRequest) {}}+func testHandoffActionPlan(now time.Time) unifiedresources.ActionPlan {+ return unifiedresources.ActionPlan{+ ActionID: "act-handoff-123",+ RequestID: "approval-123",+ Allowed: true,+ RequiresApproval: true,+ ApprovalPolicy: unifiedresources.ApprovalAdmin,+ RollbackAvailable: true,+ Message: "Plan created for workload restart. Execution requires approval.",+ PlannedAt: now,+ ExpiresAt: now.Add(10 * time.Minute),+ ResourceVersion: "resource:sha256:handoff",+ PolicyVersion: "policy:sha256:handoff",+ PlanHash: "sha256:handoff",+ Preflight: &unifiedresources.ActionPreflight{+ Target: "vm-100",+ CurrentState: "web-server is degraded",+ IntendedChange: "Restart the workload service",+ DryRunAvailable: false,+ DryRunSummary: "No provider-supported dry run is available for this action.",+ SafetyChecks: []string{+ "Approval is scoped to this organization.",+ },+ VerificationSteps: []string{+ "Confirm workload health after restart.",+ },+ GeneratedAt: now,+ },+ }+}++func seedHandoffActionAudit(t *testing.T, store unifiedresources.ResourceStore, plan unifiedresources.ActionPlan, state unifiedresources.ActionState, result *unifiedresources.ExecutionResult) {+ t.Helper()+ if store == nil {+ t.Fatal("action audit store is nil")+ }+ updatedAt := plan.PlannedAt.Add(time.Minute)+ record := unifiedresources.ActionAuditRecord{+ ID: plan.ActionID,+ CreatedAt: plan.PlannedAt,+ UpdatedAt: updatedAt,+ State: state,+ Request: unifiedresources.ActionRequest{+ RequestID: plan.RequestID,+ ResourceID: "vm-100",+ CapabilityName: "restart",+ Reason: "Recover after confirmed workload saturation",+ RequestedBy: "pulse_patrol",+ },+ Plan: plan,+ Result: result,+ }+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatalf("RecordActionAudit failed: %v", err)+ }+}+func (s *stubServiceProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {return &providers.ChatResponse{Content: "ok", Model: req.Model}, nil}@@ -126,6 +183,8 @@ func TestService_ExecuteStream_Success(t *testing.T) {}func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {+ actionNow := time.Date(2026, 5, 6, 12, 0, 0, 0, time.UTC)+ actionPlan := testHandoffActionPlan(actionNow)installTestApprovalStore(t, &approval.ApprovalRequest{ID: "approval-123",OrgID: approval.DefaultOrgID,@@ -135,6 +194,7 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {TargetName: "web-server",RiskLevel: approval.RiskMedium,ExpiresAt: time.Now().Add(10 * time.Minute),+ Plan: &actionPlan,})tmpDir := t.TempDir()@@ -143,6 +203,7 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {t.Fatalf("failed to create session store: %v", err)}timelineStore := unifiedresources.NewMemoryStore()+ seedHandoffActionAudit(t, timelineStore, actionPlan, unifiedresources.ActionStatePending, nil)if err := timelineStore.RecordChange(unifiedresources.ResourceChange{ID: "change-123",ResourceID: "vm-100",@@ -255,12 +316,39 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {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") {+ if !strings.Contains(modelUserContent, "Action Reference Approval ID: approval-123") {t.Fatalf("model user content missing approval reference: %q", modelUserContent)}- if !strings.Contains(modelUserContent, "Pending Action Approval Status: pending") {+ if !strings.Contains(modelUserContent, "Action Reference Approval Status: pending") {t.Fatalf("model user content missing approval status: %q", modelUserContent)}+ if !strings.Contains(modelUserContent, "Action Reference Action ID: act-handoff-123") {+ t.Fatalf("model user content missing canonical action id: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action State: pending_approval") {+ t.Fatalf("model user content missing canonical action state: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action Requested By: pulse_patrol") {+ t.Fatalf("model user content missing action requester: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action Capability: restart") {+ t.Fatalf("model user content missing action capability: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action Approval Policy: admin") {+ t.Fatalf("model user content missing action approval policy: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action Requires Approval: true") {+ t.Fatalf("model user content missing action approval requirement: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action Plan Expires At: 2026-05-06T12:10:00Z") {+ t.Fatalf("model user content missing action plan expiry: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action Preflight: Restart the workload service") {+ t.Fatalf("model user content missing action preflight: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Action Reference Action Dry Run Summary: No provider-supported dry run is available for this action.") {+ t.Fatalf("model user content missing action dry-run summary: %q", modelUserContent)+ }if !strings.Contains(modelUserContent, "### Recent Changes Across Infrastructure") {t.Fatalf("model user content missing timeline context: %q", modelUserContent)}@@ -506,6 +594,8 @@ func TestService_ExecuteStream_HandoffResourceRelationshipContextIsModelOnly(t *}func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testing.T) {+ actionNow := time.Date(2026, 5, 6, 12, 30, 0, 0, time.UTC)+ actionPlan := testHandoffActionPlan(actionNow)installTestApprovalStore(t, &approval.ApprovalRequest{ID: "approval-123",OrgID: approval.DefaultOrgID,@@ -515,6 +605,7 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testiTargetName: "web-server",RiskLevel: approval.RiskMedium,ExpiresAt: time.Now().Add(10 * time.Minute),+ Plan: &actionPlan,})tmpDir := t.TempDir()@@ -523,6 +614,7 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testit.Fatalf("failed to create session store: %v", err)}timelineStore := unifiedresources.NewMemoryStore()+ seedHandoffActionAudit(t, timelineStore, actionPlan, unifiedresources.ActionStatePending, nil)if err := timelineStore.RecordChange(unifiedresources.ResourceChange{ID: "change-followup",ResourceID: "vm-100",@@ -645,12 +737,18 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testiif !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") {+ if !strings.Contains(firstModelUserContent, "Action Reference Approval ID: approval-123") {t.Fatalf("first provider turn missing approval reference: %q", firstModelUserContent)}- if !strings.Contains(firstModelUserContent, "Pending Action Approval Status: pending") {+ if !strings.Contains(firstModelUserContent, "Action Reference Approval Status: pending") {t.Fatalf("first provider turn missing approval status: %q", firstModelUserContent)}+ if !strings.Contains(firstModelUserContent, "Action Reference Action ID: act-handoff-123") {+ t.Fatalf("first provider turn missing action id: %q", firstModelUserContent)+ }+ if !strings.Contains(firstModelUserContent, "Action Reference Action State: pending_approval") {+ t.Fatalf("first provider turn missing action state: %q", firstModelUserContent)+ }if !strings.Contains(firstModelUserContent, "### Recent Changes Across Infrastructure") {t.Fatalf("first provider turn missing timeline context: %q", firstModelUserContent)}@@ -664,12 +762,18 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testiif !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") {+ if !strings.Contains(secondModelUserContent, "Action Reference Approval ID: approval-123") {t.Fatalf("follow-up provider turn missing stored approval reference: %q", secondModelUserContent)}- if !strings.Contains(secondModelUserContent, "Pending Action Approval Status: pending") {+ if !strings.Contains(secondModelUserContent, "Action Reference Approval Status: pending") {t.Fatalf("follow-up provider turn missing refreshed approval status: %q", secondModelUserContent)}+ if !strings.Contains(secondModelUserContent, "Action Reference Action ID: act-handoff-123") {+ t.Fatalf("follow-up provider turn missing refreshed action id: %q", secondModelUserContent)+ }+ if !strings.Contains(secondModelUserContent, "Action Reference Action State: pending_approval") {+ t.Fatalf("follow-up provider turn missing refreshed action state: %q", secondModelUserContent)+ }if !strings.Contains(secondModelUserContent, "### Recent Changes Across Infrastructure") {t.Fatalf("follow-up provider turn missing stored resource timeline context: %q", secondModelUserContent)}@@ -800,6 +904,51 @@ func TestRefreshHandoffActionApprovalStatusRejectsCrossOrgApproval(t *testing.T)}}+func TestRefreshHandoffActionStatusHydratesCanonicalActionAudit(t *testing.T) {+ actionNow := time.Date(2026, 5, 6, 13, 0, 0, 0, time.UTC)+ actionPlan := testHandoffActionPlan(actionNow)+ store := unifiedresources.NewMemoryStore()+ seedHandoffActionAudit(t, store, actionPlan, unifiedresources.ActionStateCompleted, &unifiedresources.ExecutionResult{+ Success: true,+ Output: "restart dispatched",+ })++ actions := refreshHandoffActionStatus([]HandoffAction{{+ ActionID: "act-handoff-123",+ Description: "Restart the workload service",+ }}, approval.DefaultOrgID, store)++ if len(actions) != 1 {+ t.Fatalf("actions = %#v, want one action reference", actions)+ }+ if actions[0].ActionState != string(unifiedresources.ActionStateCompleted) {+ t.Fatalf("action state = %q, want completed", actions[0].ActionState)+ }+ if actions[0].ActionResult != "success" {+ t.Fatalf("action result = %q, want success", actions[0].ActionResult)+ }+ if actions[0].ActionCapability != "restart" || actions[0].ActionRequestedBy != "pulse_patrol" {+ t.Fatalf("action audit identity not hydrated: %#v", actions[0])+ }++ contextText := buildHandoffActionContext(actions)+ for _, expected := range []string{+ "Action Reference Action ID: act-handoff-123",+ "Action Reference Action State: completed",+ "Action Reference Action Result: success",+ "Action Reference Action Requested By: pulse_patrol",+ "Action Reference Action Capability: restart",+ "Action Reference Action Preflight: Restart the workload service",+ } {+ if !strings.Contains(contextText, expected) {+ t.Fatalf("action context missing %q: %q", expected, contextText)+ }+ }+ if strings.Contains(contextText, "restart dispatched") {+ t.Fatalf("action context should expose result state, not raw execution output: %q", contextText)+ }+}+func TestService_ClearModelHandoffContextInvalidatesUnpinnedActionScope(t *testing.T) {store, err := NewSessionStore(t.TempDir())if err != nil {diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.goindex 63040efc3d..e525d2f271 100644--- a/internal/ai/chat/session.go+++ b/internal/ai/chat/session.go@@ -101,6 +101,17 @@ func normalizeHandoffActions(actions []HandoffAction) []HandoffAction {action.ApprovalRequestedAt = strings.TrimSpace(action.ApprovalRequestedAt)action.ApprovalExpiresAt = strings.TrimSpace(action.ApprovalExpiresAt)action.ApprovalDecidedAt = strings.TrimSpace(action.ApprovalDecidedAt)+ action.ActionID = strings.TrimSpace(action.ActionID)+ action.ActionState = strings.TrimSpace(action.ActionState)+ action.ActionUpdatedAt = strings.TrimSpace(action.ActionUpdatedAt)+ action.ActionRequestedBy = strings.TrimSpace(action.ActionRequestedBy)+ action.ActionCapability = strings.TrimSpace(action.ActionCapability)+ action.ActionApprovalPolicy = strings.TrimSpace(action.ActionApprovalPolicy)+ action.ActionPlanExpiresAt = strings.TrimSpace(action.ActionPlanExpiresAt)+ action.ActionPlanMessage = strings.TrimSpace(action.ActionPlanMessage)+ action.ActionPreflight = strings.TrimSpace(action.ActionPreflight)+ action.ActionDryRunSummary = strings.TrimSpace(action.ActionDryRunSummary)+ action.ActionResult = strings.TrimSpace(action.ActionResult)action.FixID = strings.TrimSpace(action.FixID)action.Description = strings.TrimSpace(action.Description)action.RiskLevel = strings.TrimSpace(action.RiskLevel)@@ -109,10 +120,10 @@ func normalizeHandoffActions(actions []HandoffAction) []HandoffAction {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 == "" {+ if action.ApprovalID == "" && action.ActionID == "" && 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)+ key := strings.ToLower(action.FindingID + "\x00" + action.RecordID + "\x00" + action.ApprovalID + "\x00" + action.ActionID + "\x00" + action.FixID + "\x00" + action.Description + "\x00" + action.TargetResourceID + "\x00" + action.TargetHost)if _, ok := seen[key]; ok {continue}diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.goindex 2fece9dddb..7cbfd74c03 100644--- a/internal/ai/chat/types.go+++ b/internal/ai/chat/types.go@@ -100,27 +100,39 @@ type HandoffResource struct {Node string `json:"node,omitempty"`}-// HandoffAction represents a product-originated pending action reference.+// HandoffAction represents a product-originated 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"`- ApprovalStatus string `json:"approval_status,omitempty"`- ApprovalRequestedAt string `json:"approval_requested_at,omitempty"`- ApprovalExpiresAt string `json:"approval_expires_at,omitempty"`- ApprovalDecidedAt string `json:"approval_decided_at,omitempty"`- ApprovalConsumed bool `json:"approval_consumed,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"`+ FindingID string `json:"finding_id,omitempty"`+ RecordID string `json:"record_id,omitempty"`+ ApprovalID string `json:"approval_id,omitempty"`+ ApprovalStatus string `json:"approval_status,omitempty"`+ ApprovalRequestedAt string `json:"approval_requested_at,omitempty"`+ ApprovalExpiresAt string `json:"approval_expires_at,omitempty"`+ ApprovalDecidedAt string `json:"approval_decided_at,omitempty"`+ ApprovalConsumed bool `json:"approval_consumed,omitempty"`+ ActionID string `json:"action_id,omitempty"`+ ActionState string `json:"action_state,omitempty"`+ ActionUpdatedAt string `json:"action_updated_at,omitempty"`+ ActionRequestedBy string `json:"action_requested_by,omitempty"`+ ActionCapability string `json:"action_capability,omitempty"`+ ActionApprovalPolicy string `json:"action_approval_policy,omitempty"`+ ActionRequiresApproval bool `json:"action_requires_approval,omitempty"`+ ActionPlanExpiresAt string `json:"action_plan_expires_at,omitempty"`+ ActionPlanMessage string `json:"action_plan_message,omitempty"`+ ActionPreflight string `json:"action_preflight,omitempty"`+ ActionDryRunSummary string `json:"action_dry_run_summary,omitempty"`+ ActionResult string `json:"action_result,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 requestdiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 5b462ab0ff..6eb7d78968 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -191,11 +191,16 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {"sessions.GetModelHandoffResources(session.ID)","sessions.SetModelHandoffActions(session.ID, handoffActions)","sessions.GetModelHandoffActions(session.ID)",- "refreshHandoffActionApprovalStatus(handoffActions, s.orgID)",+ "refreshHandoffActionStatus(handoffActions, s.orgID, s.actionAuditStore)","mergeHandoffResourcePolicyContext(handoffContext, handoffResources, handoffResourceProvider)","mergeHandoffResourceRelationshipContext(handoffContext, handoffResources, handoffResourceProvider)","mergeHandoffResourceTimelineContext(handoffContext, handoffResources, handoffResourceProvider, s.actionAuditStore, time.Now())","handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)",+ "Action Reference",+ "Action State",+ "Action Plan Expires At",+ "Action Dry Run Summary",+ "Action Result","s.hydrateHandoffResources(session.ID, handoffResources, sessions, unifiedResourceProvider)","injectHandoffContextIntoLatestUserMessage(messages, handoffContext)","Resource Policy Context",@@ -239,7 +244,12 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {"HandoffResources []HandoffResource","type HandoffAction struct","HandoffActions []HandoffAction",- "ApprovalStatus string",+ "ApprovalStatus",+ "ActionID",+ "ActionState",+ "ActionPlanExpiresAt",+ "ActionDryRunSummary",+ "ActionResult",} {if !strings.Contains(chatTypesText, required) {t.Fatalf("chat request must carry structured handoff resource scope outside messages: missing %q", required)