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.

Fail closed on stale API action plans

rcourtman8b0f3564f6d2
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 84b18dcbaa..5b0d766d8a 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -950,7 +950,10 @@ The broadcaster drops real published events for slow subscribers
rather than blocking publishers, so the patrol-finding runtime, the
approval store's post-create callback, and the executor's
post-completion callback can publish without ever stalling on
-consumer slowness. Heartbeats are stream-local keepalives written
+consumer slowness. API-owned action execution uses the same shared
+terminal publisher, including stale-plan `action_plan_drift`
+refusals that fail the audit with a `plan_drift:` result before any
+executor is called. Heartbeats are stream-local keepalives written
to each connected response; one subscriber's heartbeat ticker must
not publish heartbeat events to every other subscriber.
The agent runtime keeps the broadcaster wired across restarts, and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index ec80441dda..7b3c954f58 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -465,6 +465,14 @@ the canonical monitored-system blocked payload.
action or an approval-free executable plan, must atomically persist the
`executing` lifecycle state before invoking a registered executor, and must
atomically persist the terminal `completed` or `failed` result afterward.
+ Before the endpoint enters `executing`, it must rebuild the current
+ resource/capability plan from the unified registry and compare the stored
+ action id, resource version, policy version, and plan hash. A mismatch is a
+ refused-before-dispatch `action_plan_drift` failure: the executor is not
+ called, the action audit is moved to `failed` with a `plan_drift:` result,
+ lifecycle evidence is appended, and the shared `action.completed` SSE bridge
+ publishes the terminal failure so agents do not poll a stale plan into
+ execution.
Dry-run-only plans are not executable plans and must fail closed before any
`executing` mutation. If no API executor is registered, the endpoint must
fail closed without mutating the approved audit record or appending execution
@@ -1396,7 +1404,8 @@ multiply heartbeat fan-out for one another. The broadcaster drops
real published events for slow subscribers rather than blocking the
publish path — publishers (the patrol findings runtime, the
approval store's post-create callback, the executor's
-post-completion callback) cannot stall on consumer slowness. The
+post-completion callback, and the API action-execution terminal
+publisher) cannot stall on consumer slowness. The
stream sits behind `monitoring:read` and runs through the same auth
path as the rest of the agent surface; the capabilities manifest declares the stream
under `subscribe_events` so external agents discover it without
@@ -1432,7 +1441,10 @@ persisted. The callback is installed once per chat-service per
org through `wireAIChatDependenciesForService` against
`chatService.GetExecutor()`, so multi-tenant chat-service rebuilds
re-wire the bridge without coupling the tools package to the api
-package. `action.completed` payloads preserve the canonical
+package. API-owned execution installs `ResourceHandlers` on the
+same `PublishActionCompletedRecord` projector so direct
+`/api/actions/{id}/execute` completions and stale-plan refusals
+emit the identical payload shape. `action.completed` payloads preserve the canonical
refusal-token prefixes (`plan_drift:`, `resource_remediation_locked:`)
on `errorMessage` verbatim so agents branch on the stable code
without parsing human messages.
@@ -1686,7 +1698,7 @@ carries `missing_id`, `invalid_id`, `invalid_action_decision`,
`invalid_action_execution`, `action_not_found`,
`action_not_approved`, `action_already_executing`,
`action_execution_final`, `action_dry_run_only`,
-`action_executor_unavailable`. 5xx internal-failure codes
+`action_plan_drift`, `action_executor_unavailable`. 5xx internal-failure codes
(audit-store outages, encode failures) are not declared per
capability; agents branch on 5xx generically.
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 6a0edf946a..4fa3849258 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -189,6 +189,11 @@ regression protection.
before returning it to AI runtime, but it must not scan run history broadly,
hydrate resource inventories, call models, or perform persistence fan-out as
part of router setup or generic request admission.
+ API action-completion event bridging in `internal/api/router.go` follows
+ the same bounded-work rule: router wiring may connect the already-completed
+ action audit record to the agent SSE projection, but it must not perform
+ executor dispatch, resource rescans, model calls, or persistence fan-out on
+ the protected request setup path.
Retiring self-hosted trial acquisition follows that same rule: removing
`/auth/trial-activate` and `POST /api/license/trial/start` from public-path
and CSRF inventories must stay as constant-time route-table absence rather
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 3a2fc20b53..84cb6676c6 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -118,7 +118,11 @@ 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. Dry-run-only plans remain planning
+creating storage-local action transport. The API execution gate also owns
+stale-plan protection: if the current resource or capability no longer hashes
+to the stored plan, execution must fail as `action_plan_drift` with a failed
+audit row and `plan_drift:` result before any provider restore/remediation
+driver runs. Dry-run-only plans remain planning
evidence only; storage and recovery surfaces must not present them as
executable, dispatch them through provider-local restore/remediation paths, or
bypass the API fail-closed execution gate.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 3498b183ca..5e89bd2339 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -146,6 +146,12 @@ cross-source deduplication.
`availability:<target-id>`, keep the probe address as hostname/platform
identity when no stronger identity exists, and preserve availability payloads
through clone, merge, API transport, and frontend decode paths.
+ Governed action execution freshness is part of the same resource-extension
+ contract: API execution consumers must re-plan against current resource
+ capabilities and policy before executor dispatch, treat action id,
+ `resourceVersion`, `policyVersion`, or `planHash` drift as
+ `action_plan_drift`, and record/publish a failed audit instead of leaving
+ executor adapters to make stale-approval decisions.
2. Add typed accessors and views in `internal/unifiedresources/views.go`
3. Add source ingestion/adaptation in the adapter layer only
Infrastructure table platform presentation extends through
@@ -2273,7 +2279,10 @@ supplemental snapshots do not duplicate resource history.
Action plans in `actions.go` still keep stale-plan protection to the canonical
`resourceVersion`, `policyVersion`, and `planHash` fields, so stale execution
checks stay in the shared resource action model rather than provider-local
-helpers.
+helpers. The API execution endpoint must consume that model before dispatch:
+it rebuilds the current resource/capability plan, rejects mismatched action id,
+resource version, policy version, or plan hash as `action_plan_drift`, and
+records the refusal as a failed action audit with a `plan_drift:` result.
`actions.go` also owns the canonical drift error vocabulary for the
governed-action broker. `ErrActionPlanDrift` is returned by brokers when
diff --git a/internal/api/actions.go b/internal/api/actions.go
index df8200f0bb..45877e9980 100644
--- a/internal/api/actions.go
+++ b/internal/api/actions.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"io"
"net/http"
"strings"
@@ -345,7 +346,32 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Re
}
actor := actionDecisionActor(h, r)
- started, startEvent, err := unified.BeginActionExecution(record, actor, time.Now().UTC())
+ if h.actionExecutor == nil {
+ writeJSONError(w, http.StatusNotImplemented, "action_executor_unavailable", "No action executor is configured for this API instance")
+ return
+ }
+
+ now := time.Now().UTC()
+ if err := unified.ValidateActionExecutionStart(record, now); err != nil {
+ writeActionExecutionApplyError(w, err)
+ return
+ }
+ if err := h.validateActionPlanFresh(orgID, record); err != nil {
+ if errors.Is(err, unified.ErrActionPlanDrift) {
+ if failed, persistErr := recordRefusedActionExecution(store, record, actor, now, err); persistErr == nil {
+ h.publishActionCompleted(failed)
+ } else {
+ writeJSONError(w, http.StatusInternalServerError, "action_execution_persist_failed", sanitizeErrorForClient(persistErr, "Failed to persist refused action execution"))
+ return
+ }
+ writeActionExecutionApplyError(w, err)
+ return
+ }
+ writeJSONError(w, http.StatusInternalServerError, "action_plan_validation_failed", sanitizeErrorForClient(err, "Failed to validate action plan freshness"))
+ return
+ }
+
+ started, startEvent, err := unified.BeginActionExecution(record, actor, now)
if err != nil {
writeActionExecutionApplyError(w, err)
return
@@ -353,10 +379,6 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Re
if execution.Reason != "" {
startEvent.Message = "Action execution started: " + execution.Reason
}
- if h.actionExecutor == nil {
- writeJSONError(w, http.StatusNotImplemented, "action_executor_unavailable", "No action executor is configured for this API instance")
- return
- }
if err := store.RecordActionExecutionStart(started, startEvent); err != nil {
writeActionExecutionPersistError(w, err)
return
@@ -375,6 +397,7 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Re
writeActionExecutionPersistError(w, err)
return
}
+ h.publishActionCompleted(completed)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(actionExecutionResponse{
@@ -387,6 +410,106 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Re
}
}
+func (h *ResourceHandlers) validateActionPlanFresh(orgID string, record unified.ActionAuditRecord) error {
+ if h == nil {
+ return fmt.Errorf("%w: resource handler unavailable", unified.ErrActionPlanDrift)
+ }
+ normalized, err := unified.NormalizeActionAuditRecord(record)
+ if err != nil {
+ return fmt.Errorf("%w: %v", unified.ErrActionPlanDrift, err)
+ }
+ registry, err := h.buildRegistry(orgID)
+ if err != nil {
+ return err
+ }
+ resource, ok := registry.Get(normalized.Request.ResourceID)
+ if !ok || resource == nil {
+ return fmt.Errorf("%w: resource %q is no longer present", unified.ErrActionPlanDrift, normalized.Request.ResourceID)
+ }
+ currentPlan, err := (actionplanner.Planner{Now: func() time.Time {
+ return normalized.Plan.PlannedAt
+ }}).Plan(normalized.Request, *resource)
+ if err != nil {
+ return fmt.Errorf("%w: %v", unified.ErrActionPlanDrift, err)
+ }
+ if currentPlan.ActionID != normalized.Plan.ActionID {
+ return fmt.Errorf("%w: action identity changed", unified.ErrActionPlanDrift)
+ }
+ if currentPlan.PlanHash != normalized.Plan.PlanHash {
+ return fmt.Errorf("%w: plan hash changed", unified.ErrActionPlanDrift)
+ }
+ if currentPlan.ResourceVersion != normalized.Plan.ResourceVersion {
+ return fmt.Errorf("%w: resource version changed", unified.ErrActionPlanDrift)
+ }
+ if currentPlan.PolicyVersion != normalized.Plan.PolicyVersion {
+ return fmt.Errorf("%w: capability policy changed", unified.ErrActionPlanDrift)
+ }
+ return nil
+}
+
+func recordRefusedActionExecution(store unified.ResourceStore, record unified.ActionAuditRecord, actor string, now time.Time, reason error) (unified.ActionAuditRecord, error) {
+ if now.IsZero() {
+ now = time.Now().UTC()
+ } else {
+ now = now.UTC()
+ }
+ actor = strings.TrimSpace(actor)
+ if actor == "" {
+ actor = "api:authenticated"
+ }
+ record.State = unified.ActionStateFailed
+ record.UpdatedAt = now
+ record.Result = &unified.ExecutionResult{
+ Success: false,
+ ErrorMessage: refusedActionExecutionMessage(reason),
+ }
+ normalized, err := unified.NormalizeActionAuditRecord(record)
+ if err != nil {
+ return unified.ActionAuditRecord{}, err
+ }
+ if store == nil {
+ return unified.ActionAuditRecord{}, errors.New("action audit store unavailable")
+ }
+ if err := store.RecordActionAudit(normalized); err != nil {
+ return unified.ActionAuditRecord{}, err
+ }
+ event, err := unified.NormalizeActionLifecycleEvent(unified.ActionLifecycleEvent{
+ ActionID: normalized.ID,
+ Timestamp: now,
+ State: unified.ActionStateFailed,
+ Actor: actor,
+ Message: normalized.Result.ErrorMessage,
+ })
+ if err != nil {
+ return unified.ActionAuditRecord{}, err
+ }
+ if err := store.RecordActionLifecycleEvent(event); err != nil {
+ return unified.ActionAuditRecord{}, err
+ }
+ return normalized, nil
+}
+
+func refusedActionExecutionMessage(reason error) string {
+ if errors.Is(reason, unified.ErrActionPlanDrift) {
+ return "plan_drift: action plan no longer matches the current resource contract; re-plan before executing"
+ }
+ message := strings.TrimSpace(fmt.Sprint(reason))
+ if message == "" {
+ message = "action execution refused before dispatch"
+ }
+ return message
+}
+
+func (h *ResourceHandlers) publishActionCompleted(record unified.ActionAuditRecord) {
+ if h == nil || h.actionCompleted == nil {
+ return
+ }
+ if record.State != unified.ActionStateCompleted && record.State != unified.ActionStateFailed {
+ return
+ }
+ h.actionCompleted(record)
+}
+
func actionDecisionActor(h *ResourceHandlers, r *http.Request) string {
if h != nil {
if actor := strings.TrimSpace(getAuthUsername(h.cfg, r)); actor != "" {
@@ -428,6 +551,8 @@ func writeActionExecutionApplyError(w http.ResponseWriter, err error) {
writeJSONError(w, http.StatusConflict, "action_plan_expired", "Action plan has expired")
case errors.Is(err, unified.ErrActionDryRunOnly):
writeJSONError(w, http.StatusConflict, "action_dry_run_only", "Action plan is dry-run only and cannot be executed")
+ case errors.Is(err, unified.ErrActionPlanDrift):
+ writeJSONError(w, http.StatusConflict, "action_plan_drift", "Action plan no longer matches the current resource contract; re-plan before executing")
default:
writeJSONError(w, http.StatusInternalServerError, "action_execution_failed", sanitizeErrorForClient(err, "Action execution failed"))
}
diff --git a/internal/api/actions_test.go b/internal/api/actions_test.go
index fcae081563..7914b7eecc 100644
--- a/internal/api/actions_test.go
+++ b/internal/api/actions_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
"strings"
@@ -360,6 +361,10 @@ func TestHandleExecuteActionRunsApprovedPlanThroughExecutor(t *testing.T) {
})
executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "restart dispatched"}}
h.SetActionExecutor(executor)
+ published := make(chan unified.ActionAuditRecord, 1)
+ h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
+ published <- record
+ })
planRec := httptest.NewRecorder()
planReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
@@ -427,6 +432,14 @@ func TestHandleExecuteActionRunsApprovedPlanThroughExecutor(t *testing.T) {
if !ok || audit.State != unified.ActionStateCompleted || audit.Result == nil || audit.Result.Output != "restart dispatched" {
t.Fatalf("persisted execution audit = %#v, ok=%v", audit, ok)
}
+ select {
+ case eventRecord := <-published:
+ if eventRecord.ID != plan.ActionID || eventRecord.State != unified.ActionStateCompleted {
+ t.Fatalf("published action completion = %#v, want completed %q", eventRecord, plan.ActionID)
+ }
+ default:
+ t.Fatal("expected API action execution to publish a terminal action completion event")
+ }
events, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
if err != nil {
t.Fatalf("GetActionLifecycleEvents: %v", err)
@@ -445,6 +458,145 @@ func TestHandleExecuteActionRunsApprovedPlanThroughExecutor(t *testing.T) {
}
}
+func TestHandleExecuteActionRejectsStalePlanBeforeExecutor(t *testing.T) {
+ now := time.Date(2026, 5, 3, 10, 0, 0, 0, time.UTC)
+ resource := 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"}},
+ },
+ },
+ },
+ }
+ provider := &mutableResourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{resource},
+ freshness: now,
+ }
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(provider)
+ executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "should not run"}}
+ h.SetActionExecutor(executor)
+ published := make(chan unified.ActionAuditRecord, 1)
+ h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
+ published <- record
+ })
+
+ planRec := httptest.NewRecorder()
+ planReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
+ "requestId":"agent-run-stale-plan",
+ "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":"approved before resource changed"
+ }`))
+ 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())
+ }
+
+ resource.Status = unified.StatusOnline
+ resource.UpdatedAt = now.Add(time.Second)
+ resource.Capabilities[0].MinimumApprovalLevel = unified.ApprovalMultiFactor
+ provider = &mutableResourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now.Add(time.Second)},
+ resources: []unified.Resource{resource},
+ freshness: now.Add(time.Second),
+ }
+ h.SetStateProvider(provider)
+ h.invalidateCache("default")
+
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("get store: %v", err)
+ }
+ approvedAudit, ok, err := store.GetActionAudit(plan.ActionID)
+ if err != nil {
+ t.Fatalf("GetActionAudit before execute: %v", err)
+ }
+ if !ok {
+ t.Fatal("expected approved action audit before execute")
+ }
+ if err := h.validateActionPlanFresh("default", approvedAudit); !errors.Is(err, unified.ErrActionPlanDrift) {
+ t.Fatalf("expected current resource contract to drift before execute, got %v", err)
+ }
+
+ executeRec := httptest.NewRecorder()
+ executeReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/execute", bytes.NewBufferString(`{}`))
+ executeReq.SetPathValue("id", plan.ActionID)
+ executeReq = executeReq.WithContext(auth.WithUser(executeReq.Context(), "[email protected]"))
+ h.HandleExecuteAction(executeRec, executeReq)
+ if executeRec.Code != http.StatusConflict {
+ t.Fatalf("execute status = %d, body=%s", executeRec.Code, executeRec.Body.String())
+ }
+ if !strings.Contains(executeRec.Body.String(), `"error":"action_plan_drift"`) {
+ t.Fatalf("execute body = %s", executeRec.Body.String())
+ }
+ if executor.calls != 0 {
+ t.Fatalf("stale plan should not call executor, calls=%d received=%#v", executor.calls, executor.received)
+ }
+
+ audit, ok, err := store.GetActionAudit(plan.ActionID)
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || audit.State != unified.ActionStateFailed || audit.Result == nil || !strings.HasPrefix(audit.Result.ErrorMessage, "plan_drift:") {
+ t.Fatalf("stale-plan audit = %#v, ok=%v", audit, ok)
+ }
+ select {
+ case eventRecord := <-published:
+ if eventRecord.ID != plan.ActionID || eventRecord.State != unified.ActionStateFailed {
+ t.Fatalf("published stale-plan completion = %#v, want failed %q", eventRecord, plan.ActionID)
+ }
+ default:
+ t.Fatal("expected stale-plan refusal to publish a terminal action completion event")
+ }
+ events, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seenFailed := false
+ for _, event := range events {
+ if event.State == unified.ActionStateFailed && strings.HasPrefix(event.Message, "plan_drift:") {
+ seenFailed = true
+ break
+ }
+ }
+ if !seenFailed {
+ t.Fatalf("expected failed plan_drift lifecycle event, got %#v", events)
+ }
+}
+
func TestHandleExecuteActionWithoutExecutorLeavesApprovedAuditUnchanged(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.go
index cc6c82c2be..ea06548592 100644
--- a/internal/api/agent_capabilities.go
+++ b/internal/api/agent_capabilities.go
@@ -217,14 +217,14 @@ var agentCapabilitiesManifest = AgentCapabilitiesManifest{
},
{
Name: "execute_action",
- Description: "Execute a previously planned and (when required) approved action. Returns the persisted audit record with the execution result attached. Refuses with stable codes when the action is in the wrong lifecycle state (action_not_approved, action_already_executing, action_execution_final, action_dry_run_only) or when the API instance has no executor wired (action_executor_unavailable). action.completed SSE events fire on every terminal state so agents watching the stream do not need to poll this endpoint after dispatch.",
+ Description: "Execute a previously planned and (when required) approved action. Returns the persisted audit record with the execution result attached. Refuses with stable codes when the action is in the wrong lifecycle state (action_not_approved, action_already_executing, action_execution_final, action_dry_run_only), when the approved plan no longer matches the current resource/capability contract (action_plan_drift), or when the API instance has no executor wired (action_executor_unavailable). action.completed SSE events fire on every terminal state so agents watching the stream do not need to poll this endpoint after dispatch.",
Category: "action",
Method: http.MethodPost,
Path: "/api/actions/{actionId}/execute",
Scope: "ai:execute",
RequestBodyShape: "{ reason?: string }",
ResponseShape: "ActionExecutionResponse",
- ErrorCodes: []string{"missing_id", "invalid_id", "invalid_action_execution", "action_not_found", "action_not_approved", "action_already_executing", "action_execution_final", "action_dry_run_only", "action_executor_unavailable"},
+ ErrorCodes: []string{"missing_id", "invalid_id", "invalid_action_execution", "action_not_found", "action_not_approved", "action_already_executing", "action_execution_final", "action_dry_run_only", "action_plan_drift", "action_executor_unavailable"},
},
},
}
diff --git a/internal/api/agent_events.go b/internal/api/agent_events.go
index 9a6a3593c6..7b24387ed6 100644
--- a/internal/api/agent_events.go
+++ b/internal/api/agent_events.go
@@ -9,6 +9,7 @@ import (
"sync/atomic"
"time"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rs/zerolog/log"
)
@@ -345,6 +346,39 @@ func (b *AgentEventBroadcaster) PublishActionCompleted(payload AgentEventActionC
})
}
+// PublishActionCompletedRecord converts a terminal action audit record into
+// the agent-stable action.completed payload. Both the Assistant executor and
+// API-owned execution endpoint route through this helper so agents hear the
+// same completion event regardless of which execution surface dispatched the
+// action.
+func (b *AgentEventBroadcaster) PublishActionCompletedRecord(record unifiedresources.ActionAuditRecord) {
+ if b == nil {
+ return
+ }
+ if record.State != unifiedresources.ActionStateCompleted && record.State != unifiedresources.ActionStateFailed {
+ return
+ }
+ payload := AgentEventActionCompletedPayload{
+ ActionID: record.ID,
+ ResourceID: record.Request.ResourceID,
+ CapabilityName: record.Request.CapabilityName,
+ State: string(record.State),
+ RequestedBy: record.Request.RequestedBy,
+ CompletedAt: record.UpdatedAt,
+ }
+ if cmd, ok := record.Request.Params["command"].(string); ok {
+ payload.Command = cmd
+ }
+ if record.Result != nil {
+ payload.Success = record.Result.Success
+ payload.ErrorMessage = record.Result.ErrorMessage
+ if v := projectAgentResourceVerification(record.Result.Verification); v != nil {
+ payload.Verification = v
+ }
+ }
+ b.PublishActionCompleted(payload)
+}
+
// AgentEventBroadcasterContextKey is the context key used to plumb
// the broadcaster into request-scoped middleware where needed. Most
// call sites don't need this — they hold a direct reference — but
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 0dea2ff110..be850ee934 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -12514,6 +12514,28 @@ func TestContract_ActionDryRunOnlyExecutionErrorJSONSnapshot(t *testing.T) {
}
}
+func TestContract_APIActionExecutionRevalidatesPlanFreshness(t *testing.T) {
+ source, err := os.ReadFile("actions.go")
+ if err != nil {
+ t.Fatalf("read actions.go: %v", err)
+ }
+ src := string(source)
+ for _, snippet := range []string{
+ "if err := h.validateActionPlanFresh(orgID, record); err != nil",
+ "errors.Is(err, unified.ErrActionPlanDrift)",
+ "recordRefusedActionExecution(store, record, actor, now, err)",
+ "writeJSONError(w, http.StatusConflict, \"action_plan_drift\"",
+ } {
+ if !strings.Contains(src, snippet) {
+ t.Fatalf("actions.go must pin API execute plan freshness guard snippet %q", snippet)
+ }
+ }
+ if strings.Index(src, "if err := h.validateActionPlanFresh(orgID, record); err != nil") >
+ strings.Index(src, "started, startEvent, err := unified.BeginActionExecution(record, actor, now)") {
+ t.Fatal("HandleExecuteAction must validate plan freshness before entering executing state or calling the executor")
+ }
+}
+
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()})
@@ -13478,13 +13500,24 @@ func TestContract_AgentEventsStreamPublishesOnActionCompleted(t *testing.T) {
if !strings.Contains(src, "executor.SetOnActionCompleted(func(record unifiedresources.ActionAuditRecord)") {
t.Error("router.go must install the post-completion callback on the executor returned from chatService.GetExecutor() so the agent SSE stream is wired per-org")
}
- if !strings.Contains(src, "broadcaster.PublishActionCompleted(payload)") {
- t.Error("router.go must bridge action completion into PublishActionCompleted — drift means agents lose the push-notification path for dispatch outcomes")
+ if !strings.Contains(src, "broadcaster.PublishActionCompletedRecord(record)") {
+ t.Error("router.go must bridge executor action completion into PublishActionCompletedRecord — drift means agents lose the push-notification path for dispatch outcomes")
+ }
+ if !strings.Contains(src, "r.resourceHandlers.SetActionCompletedPublisher(r.agentEventBroadcaster.PublishActionCompletedRecord)") {
+ t.Error("router.go must also bridge API-owned action execution completions into the agent SSE stream")
+ }
+ eventsSource, err := os.ReadFile("agent_events.go")
+ if err != nil {
+ t.Fatalf("read agent_events.go: %v", err)
+ }
+ eventsSrc := string(eventsSource)
+ if !strings.Contains(eventsSrc, "func (b *AgentEventBroadcaster) PublishActionCompletedRecord(record unifiedresources.ActionAuditRecord)") {
+ t.Error("agent_events.go must keep a shared action-audit-record projector for every action.completed producer")
}
- if !strings.Contains(src, "ActionID: record.ID") {
+ if !strings.Contains(eventsSrc, "ActionID: record.ID") {
t.Error("action.completed payload must carry the canonical action id so agents can correlate the event with /api/actions/{id}")
}
- if !strings.Contains(src, "ResourceID: record.Request.ResourceID") {
+ if !strings.Contains(eventsSrc, "ResourceID: record.Request.ResourceID") {
t.Error("action.completed payload must carry the canonical resource id so agents can match it against the rest of Pulse")
}
}
@@ -13932,6 +13965,7 @@ func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T)
"action_execution_encode_failed": true,
"action_execution_failed": true,
"action_not_executing": true,
+ "action_plan_validation_failed": true,
"resource_registry_unavailable": true,
}
diff --git a/internal/api/resources.go b/internal/api/resources.go
index 92d53f70dc..ae788db64a 100644
--- a/internal/api/resources.go
+++ b/internal/api/resources.go
@@ -31,6 +31,7 @@ type ResourceHandlers struct {
stateProvider SnapshotProvider
tenantStateProvider TenantStateProvider
actionExecutor ActionExecutor
+ actionCompleted func(unified.ActionAuditRecord)
}
type registrySeed struct {
@@ -93,6 +94,14 @@ func (h *ResourceHandlers) SetActionExecutor(executor ActionExecutor) {
h.actionExecutor = executor
}
+// SetActionCompletedPublisher configures the terminal action notification hook
+// used by the agent SSE bridge. It is intentionally outside the execution
+// driver so refused-before-dispatch failures and future executor
+// implementations all publish from the API-owned lifecycle boundary.
+func (h *ResourceHandlers) SetActionCompletedPublisher(publisher func(unified.ActionAuditRecord)) {
+ h.actionCompleted = publisher
+}
+
// SetSupplementalRecordsProvider configures additional records for a source.
func (h *ResourceHandlers) SetSupplementalRecordsProvider(source unified.DataSource, provider SupplementalRecordsProvider) {
h.supplementalMu.Lock()
diff --git a/internal/api/router.go b/internal/api/router.go
index 0f599170f0..d1594e287a 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -445,6 +445,9 @@ func (r *Router) setupRoutes() {
// read for the wrong org.
r.agentContextHandler.SetApprovalsProvider(agentApprovalStoreProvider{})
r.agentEventBroadcaster = NewAgentEventBroadcaster()
+ if r.resourceHandlers != nil && r.agentEventBroadcaster != nil {
+ r.resourceHandlers.SetActionCompletedPublisher(r.agentEventBroadcaster.PublishActionCompletedRecord)
+ }
if r.resourceHandlers != nil {
if store, err := r.resourceHandlers.getStore("default"); err == nil && store != nil {
r.monitorResourceAdapter = unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store))
@@ -2570,25 +2573,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A
if executor := chatService.GetExecutor(); executor != nil {
broadcaster := r.agentEventBroadcaster
executor.SetOnActionCompleted(func(record unifiedresources.ActionAuditRecord) {
- payload := AgentEventActionCompletedPayload{
- ActionID: record.ID,
- ResourceID: record.Request.ResourceID,
- CapabilityName: record.Request.CapabilityName,
- State: string(record.State),
- RequestedBy: record.Request.RequestedBy,
- CompletedAt: record.UpdatedAt,
- }
- if cmd, ok := record.Request.Params["command"].(string); ok {
- payload.Command = cmd
- }
- if record.Result != nil {
- payload.Success = record.Result.Success
- payload.ErrorMessage = record.Result.ErrorMessage
- if v := projectAgentResourceVerification(record.Result.Verification); v != nil {
- payload.Verification = v
- }
- }
- broadcaster.PublishActionCompleted(payload)
+ broadcaster.PublishActionCompletedRecord(record)
})
}
}
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 6fb1e21e53..8755f00c65 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -397,13 +397,27 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
filepath.Join("..", "api", "actions.go"): {
"type ActionExecutor interface",
"func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Request)",
+ "func (h *ResourceHandlers) validateActionPlanFresh(orgID string, record unified.ActionAuditRecord) error",
+ "func recordRefusedActionExecution(store unified.ResourceStore, record unified.ActionAuditRecord",
+ "func (h *ResourceHandlers) publishActionCompleted(record unified.ActionAuditRecord)",
"store.RecordActionExecutionStart(started, startEvent)",
"store.RecordActionExecutionResult(completed, doneEvent)",
+ "action_plan_drift",
"action_executor_unavailable",
},
filepath.Join("..", "api", "resources.go"): {
"actionExecutor ActionExecutor",
+ "actionCompleted func(unified.ActionAuditRecord)",
"func (h *ResourceHandlers) SetActionExecutor(executor ActionExecutor)",
+ "func (h *ResourceHandlers) SetActionCompletedPublisher(",
+ },
+ filepath.Join("..", "api", "agent_events.go"): {
+ "func (b *AgentEventBroadcaster) PublishActionCompletedRecord(record unifiedresources.ActionAuditRecord)",
+ "payload := AgentEventActionCompletedPayload{",
+ "b.PublishActionCompleted(payload)",
+ },
+ filepath.Join("..", "api", "router.go"): {
+ "r.resourceHandlers.SetActionCompletedPublisher(r.agentEventBroadcaster.PublishActionCompletedRecord)",
},
filepath.Join("..", "api", "router_routes_monitoring.go"): {
`"POST /api/actions/{id}/execute"`,