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 decision API

rcourtman20402850856d
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 069b964a16..a4809b845f 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -130,7 +130,10 @@ contract for those resource actions. Successful action plans also belong to
the API-owned action-audit trail before any lifecycle surface consumes them:
approval-required plans must be visible as `pending_approval` with initial
lifecycle evidence, and retry/idempotency handling must not create duplicate
-lifecycle events.
+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.
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/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index fe63b0343f..1efb6d246e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -300,11 +300,19 @@ the canonical monitored-system blocked payload.
not duplicate the initial lifecycle events. MCP, CLI, and UI consumers may
adapt this payload, but they must not become the source of truth for action
planning semantics.
- The supported CLI adapter for this contract is `pulse actions plan`, owned
- by `pkg/pulsecli/actions.go` and registered from `pkg/pulsecli/root.go`.
- It must remain a thin authenticated client for `POST /api/actions/plan`
- rather than importing planner internals, creating action IDs, or approving
- and executing capabilities locally. `pulse actions capabilities` may read
+ Action approval decisions are API-owned as a separate non-execution
+ contract: `POST /api/actions/{id}/decision` may only record an
+ `approved` or `rejected` decision against a persisted `pending_approval`
+ action, update the canonical action audit, and append lifecycle evidence
+ 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
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 be6111ace4..eeaf317118 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -428,6 +428,12 @@ persisted action records must identify the requester, resource, capability,
approval policy, preflight dry-run posture, and lifecycle state before they are
read through audit APIs, so audit history cannot silently accept an unscoped or
unplanned execution record.
+Action planning and action decision mutations remain privileged runtime
+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.
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 846959bde6..f50e99e58a 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -96,7 +96,11 @@ stale-plan hash, blast-radius model, or execution protocol outside
Successful action plans also remain API-owned audit facts before
storage/recovery surfaces consume them: approval-required plans must persist
as `pending_approval` with initial lifecycle evidence, and retry/idempotency
-handling must not duplicate those lifecycle events.
+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.
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 344dd6111e..7ca5a573ad 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -471,6 +471,11 @@ verification steps through `preflight`, and `RecordActionAudit` plus
`RecordActionLifecycleEvent` must normalize action id, request id, resource,
capability, approval policy, timestamps, lifecycle state, and requester before
records reach durable audit history.
+Action approval decisions belong to the same resource-owned state machine:
+`ApplyActionDecision` may transition only a persisted `pending_approval`
+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.
`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
@@ -1462,6 +1467,9 @@ memory-only models.
The in-memory store mirrors the durable audit contract by upserting action
audits on action ID, so tests and runtime callers observe the same current
record state that SQLite persists for the control-plane execution trail.
+It also mirrors the durable decision contract: approval/rejection writes must
+target an existing pending action and must fail rather than creating a
+decision-only record or overwriting an already decided action.
The enterprise audit API now reads those same unified-resource action and
export records back out, so the durable store is not just a write sink but the
canonical history surface for the control-plane verbs.
diff --git a/internal/api/actions.go b/internal/api/actions.go
index d3e6bc9b55..cc79316f6b 100644
--- a/internal/api/actions.go
+++ b/internal/api/actions.go
@@ -13,6 +13,19 @@ import (
)
const maxActionPlanRequestBytes = 1 << 20
+const maxActionDecisionRequestBytes = 64 << 10
+
+type actionDecisionRequest struct {
+ Outcome unified.ApprovalOutcome `json:"outcome"`
+ Reason string `json:"reason,omitempty"`
+}
+
+type actionDecisionResponse struct {
+ ActionID string `json:"actionId"`
+ State unified.ActionState `json:"state"`
+ Approval unified.ActionApprovalRecord `json:"approval"`
+ Audit unified.ActionAuditRecord `json:"audit"`
+}
func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -163,3 +176,126 @@ func plannedActionState(plan unified.ActionPlan) unified.ActionState {
}
return unified.ActionStatePlanned
}
+
+func (h *ResourceHandlers) HandleDecideAction(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 decision actionDecisionRequest
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxActionDecisionRequestBytes))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&decision); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{
+ "body": "request body must be a valid action decision JSON object",
+ })
+ return
+ }
+ if err := decoder.Decode(&struct{}{}); err != io.EOF {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{
+ "body": "request body must contain one JSON object",
+ })
+ return
+ }
+ decision.Outcome = unified.ApprovalOutcome(strings.TrimSpace(string(decision.Outcome)))
+ decision.Reason = strings.TrimSpace(decision.Reason)
+ if decision.Outcome != unified.OutcomeApproved && decision.Outcome != unified.OutcomeRejected {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{
+ "outcome": "outcome must be approved or rejected",
+ })
+ return
+ }
+
+ 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)
+ now := time.Now().UTC()
+ approval := unified.ActionApprovalRecord{
+ Actor: actor,
+ Method: unified.MethodAPI,
+ Timestamp: now,
+ Outcome: decision.Outcome,
+ Reason: decision.Reason,
+ }
+ updated, event, err := unified.ApplyActionDecision(record, approval, now)
+ if err != nil {
+ writeActionDecisionApplyError(w, err)
+ return
+ }
+ if err := store.RecordActionDecision(updated, event); err != nil {
+ if errors.Is(err, unified.ErrActionNotPending) {
+ writeActionDecisionApplyError(w, err)
+ return
+ }
+ writeErrorResponse(w, http.StatusInternalServerError, "action_decision_persist_failed", sanitizeErrorForClient(err, "Failed to persist action decision"), nil)
+ return
+ }
+
+ responseApproval := approval
+ if len(updated.Approvals) > 0 {
+ responseApproval = updated.Approvals[len(updated.Approvals)-1]
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(actionDecisionResponse{
+ ActionID: updated.ID,
+ State: updated.State,
+ Approval: responseApproval,
+ Audit: updated,
+ }); err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "action_decision_encode_failed", "Failed to encode action decision", nil)
+ }
+}
+
+func actionDecisionActor(h *ResourceHandlers, r *http.Request) string {
+ if h != nil {
+ if actor := strings.TrimSpace(getAuthUsername(h.cfg, r)); actor != "" {
+ return actor
+ }
+ }
+ if actor := strings.TrimSpace(getUserID(r)); actor != "" {
+ return actor
+ }
+ return "api:authenticated"
+}
+
+func writeActionDecisionApplyError(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, unified.ErrInvalidApprovalOutcome):
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{
+ "outcome": "outcome must be approved or rejected",
+ })
+ case errors.Is(err, unified.ErrActionNotPending):
+ writeErrorResponse(w, http.StatusConflict, "action_not_pending", "Action is not pending approval", 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_decision_failed", sanitizeErrorForClient(err, "Action decision failed"), nil)
+ }
+}
diff --git a/internal/api/actions_test.go b/internal/api/actions_test.go
index f0a24384df..42dbd9892f 100644
--- a/internal/api/actions_test.go
+++ b/internal/api/actions_test.go
@@ -12,6 +12,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
func TestHandlePlanActionReturnsCanonicalPlan(t *testing.T) {
@@ -198,6 +199,122 @@ func TestHandlePlanActionPersistsAuditAndLifecycle(t *testing.T) {
}
}
+func TestHandleDecideActionApprovesPendingPlanWithoutExecution(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"}},
+ },
+ },
+ },
+ },
+ },
+ })
+
+ planRec := httptest.NewRecorder()
+ planReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
+ "requestId":"agent-run-approve",
+ "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())
+ }
+
+ var decision actionDecisionResponse
+ if err := json.Unmarshal(decisionRec.Body.Bytes(), &decision); err != nil {
+ t.Fatalf("decode decision response: %v", err)
+ }
+ if decision.ActionID != plan.ActionID || decision.State != unified.ActionStateApproved {
+ t.Fatalf("decision identity/state = %q/%q, want %q/%q", decision.ActionID, decision.State, plan.ActionID, unified.ActionStateApproved)
+ }
+ if decision.Approval.Actor != "[email protected]" || decision.Approval.Method != unified.MethodAPI || decision.Approval.Outcome != unified.OutcomeApproved {
+ t.Fatalf("decision approval = %#v", decision.Approval)
+ }
+ if decision.Audit.Result != nil {
+ t.Fatalf("approval must not execute the action, got result %#v", decision.Audit.Result)
+ }
+
+ 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.ActionStateApproved || len(audit.Approvals) != 1 || audit.Result != nil {
+ t.Fatalf("persisted 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 event.State == unified.ActionStateExecuting || event.State == unified.ActionStateCompleted {
+ t.Fatalf("approval must not create execution event: %#v", event)
+ }
+ }
+ if len(events) != 3 || !seen[unified.ActionStatePlanned] || !seen[unified.ActionStatePending] || !seen[unified.ActionStateApproved] {
+ t.Fatalf("events = %#v, want planned, pending_approval, approved", events)
+ }
+
+ retryRec := httptest.NewRecorder()
+ retryReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/decision", bytes.NewBufferString(`{
+ "outcome":"rejected",
+ "reason":"late conflicting decision"
+ }`))
+ retryReq.SetPathValue("id", plan.ActionID)
+ retryReq = retryReq.WithContext(auth.WithUser(retryReq.Context(), "[email protected]"))
+ h.HandleDecideAction(retryRec, retryReq)
+ if retryRec.Code != http.StatusConflict {
+ t.Fatalf("retry decision status = %d, body=%s", retryRec.Code, retryRec.Body.String())
+ }
+ if !strings.Contains(retryRec.Body.String(), `"code":"action_not_pending"`) {
+ t.Fatalf("retry decision body = %s", retryRec.Body.String())
+ }
+}
+
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/activity_audit_handlers.go b/internal/api/activity_audit_handlers.go
index 885659beca..90d8bfd901 100644
--- a/internal/api/activity_audit_handlers.go
+++ b/internal/api/activity_audit_handlers.go
@@ -16,8 +16,8 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/audit"
)
-// validAuditEventID matches alphanumeric IDs with hyphens (UUID format)
-var validAuditEventID = regexp.MustCompile(`^[a-zA-Z0-9\-]+$`)
+// validAuditEventID matches canonical action IDs plus UUID-style audit IDs.
+var validAuditEventID = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
var resolveWebhookIPs = net.DefaultResolver.LookupIPAddr
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index d5d0799e77..c21c00f19a 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -11570,6 +11570,167 @@ func TestContract_ActionPlanAuditLifecycleSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_ActionDecisionJSONSnapshot(t *testing.T) {
+ now := time.Date(2026, 5, 4, 15, 0, 0, 0, time.UTC)
+ plannedAt := now.Add(-time.Minute)
+ record := unifiedresources.ActionAuditRecord{
+ ID: "act_decision_contract",
+ CreatedAt: plannedAt,
+ UpdatedAt: plannedAt,
+ State: unifiedresources.ActionStatePending,
+ Request: unifiedresources.ActionRequest{
+ RequestID: "agent-run-approve",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "Recover after confirmed outage",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: unifiedresources.ActionPlan{
+ ActionID: "act_decision_contract",
+ RequestID: "agent-run-approve",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ RollbackAvailable: false,
+ PlannedAt: plannedAt,
+ ExpiresAt: now.Add(4 * 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.",
+ "This endpoint plans only; it does not approve or execute the action.",
+ },
+ VerificationSteps: []string{
+ "Review /api/audit/actions/act_decision_contract/events for lifecycle evidence.",
+ },
+ GeneratedAt: plannedAt,
+ },
+ },
+ }
+
+ updated, event, err := unifiedresources.ApplyActionDecision(record, unifiedresources.ActionApprovalRecord{
+ Actor: "[email protected]",
+ Outcome: unifiedresources.OutcomeApproved,
+ Reason: "inside maintenance window",
+ }, now)
+ if err != nil {
+ t.Fatalf("apply action decision: %v", err)
+ }
+ response := actionDecisionResponse{
+ ActionID: updated.ID,
+ State: updated.State,
+ Approval: updated.Approvals[len(updated.Approvals)-1],
+ Audit: updated,
+ }
+
+ payload := struct {
+ Response actionDecisionResponse `json:"response"`
+ Event struct {
+ ActionID string `json:"actionId"`
+ State unifiedresources.ActionState `json:"state"`
+ Actor string `json:"actor"`
+ Message string `json:"message"`
+ Result *unifiedresources.ExecutionResult `json:"result,omitempty"`
+ Method unifiedresources.ApprovalMethod `json:"method"`
+ Outcome unifiedresources.ApprovalOutcome `json:"outcome"`
+ Policy unifiedresources.ActionApprovalLevel `json:"policy"`
+ } `json:"event"`
+ }{Response: response}
+ payload.Event.ActionID = event.ActionID
+ payload.Event.State = event.State
+ payload.Event.Actor = event.Actor
+ payload.Event.Message = event.Message
+ payload.Event.Result = response.Audit.Result
+ payload.Event.Method = response.Approval.Method
+ payload.Event.Outcome = response.Approval.Outcome
+ payload.Event.Policy = response.Audit.Plan.ApprovalPolicy
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal action decision contract: %v", err)
+ }
+ const want = `{
+ "response":{
+ "actionId":"act_decision_contract",
+ "state":"approved",
+ "approval":{
+ "actor":"[email protected]",
+ "method":"api",
+ "timestamp":"2026-05-04T15:00:00Z",
+ "outcome":"approved",
+ "reason":"inside maintenance window"
+ },
+ "audit":{
+ "id":"act_decision_contract",
+ "createdAt":"2026-05-04T14:59:00Z",
+ "updatedAt":"2026-05-04T15:00:00Z",
+ "state":"approved",
+ "request":{
+ "requestId":"agent-run-approve",
+ "resourceId":"vm:42",
+ "capabilityName":"restart",
+ "reason":"Recover after confirmed outage",
+ "requestedBy":"agent:oncall-helper"
+ },
+ "plan":{
+ "actionId":"act_decision_contract",
+ "requestId":"agent-run-approve",
+ "allowed":true,
+ "requiresApproval":true,
+ "approvalPolicy":"admin",
+ "rollbackAvailable":false,
+ "plannedAt":"2026-05-04T14:59:00Z",
+ "expiresAt":"2026-05-04T15:04: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.",
+ "This endpoint plans only; it does not approve or execute the action."
+ ],
+ "verificationSteps":[
+ "Review /api/audit/actions/act_decision_contract/events for lifecycle evidence."
+ ],
+ "generatedAt":"2026-05-04T14:59:00Z"
+ }
+ },
+ "approvals":[
+ {
+ "actor":"[email protected]",
+ "method":"api",
+ "timestamp":"2026-05-04T15:00:00Z",
+ "outcome":"approved",
+ "reason":"inside maintenance window"
+ }
+ ]
+ }
+ },
+ "event":{
+ "actionId":"act_decision_contract",
+ "state":"approved",
+ "actor":"[email protected]",
+ "message":"Action approved. Execution remains pending a separate execution contract.",
+ "method":"api",
+ "outcome":"approved",
+ "policy":"admin"
+ }
+ }`
+ 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/route_inventory_test.go b/internal/api/route_inventory_test.go
index 97e1ab8a40..bbfc8e4ef8 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -407,6 +407,7 @@ var allRouteAllowlist = []string{
"/api/resources/{id}/facets",
"/api/resources/{id}/timeline",
"POST /api/actions/plan",
+ "POST /api/actions/{id}/decision",
"/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 a31720c3b3..040d15ec5f 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -38,6 +38,7 @@ func (r *Router) registerMonitoringResourceRoutes(
r.mux.HandleFunc("/api/resources/{id}/timeline", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleGetResourceTimeline)))
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)))
// 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 de44948299..2d96e6e3d2 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -1184,6 +1184,8 @@ func TestAIExecuteEndpointsRequireAIExecuteScope(t *testing.T) {
paths := []string{
"/api/ai/execute",
"/api/ai/execute/stream",
+ "/api/actions/plan",
+ "/api/actions/act_test/decision",
}
for _, path := range paths {
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index 51d4237cb9..11b7edf3da 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -1,6 +1,7 @@
package unifiedresources
import (
+ "errors"
"fmt"
"strings"
"time"
@@ -125,6 +126,72 @@ type ActionEngine interface {
ExecuteAction(actionID string) (*ExecutionResult, error)
}
+var (
+ ErrActionNotPending = errors.New("action is not pending approval")
+ ErrActionPlanExpired = errors.New("action plan expired")
+ ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")
+)
+
+// ApplyActionDecision records an explicit approval or rejection against a
+// pending governed action without starting execution. Execution remains a
+// separate contract so approvals cannot become an implicit control bypass.
+func ApplyActionDecision(record ActionAuditRecord, approval ActionApprovalRecord, now time.Time) (ActionAuditRecord, ActionLifecycleEvent, error) {
+ if now.IsZero() {
+ now = time.Now().UTC()
+ } else {
+ now = now.UTC()
+ }
+ approval.Actor = strings.TrimSpace(approval.Actor)
+ approval.Reason = strings.TrimSpace(approval.Reason)
+ if approval.Method == "" {
+ approval.Method = MethodAPI
+ }
+ if approval.Timestamp.IsZero() {
+ approval.Timestamp = now
+ } else {
+ approval.Timestamp = approval.Timestamp.UTC()
+ }
+
+ var nextState ActionState
+ var message string
+ switch approval.Outcome {
+ case OutcomeApproved:
+ nextState = ActionStateApproved
+ message = "Action approved. Execution remains pending a separate execution contract."
+ case OutcomeRejected:
+ nextState = ActionStateRejected
+ message = "Action rejected before execution."
+ default:
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ErrInvalidApprovalOutcome
+ }
+ if record.State != ActionStatePending {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ErrActionNotPending
+ }
+ if !record.Plan.ExpiresAt.IsZero() && !now.Before(record.Plan.ExpiresAt) {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ErrActionPlanExpired
+ }
+
+ record.State = nextState
+ record.UpdatedAt = approval.Timestamp
+ record.Approvals = append(record.Approvals, approval)
+ normalized, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ event := ActionLifecycleEvent{
+ ActionID: normalized.ID,
+ Timestamp: approval.Timestamp,
+ State: nextState,
+ Actor: approval.Actor,
+ Message: message,
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ return normalized, normalizedEvent, nil
+}
+
// 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 9ba7730cf9..49b9e9f813 100644
--- a/internal/unifiedresources/actions_test.go
+++ b/internal/unifiedresources/actions_test.go
@@ -1,6 +1,7 @@
package unifiedresources
import (
+ "errors"
"strings"
"testing"
"time"
@@ -87,3 +88,88 @@ func TestNormalizeActionLifecycleEventRejectsInvalidEvents(t *testing.T) {
t.Fatal("expected invalid lifecycle state to be rejected")
}
}
+
+func TestApplyActionDecisionApprovesPendingActionWithoutExecution(t *testing.T) {
+ now := time.Date(2026, 5, 4, 12, 0, 0, 0, time.UTC)
+ record := ActionAuditRecord{
+ ID: "act_test",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-time.Minute),
+ State: ActionStatePending,
+ Request: ActionRequest{
+ RequestID: "req-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "recover service",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_test",
+ RequestID: "req-1",
+ 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 := ApplyActionDecision(record, ActionApprovalRecord{
+ Actor: "[email protected]",
+ Outcome: OutcomeApproved,
+ Reason: "inside maintenance window",
+ }, now)
+ if err != nil {
+ t.Fatalf("ApplyActionDecision: %v", err)
+ }
+ if updated.State != ActionStateApproved || updated.Result != nil {
+ t.Fatalf("updated action = %#v, want approved without execution result", updated)
+ }
+ if len(updated.Approvals) != 1 || updated.Approvals[0].Method != MethodAPI || updated.Approvals[0].Actor != "[email protected]" {
+ t.Fatalf("approval record = %#v", updated.Approvals)
+ }
+ if event.ActionID != "act_test" || event.State != ActionStateApproved || !strings.Contains(event.Message, "Execution remains pending") {
+ t.Fatalf("lifecycle event = %#v", event)
+ }
+}
+
+func TestApplyActionDecisionRejectsUnsafeTransitions(t *testing.T) {
+ now := time.Date(2026, 5, 4, 12, 0, 0, 0, time.UTC)
+ base := ActionAuditRecord{
+ ID: "act_test",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-time.Minute),
+ State: ActionStatePending,
+ Request: ActionRequest{
+ RequestID: "req-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "recover service",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_test",
+ RequestID: "req-1",
+ ExpiresAt: now.Add(time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ }
+ if _, _, err := ApplyActionDecision(base, ActionApprovalRecord{Outcome: ApprovalOutcome("maybe")}, now); !errors.Is(err, ErrInvalidApprovalOutcome) {
+ t.Fatalf("invalid outcome error = %v", err)
+ }
+ notPending := base
+ notPending.State = ActionStateApproved
+ if _, _, err := ApplyActionDecision(notPending, ActionApprovalRecord{Outcome: OutcomeApproved}, now); !errors.Is(err, ErrActionNotPending) {
+ t.Fatalf("not pending error = %v", err)
+ }
+ expired := base
+ expired.Plan.ExpiresAt = now.Add(-time.Second)
+ if _, _, err := ApplyActionDecision(expired, ActionApprovalRecord{Outcome: OutcomeApproved}, now); !errors.Is(err, ErrActionPlanExpired) {
+ t.Fatalf("expired error = %v", err)
+ }
+}
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 02a9ab1fd8..366a6e6d33 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -36,7 +36,9 @@ type ResourceStore interface {
CountRecentChangesBySourceAdapter(canonicalID string, since time.Time) (map[ChangeSourceAdapter]int, error)
CountRecentChangesBySourceAdapterFiltered(canonicalID string, since time.Time, filters ResourceChangeFilters) (map[ChangeSourceAdapter]int, error)
RecordActionAudit(record ActionAuditRecord) error
+ GetActionAudit(actionID string) (ActionAuditRecord, bool, error)
GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error)
+ RecordActionDecision(record ActionAuditRecord, event ActionLifecycleEvent) error
RecordActionLifecycleEvent(event ActionLifecycleEvent) error
GetActionLifecycleEvents(actionID string, since time.Time, limit int) ([]ActionLifecycleEvent, error)
RecordExportAudit(record ExportAuditRecord) error
@@ -899,16 +901,11 @@ func (s *SQLiteResourceStore) CountRecentChangesBySourceAdapterFiltered(canonica
return counts, nil
}
-func (s *SQLiteResourceStore) RecordActionAudit(record ActionAuditRecord) error {
- normalized, err := NormalizeActionAuditRecord(record)
- if err != nil {
- return err
- }
- record = normalized
-
- s.mu.Lock()
- defer s.mu.Unlock()
+type sqlExecutor interface {
+ Exec(query string, args ...any) (sql.Result, error)
+}
+func recordActionAuditSQL(exec sqlExecutor, record ActionAuditRecord) error {
requestJSON, err := json.Marshal(record.Request)
if err != nil {
return fmt.Errorf("marshal action request: %w", err)
@@ -926,7 +923,7 @@ func (s *SQLiteResourceStore) RecordActionAudit(record ActionAuditRecord) error
return fmt.Errorf("marshal action result: %w", err)
}
- _, err = s.db.Exec(`
+ _, err = exec.Exec(`
INSERT INTO action_audits (id, action_id, canonical_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
@@ -947,6 +944,65 @@ func (s *SQLiteResourceStore) RecordActionAudit(record ActionAuditRecord) error
return nil
}
+func (s *SQLiteResourceStore) RecordActionAudit(record ActionAuditRecord) error {
+ normalized, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ record = normalized
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ return recordActionAuditSQL(s.db, record)
+}
+
+type actionAuditScanner interface {
+ Scan(dest ...any) error
+}
+
+func scanActionAuditRecord(scanner actionAuditScanner) (ActionAuditRecord, error) {
+ var record ActionAuditRecord
+ var stateStr string
+ var actionID, requestID string
+ var requestJSON, planJSON, approvalsJSON, resultJSON sql.NullString
+ if err := scanner.Scan(&record.ID, &actionID, &requestID, &record.CreatedAt, &record.UpdatedAt, &stateStr, &requestJSON, &planJSON, &approvalsJSON, &resultJSON); err != nil {
+ return ActionAuditRecord{}, err
+ }
+
+ record.State = ActionState(stateStr)
+ if requestJSON.Valid && requestJSON.String != "" {
+ if err := json.Unmarshal([]byte(requestJSON.String), &record.Request); err != nil {
+ return ActionAuditRecord{}, fmt.Errorf("unmarshal action request: %w", err)
+ }
+ }
+ if planJSON.Valid && planJSON.String != "" {
+ if err := json.Unmarshal([]byte(planJSON.String), &record.Plan); err != nil {
+ return ActionAuditRecord{}, fmt.Errorf("unmarshal action plan: %w", err)
+ }
+ }
+ if approvalsJSON.Valid && approvalsJSON.String != "" {
+ if err := json.Unmarshal([]byte(approvalsJSON.String), &record.Approvals); err != nil {
+ return ActionAuditRecord{}, fmt.Errorf("unmarshal action approvals: %w", err)
+ }
+ }
+ if resultJSON.Valid && resultJSON.String != "" && resultJSON.String != "null" {
+ var result ExecutionResult
+ if err := json.Unmarshal([]byte(resultJSON.String), &result); err != nil {
+ return ActionAuditRecord{}, fmt.Errorf("unmarshal action result: %w", err)
+ }
+ record.Result = &result
+ }
+ record.Request.RequestID = requestID
+ record.Request.ResourceID = CanonicalResourceID(record.Request.ResourceID)
+ _ = actionID
+ return record, nil
+}
+
+func (s *SQLiteResourceStore) GetActionAudit(actionID string) (ActionAuditRecord, bool, error) {
+ return s.getActionAudit(actionID)
+}
+
func (s *SQLiteResourceStore) GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error) {
query := `
SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json
@@ -978,40 +1034,10 @@ func (s *SQLiteResourceStore) GetActionAudits(canonicalID string, since time.Tim
var records []ActionAuditRecord
for rows.Next() {
- var record ActionAuditRecord
- var stateStr string
- var actionID, requestID string
- var requestJSON, planJSON, approvalsJSON, resultJSON sql.NullString
- if err := rows.Scan(&record.ID, &actionID, &requestID, &record.CreatedAt, &record.UpdatedAt, &stateStr, &requestJSON, &planJSON, &approvalsJSON, &resultJSON); err != nil {
+ record, err := scanActionAuditRecord(rows)
+ if err != nil {
return nil, fmt.Errorf("scan action audit row: %w", err)
}
-
- record.State = ActionState(stateStr)
- if requestJSON.Valid && requestJSON.String != "" {
- if err := json.Unmarshal([]byte(requestJSON.String), &record.Request); err != nil {
- return nil, fmt.Errorf("unmarshal action request: %w", err)
- }
- }
- if planJSON.Valid && planJSON.String != "" {
- if err := json.Unmarshal([]byte(planJSON.String), &record.Plan); err != nil {
- return nil, fmt.Errorf("unmarshal action plan: %w", err)
- }
- }
- if approvalsJSON.Valid && approvalsJSON.String != "" {
- if err := json.Unmarshal([]byte(approvalsJSON.String), &record.Approvals); err != nil {
- return nil, fmt.Errorf("unmarshal action approvals: %w", err)
- }
- }
- if resultJSON.Valid && resultJSON.String != "" && resultJSON.String != "null" {
- var result ExecutionResult
- if err := json.Unmarshal([]byte(resultJSON.String), &result); err != nil {
- return nil, fmt.Errorf("unmarshal action result: %w", err)
- }
- record.Result = &result
- }
- record.Request.RequestID = requestID
- record.Request.ResourceID = CanonicalResourceID(record.Request.ResourceID)
- _ = actionID
records = append(records, record)
}
if err := rows.Err(); err != nil {
@@ -1020,26 +1046,100 @@ func (s *SQLiteResourceStore) GetActionAudits(canonicalID string, since time.Tim
return records, nil
}
-func (s *SQLiteResourceStore) RecordActionLifecycleEvent(event ActionLifecycleEvent) error {
- normalized, err := NormalizeActionLifecycleEvent(event)
+func recordActionLifecycleEventSQL(exec sqlExecutor, event ActionLifecycleEvent) error {
+ _, err := exec.Exec(`
+ INSERT INTO action_lifecycle_events (action_id, timestamp, state, actor, message)
+ VALUES (?, ?, ?, ?, ?)
+ `, event.ActionID, event.Timestamp, string(event.State), event.Actor, event.Message)
+ if err != nil {
+ return fmt.Errorf("insert action lifecycle event: %w", err)
+ }
+ return nil
+}
+
+func (s *SQLiteResourceStore) RecordActionDecision(record ActionAuditRecord, event ActionLifecycleEvent) error {
+ normalizedRecord, err := NormalizeActionAuditRecord(record)
if err != nil {
return err
}
- event = normalized
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return err
+ }
+ if normalizedEvent.ActionID != normalizedRecord.ID {
+ return fmt.Errorf("action decision event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
+ }
s.mu.Lock()
defer s.mu.Unlock()
- _, err = s.db.Exec(`
- INSERT INTO action_lifecycle_events (action_id, timestamp, state, actor, message)
- VALUES (?, ?, ?, ?, ?)
- `, event.ActionID, event.Timestamp, string(event.State), event.Actor, event.Message)
+ current, ok, err := s.getActionAudit(normalizedRecord.ID)
if err != nil {
- return fmt.Errorf("insert action lifecycle event: %w", err)
+ return err
+ }
+ if !ok {
+ return fmt.Errorf("action audit %q not found", normalizedRecord.ID)
+ }
+ if current.State != ActionStatePending {
+ return ErrActionNotPending
+ }
+
+ tx, err := s.db.Begin()
+ if err != nil {
+ return fmt.Errorf("begin action decision 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 decision transaction: %w", err)
+ }
+ committed = true
return nil
}
+func (s *SQLiteResourceStore) getActionAudit(actionID string) (ActionAuditRecord, bool, error) {
+ actionID = strings.TrimSpace(actionID)
+ if actionID == "" {
+ return ActionAuditRecord{}, false, nil
+ }
+ row := s.db.QueryRow(`
+ SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json
+ FROM action_audits
+ WHERE id = ?
+ `, actionID)
+ record, err := scanActionAuditRecord(row)
+ if errors.Is(err, sql.ErrNoRows) {
+ return ActionAuditRecord{}, false, nil
+ }
+ if err != nil {
+ return ActionAuditRecord{}, false, fmt.Errorf("query action audit: %w", err)
+ }
+ return record, true, nil
+}
+
+func (s *SQLiteResourceStore) RecordActionLifecycleEvent(event ActionLifecycleEvent) error {
+ normalized, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return err
+ }
+ event = normalized
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ return recordActionLifecycleEventSQL(s.db, event)
+}
+
func (s *SQLiteResourceStore) GetActionLifecycleEvents(actionID string, since time.Time, limit int) ([]ActionLifecycleEvent, error) {
query := `
SELECT action_id, timestamp, state, actor, message
@@ -1433,6 +1533,54 @@ func (m *MemoryStore) RecordActionAudit(record ActionAuditRecord) error {
return nil
}
+func (m *MemoryStore) GetActionAudit(actionID string) (ActionAuditRecord, bool, error) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ actionID = strings.TrimSpace(actionID)
+ if actionID == "" {
+ return ActionAuditRecord{}, false, nil
+ }
+ for i := len(m.actionAudits) - 1; i >= 0; i-- {
+ if m.actionAudits[i].ID == actionID {
+ return m.actionAudits[i], true, nil
+ }
+ }
+ return ActionAuditRecord{}, false, nil
+}
+
+func (m *MemoryStore) RecordActionDecision(record ActionAuditRecord, event ActionLifecycleEvent) error {
+ normalizedRecord, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return err
+ }
+ if normalizedEvent.ActionID != normalizedRecord.ID {
+ return fmt.Errorf("action decision 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 != ActionStatePending {
+ return ErrActionNotPending
+ }
+ 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 828e711c68..17cb5f968d 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -2,6 +2,7 @@ package unifiedresources
import (
"database/sql"
+ "errors"
"fmt"
"os"
"path/filepath"
@@ -1318,6 +1319,117 @@ func TestMemoryStore_RecordActionAudit_UpsertsByID(t *testing.T) {
}
}
+func TestActionAudit_GetActionAuditByID(t *testing.T) {
+ store := newTestStore(t)
+ now := time.Date(2026, 5, 4, 13, 0, 0, 0, time.UTC)
+ record := ActionAuditRecord{
+ ID: "act_lookup",
+ CreatedAt: now,
+ UpdatedAt: now,
+ State: ActionStatePending,
+ Request: ActionRequest{
+ RequestID: "req-lookup",
+ ResourceID: "vm:302",
+ CapabilityName: "restart",
+ Reason: "lookup proof",
+ RequestedBy: "agent:test",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_lookup",
+ RequestID: "req-lookup",
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+
+ got, ok, err := store.GetActionAudit("act_lookup")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || got.ID != "act_lookup" || got.Request.ResourceID != "vm:302" {
+ t.Fatalf("GetActionAudit = %#v, %v", got, ok)
+ }
+ _, ok, err = store.GetActionAudit("missing")
+ if err != nil {
+ t.Fatalf("GetActionAudit missing: %v", err)
+ }
+ if ok {
+ t.Fatal("missing action unexpectedly found")
+ }
+}
+
+func TestRecordActionDecision_UpdatesAuditAndAppendsLifecycle(t *testing.T) {
+ store := newTestStore(t)
+ now := time.Date(2026, 5, 4, 13, 30, 0, 0, time.UTC)
+ record := ActionAuditRecord{
+ ID: "act_decision",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-time.Minute),
+ State: ActionStatePending,
+ Request: ActionRequest{
+ RequestID: "req-decision",
+ ResourceID: "vm:303",
+ CapabilityName: "restart",
+ Reason: "decision proof",
+ RequestedBy: "agent:test",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_decision",
+ RequestID: "req-decision",
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+ updated, event, err := ApplyActionDecision(record, ActionApprovalRecord{
+ Actor: "[email protected]",
+ Outcome: OutcomeApproved,
+ Reason: "approved for proof",
+ }, now)
+ if err != nil {
+ t.Fatalf("ApplyActionDecision: %v", err)
+ }
+ if err := store.RecordActionDecision(updated, event); err != nil {
+ t.Fatalf("RecordActionDecision: %v", err)
+ }
+
+ got, ok, err := store.GetActionAudit("act_decision")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || got.State != ActionStateApproved || len(got.Approvals) != 1 {
+ t.Fatalf("decision audit = %#v, %v", got, ok)
+ }
+ events, err := store.GetActionLifecycleEvents("act_decision", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ if len(events) != 1 || events[0].State != ActionStateApproved || events[0].Actor != "[email protected]" {
+ t.Fatalf("decision events = %#v", events)
+ }
+
+ staleUpdate, staleEvent, err := ApplyActionDecision(record, ActionApprovalRecord{
+ Actor: "[email protected]",
+ Outcome: OutcomeRejected,
+ Reason: "late rejection",
+ }, now.Add(time.Second))
+ if err != nil {
+ t.Fatalf("ApplyActionDecision stale: %v", err)
+ }
+ if err := store.RecordActionDecision(staleUpdate, staleEvent); !errors.Is(err, ErrActionNotPending) {
+ t.Fatalf("stale RecordActionDecision error = %v, want %v", err, ErrActionNotPending)
+ }
+}
+
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 29afd32e0f..552ed92491 100644
--- a/pkg/pulsecli/actions.go
+++ b/pkg/pulsecli/actions.go
@@ -41,6 +41,14 @@ type actionCapabilitiesOptions struct {
ResourceID string
}
+type actionDecisionOptions struct {
+ APIURL string
+ Token string
+ ActionID string
+ Outcome string
+ Reason string
+}
+
type actionAuditOptions struct {
APIURL string
Token string
@@ -80,6 +88,13 @@ type actionLifecycleEventsResponse struct {
Count int `json:"count"`
}
+type actionDecisionResponse struct {
+ ActionID string `json:"actionId"`
+ State unified.ActionState `json:"state"`
+ Approval unified.ActionApprovalRecord `json:"approval"`
+ Audit unified.ActionAuditRecord `json:"audit"`
+}
+
func newActionsCmd(deps *ActionsDeps) *cobra.Command {
actionsCmd := &cobra.Command{
Use: "actions",
@@ -115,6 +130,7 @@ func newActionsCmd(deps *ActionsDeps) *cobra.Command {
actionsCmd.AddCommand(planCmd)
actionsCmd.AddCommand(newActionCapabilitiesCmd(deps))
+ actionsCmd.AddCommand(newActionDecisionCmd(deps))
actionsCmd.AddCommand(newActionAuditCmd(deps))
actionsCmd.AddCommand(newActionEventsCmd(deps))
return actionsCmd
@@ -142,6 +158,30 @@ func newActionCapabilitiesCmd(deps *ActionsDeps) *cobra.Command {
return cmd
}
+func newActionDecisionCmd(deps *ActionsDeps) *cobra.Command {
+ opts := actionDecisionOptions{
+ 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: "decide",
+ Short: "Approve or reject a governed action plan without execution",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runActionDecision(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.Outcome, "outcome", "", "decision outcome: approved or rejected")
+ cmd.Flags().StringVar(&opts.Reason, "reason", "", "audit reason for the decision")
+ return cmd
+}
+
func newActionAuditCmd(deps *ActionsDeps) *cobra.Command {
opts := actionAuditOptions{
APIURL: strings.TrimSpace(actionGetenv(deps, "PULSE_API_URL")),
@@ -248,6 +288,72 @@ func runActionPlan(cmd *cobra.Command, deps *ActionsDeps, opts actionPlanOptions
return nil
}
+func runActionDecision(cmd *cobra.Command, deps *ActionsDeps, opts actionDecisionOptions) 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)")
+ }
+ outcome := unified.ApprovalOutcome(strings.TrimSpace(opts.Outcome))
+ if outcome != unified.OutcomeApproved && outcome != unified.OutcomeRejected {
+ return fmt.Errorf("outcome must be approved or rejected (use --outcome)")
+ }
+
+ endpoint, err := pulseAPIEndpoint(opts.APIURL, "/actions/"+url.PathEscape(actionID)+"/decision")
+ if err != nil {
+ return err
+ }
+
+ body, err := json.Marshal(struct {
+ Outcome unified.ApprovalOutcome `json:"outcome"`
+ Reason string `json:"reason,omitempty"`
+ }{
+ Outcome: outcome,
+ Reason: strings.TrimSpace(opts.Reason),
+ })
+ if err != nil {
+ return fmt.Errorf("failed to encode action decision: %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 decision 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 decision request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ respBody, err := ReadBoundedHTTPBody(resp.Body, resp.ContentLength, maxPulseAPIResponseBytes, "action decision response")
+ if err != nil {
+ return fmt.Errorf("failed to read action decision response: %w", err)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return apiStatusError("action decision request", resp.Status, respBody)
+ }
+
+ var decision actionDecisionResponse
+ if err := decodeJSONBytes(respBody, &decision); err != nil {
+ return fmt.Errorf("failed to decode action decision response: %w", err)
+ }
+
+ encoder := json.NewEncoder(cmd.OutOrStdout())
+ encoder.SetIndent("", " ")
+ if err := encoder.Encode(decision); err != nil {
+ return fmt.Errorf("failed to write action decision 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 ed0353b66a..6c2e7b53f0 100644
--- a/pkg/pulsecli/actions_test.go
+++ b/pkg/pulsecli/actions_test.go
@@ -122,6 +122,132 @@ func TestActionsPlanCommandRequiresToken(t *testing.T) {
}
}
+func TestActionsDecideCommandPostsApprovalDecision(t *testing.T) {
+ now := time.Date(2026, 5, 4, 14, 30, 0, 0, time.UTC)
+ var receivedAuth string
+ var received struct {
+ Outcome unified.ApprovalOutcome `json:"outcome"`
+ 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/decision" {
+ t.Fatalf("path = %s, want /api/actions/act_test/decision", 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(actionDecisionResponse{
+ ActionID: "act_test",
+ State: unified.ActionStateApproved,
+ Approval: unified.ActionApprovalRecord{
+ Actor: "[email protected]",
+ Method: unified.MethodAPI,
+ Timestamp: now,
+ Outcome: unified.OutcomeApproved,
+ Reason: received.Reason,
+ },
+ Audit: unified.ActionAuditRecord{
+ ID: "act_test",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now,
+ State: unified.ActionStateApproved,
+ 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",
+ },
+ },
+ })
+ }))
+ defer server.Close()
+
+ cmd := newTestActionsRootCommand(map[string]string{
+ "PULSE_API_TOKEN": "test-token",
+ "PULSE_API_URL": server.URL + "/api",
+ })
+ cmd.SetArgs([]string{
+ "actions", "decide",
+ "--action-id", "act_test",
+ "--outcome", "approved",
+ "--reason", "inside maintenance window",
+ })
+ var out bytes.Buffer
+ cmd.SetOut(&out)
+
+ if err := cmd.Execute(); err != nil {
+ t.Fatalf("execute actions decide: %v", err)
+ }
+ if receivedAuth != "Bearer test-token" {
+ t.Fatalf("Authorization = %q", receivedAuth)
+ }
+ if received.Outcome != unified.OutcomeApproved || received.Reason != "inside maintenance window" {
+ t.Fatalf("received decision = %#v", received)
+ }
+
+ var decision actionDecisionResponse
+ if err := json.Unmarshal(out.Bytes(), &decision); err != nil {
+ t.Fatalf("decode command output: %v\n%s", err, out.String())
+ }
+ if decision.ActionID != "act_test" || decision.State != unified.ActionStateApproved || decision.Approval.Outcome != unified.OutcomeApproved {
+ t.Fatalf("decision output = %+v", decision)
+ }
+}
+
+func TestActionsDecideCommandRequiresToken(t *testing.T) {
+ cmd := newTestActionsRootCommand(nil)
+ cmd.SetArgs([]string{
+ "actions", "decide",
+ "--api-url", "http://127.0.0.1:7655",
+ "--action-id", "act_test",
+ "--outcome", "approved",
+ })
+
+ err := cmd.Execute()
+ if err == nil || !strings.Contains(err.Error(), "api token is required") {
+ t.Fatalf("expected token error, got %v", err)
+ }
+}
+
+func TestActionsDecideCommandValidatesDecisionFields(t *testing.T) {
+ cmd := newTestActionsRootCommand(map[string]string{
+ "PULSE_API_TOKEN": "test-token",
+ "PULSE_API_URL": "http://127.0.0.1:7655",
+ })
+ cmd.SetArgs([]string{"actions", "decide", "--outcome", "approved"})
+ if err := cmd.Execute(); err == nil || !strings.Contains(err.Error(), "actionId is required") {
+ t.Fatalf("expected action id 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", "decide", "--action-id", "act_test", "--outcome", "maybe"})
+ if err := cmd.Execute(); err == nil || !strings.Contains(err.Error(), "outcome must be approved or rejected") {
+ t.Fatalf("expected outcome error, got %v", err)
+ }
+}
+
func TestActionsCapabilitiesCommandFetchesResourceFacets(t *testing.T) {
var receivedAuth string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {