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.

Add action execution safety contract

rcourtman82a2494ffa64
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index bc786e3aea..9a13626fdf 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -133,7 +133,11 @@ lifecycle evidence, and retry/idempotency handling must not create duplicate
lifecycle events. Approval or rejection decisions for those plans must flow
through `POST /api/actions/{id}/decision`, which records API-owned audit and
lifecycle evidence only; lifecycle surfaces must not treat approval as
-implicit command execution or define a parallel execution handoff.
+implicit command execution or define a parallel execution handoff. When a
+planned resource capability is actually executed from an agent-lifecycle
+surface, that handoff must route through `POST /api/actions/{id}/execute` so
+the API-owned action audit records `executing` before dispatch and the
+terminal execution result afterward.
The node setup modal boundary must keep guided setup and manual credential
submission separate. For new PVE/PBS setup, Agent Install and Direct Connection
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index fbd8e10943..643bd2dfc4 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -789,7 +789,14 @@ incident memory first, canonical resource timeline second.
The same runtime boundary now also owns durable action execution auditing.
`internal/ai/chat/service.go` initializes the unified-resource audit store on
-startup, and the write-action tool paths under `internal/ai/tools/` persist
+startup. Governed API action execution must enter through
+`POST /api/actions/{id}/execute`, which records `executing` before invoking the
+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.
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
@@ -799,8 +806,6 @@ for those events now belongs to canonical `ResourceChange` kinds such as
`command_executed` and `runbook_executed`, keyed by canonical resource ID and
linked back to the alert through metadata instead of being stored only in AI
memory.
-append-only action lifecycle and action audit records through that shared
-store instead of leaving command execution state in memory-only tool helpers.
The patrol-local `memory.ChangeDetector.GetChangesSummary` path now also
delegates to the shared memory recent-change presentation helper, so any
future fallback summary entry point inherits the same heading, resource
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index b203f97627..56a0bc8293 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -307,12 +307,24 @@ the canonical monitored-system blocked payload.
atomically. It must not invoke the capability driver, create an
`executing`/`completed` event, or attach an execution result; execution
requires a later explicit execution contract.
- The supported CLI adapters for this contract are `pulse actions plan` and
- `pulse actions decide`, owned by `pkg/pulsecli/actions.go` and registered
- from `pkg/pulsecli/root.go`. They must remain thin authenticated clients
- for `POST /api/actions/plan` and `POST /api/actions/{id}/decision`
- rather than importing planner internals, creating action IDs, or executing
- capabilities locally. `pulse actions capabilities` may read
+ Action execution is API-owned as the next explicit contract:
+ `POST /api/actions/{id}/execute` may only start execution for an approved
+ action or an approval-free allowed plan, must atomically persist the
+ `executing` lifecycle state before invoking a registered executor, and must
+ atomically persist the terminal `completed` or `failed` result afterward.
+ If no API executor is registered, the endpoint must fail closed without
+ mutating the approved audit record or appending execution lifecycle events.
+ Approval must never imply execution, and local UI, CLI, MCP, agent, or
+ storage/recovery adapters must not bypass this endpoint with a parallel
+ execution transport.
+ The supported CLI adapters for this contract are `pulse actions plan`,
+ `pulse actions decide`, and `pulse actions execute`, owned by
+ `pkg/pulsecli/actions.go` and registered from `pkg/pulsecli/root.go`. They
+ must remain thin authenticated clients for `POST /api/actions/plan`,
+ `POST /api/actions/{id}/decision`, and
+ `POST /api/actions/{id}/execute` rather than importing planner internals,
+ creating action IDs, or executing capabilities locally.
+ `pulse actions capabilities` may read
the canonical `GET /api/resources/{id}/facets` payload to discover resource
capability names and parameter schemas before planning, but it must not
invent a parallel capability inventory or expose internal handler names.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 55c42336fe..d1e0ff16f0 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -437,7 +437,10 @@ control surfaces even though the decision endpoint does not execute the
capability. `POST /api/actions/plan` and
`POST /api/actions/{id}/decision` must both require the governed `ai:execute`
scope so API tokens cannot create or approve executable action intent through a
-read-only or mobile-only grant.
+read-only or mobile-only grant. `POST /api/actions/{id}/execute` is governed by
+the same `ai:execute` scope because it is the only API-owned handoff from
+approved intent into capability execution; missing executors must fail closed
+without creating execution lifecycle evidence.
That same token-scope boundary now also governs Pulse Mobile relay runtime
credentials: `internal/api/security_tokens.go` must mint only the dedicated
backend-owned `relay:mobile:access` scope for new mobile relay tokens, and the
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 8cf46724fd..d9565112e0 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -108,8 +108,11 @@ as `pending_approval` with initial lifecycle evidence, and retry/idempotency
handling must not duplicate those lifecycle events. Storage/recovery
approval or rejection decisions must route through
`POST /api/actions/{id}/decision`, which records the API-owned audit decision
-without executing the underlying capability or creating storage-local action
-transport.
+without executing the underlying capability. Any storage/recovery execution
+handoff for the approved action must route through
+`POST /api/actions/{id}/execute` so the API-owned action audit records
+`executing` before dispatch and the terminal result afterward instead of
+creating storage-local action transport.
1. Add or change recovery-point persistence, rollups, or series derivation through `internal/recovery/`
2. Add or change recovery page UX through `frontend-modern/src/components/Recovery/` and keep canonical route/query/filter state ownership in `frontend-modern/src/features/recovery/useRecoverySurfaceState.ts`
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 7ca5a573ad..4a30ac9a06 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -476,6 +476,14 @@ Action approval decisions belong to the same resource-owned state machine:
record to `approved` or `rejected`, while `RecordActionDecision` must update
the current audit record and append the lifecycle event atomically without
creating execution results or accepting stale second decisions.
+Action execution now follows that same resource-owned state machine:
+`BeginActionExecution` may transition only an approved action, or an
+approval-free allowed plan, into `executing`; `CompleteActionExecution` may
+transition only an executing record into `completed` or `failed` with an
+explicit `ExecutionResult`. `RecordActionExecutionStart` and
+`RecordActionExecutionResult` must perform the audit update and lifecycle
+append atomically against the current persisted state, reject stale duplicate
+starts or terminal writes, and preserve approval as separate from execution.
`ResourceActionHistory.tsx` now surfaces that same normalized action audit
trail inside the resource-detail workflow through the canonical
`frontend-modern/src/api/actionAudit.ts` client and shared
diff --git a/internal/api/actions.go b/internal/api/actions.go
index cc79316f6b..4e23606a63 100644
--- a/internal/api/actions.go
+++ b/internal/api/actions.go
@@ -1,6 +1,7 @@
package api
import (
+ "context"
"encoding/json"
"errors"
"io"
@@ -14,6 +15,13 @@ import (
const maxActionPlanRequestBytes = 1 << 20
const maxActionDecisionRequestBytes = 64 << 10
+const maxActionExecutionRequestBytes = 64 << 10
+
+// ActionExecutor runs a previously planned and approved action through the
+// API-owned execution contract.
+type ActionExecutor interface {
+ ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error)
+}
type actionDecisionRequest struct {
Outcome unified.ApprovalOutcome `json:"outcome"`
@@ -27,6 +35,17 @@ type actionDecisionResponse struct {
Audit unified.ActionAuditRecord `json:"audit"`
}
+type actionExecutionRequest struct {
+ Reason string `json:"reason,omitempty"`
+}
+
+type actionExecutionResponse struct {
+ ActionID string `json:"actionId"`
+ State unified.ActionState `json:"state"`
+ Result *unified.ExecutionResult `json:"result,omitempty"`
+ Audit unified.ActionAuditRecord `json:"audit"`
+}
+
func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
@@ -273,6 +292,101 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.Req
}
}
+func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ actionID := strings.TrimSpace(r.PathValue("id"))
+ if actionID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_id", "Missing action ID", nil)
+ return
+ }
+ if !validAuditEventID.MatchString(actionID) || len(actionID) > 128 {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format", nil)
+ return
+ }
+
+ var execution actionExecutionRequest
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxActionExecutionRequestBytes))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&execution); err != nil {
+ if !errors.Is(err, io.EOF) {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{
+ "body": "request body must be a valid action execution JSON object",
+ })
+ return
+ }
+ } else if err := decoder.Decode(&struct{}{}); err != io.EOF {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{
+ "body": "request body must contain one JSON object",
+ })
+ return
+ }
+ execution.Reason = strings.TrimSpace(execution.Reason)
+
+ orgID := GetOrgID(r.Context())
+ store, err := h.getStore(orgID)
+ if err != nil {
+ writeErrorResponse(w, http.StatusServiceUnavailable, "action_audit_unavailable", "Action audit history is not available", nil)
+ return
+ }
+ record, ok, err := store.GetActionAudit(actionID)
+ if err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "action_audit_query_failed", "Failed to query action audit", nil)
+ return
+ }
+ if !ok {
+ writeErrorResponse(w, http.StatusNotFound, "action_not_found", "Action not found", map[string]string{
+ "actionId": actionID,
+ })
+ return
+ }
+
+ actor := actionDecisionActor(h, r)
+ started, startEvent, err := unified.BeginActionExecution(record, actor, time.Now().UTC())
+ if err != nil {
+ writeActionExecutionApplyError(w, err)
+ return
+ }
+ if execution.Reason != "" {
+ startEvent.Message = "Action execution started: " + execution.Reason
+ }
+ if h.actionExecutor == nil {
+ writeErrorResponse(w, http.StatusNotImplemented, "action_executor_unavailable", "No action executor is configured for this API instance", nil)
+ return
+ }
+ if err := store.RecordActionExecutionStart(started, startEvent); err != nil {
+ writeActionExecutionPersistError(w, err)
+ return
+ }
+
+ result, execErr := h.actionExecutor.ExecuteAction(r.Context(), started)
+ if execErr != nil {
+ result = &unified.ExecutionResult{Success: false, ErrorMessage: execErr.Error()}
+ }
+ completed, doneEvent, err := unified.CompleteActionExecution(started, result, actor, time.Now().UTC())
+ if err != nil {
+ writeActionExecutionApplyError(w, err)
+ return
+ }
+ if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {
+ writeActionExecutionPersistError(w, err)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(actionExecutionResponse{
+ ActionID: completed.ID,
+ State: completed.State,
+ Result: completed.Result,
+ Audit: completed,
+ }); err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "action_execution_encode_failed", "Failed to encode action execution", nil)
+ }
+}
+
func actionDecisionActor(h *ResourceHandlers, r *http.Request) string {
if h != nil {
if actor := strings.TrimSpace(getAuthUsername(h.cfg, r)); actor != "" {
@@ -299,3 +413,33 @@ func writeActionDecisionApplyError(w http.ResponseWriter, err error) {
writeErrorResponse(w, http.StatusInternalServerError, "action_decision_failed", sanitizeErrorForClient(err, "Action decision failed"), nil)
}
}
+
+func writeActionExecutionApplyError(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, unified.ErrActionNotApproved):
+ writeErrorResponse(w, http.StatusConflict, "action_not_approved", "Action is not approved for execution", nil)
+ case errors.Is(err, unified.ErrActionAlreadyExecuting):
+ writeErrorResponse(w, http.StatusConflict, "action_already_executing", "Action is already executing", nil)
+ case errors.Is(err, unified.ErrActionExecutionFinal):
+ writeErrorResponse(w, http.StatusConflict, "action_execution_final", "Action execution is already final", nil)
+ case errors.Is(err, unified.ErrActionNotExecuting):
+ writeErrorResponse(w, http.StatusConflict, "action_not_executing", "Action is not executing", nil)
+ case errors.Is(err, unified.ErrActionPlanExpired):
+ writeErrorResponse(w, http.StatusConflict, "action_plan_expired", "Action plan has expired", nil)
+ default:
+ writeErrorResponse(w, http.StatusInternalServerError, "action_execution_failed", sanitizeErrorForClient(err, "Action execution failed"), nil)
+ }
+}
+
+func writeActionExecutionPersistError(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, unified.ErrActionNotApproved),
+ errors.Is(err, unified.ErrActionAlreadyExecuting),
+ errors.Is(err, unified.ErrActionExecutionFinal),
+ errors.Is(err, unified.ErrActionNotExecuting),
+ errors.Is(err, unified.ErrActionPlanExpired):
+ writeActionExecutionApplyError(w, err)
+ default:
+ writeErrorResponse(w, http.StatusInternalServerError, "action_execution_persist_failed", sanitizeErrorForClient(err, "Failed to persist action execution"), nil)
+ }
+}
diff --git a/internal/api/actions_test.go b/internal/api/actions_test.go
index 42dbd9892f..c208bad963 100644
--- a/internal/api/actions_test.go
+++ b/internal/api/actions_test.go
@@ -2,6 +2,7 @@ package api
import (
"bytes"
+ "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -15,6 +16,19 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
+type stubActionExecutor struct {
+ result *unified.ExecutionResult
+ err error
+ received unified.ActionAuditRecord
+ calls int
+}
+
+func (s *stubActionExecutor) ExecuteAction(_ context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {
+ s.calls++
+ s.received = record
+ return s.result, s.err
+}
+
func TestHandlePlanActionReturnsCanonicalPlan(t *testing.T) {
now := time.Date(2026, 5, 3, 10, 0, 0, 0, time.UTC)
h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
@@ -315,6 +329,195 @@ func TestHandleDecideActionApprovesPendingPlanWithoutExecution(t *testing.T) {
}
}
+func TestHandleExecuteActionRunsApprovedPlanThroughExecutor(t *testing.T) {
+ now := time.Date(2026, 5, 4, 14, 0, 0, 0, time.UTC)
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ {
+ ID: "vm:42",
+ Type: unified.ResourceTypeVM,
+ Name: "web-42",
+ Status: unified.StatusWarning,
+ LastSeen: now,
+ UpdatedAt: now,
+ Sources: []unified.DataSource{unified.SourceProxmox},
+ Capabilities: []unified.ResourceCapability{
+ {
+ Name: "restart",
+ Type: unified.CapabilityTypeCommon,
+ Description: "Restart the VM",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ InternalHandler: "proxmox.vm.restart",
+ Params: []unified.CapabilityParam{
+ {Name: "mode", Type: "string", Required: true, Enum: []string{"graceful", "force"}},
+ },
+ },
+ },
+ },
+ },
+ })
+ executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "restart dispatched"}}
+ h.SetActionExecutor(executor)
+
+ planRec := httptest.NewRecorder()
+ planReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
+ "requestId":"agent-run-execute",
+ "resourceId":"vm:42",
+ "capabilityName":"restart",
+ "params":{"mode":"graceful"},
+ "reason":"Recover after confirmed outage",
+ "requestedBy":"agent:oncall-helper"
+ }`))
+ h.HandlePlanAction(planRec, planReq)
+ if planRec.Code != http.StatusOK {
+ t.Fatalf("plan status = %d, body=%s", planRec.Code, planRec.Body.String())
+ }
+ var plan unified.ActionPlan
+ if err := json.Unmarshal(planRec.Body.Bytes(), &plan); err != nil {
+ t.Fatalf("decode plan response: %v", err)
+ }
+
+ decisionRec := httptest.NewRecorder()
+ decisionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/decision", bytes.NewBufferString(`{
+ "outcome":"approved",
+ "reason":"inside maintenance window"
+ }`))
+ decisionReq.SetPathValue("id", plan.ActionID)
+ decisionReq = decisionReq.WithContext(auth.WithUser(decisionReq.Context(), "[email protected]"))
+ h.HandleDecideAction(decisionRec, decisionReq)
+ if decisionRec.Code != http.StatusOK {
+ t.Fatalf("decision status = %d, body=%s", decisionRec.Code, decisionRec.Body.String())
+ }
+
+ executeRec := httptest.NewRecorder()
+ executeReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/execute", bytes.NewBufferString(`{
+ "reason":"execute during approved maintenance window"
+ }`))
+ executeReq.SetPathValue("id", plan.ActionID)
+ executeReq = executeReq.WithContext(auth.WithUser(executeReq.Context(), "[email protected]"))
+ h.HandleExecuteAction(executeRec, executeReq)
+ if executeRec.Code != http.StatusOK {
+ t.Fatalf("execute status = %d, body=%s", executeRec.Code, executeRec.Body.String())
+ }
+
+ var execution actionExecutionResponse
+ if err := json.Unmarshal(executeRec.Body.Bytes(), &execution); err != nil {
+ t.Fatalf("decode execution response: %v", err)
+ }
+ if execution.ActionID != plan.ActionID || execution.State != unified.ActionStateCompleted {
+ t.Fatalf("execution identity/state = %q/%q, want %q/%q", execution.ActionID, execution.State, plan.ActionID, unified.ActionStateCompleted)
+ }
+ if execution.Result == nil || !execution.Result.Success || execution.Result.Output != "restart dispatched" {
+ t.Fatalf("execution result = %#v", execution.Result)
+ }
+ if executor.calls != 1 || executor.received.State != unified.ActionStateExecuting || executor.received.Result != nil {
+ t.Fatalf("executor received = %#v after %d calls", executor.received, executor.calls)
+ }
+
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("get store: %v", err)
+ }
+ audit, ok, err := store.GetActionAudit(plan.ActionID)
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || audit.State != unified.ActionStateCompleted || audit.Result == nil || audit.Result.Output != "restart dispatched" {
+ t.Fatalf("persisted execution audit = %#v, ok=%v", audit, ok)
+ }
+ events, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seen := map[unified.ActionState]bool{}
+ for _, event := range events {
+ seen[event.State] = true
+ }
+ if len(events) != 5 ||
+ !seen[unified.ActionStatePlanned] ||
+ !seen[unified.ActionStatePending] ||
+ !seen[unified.ActionStateApproved] ||
+ !seen[unified.ActionStateExecuting] ||
+ !seen[unified.ActionStateCompleted] {
+ t.Fatalf("events = %#v, want full planned-to-completed lifecycle", events)
+ }
+}
+
+func TestHandleExecuteActionWithoutExecutorLeavesApprovedAuditUnchanged(t *testing.T) {
+ now := time.Now().UTC().Truncate(time.Second)
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("get store: %v", err)
+ }
+ record := unified.ActionAuditRecord{
+ ID: "act_no_executor",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now,
+ State: unified.ActionStateApproved,
+ Request: unified.ActionRequest{
+ RequestID: "req-no-executor",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "Recover after confirmed outage",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: unified.ActionPlan{
+ ActionID: "act_no_executor",
+ RequestID: "req-no-executor",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unified.ApprovalAdmin,
+ PlannedAt: now.Add(-time.Minute),
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ Approvals: []unified.ActionApprovalRecord{
+ {
+ Actor: "[email protected]",
+ Method: unified.MethodAPI,
+ Timestamp: now,
+ Outcome: unified.OutcomeApproved,
+ Reason: "approved for proof",
+ },
+ },
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+
+ executeRec := httptest.NewRecorder()
+ executeReq := httptest.NewRequest(http.MethodPost, "/api/actions/act_no_executor/execute", bytes.NewBufferString(`{}`))
+ executeReq.SetPathValue("id", "act_no_executor")
+ executeReq = executeReq.WithContext(auth.WithUser(executeReq.Context(), "[email protected]"))
+ h.HandleExecuteAction(executeRec, executeReq)
+ if executeRec.Code != http.StatusNotImplemented {
+ t.Fatalf("execute status = %d, body=%s", executeRec.Code, executeRec.Body.String())
+ }
+ if !strings.Contains(executeRec.Body.String(), `"code":"action_executor_unavailable"`) {
+ t.Fatalf("execute body = %s", executeRec.Body.String())
+ }
+
+ got, ok, err := store.GetActionAudit("act_no_executor")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || got.State != unified.ActionStateApproved || got.Result != nil {
+ t.Fatalf("audit changed despite missing executor = %#v, ok=%v", got, ok)
+ }
+ events, err := store.GetActionLifecycleEvents("act_no_executor", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ if len(events) != 0 {
+ t.Fatalf("missing executor must not append lifecycle events: %#v", events)
+ }
+}
+
func TestPersistActionPlanAuditFillsMissingLifecycleState(t *testing.T) {
now := time.Date(2026, 5, 3, 10, 0, 0, 0, time.UTC)
store := unified.NewMemoryStore()
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index e66a52801f..90b8be883e 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -11837,6 +11837,188 @@ func TestContract_ActionDecisionJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_ActionExecutionJSONSnapshot(t *testing.T) {
+ startedAt := time.Date(2026, 5, 4, 15, 30, 0, 0, time.UTC)
+ completedAt := startedAt.Add(30 * time.Second)
+ plannedAt := startedAt.Add(-2 * time.Minute)
+ approvedAt := startedAt.Add(-time.Minute)
+ record := unifiedresources.ActionAuditRecord{
+ ID: "act_execution_contract",
+ CreatedAt: plannedAt,
+ UpdatedAt: approvedAt,
+ State: unifiedresources.ActionStateApproved,
+ Request: unifiedresources.ActionRequest{
+ RequestID: "agent-run-execute",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "Recover after confirmed outage",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: unifiedresources.ActionPlan{
+ ActionID: "act_execution_contract",
+ RequestID: "agent-run-execute",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ RollbackAvailable: false,
+ PlannedAt: plannedAt,
+ ExpiresAt: startedAt.Add(3 * time.Minute),
+ ResourceVersion: "resource:sha256:contract",
+ PolicyVersion: "policy:sha256:contract",
+ PlanHash: "sha256:contract",
+ Preflight: &unifiedresources.ActionPreflight{
+ Target: "vm:42",
+ CurrentState: "web-42 is warning",
+ IntendedChange: "Restart the VM",
+ DryRunAvailable: false,
+ DryRunSummary: "No provider-supported dry run is advertised for this capability.",
+ SafetyChecks: []string{
+ "Resource was resolved from the unified resource registry.",
+ "Execution must use POST /api/actions/{id}/execute after approval.",
+ },
+ VerificationSteps: []string{
+ "Review /api/audit/actions/act_execution_contract/events for lifecycle evidence.",
+ },
+ GeneratedAt: plannedAt,
+ },
+ },
+ Approvals: []unifiedresources.ActionApprovalRecord{
+ {
+ Actor: "[email protected]",
+ Method: unifiedresources.MethodAPI,
+ Timestamp: approvedAt,
+ Outcome: unifiedresources.OutcomeApproved,
+ Reason: "inside maintenance window",
+ },
+ },
+ }
+
+ started, startEvent, err := unifiedresources.BeginActionExecution(record, "[email protected]", startedAt)
+ if err != nil {
+ t.Fatalf("begin action execution: %v", err)
+ }
+ completed, doneEvent, err := unifiedresources.CompleteActionExecution(started, &unifiedresources.ExecutionResult{
+ Success: true,
+ Output: "restart dispatched",
+ }, "[email protected]", completedAt)
+ if err != nil {
+ t.Fatalf("complete action execution: %v", err)
+ }
+ response := actionExecutionResponse{
+ ActionID: completed.ID,
+ State: completed.State,
+ Result: completed.Result,
+ Audit: completed,
+ }
+
+ payload := struct {
+ Response actionExecutionResponse `json:"response"`
+ Events []struct {
+ ActionID string `json:"actionId"`
+ State unifiedresources.ActionState `json:"state"`
+ Actor string `json:"actor"`
+ Message string `json:"message"`
+ } `json:"events"`
+ }{Response: response}
+ for _, event := range []unifiedresources.ActionLifecycleEvent{startEvent, doneEvent} {
+ payload.Events = append(payload.Events, struct {
+ ActionID string `json:"actionId"`
+ State unifiedresources.ActionState `json:"state"`
+ Actor string `json:"actor"`
+ Message string `json:"message"`
+ }{
+ ActionID: event.ActionID,
+ State: event.State,
+ Actor: event.Actor,
+ Message: event.Message,
+ })
+ }
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal action execution contract: %v", err)
+ }
+ const want = `{
+ "response":{
+ "actionId":"act_execution_contract",
+ "state":"completed",
+ "result":{
+ "success":true,
+ "output":"restart dispatched"
+ },
+ "audit":{
+ "id":"act_execution_contract",
+ "createdAt":"2026-05-04T15:28:00Z",
+ "updatedAt":"2026-05-04T15:30:30Z",
+ "state":"completed",
+ "request":{
+ "requestId":"agent-run-execute",
+ "resourceId":"vm:42",
+ "capabilityName":"restart",
+ "reason":"Recover after confirmed outage",
+ "requestedBy":"agent:oncall-helper"
+ },
+ "plan":{
+ "actionId":"act_execution_contract",
+ "requestId":"agent-run-execute",
+ "allowed":true,
+ "requiresApproval":true,
+ "approvalPolicy":"admin",
+ "rollbackAvailable":false,
+ "plannedAt":"2026-05-04T15:28:00Z",
+ "expiresAt":"2026-05-04T15:33:00Z",
+ "resourceVersion":"resource:sha256:contract",
+ "policyVersion":"policy:sha256:contract",
+ "planHash":"sha256:contract",
+ "preflight":{
+ "target":"vm:42",
+ "currentState":"web-42 is warning",
+ "intendedChange":"Restart the VM",
+ "dryRunAvailable":false,
+ "dryRunSummary":"No provider-supported dry run is advertised for this capability.",
+ "safetyChecks":[
+ "Resource was resolved from the unified resource registry.",
+ "Execution must use POST /api/actions/{id}/execute after approval."
+ ],
+ "verificationSteps":[
+ "Review /api/audit/actions/act_execution_contract/events for lifecycle evidence."
+ ],
+ "generatedAt":"2026-05-04T15:28:00Z"
+ }
+ },
+ "approvals":[
+ {
+ "actor":"[email protected]",
+ "method":"api",
+ "timestamp":"2026-05-04T15:29:00Z",
+ "outcome":"approved",
+ "reason":"inside maintenance window"
+ }
+ ],
+ "result":{
+ "success":true,
+ "output":"restart dispatched"
+ }
+ }
+ },
+ "events":[
+ {
+ "actionId":"act_execution_contract",
+ "state":"executing",
+ "actor":"[email protected]",
+ "message":"Action execution started."
+ },
+ {
+ "actionId":"act_execution_contract",
+ "state":"completed",
+ "actor":"[email protected]",
+ "message":"Action execution completed."
+ }
+ ]
+ }`
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_ResourceTimelineEndpointsIncludeRelatedChanges(t *testing.T) {
now := time.Date(2026, 4, 25, 22, 15, 0, 0, time.UTC)
h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
diff --git a/internal/api/resources.go b/internal/api/resources.go
index 3192307966..bed50f0ef2 100644
--- a/internal/api/resources.go
+++ b/internal/api/resources.go
@@ -30,6 +30,7 @@ type ResourceHandlers struct {
supplementalRecords map[unified.DataSource]SupplementalRecordsProvider
stateProvider SnapshotProvider
tenantStateProvider TenantStateProvider
+ actionExecutor ActionExecutor
}
type registrySeed struct {
@@ -87,6 +88,11 @@ func (h *ResourceHandlers) SetTenantStateProvider(provider TenantStateProvider)
h.tenantStateProvider = provider
}
+// SetActionExecutor configures the API-owned action execution driver.
+func (h *ResourceHandlers) SetActionExecutor(executor ActionExecutor) {
+ h.actionExecutor = executor
+}
+
// SetSupplementalRecordsProvider configures additional records for a source.
func (h *ResourceHandlers) SetSupplementalRecordsProvider(source unified.DataSource, provider SupplementalRecordsProvider) {
h.supplementalMu.Lock()
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index bbfc8e4ef8..cd00ecd9e0 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -408,6 +408,7 @@ var allRouteAllowlist = []string{
"/api/resources/{id}/timeline",
"POST /api/actions/plan",
"POST /api/actions/{id}/decision",
+ "POST /api/actions/{id}/execute",
"/api/guests/metadata",
"/api/guests/metadata/",
"/api/docker/metadata",
diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.go
index 040d15ec5f..e5364ea025 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -39,6 +39,7 @@ func (r *Router) registerMonitoringResourceRoutes(
r.mux.HandleFunc("/api/resources/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleResourceRoutes)))
r.mux.HandleFunc("POST /api/actions/plan", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandlePlanAction)))
r.mux.HandleFunc("POST /api/actions/{id}/decision", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleDecideAction)))
+ r.mux.HandleFunc("POST /api/actions/{id}/execute", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleExecuteAction)))
// Guest metadata routes
r.mux.HandleFunc("/api/guests/metadata", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, guestMetadataHandler.HandleGetMetadata)))
r.mux.HandleFunc("/api/guests/metadata/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 2d96e6e3d2..3b185a53ff 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -1186,6 +1186,7 @@ func TestAIExecuteEndpointsRequireAIExecuteScope(t *testing.T) {
"/api/ai/execute/stream",
"/api/actions/plan",
"/api/actions/act_test/decision",
+ "/api/actions/act_test/execute",
}
for _, path := range paths {
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index 11b7edf3da..97210c2ee8 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -128,6 +128,10 @@ type ActionEngine interface {
var (
ErrActionNotPending = errors.New("action is not pending approval")
+ ErrActionNotApproved = errors.New("action is not approved for execution")
+ ErrActionNotExecuting = errors.New("action is not executing")
+ ErrActionAlreadyExecuting = errors.New("action is already executing")
+ ErrActionExecutionFinal = errors.New("action execution is already final")
ErrActionPlanExpired = errors.New("action plan expired")
ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")
)
@@ -192,6 +196,126 @@ func ApplyActionDecision(record ActionAuditRecord, approval ActionApprovalRecord
return normalized, normalizedEvent, nil
}
+// BeginActionExecution moves an explicitly executable action into executing.
+// Approval remains separate from execution: approval-required plans must be
+// approved first, while approval-free plans may start from planned only through
+// this explicit execution contract.
+func BeginActionExecution(record ActionAuditRecord, actor string, now time.Time) (ActionAuditRecord, ActionLifecycleEvent, error) {
+ if now.IsZero() {
+ now = time.Now().UTC()
+ } else {
+ now = now.UTC()
+ }
+ if err := ValidateActionExecutionStart(record, now); err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ actor = strings.TrimSpace(actor)
+ if actor == "" {
+ actor = "api:authenticated"
+ }
+
+ record.State = ActionStateExecuting
+ record.UpdatedAt = now
+ normalized, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ event := ActionLifecycleEvent{
+ ActionID: normalized.ID,
+ Timestamp: now,
+ State: ActionStateExecuting,
+ Actor: actor,
+ Message: "Action execution started.",
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ return normalized, normalizedEvent, nil
+}
+
+// CompleteActionExecution records the terminal result for an action that has
+// already entered executing state.
+func CompleteActionExecution(record ActionAuditRecord, result *ExecutionResult, actor string, now time.Time) (ActionAuditRecord, ActionLifecycleEvent, error) {
+ if now.IsZero() {
+ now = time.Now().UTC()
+ } else {
+ now = now.UTC()
+ }
+ if record.State != ActionStateExecuting {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ErrActionNotExecuting
+ }
+ actor = strings.TrimSpace(actor)
+ if actor == "" {
+ actor = "api:authenticated"
+ }
+ if result == nil {
+ result = &ExecutionResult{Success: true}
+ }
+ result.Output = strings.TrimSpace(result.Output)
+ result.ErrorMessage = strings.TrimSpace(result.ErrorMessage)
+
+ nextState := ActionStateCompleted
+ message := "Action execution completed."
+ if !result.Success {
+ nextState = ActionStateFailed
+ message = result.ErrorMessage
+ if message == "" {
+ message = "Action execution failed."
+ }
+ }
+
+ record.State = nextState
+ record.UpdatedAt = now
+ record.Result = result
+ normalized, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ event := ActionLifecycleEvent{
+ ActionID: normalized.ID,
+ Timestamp: now,
+ State: nextState,
+ Actor: actor,
+ Message: message,
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ return normalized, normalizedEvent, nil
+}
+
+// ValidateActionExecutionStart checks whether the current persisted state may
+// enter execution without mutating the record.
+func ValidateActionExecutionStart(record ActionAuditRecord, now time.Time) error {
+ if now.IsZero() {
+ now = time.Now().UTC()
+ } else {
+ now = now.UTC()
+ }
+ if !record.Plan.ExpiresAt.IsZero() && !now.Before(record.Plan.ExpiresAt) {
+ return ErrActionPlanExpired
+ }
+ switch record.State {
+ case ActionStateApproved:
+ return nil
+ case ActionStatePlanned:
+ if record.Plan.Allowed && !record.Plan.RequiresApproval {
+ return nil
+ }
+ return ErrActionNotApproved
+ case ActionStatePending, ActionStateRejected:
+ return ErrActionNotApproved
+ case ActionStateExecuting:
+ return ErrActionAlreadyExecuting
+ case ActionStateCompleted, ActionStateFailed:
+ return ErrActionExecutionFinal
+ default:
+ return fmt.Errorf("unsupported action state %q", record.State)
+ }
+}
+
// NormalizeActionAuditRecord applies the canonical action-governance floor
// before a record is persisted. It keeps older callers usable by filling safe
// deterministic defaults, but rejects records that cannot identify the action,
diff --git a/internal/unifiedresources/actions_test.go b/internal/unifiedresources/actions_test.go
index 49b9e9f813..bc46733999 100644
--- a/internal/unifiedresources/actions_test.go
+++ b/internal/unifiedresources/actions_test.go
@@ -173,3 +173,151 @@ func TestApplyActionDecisionRejectsUnsafeTransitions(t *testing.T) {
t.Fatalf("expired error = %v", err)
}
}
+
+func TestBeginActionExecutionStartsApprovedAction(t *testing.T) {
+ now := time.Date(2026, 5, 4, 12, 30, 0, 0, time.UTC)
+ record := ActionAuditRecord{
+ ID: "act_execute",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-30 * time.Second),
+ State: ActionStateApproved,
+ Request: ActionRequest{
+ RequestID: "req-execute",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "recover service",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_execute",
+ RequestID: "req-execute",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: ApprovalAdmin,
+ PlannedAt: now.Add(-time.Minute),
+ ExpiresAt: now.Add(time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ Approvals: []ActionApprovalRecord{
+ {Actor: "[email protected]", Outcome: OutcomeApproved, Timestamp: now.Add(-30 * time.Second)},
+ },
+ }
+
+ updated, event, err := BeginActionExecution(record, "[email protected]", now)
+ if err != nil {
+ t.Fatalf("BeginActionExecution: %v", err)
+ }
+ if updated.State != ActionStateExecuting || updated.Result != nil || !updated.UpdatedAt.Equal(now) {
+ t.Fatalf("updated action = %#v, want executing without result", updated)
+ }
+ if event.ActionID != "act_execute" || event.State != ActionStateExecuting || event.Actor != "[email protected]" {
+ t.Fatalf("lifecycle event = %#v", event)
+ }
+}
+
+func TestBeginActionExecutionRejectsUnsafeStates(t *testing.T) {
+ now := time.Date(2026, 5, 4, 12, 30, 0, 0, time.UTC)
+ base := ActionAuditRecord{
+ ID: "act_execute",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-time.Minute),
+ State: ActionStatePending,
+ Request: ActionRequest{
+ RequestID: "req-execute",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "recover service",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_execute",
+ RequestID: "req-execute",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: ApprovalAdmin,
+ PlannedAt: now.Add(-time.Minute),
+ ExpiresAt: now.Add(time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ }
+ if _, _, err := BeginActionExecution(base, "[email protected]", now); !errors.Is(err, ErrActionNotApproved) {
+ t.Fatalf("pending error = %v, want %v", err, ErrActionNotApproved)
+ }
+ executing := base
+ executing.State = ActionStateExecuting
+ if _, _, err := BeginActionExecution(executing, "[email protected]", now); !errors.Is(err, ErrActionAlreadyExecuting) {
+ t.Fatalf("executing error = %v, want %v", err, ErrActionAlreadyExecuting)
+ }
+ completed := base
+ completed.State = ActionStateCompleted
+ if _, _, err := BeginActionExecution(completed, "[email protected]", now); !errors.Is(err, ErrActionExecutionFinal) {
+ t.Fatalf("completed error = %v, want %v", err, ErrActionExecutionFinal)
+ }
+ expired := base
+ expired.State = ActionStateApproved
+ expired.Plan.ExpiresAt = now.Add(-time.Second)
+ if _, _, err := BeginActionExecution(expired, "[email protected]", now); !errors.Is(err, ErrActionPlanExpired) {
+ t.Fatalf("expired error = %v, want %v", err, ErrActionPlanExpired)
+ }
+}
+
+func TestCompleteActionExecutionRecordsResult(t *testing.T) {
+ now := time.Date(2026, 5, 4, 12, 45, 0, 0, time.UTC)
+ record := ActionAuditRecord{
+ ID: "act_execute",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-30 * time.Second),
+ State: ActionStateExecuting,
+ Request: ActionRequest{
+ RequestID: "req-execute",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "recover service",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_execute",
+ RequestID: "req-execute",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: ApprovalAdmin,
+ PlannedAt: now.Add(-time.Minute),
+ ExpiresAt: now.Add(time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ }
+
+ updated, event, err := CompleteActionExecution(record, &ExecutionResult{Success: true, Output: "done"}, "[email protected]", now)
+ if err != nil {
+ t.Fatalf("CompleteActionExecution: %v", err)
+ }
+ if updated.State != ActionStateCompleted || updated.Result == nil || updated.Result.Output != "done" {
+ t.Fatalf("completed action = %#v", updated)
+ }
+ if event.State != ActionStateCompleted || event.Message != "Action execution completed." {
+ t.Fatalf("completed event = %#v", event)
+ }
+
+ failed, failedEvent, err := CompleteActionExecution(record, &ExecutionResult{Success: false, ErrorMessage: "provider rejected restart"}, "[email protected]", now)
+ if err != nil {
+ t.Fatalf("CompleteActionExecution failed result: %v", err)
+ }
+ if failed.State != ActionStateFailed || failed.Result == nil || failed.Result.ErrorMessage != "provider rejected restart" {
+ t.Fatalf("failed action = %#v", failed)
+ }
+ if failedEvent.State != ActionStateFailed || failedEvent.Message != "provider rejected restart" {
+ t.Fatalf("failed event = %#v", failedEvent)
+ }
+
+ notExecuting := record
+ notExecuting.State = ActionStateApproved
+ if _, _, err := CompleteActionExecution(notExecuting, nil, "[email protected]", now); !errors.Is(err, ErrActionNotExecuting) {
+ t.Fatalf("not executing error = %v, want %v", err, ErrActionNotExecuting)
+ }
+}
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 6671a82788..4488051e8a 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -313,6 +313,50 @@ func TestResourceAPIExposesDedicatedFacetReads(t *testing.T) {
}
}
+func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
+ requiredSnippets := map[string][]string{
+ filepath.Join(".", "actions.go"): {
+ "func BeginActionExecution(record ActionAuditRecord, actor string, now time.Time)",
+ "func CompleteActionExecution(record ActionAuditRecord, result *ExecutionResult, actor string, now time.Time)",
+ "func ValidateActionExecutionStart(record ActionAuditRecord, now time.Time) error",
+ },
+ filepath.Join(".", "store.go"): {
+ "RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error",
+ "RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error",
+ "func (s *SQLiteResourceStore) RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error",
+ "func (s *SQLiteResourceStore) RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error",
+ },
+ filepath.Join("..", "api", "actions.go"): {
+ "type ActionExecutor interface",
+ "func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Request)",
+ "store.RecordActionExecutionStart(started, startEvent)",
+ "store.RecordActionExecutionResult(completed, doneEvent)",
+ "action_executor_unavailable",
+ },
+ filepath.Join("..", "api", "resources.go"): {
+ "actionExecutor ActionExecutor",
+ "func (h *ResourceHandlers) SetActionExecutor(executor ActionExecutor)",
+ },
+ filepath.Join("..", "api", "router_routes_monitoring.go"): {
+ `"POST /api/actions/{id}/execute"`,
+ "RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleExecuteAction)",
+ },
+ }
+
+ for name, snippets := range requiredSnippets {
+ data, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatalf("failed to read %s: %v", name, err)
+ }
+ source := string(data)
+ for _, snippet := range snippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("%s must contain %q", name, snippet)
+ }
+ }
+ }
+}
+
func TestResourcePolicySummaryContractOmitsRawSignals(t *testing.T) {
policy := ResourcePolicy{
Sensitivity: ResourceSensitivityRestricted,
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 366a6e6d33..ea696a4cd1 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -39,6 +39,8 @@ type ResourceStore interface {
GetActionAudit(actionID string) (ActionAuditRecord, bool, error)
GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error)
RecordActionDecision(record ActionAuditRecord, event ActionLifecycleEvent) error
+ RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error
+ RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error
RecordActionLifecycleEvent(event ActionLifecycleEvent) error
GetActionLifecycleEvents(actionID string, since time.Time, limit int) ([]ActionLifecycleEvent, error)
RecordExportAudit(record ExportAuditRecord) error
@@ -1107,6 +1109,115 @@ func (s *SQLiteResourceStore) RecordActionDecision(record ActionAuditRecord, eve
return nil
}
+func (s *SQLiteResourceStore) RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error {
+ normalizedRecord, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return err
+ }
+ if normalizedRecord.State != ActionStateExecuting || normalizedEvent.State != ActionStateExecuting {
+ return fmt.Errorf("action execution start must persist executing state")
+ }
+ if normalizedEvent.ActionID != normalizedRecord.ID {
+ return fmt.Errorf("action execution start event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ current, ok, err := s.getActionAudit(normalizedRecord.ID)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return fmt.Errorf("action audit %q not found", normalizedRecord.ID)
+ }
+ if err := ValidateActionExecutionStart(current, normalizedEvent.Timestamp); err != nil {
+ return err
+ }
+
+ tx, err := s.db.Begin()
+ if err != nil {
+ return fmt.Errorf("begin action execution start transaction: %w", err)
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback()
+ }
+ }()
+ if err := recordActionAuditSQL(tx, normalizedRecord); err != nil {
+ return err
+ }
+ if err := recordActionLifecycleEventSQL(tx, normalizedEvent); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("commit action execution start transaction: %w", err)
+ }
+ committed = true
+ return nil
+}
+
+func (s *SQLiteResourceStore) RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error {
+ normalizedRecord, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return err
+ }
+ if normalizedRecord.State != ActionStateCompleted && normalizedRecord.State != ActionStateFailed {
+ return fmt.Errorf("action execution result must persist terminal execution state")
+ }
+ if normalizedEvent.State != normalizedRecord.State {
+ return fmt.Errorf("action execution result event state %q does not match audit state %q", normalizedEvent.State, normalizedRecord.State)
+ }
+ if normalizedEvent.ActionID != normalizedRecord.ID {
+ return fmt.Errorf("action execution result event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ current, ok, err := s.getActionAudit(normalizedRecord.ID)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return fmt.Errorf("action audit %q not found", normalizedRecord.ID)
+ }
+ if current.State != ActionStateExecuting {
+ return ErrActionNotExecuting
+ }
+
+ tx, err := s.db.Begin()
+ if err != nil {
+ return fmt.Errorf("begin action execution result transaction: %w", err)
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback()
+ }
+ }()
+ if err := recordActionAuditSQL(tx, normalizedRecord); err != nil {
+ return err
+ }
+ if err := recordActionLifecycleEventSQL(tx, normalizedEvent); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("commit action execution result transaction: %w", err)
+ }
+ committed = true
+ return nil
+}
+
func (s *SQLiteResourceStore) getActionAudit(actionID string) (ActionAuditRecord, bool, error) {
actionID = strings.TrimSpace(actionID)
if actionID == "" {
@@ -1581,6 +1692,81 @@ func (m *MemoryStore) RecordActionDecision(record ActionAuditRecord, event Actio
return nil
}
+func (m *MemoryStore) RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error {
+ normalizedRecord, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return err
+ }
+ if normalizedRecord.State != ActionStateExecuting || normalizedEvent.State != ActionStateExecuting {
+ return fmt.Errorf("action execution start must persist executing state")
+ }
+ if normalizedEvent.ActionID != normalizedRecord.ID {
+ return fmt.Errorf("action execution start event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ replaced := false
+ for i := range m.actionAudits {
+ if m.actionAudits[i].ID == normalizedRecord.ID {
+ if err := ValidateActionExecutionStart(m.actionAudits[i], normalizedEvent.Timestamp); err != nil {
+ return err
+ }
+ m.actionAudits[i] = normalizedRecord
+ replaced = true
+ break
+ }
+ }
+ if !replaced {
+ return fmt.Errorf("action audit %q not found", normalizedRecord.ID)
+ }
+ m.actionLifecycleEvents = append(m.actionLifecycleEvents, normalizedEvent)
+ return nil
+}
+
+func (m *MemoryStore) RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error {
+ normalizedRecord, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return err
+ }
+ if normalizedRecord.State != ActionStateCompleted && normalizedRecord.State != ActionStateFailed {
+ return fmt.Errorf("action execution result must persist terminal execution state")
+ }
+ if normalizedEvent.State != normalizedRecord.State {
+ return fmt.Errorf("action execution result event state %q does not match audit state %q", normalizedEvent.State, normalizedRecord.State)
+ }
+ if normalizedEvent.ActionID != normalizedRecord.ID {
+ return fmt.Errorf("action execution result event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ replaced := false
+ for i := range m.actionAudits {
+ if m.actionAudits[i].ID == normalizedRecord.ID {
+ if m.actionAudits[i].State != ActionStateExecuting {
+ return ErrActionNotExecuting
+ }
+ m.actionAudits[i] = normalizedRecord
+ replaced = true
+ break
+ }
+ }
+ if !replaced {
+ return fmt.Errorf("action audit %q not found", normalizedRecord.ID)
+ }
+ m.actionLifecycleEvents = append(m.actionLifecycleEvents, normalizedEvent)
+ return nil
+}
+
func (m *MemoryStore) GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error) {
m.mu.RLock()
defer m.mu.RUnlock()
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index 17cb5f968d..348983c186 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -1430,6 +1430,96 @@ func TestRecordActionDecision_UpdatesAuditAndAppendsLifecycle(t *testing.T) {
}
}
+func TestRecordActionExecutionStartAndResult_UpdatesAuditAndAppendsLifecycle(t *testing.T) {
+ store := newTestStore(t)
+ now := time.Date(2026, 5, 4, 14, 30, 0, 0, time.UTC)
+ record := ActionAuditRecord{
+ ID: "act_execution",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-30 * time.Second),
+ State: ActionStateApproved,
+ Request: ActionRequest{
+ RequestID: "req-execution",
+ ResourceID: "vm:304",
+ CapabilityName: "restart",
+ Reason: "execution proof",
+ RequestedBy: "agent:test",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_execution",
+ RequestID: "req-execution",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: ApprovalAdmin,
+ PlannedAt: now.Add(-time.Minute),
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ Approvals: []ActionApprovalRecord{
+ {
+ Actor: "[email protected]",
+ Method: MethodAPI,
+ Timestamp: now.Add(-30 * time.Second),
+ Outcome: OutcomeApproved,
+ Reason: "approved for proof",
+ },
+ },
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+
+ started, startEvent, err := BeginActionExecution(record, "[email protected]", now)
+ if err != nil {
+ t.Fatalf("BeginActionExecution: %v", err)
+ }
+ if err := store.RecordActionExecutionStart(started, startEvent); err != nil {
+ t.Fatalf("RecordActionExecutionStart: %v", err)
+ }
+ got, ok, err := store.GetActionAudit("act_execution")
+ if err != nil {
+ t.Fatalf("GetActionAudit after start: %v", err)
+ }
+ if !ok || got.State != ActionStateExecuting || got.Result != nil {
+ t.Fatalf("started audit = %#v, %v", got, ok)
+ }
+ if err := store.RecordActionExecutionStart(started, startEvent); !errors.Is(err, ErrActionAlreadyExecuting) {
+ t.Fatalf("stale RecordActionExecutionStart error = %v, want %v", err, ErrActionAlreadyExecuting)
+ }
+
+ completed, doneEvent, err := CompleteActionExecution(started, &ExecutionResult{Success: true, Output: "done"}, "[email protected]", now.Add(time.Second))
+ if err != nil {
+ t.Fatalf("CompleteActionExecution: %v", err)
+ }
+ if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {
+ t.Fatalf("RecordActionExecutionResult: %v", err)
+ }
+ got, ok, err = store.GetActionAudit("act_execution")
+ if err != nil {
+ t.Fatalf("GetActionAudit after result: %v", err)
+ }
+ if !ok || got.State != ActionStateCompleted || got.Result == nil || got.Result.Output != "done" {
+ t.Fatalf("completed audit = %#v, %v", got, ok)
+ }
+ if err := store.RecordActionExecutionResult(completed, doneEvent); !errors.Is(err, ErrActionNotExecuting) {
+ t.Fatalf("stale RecordActionExecutionResult error = %v, want %v", err, ErrActionNotExecuting)
+ }
+
+ events, err := store.GetActionLifecycleEvents("act_execution", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seen := map[ActionState]bool{}
+ for _, event := range events {
+ seen[event.State] = true
+ }
+ if len(events) != 2 || !seen[ActionStateExecuting] || !seen[ActionStateCompleted] {
+ t.Fatalf("execution events = %#v", events)
+ }
+}
+
func TestRecordActionAudit_NormalizesGovernedPlan(t *testing.T) {
store := newTestStore(t)
now := time.Date(2026, 4, 25, 22, 40, 0, 0, time.UTC)
diff --git a/pkg/pulsecli/actions.go b/pkg/pulsecli/actions.go
index 552ed92491..b18351e8e1 100644
--- a/pkg/pulsecli/actions.go
+++ b/pkg/pulsecli/actions.go
@@ -49,6 +49,13 @@ type actionDecisionOptions struct {
Reason string
}
+type actionExecutionOptions struct {
+ APIURL string
+ Token string
+ ActionID string
+ Reason string
+}
+
type actionAuditOptions struct {
APIURL string
Token string
@@ -95,6 +102,13 @@ type actionDecisionResponse struct {
Audit unified.ActionAuditRecord `json:"audit"`
}
+type actionExecutionResponse struct {
+ ActionID string `json:"actionId"`
+ State unified.ActionState `json:"state"`
+ Result *unified.ExecutionResult `json:"result,omitempty"`
+ Audit unified.ActionAuditRecord `json:"audit"`
+}
+
func newActionsCmd(deps *ActionsDeps) *cobra.Command {
actionsCmd := &cobra.Command{
Use: "actions",
@@ -131,6 +145,7 @@ func newActionsCmd(deps *ActionsDeps) *cobra.Command {
actionsCmd.AddCommand(planCmd)
actionsCmd.AddCommand(newActionCapabilitiesCmd(deps))
actionsCmd.AddCommand(newActionDecisionCmd(deps))
+ actionsCmd.AddCommand(newActionExecutionCmd(deps))
actionsCmd.AddCommand(newActionAuditCmd(deps))
actionsCmd.AddCommand(newActionEventsCmd(deps))
return actionsCmd
@@ -182,6 +197,29 @@ func newActionDecisionCmd(deps *ActionsDeps) *cobra.Command {
return cmd
}
+func newActionExecutionCmd(deps *ActionsDeps) *cobra.Command {
+ opts := actionExecutionOptions{
+ APIURL: strings.TrimSpace(actionGetenv(deps, "PULSE_API_URL")),
+ Token: strings.TrimSpace(actionGetenv(deps, "PULSE_API_TOKEN")),
+ }
+ if opts.APIURL == "" {
+ opts.APIURL = defaultPulseAPIURL
+ }
+
+ cmd := &cobra.Command{
+ Use: "execute",
+ Short: "Execute a governed action through the API action contract",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runActionExecution(cmd, deps, opts)
+ },
+ }
+ cmd.Flags().StringVar(&opts.APIURL, "api-url", opts.APIURL, "Pulse server URL or /api base URL")
+ cmd.Flags().StringVar(&opts.Token, "token", opts.Token, "Pulse API token; defaults to PULSE_API_TOKEN")
+ cmd.Flags().StringVar(&opts.ActionID, "action-id", "", "governed action id")
+ cmd.Flags().StringVar(&opts.Reason, "reason", "", "audit reason for starting execution")
+ return cmd
+}
+
func newActionAuditCmd(deps *ActionsDeps) *cobra.Command {
opts := actionAuditOptions{
APIURL: strings.TrimSpace(actionGetenv(deps, "PULSE_API_URL")),
@@ -354,6 +392,66 @@ func runActionDecision(cmd *cobra.Command, deps *ActionsDeps, opts actionDecisio
return nil
}
+func runActionExecution(cmd *cobra.Command, deps *ActionsDeps, opts actionExecutionOptions) error {
+ token := strings.TrimSpace(opts.Token)
+ if token == "" {
+ return fmt.Errorf("api token is required (use --token or PULSE_API_TOKEN)")
+ }
+
+ actionID := strings.TrimSpace(opts.ActionID)
+ if actionID == "" {
+ return fmt.Errorf("actionId is required (use --action-id)")
+ }
+
+ endpoint, err := pulseAPIEndpoint(opts.APIURL, "/actions/"+url.PathEscape(actionID)+"/execute")
+ if err != nil {
+ return err
+ }
+
+ body, err := json.Marshal(struct {
+ Reason string `json:"reason,omitempty"`
+ }{
+ Reason: strings.TrimSpace(opts.Reason),
+ })
+ if err != nil {
+ return fmt.Errorf("failed to encode action execution: %w", err)
+ }
+
+ httpReq, err := http.NewRequestWithContext(cmd.Context(), http.MethodPost, endpoint.String(), bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("failed to build action execution request: %w", err)
+ }
+ httpReq.Header.Set("Accept", "application/json")
+ httpReq.Header.Set("Authorization", "Bearer "+token)
+ httpReq.Header.Set("Content-Type", "application/json")
+
+ resp, err := actionHTTPClient(deps).Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("action execution request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ respBody, err := ReadBoundedHTTPBody(resp.Body, resp.ContentLength, maxPulseAPIResponseBytes, "action execution response")
+ if err != nil {
+ return fmt.Errorf("failed to read action execution response: %w", err)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return apiStatusError("action execution request", resp.Status, respBody)
+ }
+
+ var execution actionExecutionResponse
+ if err := decodeJSONBytes(respBody, &execution); err != nil {
+ return fmt.Errorf("failed to decode action execution response: %w", err)
+ }
+
+ encoder := json.NewEncoder(cmd.OutOrStdout())
+ encoder.SetIndent("", " ")
+ if err := encoder.Encode(execution); err != nil {
+ return fmt.Errorf("failed to write action execution response: %w", err)
+ }
+ return nil
+}
+
func runActionCapabilities(cmd *cobra.Command, deps *ActionsDeps, opts actionCapabilitiesOptions) error {
token := strings.TrimSpace(opts.Token)
if token == "" {
diff --git a/pkg/pulsecli/actions_test.go b/pkg/pulsecli/actions_test.go
index 6c2e7b53f0..abbf96f4c7 100644
--- a/pkg/pulsecli/actions_test.go
+++ b/pkg/pulsecli/actions_test.go
@@ -248,6 +248,113 @@ func TestActionsDecideCommandValidatesDecisionFields(t *testing.T) {
}
}
+func TestActionsExecuteCommandPostsExecutionRequest(t *testing.T) {
+ now := time.Date(2026, 5, 4, 14, 45, 0, 0, time.UTC)
+ var receivedAuth string
+ var received struct {
+ Reason string `json:"reason"`
+ }
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ t.Fatalf("method = %s, want POST", r.Method)
+ }
+ if r.URL.Path != "/api/actions/act_test/execute" {
+ t.Fatalf("path = %s, want /api/actions/act_test/execute", r.URL.Path)
+ }
+ receivedAuth = r.Header.Get("Authorization")
+ if got := r.Header.Get("Content-Type"); !strings.Contains(got, "application/json") {
+ t.Fatalf("Content-Type = %q, want application/json", got)
+ }
+ if err := json.NewDecoder(r.Body).Decode(&received); err != nil {
+ t.Fatalf("decode request: %v", err)
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(actionExecutionResponse{
+ ActionID: "act_test",
+ State: unified.ActionStateCompleted,
+ Result: &unified.ExecutionResult{Success: true, Output: "restart dispatched"},
+ Audit: unified.ActionAuditRecord{
+ ID: "act_test",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now,
+ State: unified.ActionStateCompleted,
+ Request: unified.ActionRequest{
+ RequestID: "req-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "Recover",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: unified.ActionPlan{
+ ActionID: "act_test",
+ RequestID: "req-1",
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ Result: &unified.ExecutionResult{Success: true, Output: "restart dispatched"},
+ },
+ })
+ }))
+ defer server.Close()
+
+ cmd := newTestActionsRootCommand(map[string]string{
+ "PULSE_API_TOKEN": "test-token",
+ "PULSE_API_URL": server.URL + "/api",
+ })
+ cmd.SetArgs([]string{
+ "actions", "execute",
+ "--action-id", "act_test",
+ "--reason", "inside approved maintenance window",
+ })
+ var out bytes.Buffer
+ cmd.SetOut(&out)
+
+ if err := cmd.Execute(); err != nil {
+ t.Fatalf("execute actions execute: %v", err)
+ }
+ if receivedAuth != "Bearer test-token" {
+ t.Fatalf("Authorization = %q", receivedAuth)
+ }
+ if received.Reason != "inside approved maintenance window" {
+ t.Fatalf("received execution request = %#v", received)
+ }
+
+ var execution actionExecutionResponse
+ if err := json.Unmarshal(out.Bytes(), &execution); err != nil {
+ t.Fatalf("decode command output: %v\n%s", err, out.String())
+ }
+ if execution.ActionID != "act_test" || execution.State != unified.ActionStateCompleted || execution.Result == nil || execution.Result.Output != "restart dispatched" {
+ t.Fatalf("execution output = %+v", execution)
+ }
+}
+
+func TestActionsExecuteCommandValidatesRequiredFields(t *testing.T) {
+ cmd := newTestActionsRootCommand(nil)
+ cmd.SetArgs([]string{
+ "actions", "execute",
+ "--api-url", "http://127.0.0.1:7655",
+ "--action-id", "act_test",
+ })
+
+ err := cmd.Execute()
+ if err == nil || !strings.Contains(err.Error(), "api token is required") {
+ t.Fatalf("expected token error, got %v", err)
+ }
+
+ cmd = newTestActionsRootCommand(map[string]string{
+ "PULSE_API_TOKEN": "test-token",
+ "PULSE_API_URL": "http://127.0.0.1:7655",
+ })
+ cmd.SetArgs([]string{"actions", "execute"})
+ if err := cmd.Execute(); err == nil || !strings.Contains(err.Error(), "actionId is required") {
+ t.Fatalf("expected action id error, got %v", err)
+ }
+}
+
func TestActionsCapabilitiesCommandFetchesResourceFacets(t *testing.T) {
var receivedAuth string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {