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.

Align AI action audits with execution lifecycle

rcourtman235e7343b253
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 643bd2dfc4..de2f4aea49 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -795,8 +795,11 @@ registered executor and records the terminal `completed` or `failed` result
afterward; missing executors must fail closed without mutating the approved
audit record. Existing write-action tool paths under `internal/ai/tools/`
must keep their persisted lifecycle and result records aligned with that same
-unified-resource action state machine rather than inventing AI-local execution
-states.
+unified-resource action state machine: approval decisions must use the
+canonical action decision transition, execution starts must use
+`BeginActionExecution` plus `RecordActionExecutionStart`, and terminal tool
+results must use `CompleteActionExecution` plus
+`RecordActionExecutionResult` rather than inventing AI-local execution states.
AI incident handling must now also write durable resource-history facts
through the canonical unified-resource change store when a concrete resource
target is known. Command executions and runbook executions triggered during an
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
index d97a299fe6..97d417946b 100644
--- a/internal/ai/tools/action_audit.go
+++ b/internal/ai/tools/action_audit.go
@@ -72,12 +72,13 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
if planFromApproval {
plan = mergeApprovedActionPlan(*approvalReq.Plan, plan)
}
+ approvalRecords := approvalRecordsForID(approvalID)
record := unifiedresources.ActionAuditRecord{
ID: actionID,
CreatedAt: now,
UpdatedAt: now,
- State: unifiedresources.ActionStateExecuting,
+ State: actionPreExecutionState(planFromApproval, approvalRecords),
Request: unifiedresources.ActionRequest{
RequestID: requestCorrelationID,
ResourceID: strings.TrimSpace(resourceID),
@@ -95,22 +96,19 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
},
Plan: plan,
}
- record.Approvals = approvalRecordsForID(approvalID)
+ record.Approvals = approvalRecords
- if !planFromApproval {
- e.recordActionLifecycle(actionID, unifiedresources.ActionStatePlanned, requestedBy, reason)
+ record, err := e.recordActionExecutionStart(record, approvalID, requestedBy, fmt.Sprintf("dispatching command to agent %s", agentID), planFromApproval)
+ if err != nil {
+ return nil, err
}
- e.recordActionLifecycle(actionID, unifiedresources.ActionStateExecuting, requestedBy, fmt.Sprintf("dispatching command to agent %s", agentID))
- e.recordActionAudit(record)
payload.ApprovalID = strings.TrimSpace(approvalID)
result, err := e.agentServer.ExecuteCommand(ctx, agentID, payload)
- finalState := unifiedresources.ActionStateCompleted
finalMessage := "command completed"
executionResult := &unifiedresources.ExecutionResult{Success: true}
if err != nil {
- finalState = unifiedresources.ActionStateFailed
finalMessage = err.Error()
executionResult.Success = false
executionResult.ErrorMessage = err.Error()
@@ -124,18 +122,13 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
}
executionResult.Output = output
if result.ExitCode != 0 {
- finalState = unifiedresources.ActionStateFailed
finalMessage = fmt.Sprintf("exit code %d", result.ExitCode)
executionResult.Success = false
executionResult.ErrorMessage = finalMessage
}
}
- record.State = finalState
- record.UpdatedAt = time.Now().UTC()
- record.Result = executionResult
- e.recordActionAudit(record)
- e.recordActionLifecycle(actionID, finalState, requestedBy, finalMessage)
+ e.recordActionExecutionResult(record, executionResult, requestedBy, finalMessage)
return result, err
}
@@ -190,12 +183,13 @@ func (e *PulseToolExecutor) executeNativeActionWithAudit(
if planFromApproval {
plan = mergeApprovedActionPlan(*approvalReq.Plan, plan)
}
+ approvalRecords := approvalRecordsForID(approvalID)
record := unifiedresources.ActionAuditRecord{
ID: actionID,
CreatedAt: now,
UpdatedAt: now,
- State: unifiedresources.ActionStateExecuting,
+ State: actionPreExecutionState(planFromApproval, approvalRecords),
Request: unifiedresources.ActionRequest{
RequestID: requestCorrelationID,
ResourceID: strings.TrimSpace(resourceID),
@@ -206,28 +200,24 @@ func (e *PulseToolExecutor) executeNativeActionWithAudit(
},
Plan: plan,
}
- record.Approvals = approvalRecordsForID(approvalID)
+ record.Approvals = approvalRecords
- if !planFromApproval {
- e.recordActionLifecycle(actionID, unifiedresources.ActionStatePlanned, requestedBy, reason)
+ record, err := e.recordActionExecutionStart(record, approvalID, requestedBy, "dispatching native resource action", planFromApproval)
+ if err != nil {
+ return &unifiedresources.ExecutionResult{Success: false, ErrorMessage: err.Error()}, err
}
- e.recordActionLifecycle(actionID, unifiedresources.ActionStateExecuting, requestedBy, "dispatching native resource action")
- e.recordActionAudit(record)
result, err := execute(ctx)
- finalState := unifiedresources.ActionStateCompleted
finalMessage := "native resource action completed"
executionResult := &unifiedresources.ExecutionResult{Success: true}
if err != nil {
- finalState = unifiedresources.ActionStateFailed
finalMessage = err.Error()
executionResult.Success = false
executionResult.ErrorMessage = err.Error()
} else if result != nil {
executionResult = result
if !result.Success {
- finalState = unifiedresources.ActionStateFailed
finalMessage = strings.TrimSpace(result.ErrorMessage)
if finalMessage == "" {
finalMessage = "native resource action failed"
@@ -235,15 +225,189 @@ func (e *PulseToolExecutor) executeNativeActionWithAudit(
}
}
- record.State = finalState
- record.UpdatedAt = time.Now().UTC()
- record.Result = executionResult
- e.recordActionAudit(record)
- e.recordActionLifecycle(actionID, finalState, requestedBy, finalMessage)
+ e.recordActionExecutionResult(record, executionResult, requestedBy, finalMessage)
return executionResult, err
}
+func actionPreExecutionState(planFromApproval bool, approvals []unifiedresources.ActionApprovalRecord) unifiedresources.ActionState {
+ if planFromApproval || hasApprovedActionApproval(approvals) {
+ return unifiedresources.ActionStateApproved
+ }
+ return unifiedresources.ActionStatePlanned
+}
+
+func hasApprovedActionApproval(approvals []unifiedresources.ActionApprovalRecord) bool {
+ for _, approval := range approvals {
+ if approval.Outcome == unifiedresources.OutcomeApproved {
+ return true
+ }
+ }
+ return false
+}
+
+func (e *PulseToolExecutor) recordActionExecutionStart(record unifiedresources.ActionAuditRecord, approvalID, actor, message string, planFromApproval bool) (unifiedresources.ActionAuditRecord, error) {
+ now := time.Now().UTC()
+ if strings.TrimSpace(actor) == "" {
+ actor = approvalAuditActor
+ }
+ if planFromApproval {
+ var err error
+ record, err = e.ensureApprovalDecisionBeforeExecution(record, approvalID, actor, now)
+ if err != nil {
+ return record, err
+ }
+ } else if e != nil && e.actionAuditStore != nil {
+ if err := e.actionAuditStore.RecordActionAudit(record); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", record.ID).
+ Str("resource_id", record.Request.ResourceID).
+ Msg("failed to persist planned action audit")
+ return record, err
+ }
+ event := unifiedresources.ActionLifecycleEvent{
+ ActionID: record.ID,
+ Timestamp: now,
+ State: unifiedresources.ActionStatePlanned,
+ Actor: actor,
+ Message: strings.TrimSpace(record.Request.Reason),
+ }
+ if err := e.actionAuditStore.RecordActionLifecycleEvent(event); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", record.ID).
+ Str("state", string(unifiedresources.ActionStatePlanned)).
+ Msg("failed to persist planned action lifecycle event")
+ return record, err
+ }
+ }
+
+ started, event, err := unifiedresources.BeginActionExecution(record, actor, now)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", record.ID).
+ Str("state", string(record.State)).
+ Msg("failed to normalize action execution start")
+ return record, err
+ }
+ if strings.TrimSpace(message) != "" {
+ event.Message = strings.TrimSpace(message)
+ }
+ if e == nil || e.actionAuditStore == nil {
+ return started, nil
+ }
+ if err := e.actionAuditStore.RecordActionExecutionStart(started, event); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", started.ID).
+ Str("state", string(started.State)).
+ Msg("failed to persist action execution start")
+ return record, err
+ }
+ return started, nil
+}
+
+func (e *PulseToolExecutor) ensureApprovalDecisionBeforeExecution(record unifiedresources.ActionAuditRecord, approvalID, actor string, now time.Time) (unifiedresources.ActionAuditRecord, error) {
+ if e == nil || e.actionAuditStore == nil {
+ return record, nil
+ }
+
+ current, ok, err := e.actionAuditStore.GetActionAudit(record.ID)
+ if err != nil {
+ log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to query action audit before execution")
+ return record, err
+ }
+ if !ok {
+ if err := e.actionAuditStore.RecordActionAudit(record); err != nil {
+ log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to persist approved action audit before execution")
+ return record, err
+ }
+ return record, nil
+ }
+ if current.State != unifiedresources.ActionStatePending {
+ return current, nil
+ }
+
+ approvalRecord := actionApprovalRecordForExecution(approvalID, actor, now, unifiedresources.OutcomeApproved)
+ updated, event, err := unifiedresources.ApplyActionDecision(current, approvalRecord, approvalRecord.Timestamp)
+ if err != nil {
+ log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to normalize approval decision before execution")
+ return current, err
+ }
+ if err := e.actionAuditStore.RecordActionDecision(updated, event); err != nil {
+ log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to persist approval decision before execution")
+ return current, err
+ }
+ return updated, nil
+}
+
+func actionApprovalRecordForExecution(approvalID, actor string, now time.Time, fallbackOutcome unifiedresources.ApprovalOutcome) unifiedresources.ActionApprovalRecord {
+ if fallbackOutcome == "" {
+ fallbackOutcome = unifiedresources.OutcomeApproved
+ }
+ records := approvalRecordsForID(approvalID)
+ if len(records) > 0 {
+ record := records[len(records)-1]
+ if record.Outcome == "" {
+ record.Outcome = fallbackOutcome
+ }
+ if record.Timestamp.IsZero() {
+ record.Timestamp = now
+ }
+ if strings.TrimSpace(record.Actor) == "" {
+ record.Actor = actor
+ }
+ return record
+ }
+ return unifiedresources.ActionApprovalRecord{
+ Actor: actor,
+ Method: unifiedresources.MethodAPI,
+ Timestamp: now,
+ Outcome: fallbackOutcome,
+ }
+}
+
+func (e *PulseToolExecutor) recordActionExecutionResult(record unifiedresources.ActionAuditRecord, result *unifiedresources.ExecutionResult, actor, message string) unifiedresources.ActionAuditRecord {
+ now := time.Now().UTC()
+ if strings.TrimSpace(actor) == "" {
+ actor = approvalAuditActor
+ }
+ completed, event, err := unifiedresources.CompleteActionExecution(record, result, actor, now)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", record.ID).
+ Str("state", string(record.State)).
+ Msg("failed to normalize action execution result")
+ record.UpdatedAt = now
+ record.Result = result
+ if result != nil && result.Success {
+ record.State = unifiedresources.ActionStateCompleted
+ } else {
+ record.State = unifiedresources.ActionStateFailed
+ }
+ e.recordActionAudit(record)
+ e.recordActionLifecycle(record.ID, record.State, actor, message)
+ return record
+ }
+ if strings.TrimSpace(message) != "" {
+ event.Message = strings.TrimSpace(message)
+ }
+ if e == nil || e.actionAuditStore == nil {
+ return completed
+ }
+ if err := e.actionAuditStore.RecordActionExecutionResult(completed, event); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", completed.ID).
+ Str("state", string(completed.State)).
+ Msg("failed to persist action execution result")
+ }
+ return completed
+}
+
func (e *PulseToolExecutor) recordActionAudit(record unifiedresources.ActionAuditRecord) {
if e == nil || e.actionAuditStore == nil {
return
@@ -292,10 +456,58 @@ func (e *PulseToolExecutor) RecordApprovalDecision(approvalID string, state unif
}
record := actionAuditRecordFromApproval(req, state, actor)
record.Approvals = approvalRecordsForID(req.ID)
+ if e.recordApprovalDecisionAtomically(req.ID, record, actor) {
+ return
+ }
e.recordActionAudit(record)
e.recordActionLifecycle(req.Plan.ActionID, state, actor, message)
}
+func (e *PulseToolExecutor) recordApprovalDecisionAtomically(approvalID string, record unifiedresources.ActionAuditRecord, actor string) bool {
+ if e == nil || e.actionAuditStore == nil {
+ return false
+ }
+ if record.State != unifiedresources.ActionStateApproved && record.State != unifiedresources.ActionStateRejected {
+ return false
+ }
+
+ current, ok, err := e.actionAuditStore.GetActionAudit(record.ID)
+ if err != nil {
+ log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to query action audit before approval decision")
+ return false
+ }
+ if !ok {
+ return false
+ }
+ if current.State != unifiedresources.ActionStatePending {
+ if current.State != record.State {
+ log.Warn().
+ Str("action_id", record.ID).
+ Str("current_state", string(current.State)).
+ Str("decision_state", string(record.State)).
+ Msg("ignoring approval decision for action audit that has already moved past pending")
+ }
+ return true
+ }
+
+ outcome := unifiedresources.OutcomeApproved
+ if record.State == unifiedresources.ActionStateRejected {
+ outcome = unifiedresources.OutcomeRejected
+ }
+ approvalRecord := actionApprovalRecordForExecution(approvalID, actor, time.Now().UTC(), outcome)
+ approvalRecord.Outcome = outcome
+ updated, event, err := unifiedresources.ApplyActionDecision(current, approvalRecord, approvalRecord.Timestamp)
+ if err != nil {
+ log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to normalize approval decision")
+ return false
+ }
+ if err := e.actionAuditStore.RecordActionDecision(updated, event); err != nil {
+ log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to persist approval decision")
+ return false
+ }
+ return true
+}
+
func (e *PulseToolExecutor) recordPendingApprovalAction(req *approval.ApprovalRequest) {
if e == nil || req == nil || req.Plan == nil {
return
diff --git a/internal/ai/tools/action_audit_execution_test.go b/internal/ai/tools/action_audit_execution_test.go
new file mode 100644
index 0000000000..95caf7bffd
--- /dev/null
+++ b/internal/ai/tools/action_audit_execution_test.go
@@ -0,0 +1,484 @@
+package tools
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/stretchr/testify/mock"
+)
+
+func TestExecuteCommandWithAuditUsesExecutionStateMachine(t *testing.T) {
+ store := unifiedresources.NewMemoryStore()
+ agentServer := &mockAgentServer{}
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-1", mock.MatchedBy(func(payload agentexec.ExecuteCommandPayload) bool {
+ return payload.Command == "uptime" && payload.TargetType == "agent" && payload.TargetID == "agent-1"
+ })).Return(&agentexec.CommandResultPayload{
+ Success: true,
+ Stdout: "ok",
+ ExitCode: 0,
+ }, nil).Once()
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: store,
+ })
+ result, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "node-1",
+ "",
+ false,
+ "agent-1",
+ agentexec.ExecuteCommandPayload{
+ Command: "uptime",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ },
+ "pulse_control",
+ "run uptime",
+ )
+ if err != nil {
+ t.Fatalf("executeCommandWithAudit: %v", err)
+ }
+ if result == nil || result.Stdout != "ok" {
+ t.Fatalf("command result = %#v", result)
+ }
+
+ audits, err := store.GetActionAudits("node-1", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ if len(audits) != 1 {
+ t.Fatalf("audits len = %d, want 1", len(audits))
+ }
+ audit := audits[0]
+ if audit.State != unifiedresources.ActionStateCompleted || audit.Result == nil || audit.Result.Output != "ok" {
+ t.Fatalf("audit = %#v", audit)
+ }
+
+ events, err := store.GetActionLifecycleEvents(audit.ID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seen := map[unifiedresources.ActionState]string{}
+ for _, event := range events {
+ seen[event.State] = event.Message
+ }
+ for _, state := range []unifiedresources.ActionState{
+ unifiedresources.ActionStatePlanned,
+ unifiedresources.ActionStateExecuting,
+ unifiedresources.ActionStateCompleted,
+ } {
+ if _, ok := seen[state]; !ok {
+ t.Fatalf("missing lifecycle state %q in %#v", state, events)
+ }
+ }
+ if seen[unifiedresources.ActionStateExecuting] != "dispatching command to agent agent-1" {
+ t.Fatalf("executing event message = %q", seen[unifiedresources.ActionStateExecuting])
+ }
+ agentServer.AssertExpectations(t)
+}
+
+func TestExecuteNativeActionWithApprovedAuditRecordsDecisionBeforeExecution(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+ approvalStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ })
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ previousApprovalStore := approval.GetStore()
+ approval.SetStore(approvalStore)
+ t.Cleanup(func() { approval.SetStore(previousApprovalStore) })
+
+ now := time.Now().UTC()
+ plan := unifiedresources.ActionPlan{
+ ActionID: "act-approved-native",
+ RequestID: "approval-native",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ }
+ req := &approval.ApprovalRequest{
+ ID: "approval-native",
+ Command: "restart app",
+ TargetType: "docker",
+ TargetID: "docker-host:app",
+ TargetName: "app",
+ Context: "restart app during maintenance",
+ Plan: &plan,
+ }
+ if err := approvalStore.CreateApproval(req); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+
+ executor := NewPulseToolExecutor(ExecutorConfig{ActionAuditStore: actionStore})
+ executor.recordPendingApprovalAction(req)
+ if _, err := approvalStore.Approve("approval-native", "[email protected]"); err != nil {
+ t.Fatalf("Approve: %v", err)
+ }
+
+ result, err := executor.executeNativeActionWithAudit(
+ context.Background(),
+ "pulse_docker",
+ "docker-host:app",
+ "approval-native",
+ true,
+ map[string]any{"action": "restart"},
+ "pulse_control",
+ "restart app during maintenance",
+ func(context.Context) (*unifiedresources.ExecutionResult, error) {
+ return &unifiedresources.ExecutionResult{Success: false, ErrorMessage: "provider rejected restart"}, nil
+ },
+ )
+ if err != nil {
+ t.Fatalf("executeNativeActionWithAudit: %v", err)
+ }
+ if result == nil || result.Success || result.ErrorMessage != "provider rejected restart" {
+ t.Fatalf("execution result = %#v", result)
+ }
+
+ audit, ok, err := actionStore.GetActionAudit("act-approved-native")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || audit.State != unifiedresources.ActionStateFailed || len(audit.Approvals) != 1 || audit.Result == nil {
+ t.Fatalf("audit = %#v, ok=%v", audit, ok)
+ }
+ if audit.Approvals[0].Actor != "[email protected]" || audit.Approvals[0].Outcome != unifiedresources.OutcomeApproved {
+ t.Fatalf("approval audit = %#v", audit.Approvals[0])
+ }
+
+ events, err := actionStore.GetActionLifecycleEvents("act-approved-native", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seen := map[unifiedresources.ActionState]bool{}
+ for _, event := range events {
+ seen[event.State] = true
+ }
+ for _, state := range []unifiedresources.ActionState{
+ unifiedresources.ActionStatePlanned,
+ unifiedresources.ActionStatePending,
+ unifiedresources.ActionStateApproved,
+ unifiedresources.ActionStateExecuting,
+ unifiedresources.ActionStateFailed,
+ } {
+ if !seen[state] {
+ t.Fatalf("missing lifecycle state %q in %#v", state, events)
+ }
+ }
+}
+
+func TestRecordApprovalDecisionUsesActionDecisionStoreContract(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+ approvalStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ })
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ previousApprovalStore := approval.GetStore()
+ approval.SetStore(approvalStore)
+ t.Cleanup(func() { approval.SetStore(previousApprovalStore) })
+
+ now := time.Now().UTC()
+ plan := unifiedresources.ActionPlan{
+ ActionID: "act-decision-contract",
+ RequestID: "approval-decision",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ }
+ req := &approval.ApprovalRequest{
+ ID: "approval-decision",
+ Command: "restart vm",
+ TargetType: "vm",
+ TargetID: "vm:42",
+ TargetName: "web-42",
+ Context: "restart vm during maintenance",
+ Plan: &plan,
+ }
+ if err := approvalStore.CreateApproval(req); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+ executor := NewPulseToolExecutor(ExecutorConfig{ActionAuditStore: actionStore})
+ executor.recordPendingApprovalAction(req)
+ if _, err := approvalStore.Approve("approval-decision", "[email protected]"); err != nil {
+ t.Fatalf("Approve: %v", err)
+ }
+
+ executor.RecordApprovalDecision("approval-decision", unifiedresources.ActionStateApproved, "[email protected]", "approval granted")
+
+ audit, ok, err := actionStore.GetActionAudit("act-decision-contract")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || audit.State != unifiedresources.ActionStateApproved || len(audit.Approvals) != 1 || audit.Result != nil {
+ t.Fatalf("audit = %#v, ok=%v", audit, ok)
+ }
+ events, err := actionStore.GetActionLifecycleEvents("act-decision-contract", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seen := map[unifiedresources.ActionState]bool{}
+ for _, event := range events {
+ seen[event.State] = true
+ if event.State == unifiedresources.ActionStateExecuting || event.State == unifiedresources.ActionStateCompleted {
+ t.Fatalf("approval decision must not create execution lifecycle event: %#v", event)
+ }
+ }
+ for _, state := range []unifiedresources.ActionState{
+ unifiedresources.ActionStatePlanned,
+ unifiedresources.ActionStatePending,
+ unifiedresources.ActionStateApproved,
+ } {
+ if !seen[state] {
+ t.Fatalf("missing lifecycle state %q in %#v", state, events)
+ }
+ }
+}
+
+func TestRecordApprovalDecisionUsesRejectedActionDecisionStoreContract(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+ approvalStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ })
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ previousApprovalStore := approval.GetStore()
+ approval.SetStore(approvalStore)
+ t.Cleanup(func() { approval.SetStore(previousApprovalStore) })
+
+ now := time.Now().UTC()
+ plan := unifiedresources.ActionPlan{
+ ActionID: "act-rejected-decision-contract",
+ RequestID: "approval-rejected-decision",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ }
+ req := &approval.ApprovalRequest{
+ ID: "approval-rejected-decision",
+ Command: "delete pod",
+ TargetType: "kubernetes",
+ TargetID: "pod:danger",
+ TargetName: "danger",
+ Context: "delete pod outside maintenance",
+ Plan: &plan,
+ }
+ if err := approvalStore.CreateApproval(req); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+ executor := NewPulseToolExecutor(ExecutorConfig{ActionAuditStore: actionStore})
+ executor.recordPendingApprovalAction(req)
+ if _, err := approvalStore.Deny("approval-rejected-decision", "[email protected]", "outside maintenance"); err != nil {
+ t.Fatalf("Deny: %v", err)
+ }
+
+ executor.RecordApprovalDecision("approval-rejected-decision", unifiedresources.ActionStateRejected, "[email protected]", "outside maintenance")
+
+ audit, ok, err := actionStore.GetActionAudit("act-rejected-decision-contract")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || audit.State != unifiedresources.ActionStateRejected || len(audit.Approvals) != 1 || audit.Result != nil {
+ t.Fatalf("audit = %#v, ok=%v", audit, ok)
+ }
+ if audit.Approvals[0].Outcome != unifiedresources.OutcomeRejected {
+ t.Fatalf("approval outcome = %q, want %q", audit.Approvals[0].Outcome, unifiedresources.OutcomeRejected)
+ }
+ events, err := actionStore.GetActionLifecycleEvents("act-rejected-decision-contract", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seen := map[unifiedresources.ActionState]bool{}
+ for _, event := range events {
+ seen[event.State] = true
+ if event.State == unifiedresources.ActionStateExecuting || event.State == unifiedresources.ActionStateCompleted {
+ t.Fatalf("rejected approval decision must not create execution lifecycle event: %#v", event)
+ }
+ }
+ for _, state := range []unifiedresources.ActionState{
+ unifiedresources.ActionStatePlanned,
+ unifiedresources.ActionStatePending,
+ unifiedresources.ActionStateRejected,
+ } {
+ if !seen[state] {
+ t.Fatalf("missing lifecycle state %q in %#v", state, events)
+ }
+ }
+}
+
+func TestRecordApprovalDecisionDoesNotRegressExecutingAudit(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+ approvalStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ })
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ previousApprovalStore := approval.GetStore()
+ approval.SetStore(approvalStore)
+ t.Cleanup(func() { approval.SetStore(previousApprovalStore) })
+
+ now := time.Now().UTC()
+ plan := unifiedresources.ActionPlan{
+ ActionID: "act-decision-no-regress",
+ RequestID: "approval-decision-no-regress",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ }
+ req := &approval.ApprovalRequest{
+ ID: "approval-decision-no-regress",
+ Command: "restart service",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ TargetName: "agent-1",
+ Context: "restart service during maintenance",
+ Plan: &plan,
+ }
+ if err := approvalStore.CreateApproval(req); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+ if _, err := approvalStore.Approve("approval-decision-no-regress", "[email protected]"); err != nil {
+ t.Fatalf("Approve: %v", err)
+ }
+ executor := NewPulseToolExecutor(ExecutorConfig{ActionAuditStore: actionStore})
+ record := actionAuditRecordFromApproval(req, unifiedresources.ActionStateExecuting, "pulse_control")
+ record.Approvals = approvalRecordsForID(req.ID)
+ if err := actionStore.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+
+ executor.RecordApprovalDecision("approval-decision-no-regress", unifiedresources.ActionStateApproved, "[email protected]", "approval granted")
+
+ audit, ok, err := actionStore.GetActionAudit("act-decision-no-regress")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || audit.State != unifiedresources.ActionStateExecuting || audit.Result != nil {
+ t.Fatalf("audit = %#v, ok=%v", audit, ok)
+ }
+}
+
+func TestExecuteCommandWithDeniedApprovalDoesNotDispatch(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+ approvalStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ })
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ previousApprovalStore := approval.GetStore()
+ approval.SetStore(approvalStore)
+ t.Cleanup(func() { approval.SetStore(previousApprovalStore) })
+
+ now := time.Now().UTC()
+ plan := unifiedresources.ActionPlan{
+ ActionID: "act-denied-command",
+ RequestID: "approval-denied-command",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ }
+ req := &approval.ApprovalRequest{
+ ID: "approval-denied-command",
+ Command: "rm -rf /tmp/pulse-test",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ TargetName: "agent-1",
+ Context: "unsafe cleanup command",
+ Plan: &plan,
+ }
+ if err := approvalStore.CreateApproval(req); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+ if _, err := approvalStore.Deny("approval-denied-command", "[email protected]", "unsafe command"); err != nil {
+ t.Fatalf("Deny: %v", err)
+ }
+
+ agentServer := &mockAgentServer{}
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: actionStore,
+ })
+ executor.recordPendingApprovalAction(req)
+
+ result, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "agent-1",
+ "approval-denied-command",
+ true,
+ "agent-1",
+ agentexec.ExecuteCommandPayload{
+ Command: "rm -rf /tmp/pulse-test",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ },
+ "pulse_control",
+ "unsafe cleanup command",
+ )
+ if !errors.Is(err, unifiedresources.ErrActionNotApproved) {
+ t.Fatalf("executeCommandWithAudit error = %v, want %v", err, unifiedresources.ErrActionNotApproved)
+ }
+ if result != nil {
+ t.Fatalf("command result = %#v, want nil", result)
+ }
+ agentServer.AssertNotCalled(t, "ExecuteCommand", mock.Anything, mock.Anything, mock.Anything)
+
+ audit, ok, err := actionStore.GetActionAudit("act-denied-command")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || audit.State != unifiedresources.ActionStateRejected || len(audit.Approvals) != 1 || audit.Approvals[0].Outcome != unifiedresources.OutcomeRejected {
+ t.Fatalf("audit = %#v, ok=%v", audit, ok)
+ }
+ events, err := actionStore.GetActionLifecycleEvents("act-denied-command", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ for _, event := range events {
+ if event.State == unifiedresources.ActionStateExecuting || event.State == unifiedresources.ActionStateCompleted {
+ t.Fatalf("denied approval must not create execution lifecycle event: %#v", event)
+ }
+ }
+}