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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Bring action endpoints onto the agent surface with the agent-stable envelope
rcourtman728c42e47ba8
diff --git a/docs/AGENT_SUBSTRATE.md b/docs/AGENT_SUBSTRATE.mdindex aa7adc3911..d59da5056c 100644--- a/docs/AGENT_SUBSTRATE.md+++ b/docs/AGENT_SUBSTRATE.md@@ -30,13 +30,21 @@ rollup across the whole org: identity, operator flags, per-severityfinding counts, pending-approval count. One read for "where do Ifocus?", with the per-resource bundle for follow-up depth.-**Write.** The operator-state intent loop+**Write.** Two write surfaces. The operator-state intent loop(`/api/resources/{id}/operator-state`) lets an agent record-per-resource commitments (intentionally offline, never auto-remediate,-maintenance window, criticality). The server populates attribution so-client values cannot spoof who-did-it. Validation failures emit the-`operator_state_invalid` stable code; reads on unset resources emit-`operator_state_not_set`.+per-resource commitments (intentionally offline, never+auto-remediate, maintenance window, criticality). The action+governance loop (`/api/actions/plan`, `/api/actions/{id}/decision`,+`/api/actions/{id}/execute`) lets an agent plan, approve, and+execute capability invocations against a resource through the+canonical audit store. The server populates attribution so client+values cannot spoof who-did-it. Validation failures emit the+`operator_state_invalid` and `invalid_action_request` stable+codes; lifecycle conflicts on the action loop emit+`action_not_pending`, `action_not_approved`,+`action_already_executing`, `action_execution_final`, and+`action_dry_run_only` so agents branch on the conflict rather+than retrying blindly.**Push.** `/api/agent/events` is an SSE stream that fires`finding.created`, `approval.pending`, and `action.completed` events@@ -70,20 +78,27 @@ manifest-driven:## What it does not do yet-- The substrate does not yet expose the governed action-execution- surface (`/api/actions/plan`, `/api/actions/{id}/decision`,- `/api/actions/{id}/execute`) as agent-stable manifest entries.- Those handlers exist and are wired through the action audit store,- but they emit a different error envelope from the agent surface- (`APIError` shape: stable code under `code`, human message under- `error`) versus the agent-stable shape (stable code under `error`,- human under `message`). Adding them to the manifest as-is would- force agents to remember which envelope each capability uses.- Resolving that mismatch is a focused slice of its own. Until then,- action governance flows through the existing approval store and- the `action.completed` push channel: the AI service plans, an- operator (or operator-acting agent) approves, the substrate emits- the event.+- Real-world consumer feedback. The substrate ships with two+ reference adapters (HTTP and MCP) and end-to-end contract tests,+ but no external integration has been load-bearing on it yet.+ Until somebody wires `pulse-mcp` into Claude Desktop or builds+ against the agent surface from a custom client, the next+ meaningful work item is whatever friction usage surfaces, not+ more substrate plumbing.++- A user-facing surface inside Pulse for managing agent+ integrations. Today the agent surface is invisible to the+ operator running Pulse: there is no Settings panel listing the+ declared capabilities, no "generate MCP config snippet" button,+ no token template that says "create token for agent+ integration." Adding those is what makes the substrate real for+ humans, not just for agents.++- A distribution path for `pulse-mcp`. Today an integrator must+ clone the repo and `go build`. A release artifact (Homebrew+ formula, Docker image, signed binary) would turn integration+ from "build from source" into "install Pulse, copy this+ config."## Provable claimsdiff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex e7232ca331..8e953bd015 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -987,6 +987,16 @@ able to introspect Pulse to learn how to ask for one. Theunderlying capabilities the manifest declares keep their own authscopes — the public posture applies only to discovery itself.+The action governance loop (`/api/actions/plan`,+`/api/actions/{id}/decision`, `/api/actions/{id}/execute`) joined+the agent surface via the manifest under a new `action` category,+gated by the `ai:execute` scope (distinct from `monitoring:write`+because action governance is the governed-execution dimension).+The handlers were migrated from the platform-wide `APIError`+envelope to the agent-stable `{"error", "message", "details"?}`+shape so the substrate keeps a single envelope contract across+read, write, and action capabilities.+The findings runtime now consumes operator-set per-resource statethrough a provider adapter wired in `internal/api/router.go` atstartup. The adapter returns a `ResourceOperatorStateProjection`diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 0d2ac663c8..02b2d8c358 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1447,11 +1447,15 @@ error codes are, what category each belongs to) cannot driftbehind code changes.The agent surface uses one error-envelope shape across every-endpoint — `{"error": "<stable_code>", "message": "<human>"}` —-written via `writeJSONError`. Agents branch on the `error` field+endpoint — `{"error": "<stable_code>", "message": "<human>",+"details"?: {"<field>": "<reason>"}}` — written via+`writeJSONError` (no details) or `writeJSONErrorWithDetails`+(with field-level reasons). Agents branch on the `error` field(snake_case stable codes); the `message` field carrieshuman-readable text agents can surface to operators without-losing the code.+losing the code; the optional `details` map carries field-level+failure reasons on validation errors so agents do not parse+human text to identify which field went wrong.There are two layers of stable codes. First, **capability-specificcodes** are declared per capability in the manifest's `errorCodes`@@ -1638,6 +1642,46 @@ present). The handler dispatches off `r.Method` rather than mountingthree sibling routes so the URL surface stays a single resource pathmatching the rest of `/api/resources/{id}/...`.+The action governance loop at `/api/actions/plan`,+`/api/actions/{id}/decision`, and `/api/actions/{id}/execute` is+the canonical write surface for capability invocations against a+resource. All three require the `ai:execute` scope, which is+distinct from `monitoring:write` because action governance is the+governed-execution dimension of the substrate. The handlers emit+the agent-stable error envelope (`{"error": "<code>", "message":+"...", "details": {...}}`), matching the rest of the agent+surface, so an agent that branches on the `error` field across+read, write, and action capabilities sees the same envelope+shape everywhere. The `details` map is optional and carries+field-level reasons on validation failures (e.g.+`{"resourceId": "resource id is required"}`) so agents do not+need to parse human text to know which field went wrong. The+manifest's per-capability `errorCodes` lists declare the closed+set: `plan_action` carries `invalid_action_request`,+`resource_not_found`, `capability_not_found`; `decide_action`+carries `missing_id`, `invalid_id`, `invalid_action_decision`,+`action_not_found`, `action_not_pending`, `action_plan_expired`;+`execute_action` carries `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`. 5xx internal-failure codes+(audit-store outages, encode failures) are not declared per+capability; agents branch on 5xx generically.++The action endpoints do not introduce new routes. The same paths+that the frontend has historically called (zero current frontend+consumers, verified) now back the manifest entries; the+substrate's "manifest projection is cheap" promise has a+documented footnote that bringing an existing endpoint into the+agent surface may require migrating its error envelope from the+platform-wide `APIError` shape to the agent-stable shape. That+migration was the slice 58 work for these three handlers; future+agent-surface additions on existing endpoints will pay the same+cost. The trade-off is intentional: the agent surface keeps a+single envelope contract rather than carrying a wrapper layer to+translate per capability.+Deploy-job monitored-system volume denials are retired. API routes may stillaccept historical payloads that mention old license-slot terminology formigration or diagnostics, but runtime deploy responses must not emitdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 0601c8ea8d..8d36e3eecd 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -975,6 +975,17 @@ read-only and stateless — no persistence is involved. The manifestis hand-authored in `internal/api/agent_capabilities.go`; storageflows are not affected.+The action governance loop endpoints (`/api/actions/plan`,+`/api/actions/{id}/decision`, `/api/actions/{id}/execute`) joined+the agent surface but introduce no new persistence. Plan, decide,+and execute all write to the same `ActionAuditRecord` /+`ActionLifecycleEvent` durable storage the action audit store+already manages; the only delta is the wire shape returned to+clients on error (now the agent-stable envelope rather than the+platform-wide `APIError` shape). Recovery posture is identical:+when the action audit store rehydrates on startup, the action+endpoints recover the same lifecycle records they always did.+The agent-consumable bundled context endpoint`/api/agent/resource-context/{id}` reads the same durable`resource_operator_state` table and `action_audits` table through thediff --git a/internal/api/actions.go b/internal/api/actions.goindex ae6de68531..df8200f0bb 100644--- a/internal/api/actions.go+++ b/internal/api/actions.go@@ -56,13 +56,13 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requedecoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxActionPlanRequestBytes))decoder.DisallowUnknownFields()if err := decoder.Decode(&req); err != nil {- writeErrorResponse(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{"body": "request body must be a valid ActionRequest JSON object",})return}if err := decoder.Decode(&struct{}{}); err != io.EOF {- writeErrorResponse(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{"body": "request body must contain one JSON object",})return@@ -70,7 +70,7 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requereq.ResourceID = unified.CanonicalResourceID(req.ResourceID)if req.ResourceID == "" {- writeErrorResponse(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{"resourceId": "resource id is required",})return@@ -79,13 +79,13 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.RequeorgID := GetOrgID(r.Context())registry, err := h.buildRegistry(orgID)if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "resource_registry_unavailable", sanitizeErrorForClient(err, "Resource registry unavailable"), nil)+ writeJSONError(w, http.StatusInternalServerError, "resource_registry_unavailable", sanitizeErrorForClient(err, "Resource registry unavailable"))return}resource, ok := registry.Get(req.ResourceID)if !ok || resource == nil {- writeErrorResponse(w, http.StatusNotFound, "resource_not_found", "Resource not found", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, "resource_not_found", "Resource not found", map[string]string{"resourceId": req.ResourceID,})return@@ -98,34 +98,34 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requeif validationErr.Field != "" {details[validationErr.Field] = validationErr.Message}- writeErrorResponse(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", details)+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", details)return}if errors.Is(err, actionplanner.ErrCapabilityNotFound) {- writeErrorResponse(w, http.StatusNotFound, "capability_not_found", "Capability not found on resource", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, "capability_not_found", "Capability not found on resource", map[string]string{"resourceId": req.ResourceID,"capabilityName": req.CapabilityName,})return}- writeErrorResponse(w, http.StatusInternalServerError, "action_plan_failed", sanitizeErrorForClient(err, "Action planning failed"), nil)+ writeJSONError(w, http.StatusInternalServerError, "action_plan_failed", sanitizeErrorForClient(err, "Action planning failed"))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)+ writeJSONError(w, http.StatusServiceUnavailable, "action_audit_unavailable", "Action audit history is not available")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)+ writeJSONError(w, http.StatusInternalServerError, "action_audit_persist_failed", sanitizeErrorForClient(err, "Failed to persist action audit"))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)+ writeJSONError(w, http.StatusInternalServerError, "action_plan_encode_failed", "Failed to encode action plan")}}@@ -204,11 +204,11 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.ReqactionID := strings.TrimSpace(r.PathValue("id"))if actionID == "" {- writeErrorResponse(w, http.StatusBadRequest, "missing_id", "Missing action ID", nil)+ writeJSONError(w, http.StatusBadRequest, "missing_id", "Missing action ID")return}if !validAuditEventID.MatchString(actionID) || len(actionID) > 128 {- writeErrorResponse(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format", nil)+ writeJSONError(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format")return}@@ -216,13 +216,13 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.Reqdecoder := 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{+ writeJSONErrorWithDetails(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{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{"body": "request body must contain one JSON object",})return@@ -230,7 +230,7 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.Reqdecision.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{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{"outcome": "outcome must be approved or rejected",})return@@ -239,16 +239,16 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.ReqorgID := 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)+ writeJSONError(w, http.StatusServiceUnavailable, "action_audit_unavailable", "Action audit history is not available")return}record, ok, err := store.GetActionAudit(actionID)if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "action_audit_query_failed", "Failed to query action audit", nil)+ writeJSONError(w, http.StatusInternalServerError, "action_audit_query_failed", "Failed to query action audit")return}if !ok {- writeErrorResponse(w, http.StatusNotFound, "action_not_found", "Action not found", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, "action_not_found", "Action not found", map[string]string{"actionId": actionID,})return@@ -273,7 +273,7 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.ReqwriteActionDecisionApplyError(w, err)return}- writeErrorResponse(w, http.StatusInternalServerError, "action_decision_persist_failed", sanitizeErrorForClient(err, "Failed to persist action decision"), nil)+ writeJSONError(w, http.StatusInternalServerError, "action_decision_persist_failed", sanitizeErrorForClient(err, "Failed to persist action decision"))return}@@ -288,7 +288,7 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.ReqApproval: responseApproval,Audit: updated,}); err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "action_decision_encode_failed", "Failed to encode action decision", nil)+ writeJSONError(w, http.StatusInternalServerError, "action_decision_encode_failed", "Failed to encode action decision")}}@@ -300,11 +300,11 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.ReactionID := strings.TrimSpace(r.PathValue("id"))if actionID == "" {- writeErrorResponse(w, http.StatusBadRequest, "missing_id", "Missing action ID", nil)+ writeJSONError(w, http.StatusBadRequest, "missing_id", "Missing action ID")return}if !validAuditEventID.MatchString(actionID) || len(actionID) > 128 {- writeErrorResponse(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format", nil)+ writeJSONError(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format")return}@@ -313,13 +313,13 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Redecoder.DisallowUnknownFields()if err := decoder.Decode(&execution); err != nil {if !errors.Is(err, io.EOF) {- writeErrorResponse(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{"body": "request body must be a valid action execution JSON object",})return}} else if err := decoder.Decode(&struct{}{}); err != io.EOF {- writeErrorResponse(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{"body": "request body must contain one JSON object",})return@@ -329,16 +329,16 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.ReorgID := 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)+ writeJSONError(w, http.StatusServiceUnavailable, "action_audit_unavailable", "Action audit history is not available")return}record, ok, err := store.GetActionAudit(actionID)if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "action_audit_query_failed", "Failed to query action audit", nil)+ writeJSONError(w, http.StatusInternalServerError, "action_audit_query_failed", "Failed to query action audit")return}if !ok {- writeErrorResponse(w, http.StatusNotFound, "action_not_found", "Action not found", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, "action_not_found", "Action not found", map[string]string{"actionId": actionID,})return@@ -354,7 +354,7 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.RestartEvent.Message = "Action execution started: " + execution.Reason}if h.actionExecutor == nil {- writeErrorResponse(w, http.StatusNotImplemented, "action_executor_unavailable", "No action executor is configured for this API instance", nil)+ 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 {@@ -383,7 +383,7 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.ReResult: completed.Result,Audit: completed,}); err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "action_execution_encode_failed", "Failed to encode action execution", nil)+ writeJSONError(w, http.StatusInternalServerError, "action_execution_encode_failed", "Failed to encode action execution")}}@@ -402,34 +402,34 @@ func actionDecisionActor(h *ResourceHandlers, r *http.Request) string {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{+ writeJSONErrorWithDetails(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)+ writeJSONError(w, http.StatusConflict, "action_not_pending", "Action is not pending approval")case errors.Is(err, unified.ErrActionPlanExpired):- writeErrorResponse(w, http.StatusConflict, "action_plan_expired", "Action plan has expired", nil)+ writeJSONError(w, http.StatusConflict, "action_plan_expired", "Action plan has expired")default:- writeErrorResponse(w, http.StatusInternalServerError, "action_decision_failed", sanitizeErrorForClient(err, "Action decision failed"), nil)+ writeJSONError(w, http.StatusInternalServerError, "action_decision_failed", sanitizeErrorForClient(err, "Action decision failed"))}}func writeActionExecutionApplyError(w http.ResponseWriter, err error) {switch {case errors.Is(err, unified.ErrActionNotApproved):- writeErrorResponse(w, http.StatusConflict, "action_not_approved", "Action is not approved for execution", nil)+ writeJSONError(w, http.StatusConflict, "action_not_approved", "Action is not approved for execution")case errors.Is(err, unified.ErrActionAlreadyExecuting):- writeErrorResponse(w, http.StatusConflict, "action_already_executing", "Action is already executing", nil)+ writeJSONError(w, http.StatusConflict, "action_already_executing", "Action is already executing")case errors.Is(err, unified.ErrActionExecutionFinal):- writeErrorResponse(w, http.StatusConflict, "action_execution_final", "Action execution is already final", nil)+ writeJSONError(w, http.StatusConflict, "action_execution_final", "Action execution is already final")case errors.Is(err, unified.ErrActionNotExecuting):- writeErrorResponse(w, http.StatusConflict, "action_not_executing", "Action is not executing", nil)+ writeJSONError(w, http.StatusConflict, "action_not_executing", "Action is not executing")case errors.Is(err, unified.ErrActionPlanExpired):- writeErrorResponse(w, http.StatusConflict, "action_plan_expired", "Action plan has expired", nil)+ writeJSONError(w, http.StatusConflict, "action_plan_expired", "Action plan has expired")case errors.Is(err, unified.ErrActionDryRunOnly):- writeErrorResponse(w, http.StatusConflict, "action_dry_run_only", "Action plan is dry-run only and cannot be executed", nil)+ writeJSONError(w, http.StatusConflict, "action_dry_run_only", "Action plan is dry-run only and cannot be executed")default:- writeErrorResponse(w, http.StatusInternalServerError, "action_execution_failed", sanitizeErrorForClient(err, "Action execution failed"), nil)+ writeJSONError(w, http.StatusInternalServerError, "action_execution_failed", sanitizeErrorForClient(err, "Action execution failed"))}}@@ -443,6 +443,6 @@ func writeActionExecutionPersistError(w http.ResponseWriter, err error) {errors.Is(err, unified.ErrActionDryRunOnly):writeActionExecutionApplyError(w, err)default:- writeErrorResponse(w, http.StatusInternalServerError, "action_execution_persist_failed", sanitizeErrorForClient(err, "Failed to persist action execution"), nil)+ writeJSONError(w, http.StatusInternalServerError, "action_execution_persist_failed", sanitizeErrorForClient(err, "Failed to persist action execution"))}}diff --git a/internal/api/actions_test.go b/internal/api/actions_test.goindex 628f1aaee1..fcae081563 100644--- a/internal/api/actions_test.go+++ b/internal/api/actions_test.go@@ -324,7 +324,7 @@ func TestHandleDecideActionApprovesPendingPlanWithoutExecution(t *testing.T) {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"`) {+ if !strings.Contains(retryRec.Body.String(), `"error":"action_not_pending"`) {t.Fatalf("retry decision body = %s", retryRec.Body.String())}}@@ -498,7 +498,7 @@ func TestHandleExecuteActionWithoutExecutorLeavesApprovedAuditUnchanged(t *testiif executeRec.Code != http.StatusNotImplemented {t.Fatalf("execute status = %d, body=%s", executeRec.Code, executeRec.Body.String())}- if !strings.Contains(executeRec.Body.String(), `"code":"action_executor_unavailable"`) {+ if !strings.Contains(executeRec.Body.String(), `"error":"action_executor_unavailable"`) {t.Fatalf("execute body = %s", executeRec.Body.String())}@@ -564,7 +564,7 @@ func TestHandleExecuteActionRejectsDryRunOnlyPlan(t *testing.T) {if executeRec.Code != http.StatusConflict {t.Fatalf("execute status = %d, body=%s", executeRec.Code, executeRec.Body.String())}- if !strings.Contains(executeRec.Body.String(), `"code":"action_dry_run_only"`) {+ if !strings.Contains(executeRec.Body.String(), `"error":"action_dry_run_only"`) {t.Fatalf("execute body = %s", executeRec.Body.String())}if executor.calls != 0 {@@ -670,7 +670,7 @@ func TestHandlePlanActionRejectsMissingCapability(t *testing.T) {if rec.Code != http.StatusNotFound {t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusNotFound, rec.Body.String())}- if !strings.Contains(rec.Body.String(), `"code":"capability_not_found"`) {+ if !strings.Contains(rec.Body.String(), `"error":"capability_not_found"`) {t.Fatalf("unexpected response body: %s", rec.Body.String())}}diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.goindex 7e7bc5719b..b933c942de 100644--- a/internal/api/agent_capabilities.go+++ b/internal/api/agent_capabilities.go@@ -193,6 +193,39 @@ var agentCapabilitiesManifest = AgentCapabilitiesManifest{Scope: "monitoring:write",RequestBodyShape: "{ finding_id: string }",},+ {+ Name: "plan_action",+ Description: "Plan an action against a resource. The planner validates the request, looks up the capability on the resource, and returns an ActionPlan with the approval policy, blast radius, plan hash, and preflight summary. The plan is persisted to the audit history at the planned/pending state so subsequent decide_action and execute_action calls can reference it by id. Plan-and-execute is a two-step flow when the resulting plan requires approval, one-step otherwise.",+ Category: "action",+ Method: http.MethodPost,+ Path: "/api/actions/plan",+ Scope: "ai:execute",+ RequestBodyShape: "ActionRequest",+ ResponseShape: "ActionPlan",+ ErrorCodes: []string{"invalid_action_request", "resource_not_found", "capability_not_found"},+ },+ {+ Name: "decide_action",+ Description: "Record an approval decision (approved or rejected) on a previously planned action. The actor is taken from the authenticated identity; an explicit reason can be passed in the body. Idempotent on the persisted decision: re-deciding a non-pending action surfaces the action_not_pending stable code so agents can branch on the conflict rather than retrying blindly.",+ Category: "action",+ Method: http.MethodPost,+ Path: "/api/actions/{actionId}/decision",+ Scope: "ai:execute",+ RequestBodyShape: "{ outcome: \"approved\"|\"rejected\", reason?: string }",+ ResponseShape: "ActionDecisionResponse",+ ErrorCodes: []string{"missing_id", "invalid_id", "invalid_action_decision", "action_not_found", "action_not_pending", "action_plan_expired"},+ },+ {+ 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.",+ 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"},+ },},}diff --git a/internal/api/agent_capabilities_test.go b/internal/api/agent_capabilities_test.goindex 884d68a816..7651d10a2e 100644--- a/internal/api/agent_capabilities_test.go+++ b/internal/api/agent_capabilities_test.go@@ -102,6 +102,7 @@ func TestAgentCapabilitiesManifest_CategoriesAreClosed(t *testing.T) {"context": true,"operator-state": true,"finding": true,+ "action": true,}for _, cap := range agentCapabilitiesManifest.Capabilities {if !allowed[cap.Category] {diff --git a/internal/api/agent_substrate_e2e_test.go b/internal/api/agent_substrate_e2e_test.goindex 495f777a86..0d648ba93d 100644--- a/internal/api/agent_substrate_e2e_test.go+++ b/internal/api/agent_substrate_e2e_test.go@@ -433,3 +433,143 @@ func stringSliceContains(haystack []string, needle string) bool {}return false}++// TestAgentSubstrate_ActionEndpointsEmitAgentStableEnvelope is the+// end-to-end contract proof for the action surface joining the+// agent manifest. The three action endpoints (plan/decide/execute)+// previously emitted the platform-wide APIError shape (stable code+// under `code`, human under `error`); after the slice-58 refactor+// they emit the agent-stable envelope (stable code under `error`,+// human under `message`) so an agent that branched on the agent+// surface sees identical envelope semantics across read, write,+// and action capabilities.+//+// The test covers three error paths through the actual HTTP+// boundary, one per endpoint:+//+// - plan_action with a missing resourceId surfaces+// invalid_action_request under the agent-stable `error` key+// and includes a `details` map naming the field that failed.+// - decide_action against a non-existent action id surfaces+// action_not_found.+// - execute_action against a non-existent action id surfaces+// action_not_found.+//+// Each error path also asserts the message is non-empty so agents+// surfacing copy to humans get something readable, and that the+// APIError-shape fields (`code`, `status_code`, `timestamp`) do+// NOT appear, since their presence would mean the refactor+// regressed.+func TestAgentSubstrate_ActionEndpointsEmitAgentStableEnvelope(t *testing.T) {+ rawToken := "agent-substrate-action-e2e.12345678"+ record := newTokenRecord(t, rawToken,+ []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil)+ cfg := newTestConfigWithTokens(t, record)+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")++ // First verify the manifest declares the three action+ // capabilities, since the substrate's promise is that the+ // envelope an agent encounters matches what the manifest's+ // errorCodes list documents.+ req := httptest.NewRequest(http.MethodGet, "/api/agent/capabilities", nil)+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("capabilities GET: status = %d", rec.Code)+ }+ var manifest AgentCapabilitiesManifest+ if err := json.NewDecoder(rec.Body).Decode(&manifest); err != nil {+ t.Fatalf("decode manifest: %v", err)+ }+ byName := map[string]AgentCapability{}+ for _, c := range manifest.Capabilities {+ byName[c.Name] = c+ }+ for _, want := range []string{"plan_action", "decide_action", "execute_action"} {+ cap, ok := byName[want]+ if !ok {+ t.Fatalf("manifest missing %q capability", want)+ }+ if cap.Category != "action" {+ t.Errorf("%s: category = %q, want \"action\"", want, cap.Category)+ }+ if cap.Scope != "ai:execute" {+ t.Errorf("%s: scope = %q, want \"ai:execute\"", want, cap.Scope)+ }+ if len(cap.ErrorCodes) == 0 {+ t.Errorf("%s: must declare at least one stable errorCode", want)+ }+ }++ // --- 1. plan_action: invalid request body lands under the+ // stable invalid_action_request code with a details map. ---+ planCap := byName["plan_action"]+ body := strings.NewReader(`{"resourceId": "", "capabilityName": "restart"}`)+ req = httptest.NewRequest(http.MethodPost, planCap.Path, body)+ req.Header.Set("X-API-Token", rawToken)+ req.Header.Set("Content-Type", "application/json")+ rec = httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("plan_action invalid: status = %d, want 400, body = %s", rec.Code, rec.Body.String())+ }+ assertAgentStableEnvelope(t, "plan_action", rec.Body.String(), "invalid_action_request")+ if !stringSliceContains(planCap.ErrorCodes, "invalid_action_request") {+ t.Errorf("manifest plan_action.ErrorCodes must declare invalid_action_request; got %v", planCap.ErrorCodes)+ }++ // --- 2. decide_action against a non-existent action id. ---+ decideCap := byName["decide_action"]+ decidePath := strings.Replace(decideCap.Path, "{actionId}", "act_does_not_exist_xyz", 1)+ body = strings.NewReader(`{"outcome": "approved"}`)+ req = httptest.NewRequest(http.MethodPost, decidePath, body)+ req.Header.Set("X-API-Token", rawToken)+ req.Header.Set("Content-Type", "application/json")+ rec = httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("decide_action unknown: status = %d, want 404, body = %s", rec.Code, rec.Body.String())+ }+ assertAgentStableEnvelope(t, "decide_action", rec.Body.String(), "action_not_found")++ // --- 3. execute_action against a non-existent action id. ---+ executeCap := byName["execute_action"]+ executePath := strings.Replace(executeCap.Path, "{actionId}", "act_does_not_exist_xyz", 1)+ req = httptest.NewRequest(http.MethodPost, executePath, strings.NewReader(`{}`))+ req.Header.Set("X-API-Token", rawToken)+ req.Header.Set("Content-Type", "application/json")+ rec = httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("execute_action unknown: status = %d, want 404, body = %s", rec.Code, rec.Body.String())+ }+ assertAgentStableEnvelope(t, "execute_action", rec.Body.String(), "action_not_found")+}++// assertAgentStableEnvelope is the inverse APIError-shape check: it+// asserts the response body uses the agent-stable envelope (stable+// code under `error`, human under `message`) and explicitly does+// NOT carry the legacy APIError fields (`code`, `status_code`,+// `timestamp`). Drift back to APIError would mean the slice-58+// refactor regressed, and an agent that read `error` for the+// stable code would silently get human text instead.+func assertAgentStableEnvelope(t *testing.T, label, body, wantCode string) {+ t.Helper()+ var envelope map[string]any+ if err := json.Unmarshal([]byte(body), &envelope); err != nil {+ t.Fatalf("%s: response body is not JSON: %v\nbody=%s", label, err, body)+ }+ gotCode, _ := envelope["error"].(string)+ if gotCode != wantCode {+ t.Errorf("%s: error code = %q, want %q (envelope=%s)", label, gotCode, wantCode, body)+ }+ gotMsg, _ := envelope["message"].(string)+ if strings.TrimSpace(gotMsg) == "" {+ t.Errorf("%s: message must be non-empty so agents can surface human text; envelope=%s", label, body)+ }+ for _, legacy := range []string{"code", "status_code", "timestamp"} {+ if _, has := envelope[legacy]; has {+ t.Errorf("%s: envelope must not carry legacy APIError field %q after agent-stable refactor; envelope=%s", label, legacy, body)+ }+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 74cb943d2c..8724873090 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -12420,19 +12420,28 @@ func TestContract_ActionDryRunOnlyExecutionErrorJSONSnapshot(t *testing.T) {if rec.Code != http.StatusConflict {t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusConflict, rec.Body.String())}- var apiErr APIError- if err := json.Unmarshal(rec.Body.Bytes(), &apiErr); err != nil {+ // The action endpoints now emit the agent-stable error+ // envelope (slice 58 refactor): the stable code lives under+ // the top-level `error` field and the human message lives+ // under `message`. The previous APIError shape (code under+ // `code`, message under `error`) is gone for these handlers+ // because they joined the agent surface.+ var envelope struct {+ Error string `json:"error"`+ Message string `json:"message"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &envelope); err != nil {t.Fatalf("decode dry-run execution error: %v", err)}payload := struct {- Status int `json:"status"`- Error struct {- Code string `json:"code"`- Message string `json:"message"`- } `json:"error"`- }{Status: rec.Code}- payload.Error.Code = apiErr.Code- payload.Error.Message = apiErr.ErrorMessage+ Status int `json:"status"`+ ErrorKey string `json:"error"`+ Message string `json:"message"`+ }{+ Status: rec.Code,+ ErrorKey: envelope.Error,+ Message: envelope.Message,+ }got, err := json.Marshal(payload)if err != nil {@@ -12440,10 +12449,8 @@ func TestContract_ActionDryRunOnlyExecutionErrorJSONSnapshot(t *testing.T) {}const want = `{"status":409,- "error":{- "code":"action_dry_run_only",- "message":"Action plan is dry-run only and cannot be executed"- }+ "error":"action_dry_run_only",+ "message":"Action plan is dry-run only and cannot be executed"}`assertJSONSnapshot(t, got, want)@@ -13771,28 +13778,55 @@ func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T)handlerFiles := []string{"agent_resource_context.go","resources_operator_state.go",- }-- // Extract every (status, code) pair from writeJSONError calls.- // The regex tolerates whitespace/newlines that gofmt may insert- // between the call's arguments.+ "actions.go",+ }++ // Codes the action handlers emit that are deliberately NOT in+ // the per-capability manifest entries: 5xx internal-failure+ // codes (audit-store outages, encode failures) and codes that+ // surface from edge paths the manifest declares against a+ // different capability. Agents branch on 5xx generically; they+ // don't need the specific token. Whitelisted here so the+ // emit/declare audit doesn't false-positive on them.+ internalOnlyCodes := map[string]bool{+ "action_audit_unavailable": true,+ "action_audit_persist_failed": true,+ "action_plan_failed": true,+ "action_plan_encode_failed": true,+ "action_audit_query_failed": true,+ "action_decision_persist_failed": true,+ "action_decision_encode_failed": true,+ "action_decision_failed": true,+ "action_execution_persist_failed": true,+ "action_execution_encode_failed": true,+ "action_execution_failed": true,+ "action_not_executing": true,+ "resource_registry_unavailable": true,+ }++ // Extract every emitted code from writeJSONError /+ // writeJSONErrorWithDetails calls. The regex tolerates+ // whitespace/newlines that gofmt may insert between the call's+ // arguments and matches both function names since they share+ // the same envelope contract.emitted := map[string]bool{}- codeRE := regexp.MustCompile(`writeJSONError\([^"]*"[^"]+",\s*"([a-z_][a-z_0-9]*)"`)for _, file := range handlerFiles {body, err := os.ReadFile(file)if err != nil {t.Fatalf("read %s: %v", file, err)}- // codeRE captures the second string literal (the code), but- // the first arg is `w` (an identifier), then a status int, so- // we use a looser pattern: find writeJSONError followed by- // `, "code"` somewhere on the same logical call.- looseRE := regexp.MustCompile(`writeJSONError\([^)]*?"([a-z_][a-z_0-9]+)"`)- // Try the strict match first for documentation; fall back to- // the loose one for actual extraction.- _ = codeRE+ // Match the second string literal (the code) on+ // writeJSONError(w, status, "code", ...) or+ // writeJSONErrorWithDetails(w, status, "code", ...). The+ // first arg `w` is an identifier, then a status int or+ // http.StatusXxx selector, so the regex skips past those.+ looseRE := regexp.MustCompile(`writeJSONError(?:WithDetails)?\([^)]*?"([a-z_][a-z_0-9]+)"`)for _, m := range looseRE.FindAllSubmatch(body, -1) {- emitted[string(m[1])] = true+ code := string(m[1])+ if internalOnlyCodes[code] {+ continue+ }+ emitted[code] = true}}if len(emitted) == 0 {diff --git a/internal/api/middleware_tenant.go b/internal/api/middleware_tenant.goindex 332880d8cb..f8909968e2 100644--- a/internal/api/middleware_tenant.go+++ b/internal/api/middleware_tenant.go@@ -211,14 +211,43 @@ func (m *TenantMiddleware) Middleware(next http.Handler) http.Handler {})}-// writeJSONError writes a JSON error response.+// writeJSONError writes the agent-stable error envelope.+//+// The shape is `{"error": "<stable_code>", "message": "<human>"}`,+// in contrast to the platform-wide APIError envelope written by+// writeErrorResponse (where the stable code lives under `code` and+// `error` carries the human message). Agent-surface endpoints emit+// this shape so external agents can branch on the `error` field+// without remembering which envelope a given capability uses.func writeJSONError(w http.ResponseWriter, status int, code, message string) {+ writeJSONErrorWithDetails(w, status, code, message, nil)+}++// writeJSONErrorWithDetails extends writeJSONError with an optional+// `details` map for field-level failure reasons. When non-empty, the+// envelope grows a third top-level `details` field so agents see+// structured per-field reasons (e.g. which body field failed+// validation) without parsing the human message. Empty/nil details+// preserve the two-field shape so the contract for callers that+// don't pass details stays unchanged.+//+// Used by the action endpoints (actions.go) where the platform-wide+// writeErrorResponse calls historically passed a details map; the+// agent-stable envelope now carries the same information at the+// matching key. The pattern lets future agent-surface endpoints+// adopt structured field reasons without growing yet another+// envelope shape.+func writeJSONErrorWithDetails(w http.ResponseWriter, status int, code, message string, details map[string]string) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(status)- json.NewEncoder(w).Encode(map[string]string{+ body := map[string]any{"error": code,"message": message,- })+ }+ if len(details) > 0 {+ body["details"] = details+ }+ _ = json.NewEncoder(w).Encode(body)}// Helper to get OrgID from context