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.

Persist action plans in audit trail

rcourtman9291ee299940
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 392e7282ba..995b251863 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -126,7 +126,11 @@ Agent lifecycle and fleet-operation surfaces may consume
contract remains API-owned through `internal/api/actions.go` and
`internal/actionplanner/planner.go`. Agent lifecycle work must not define a
parallel approval policy, blast-radius model, stale-plan hash, or execution
-contract for those resource actions.
+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.
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 6fb6e6fc1b..9280673ef7 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -293,8 +293,13 @@ the canonical monitored-system blocked payload.
`internal/api/contract_test.go` together, returning deterministic
`ActionPlan` identity, approval policy, blast radius, resource/policy
versions, plan hash, and preflight checks without approving or executing the
- capability. MCP, CLI, and UI consumers may adapt this payload, but they must
- not become the source of truth for action planning semantics.
+ capability. A successful plan must also be durably recorded in the unified
+ action-audit store with initial lifecycle evidence before the API returns:
+ approval-required plans land as `pending_approval`, retries with the same
+ deterministic action identity may upsert the audit record, and retries must
+ 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`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index fbd4c8dfe0..20b6cffe78 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -85,6 +85,10 @@ Storage/recovery remediation or restore-adjacent workflows may consume
contract. This subsystem must not create a storage-local approval policy,
stale-plan hash, blast-radius model, or execution protocol outside
`internal/api/actions.go` and `internal/actionplanner/planner.go`.
+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.
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/internal/api/actions.go b/internal/api/actions.go
index 4903c54ef5..d3e6bc9b55 100644
--- a/internal/api/actions.go
+++ b/internal/api/actions.go
@@ -5,6 +5,8 @@ import (
"errors"
"io"
"net/http"
+ "strings"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/actionplanner"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
@@ -78,8 +80,86 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Reque
return
}
+ req = normalizeActionRequestForAudit(req)
+ store, err := h.getStore(orgID)
+ if err != nil {
+ writeErrorResponse(w, http.StatusServiceUnavailable, "action_audit_unavailable", "Action audit history is not available", nil)
+ return
+ }
+ if err := persistActionPlanAudit(store, req, plan); err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "action_audit_persist_failed", sanitizeErrorForClient(err, "Failed to persist action audit"), nil)
+ return
+ }
+
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(plan); err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "action_plan_encode_failed", "Failed to encode action plan", nil)
}
}
+
+func normalizeActionRequestForAudit(req unified.ActionRequest) unified.ActionRequest {
+ req.RequestID = strings.TrimSpace(req.RequestID)
+ req.ResourceID = unified.CanonicalResourceID(req.ResourceID)
+ req.CapabilityName = strings.TrimSpace(req.CapabilityName)
+ req.Reason = strings.TrimSpace(req.Reason)
+ req.RequestedBy = strings.TrimSpace(req.RequestedBy)
+ if req.Params == nil {
+ req.Params = map[string]any{}
+ }
+ return req
+}
+
+func persistActionPlanAudit(store unified.ResourceStore, req unified.ActionRequest, plan unified.ActionPlan) error {
+ state := plannedActionState(plan)
+ record := unified.ActionAuditRecord{
+ ID: plan.ActionID,
+ CreatedAt: plan.PlannedAt,
+ UpdatedAt: plan.PlannedAt,
+ State: state,
+ Request: req,
+ Plan: plan,
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ return err
+ }
+
+ existingEvents, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 100)
+ if err != nil {
+ return err
+ }
+ seenStates := map[unified.ActionState]bool{}
+ for _, event := range existingEvents {
+ seenStates[event.State] = true
+ }
+
+ if !seenStates[unified.ActionStatePlanned] {
+ if err := store.RecordActionLifecycleEvent(unified.ActionLifecycleEvent{
+ ActionID: plan.ActionID,
+ Timestamp: plan.PlannedAt,
+ State: unified.ActionStatePlanned,
+ Actor: req.RequestedBy,
+ Message: "Action plan created.",
+ }); err != nil {
+ return err
+ }
+ }
+ if state != unified.ActionStatePlanned && !seenStates[state] {
+ if err := store.RecordActionLifecycleEvent(unified.ActionLifecycleEvent{
+ ActionID: plan.ActionID,
+ Timestamp: plan.PlannedAt,
+ State: state,
+ Actor: req.RequestedBy,
+ Message: "Action is waiting for approval before execution.",
+ }); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func plannedActionState(plan unified.ActionPlan) unified.ActionState {
+ if plan.RequiresApproval {
+ return unified.ActionStatePending
+ }
+ return unified.ActionStatePlanned
+}
diff --git a/internal/api/actions_test.go b/internal/api/actions_test.go
index cd46e0457b..f0a24384df 100644
--- a/internal/api/actions_test.go
+++ b/internal/api/actions_test.go
@@ -95,6 +95,168 @@ func TestHandlePlanActionReturnsCanonicalPlan(t *testing.T) {
}
}
+func TestHandlePlanActionPersistsAuditAndLifecycle(t *testing.T) {
+ now := time.Date(2026, 5, 3, 10, 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"}},
+ },
+ },
+ },
+ },
+ },
+ })
+ body := func() *bytes.Buffer {
+ return bytes.NewBufferString(`{
+ "requestId":"agent-run-123",
+ "resourceId":"vm:42",
+ "capabilityName":"restart",
+ "params":{"mode":"graceful"},
+ "reason":"Recover after confirmed outage",
+ "requestedBy":"agent:oncall-helper"
+ }`)
+ }
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/actions/plan", body())
+ h.HandlePlanAction(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
+ }
+ var plan unified.ActionPlan
+ if err := json.Unmarshal(rec.Body.Bytes(), &plan); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("get store: %v", err)
+ }
+ audits, err := store.GetActionAudits("vm:42", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ if len(audits) != 1 {
+ t.Fatalf("audits len = %d, want 1: %#v", len(audits), audits)
+ }
+ audit := audits[0]
+ if audit.ID != plan.ActionID || audit.State != unified.ActionStatePending {
+ t.Fatalf("audit identity/state = %q/%q, want %q/%q", audit.ID, audit.State, plan.ActionID, unified.ActionStatePending)
+ }
+ if audit.Request.RequestID != "agent-run-123" || audit.Request.RequestedBy != "agent:oncall-helper" {
+ t.Fatalf("audit request was not preserved: %#v", audit.Request)
+ }
+ if audit.Plan.PlanHash != plan.PlanHash || audit.Plan.Preflight == nil {
+ t.Fatalf("audit plan did not preserve plan/preflight: %#v", audit.Plan)
+ }
+
+ events, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seenStates := map[unified.ActionState]bool{}
+ for _, event := range events {
+ seenStates[event.State] = true
+ if event.Actor != "agent:oncall-helper" {
+ t.Fatalf("event actor = %q, want requester", event.Actor)
+ }
+ }
+ if len(events) != 2 || !seenStates[unified.ActionStatePlanned] || !seenStates[unified.ActionStatePending] {
+ t.Fatalf("events = %#v, want planned and pending_approval", events)
+ }
+
+ retryRec := httptest.NewRecorder()
+ retryReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", body())
+ h.HandlePlanAction(retryRec, retryReq)
+ if retryRec.Code != http.StatusOK {
+ t.Fatalf("retry status = %d, body=%s", retryRec.Code, retryRec.Body.String())
+ }
+ events, err = store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents after retry: %v", err)
+ }
+ if len(events) != 2 {
+ t.Fatalf("retry duplicated lifecycle events: %#v", events)
+ }
+}
+
+func TestPersistActionPlanAuditFillsMissingLifecycleState(t *testing.T) {
+ now := time.Date(2026, 5, 3, 10, 0, 0, 0, time.UTC)
+ store := unified.NewMemoryStore()
+ req := unified.ActionRequest{
+ RequestID: "agent-run-123",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "Recover after confirmed outage",
+ RequestedBy: "agent:oncall-helper",
+ }
+ plan := unified.ActionPlan{
+ ActionID: "act_partial",
+ RequestID: "agent-run-123",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unified.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ }
+ if err := store.RecordActionLifecycleEvent(unified.ActionLifecycleEvent{
+ ActionID: plan.ActionID,
+ Timestamp: now,
+ State: unified.ActionStatePlanned,
+ Actor: req.RequestedBy,
+ Message: "Action plan created.",
+ }); err != nil {
+ t.Fatalf("seed lifecycle event: %v", err)
+ }
+
+ if err := persistActionPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("persistActionPlanAudit: %v", err)
+ }
+ events, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seenStates := map[unified.ActionState]bool{}
+ for _, event := range events {
+ seenStates[event.State] = true
+ }
+ if len(events) != 2 || !seenStates[unified.ActionStatePlanned] || !seenStates[unified.ActionStatePending] {
+ t.Fatalf("events = %#v, want one planned and one pending event", events)
+ }
+
+ if err := persistActionPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("persistActionPlanAudit retry: %v", err)
+ }
+ events, err = store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents retry: %v", err)
+ }
+ if len(events) != 2 {
+ t.Fatalf("retry duplicated lifecycle events: %#v", events)
+ }
+}
+
func TestHandlePlanActionRejectsMissingCapability(t *testing.T) {
now := time.Date(2026, 5, 3, 10, 0, 0, 0, time.UTC)
h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index f900bc92f9..dd1cd83538 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -11407,6 +11407,127 @@ func TestContract_ActionPlanJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_ActionPlanAuditLifecycleSnapshot(t *testing.T) {
+ now := time.Date(2026, 5, 3, 10, 0, 0, 0, time.UTC)
+ resource := unifiedresources.Resource{
+ ID: "vm:42",
+ Type: unifiedresources.ResourceTypeVM,
+ Name: "web-42",
+ Status: unifiedresources.StatusWarning,
+ LastSeen: now,
+ UpdatedAt: now,
+ Sources: []unifiedresources.DataSource{unifiedresources.SourceProxmox},
+ Capabilities: []unifiedresources.ResourceCapability{
+ {
+ Name: "restart",
+ Type: unifiedresources.CapabilityTypeCommon,
+ Description: "Restart the VM",
+ MinimumApprovalLevel: unifiedresources.ApprovalAdmin,
+ InternalHandler: "proxmox.vm.restart",
+ Params: []unifiedresources.CapabilityParam{
+ {Name: "mode", Type: "string", Required: true, Enum: []string{"graceful", "force"}},
+ },
+ },
+ },
+ }
+ req := unifiedresources.ActionRequest{
+ RequestID: "agent-run-123",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Params: map[string]any{"mode": "graceful"},
+ Reason: "Recover after confirmed outage",
+ RequestedBy: "agent:oncall-helper",
+ }
+ plan, err := (actionplanner.Planner{Now: func() time.Time { return now }}).Plan(req, resource)
+ if err != nil {
+ t.Fatalf("plan action: %v", err)
+ }
+
+ store := unifiedresources.NewMemoryStore()
+ if err := persistActionPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("persist action plan audit: %v", err)
+ }
+ audits, err := store.GetActionAudits("vm:42", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ events, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ payload := struct {
+ Audit struct {
+ ID string `json:"id"`
+ State unifiedresources.ActionState `json:"state"`
+ ResourceID string `json:"resourceId"`
+ RequestID string `json:"requestId"`
+ RequestedBy string `json:"requestedBy"`
+ ApprovalPolicy unifiedresources.ActionApprovalLevel `json:"approvalPolicy"`
+ PlanHash string `json:"planHash"`
+ PreflightSummary string `json:"preflightSummary"`
+ } `json:"audit"`
+ Events []struct {
+ State unifiedresources.ActionState `json:"state"`
+ Actor string `json:"actor"`
+ Message string `json:"message"`
+ } `json:"events"`
+ }{}
+ if len(audits) != 1 {
+ t.Fatalf("audits len = %d, want 1", len(audits))
+ }
+ payload.Audit.ID = audits[0].ID
+ payload.Audit.State = audits[0].State
+ payload.Audit.ResourceID = audits[0].Request.ResourceID
+ payload.Audit.RequestID = audits[0].Request.RequestID
+ payload.Audit.RequestedBy = audits[0].Request.RequestedBy
+ payload.Audit.ApprovalPolicy = audits[0].Plan.ApprovalPolicy
+ payload.Audit.PlanHash = audits[0].Plan.PlanHash
+ if audits[0].Plan.Preflight != nil {
+ payload.Audit.PreflightSummary = audits[0].Plan.Preflight.DryRunSummary
+ }
+ for _, event := range events {
+ payload.Events = append(payload.Events, struct {
+ State unifiedresources.ActionState `json:"state"`
+ Actor string `json:"actor"`
+ Message string `json:"message"`
+ }{
+ State: event.State,
+ Actor: event.Actor,
+ Message: event.Message,
+ })
+ }
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal persisted action audit contract: %v", err)
+ }
+ const want = `{
+ "audit":{
+ "id":"act_f464b1a69ce73d27a986b445104ad708",
+ "state":"pending_approval",
+ "resourceId":"vm:42",
+ "requestId":"agent-run-123",
+ "requestedBy":"agent:oncall-helper",
+ "approvalPolicy":"admin",
+ "planHash":"sha256:e2998e7fe1b9b97c8180102bd474ece7411146db70bbb6299cdc47582de7bd1d",
+ "preflightSummary":"No provider-supported dry run is advertised for this capability."
+ },
+ "events":[
+ {
+ "state":"pending_approval",
+ "actor":"agent:oncall-helper",
+ "message":"Action is waiting for approval before execution."
+ },
+ {
+ "state":"planned",
+ "actor":"agent:oncall-helper",
+ "message":"Action plan created."
+ }
+ ]
+ }`
+ 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()})