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
Add durable action dispatch continuity
rcourtman71ea14e4dd19
diff --git a/docs/release-control/v6/internal/SOURCE_OF_TRUTH.md b/docs/release-control/v6/internal/SOURCE_OF_TRUTH.mdindex 96f63168f4..b780ae36f6 100644--- a/docs/release-control/v6/internal/SOURCE_OF_TRUTH.md+++ b/docs/release-control/v6/internal/SOURCE_OF_TRUTH.md@@ -216,11 +216,18 @@ boundaries with auditability, and first-class fleet governance.Governed action identity is create-once and lifecycle state is monotonic. Adeterministic replay returns the authoritative persisted record; it cannotreplace approvals, execution results, verification, origin, or terminal state.-Only the store-level compare-and-swap winner that persists the `executing`-transition and its event may admit the executor. This is an exactly-one-admission guarantee, not permission to claim exactly-once external effects-after a process crash; durable effect recovery remains a separately governed-continuity obligation.+Only the store-level compare-and-swap winner that atomically persists the+`executing` transition, lifecycle event, create-once dispatch-attempt identity,+and outbox row may admit transport. Claiming the outbox is not permission to+send: `MarkActionDispatchStarted` is the durable pre-send linearization point.+An expired pre-send claim requeues the same attempt; after that point recovery+may only reconcile the attempt or accept an authenticated correlated receipt,+never blindly resend. A correlated response that carries today's execution+result commits its receipt with the terminal audit and event atomically, so a+crash cannot preserve the receipt while losing the accompanying result. This is+durable transport admission and continuity, not+permission to infer execution, verification, evidence, or compensation truth;+Task 10 remains the sole owner of those terminal semantics.## Evergreen Readiness Assertionsdiff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 251c723bf3..dd3d4798d3 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -4049,7 +4049,8 @@{"repo": "pulse","path": "internal/actionlifecycle/service_test.go",- "kind": "file"+ "kind": "file",+ "evidence_tier": "test-proof"},{"repo": "pulse",@@ -5808,7 +5809,7 @@"status": "partial","completion": {"state": "bounded-residual",- "summary": "Action governance has a first-class governed floor AND the typed action lifecycle is now the only autonomous route for Patrol: investigations run under a core-owned, non-interactive, read-only execution profile and can only emit a side-effect-free typed action proposal (patrol_propose_action), which the shared action lifecycle plans, approves, and executes with plan hashing, remediation locks, plan-drift revalidation, and read-after-write verification. Three policy-authorized verticals are live. Docker/Podman restart is capability-owned low-risk eligible. Agent-managed APT host updates are capability-owned elevated eligible and cross a closed typed host_update protocol with no command, package-selection, removal, or reboot authority; the agent owns metadata refresh, preflight simulation, guarded installation, and post-install simulation, while the audit records verified, failed, or honestly inconclusive outcomes plus reboot-required state. Agent-managed package-cache cleanup is capability-owned low-risk eligible and crosses a separate fingerprint-bound host_storage_cleanup protocol with no command, path, package selector, installed-package removal, or reboot authority; it is available only for meaningful reclaimable bytes on the actual pressured cache filesystem, and the audit verifies the bytes reclaimed. All three require explicit per-resource capability allowlists and optional recurring timezone windows, remain bounded by tenant Patrol mode and full-mode unlock, recheck policy/readiness before decision and dispatch, and record server-owned policy approval plus terminal verification in the same audit trail. Never-auto-remediate, missing/unknown policy, unsupported capabilities, stale/error/empty package or cleanup inventories, cleared storage pressure, dry-run/MFA floors, closed windows, and mode downgrades all fail closed. Action continuity is audit-authoritative: idempotent proposal replay cannot rewind or double-execute a terminal action, callbacks trigger org-scoped re-reads, investigation reads recover missed transitions by trusted origin, desktop and mobile decisions use the canonical /api/actions routes, terminal verification maps honestly onto Patrol findings and push outcomes, and legacy command-shaped history remains inert. Remaining post-RC hardening: broader tenant defaults/inheritance and automation rate budgets, richer dry-run providers, multi-actor approvals, additional package-manager and bounded cleanup providers beyond APT, separately governed reboot orchestration, and a real-lab detect-plan-execute-verify-rollback journey proof.",+ "summary": "Action governance has a first-class governed floor AND the typed action lifecycle is now the only autonomous route for Patrol: investigations run under a core-owned, non-interactive, read-only execution profile and can only emit a side-effect-free typed action proposal (patrol_propose_action), which the shared action lifecycle plans, approves, and executes with plan hashing, remediation locks, plan-drift revalidation, and read-after-write verification. Three policy-authorized verticals are live. Docker/Podman restart is capability-owned low-risk eligible. Agent-managed APT host updates are capability-owned elevated eligible and cross a closed typed host_update protocol with no command, package-selection, removal, or reboot authority; the agent owns metadata refresh, preflight simulation, guarded installation, and post-install simulation, while the audit records verified, failed, or honestly inconclusive outcomes plus reboot-required state. Agent-managed package-cache cleanup is capability-owned low-risk eligible and crosses a separate fingerprint-bound host_storage_cleanup protocol with no command, path, package selector, installed-package removal, or reboot authority; it is available only for meaningful reclaimable bytes on the actual pressured cache filesystem, and the audit verifies the bytes reclaimed. All three require explicit per-resource capability allowlists and optional recurring timezone windows, remain bounded by tenant Patrol mode and full-mode unlock, recheck policy/readiness before decision and dispatch, and record server-owned policy approval plus terminal verification in the same audit trail. Never-auto-remediate, missing/unknown policy, unsupported capabilities, stale/error/empty package or cleanup inventories, cleared storage pressure, dry-run/MFA floors, closed windows, and mode downgrades all fail closed. Action continuity is audit-authoritative and now has a Phase B1 durable transport foundation: execution admission atomically creates the deterministic dispatch attempt/outbox, a one-shot pre-send CAS prevents concurrent duplicate sends, expired pre-send claims safely requeue, post-send uncertainty remains receipt-pending for query-only reconciliation, explicit expiry is durable, and canonical detail plus pending/settled reads are tenant-scoped. Generic transport errors cannot fabricate receipts or terminal truth, legacy executing rows without attempts remain inert, callbacks trigger org-scoped re-reads, investigation reads recover missed transitions by trusted origin, desktop and mobile decisions use the canonical /api/actions routes, terminal verification maps honestly onto Patrol findings and push outcomes, and legacy command-shaped history remains inert. Remaining post-RC hardening includes Task 10-owned terminal execution/verification/evidence/compensation truth before Task 07 Phase B2 compensation and verification-attempt recovery, mobile/relay inbox and push-dedup consumption, broader tenant defaults/inheritance and automation rate budgets, richer dry-run providers, multi-actor approvals, additional package-manager and bounded cleanup providers beyond APT, separately governed reboot orchestration, and a real-lab detect-plan-execute-verify-rollback journey proof.","tracking": [{"kind": "lane-followup",@@ -5927,6 +5928,16 @@"path": "frontend-modern/src/utils/actionAuditPresentation.ts","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/actionlifecycle/service.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/actionlifecycle/service_test.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/agentcontext/resource_context_sections.go",@@ -6043,6 +6054,22 @@"kind": "file","evidence_tier": "test-proof"},+ {+ "repo": "pulse",+ "path": "internal/unifiedresources/action_dispatch.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/unifiedresources/action_dispatch_store.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/unifiedresources/action_dispatch_store_test.go",+ "kind": "file",+ "evidence_tier": "test-proof"+ },{"repo": "pulse","path": "internal/unifiedresources/actions.go",@@ -7536,7 +7563,7 @@},{"id": "action-governance-auditability-post-rc-hardening",- "summary": "Track governed residuals behind the closed canonical mutation registry: Task 07 owns durable delivery/reconnect before Docker update, Docker runtime stop, Kubernetes scale/restart/delete, or native-provider transport can activate; Task 10 owns terminal truth, verification, compensation, and rollback representation; Task 12 owns the final L1/governance verdict and administrative-exception review. Raw model command, file write, arbitrary pod exec, legacy run_command, /api/ai/run-command, and enterprise command remediation are retired with no replacement or executable historical authority.",+ "summary": "Task 07 Phase B1 has landed the core durable delivery/reconnect foundation: transactional action admission plus deterministic attempt/outbox, one-shot pre-send CAS, receipt correlation, explicit expiry, query-only restart reconciliation, and tenant-scoped detail/pending/settled APIs. Phase B2 remains planned after Task 10, which solely owns terminal execution, verification, evidence, compensation, and rollback truth; B2 then owns compensation/verification-attempt recovery plus mobile/relay inbox and push-dedup consumption, with no local workaround for absent core APIs. Task 12 owns the final L1/governance verdict and administrative-exception review. Raw model command, file write, arbitrary pod exec, legacy run_command, /api/ai/run-command, and enterprise command remediation remain retired with no replacement or executable historical authority.","owner": "project-owner","status": "planned","recorded_at": "2026-04-25",diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 7720a2a6db..51c2de0d7d 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -2448,6 +2448,13 @@ and export audit reads alongside the enterprise audit surface. That read pathbelongs to the API and unified-resource contracts, not to lifecycle ownership,so the agent-install and registration lane stays focused on fleet continuityinstead of adopting execution-history persistence as a side effect.+Agent-backed action transports may receive a mutation only after the canonical+lifecycle commits a durable dispatch attempt and crosses its one-shot pre-send+boundary. The transport `request_id` is that attempt identity while the action+or approval field remains the canonical action identity. Timeouts and late+agent responses do not authorize lifecycle-local retry: restart recovery must+reconcile the persisted attempt without resending, and transport receipt state+must not be interpreted as Task 10 execution or verification truth.That shared audit-read path also now requires the dedicated `audit:read`token scope instead of inheriting broader `settings:read` access, solifecycle-adjacent install and registration surfaces cannot regain enterprisediff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 585915b7bd..68a1f86d11 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -891,7 +891,12 @@ wire contract is owned by the Pulse Intelligence agent surface once the routeis advertised there. The exported `agentcapabilities.AgentErrCode*` constantsare the source of those values for both manifest declarations and`internal/api/` handler emissions; local string literals in either layer are-contract drift. Manifest `scope` values are auth-owned vocabulary from+contract drift.+`GET /api/actions` and `GET /api/actions/{id}` use that same shared vocabulary+for invalid view/limit and internal list/detail failures even though those+relay-mobile continuity reads are not separate Assistant tools; their codes+must not drift into handler-local literals or imply Task 10 terminal truth.+Manifest `scope` values are auth-owned vocabulary from`pkg/auth` and must be declared through manifest-local aliases to thoseconstants, not repeated as string literals, so MCP tools and direct HTTP agentsadvertise the same scopes the API authorization layer enforces. Patrol findingdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 761ff27a96..ac02accb5f 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -7292,8 +7292,11 @@ when no session cookie exists, the same request may retain the API-tokenfallback for scoped read access. This prevents first-run token persistence fromsilently converting session administration calls into rejected token calls.-The canonical pending-action surface is `GET /api/actions/pending`; decisions-and execution remain `POST /api/actions/{id}/decision` and+The canonical decision queue remains `GET /api/actions/pending`. Durable inbox+consumers use `GET /api/actions?view=pending|settled`, while+`GET /api/actions/{id}` returns the authoritative audit, lifecycle events,+dispatch attempt, and correlated receipt. Decisions and execution remain+`POST /api/actions/{id}/decision` and`POST /api/actions/{id}/execute`. All three routes are in the relay-mobileinventory and router allowlist, and queue failures use the shared`agentcapabilities` vocabulary. Pending rows are oldest-first and expose the@@ -7309,11 +7312,28 @@ Planning uses atomic `CreateActionAudit` with its initial lifecycle events; itdoes not perform a separate existence read followed by an upsert. Identicalreplay returns the authoritative current plan and disposition, while adeterministic action-ID collision with different stable request, plan hash, or-broker-owned origin fails without a write. Decision, refusal, execution-start,-and execution-result writes are conditional state transitions whose event and-record update commit together. Only the successful execution-start CAS winner-may call the executor; a concurrent or post-restart duplicate returns the-current executing or terminal record without another admission.+broker-owned origin fails without a write. Decision, expiry, refusal,+execution-admission, and execution-result writes are conditional state+transitions. Admission commits the executing record, event, deterministic+dispatch attempt, and outbox together. Only a call-unique lease owner that+crosses the one-shot `MarkActionDispatchStarted` CAS may reach a transport, and+the request carries both action and attempt identity. A crash before that+boundary safely reclaims the same attempt; a timeout, disconnect, cancellation,+or crash afterward remains `executing`/`receipt_pending` and can only use the+callable reconciliation path by attempt ID. Generic executor errors never+synthesize receipts or terminal results. Exact duplicate decisions, executes,+receipts, and resumes return authoritative current state; conflicting, forged,+late, and out-of-order transitions cannot regress state or resend transport.+A correlated response carrying today's existing result shape commits its+receipt and terminal audit/event atomically, eliminating the+receipt-recorded/result-lost crash window without extending Task 10's schema.+Legacy executing rows without an attempt remain readable but inert.++This Task 07 Phase B1 contract intentionally stops at transport continuity.+Task 10 remains sole schema owner for execution, verification, evidence, and+compensation truth. Compensation and verification-attempt recovery, plus+mobile and relay inbox/push-dedup consumption, remain Phase B2 work after Task+10; no mobile or relay-local workaround may compensate for a missing core API.### Canonical mutation planediff --git a/docs/release-control/v6/internal/subsystems/relay-runtime.md b/docs/release-control/v6/internal/subsystems/relay-runtime.mdindex a3d576e7ca..1ae7708223 100644--- a/docs/release-control/v6/internal/subsystems/relay-runtime.md+++ b/docs/release-control/v6/internal/subsystems/relay-runtime.md@@ -134,7 +134,12 @@ creating a `relay:mobile:access` token so Community installs cannot bypassRelay/mobile gating through direct API calls.The mobile relay capability inventory and router allowlist include the-canonical pending-action read, action decision, and action execution routes.+canonical pending-action read, global pending/settled action list, authoritative+action detail, action decision, and action execution routes. These core reads+expose the durable attempt/receipt correlation without moving inbox or push+deduplication into Pulse core; Pulse Mobile and pulse-pro relay consumption+remain Task 07 Phase B2 after Task 10, and no relay-local retry may compensate+for an absent or receipt-pending core action result.Patrol approval pushes use `decide_action` with a canonical action id; terminalpushes distinguish verified, unverified, verification-failed, andexecution-failed outcomes. Relay must not revive `/api/ai/approvals` as a livediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 42b6b57a98..32acefb820 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -1703,6 +1703,12 @@ terminal state, and exactly-one executor admission from the shared lifecycle.They must not retry an `executing` action as a new dispatch after restart;recovery must resolve the existing attempt through the separately governedcontinuity contract.+The shared store materializes that continuity as a transactional dispatch+attempt/outbox and a one-shot pre-send `MarkActionDispatchStarted` boundary.+Storage and recovery consumers may observe action detail, pending/settled+projections, and correlated receipt state, but may not infer restore,+verification, rollback, or compensation truth from those transport-only fields+or create a local retry path when the core attempt is `receipt_pending`.Unified Agent lifecycle fields added to the shared host and connections API areadjacent monitoring/API state only. Applied config fingerprints, updaterdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex e424986dc4..5016793a66 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -61,6 +61,8 @@ temperature, capacity, health, and identity enrichment.24. `internal/unifiedresources/relationships.go`25. `internal/unifiedresources/privacy.go`26. `internal/unifiedresources/actions.go`+26a. `internal/unifiedresources/action_dispatch.go`+26b. `internal/unifiedresources/action_dispatch_store.go`27. `internal/unifiedresources/audit_redaction.go`28. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`29. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`@@ -2898,10 +2900,26 @@ create-or-return-current action identity and monotonic typed transitions; itmust never replace an existing action record merely because an ID collides.SQLite uses insert-on-conflict-do-nothing for creation and conditional stateupdates for transitions, with the lifecycle event committed in the same-transaction. Both stores treat rejected, completed, and failed states as+transaction. Both stores treat rejected, explicitly expired, completed, and failed states asabsorbing and admit exactly one successful transition to executing. Lifecycleevents are unique per action and state, with migration deduplication for rowswritten before this invariant became database-enforced.+Execution admission commits the audit transition and lifecycle event with one+deterministic `ActionDispatchAttempt` and its outbox row in the same+transaction. Transport states are deliberately limited to `queued`, `claimed`,+`receipt_pending`, and `receipt_recorded`; they do not encode Task 10 execution,+verification, evidence, or compensation truth. An expired claim before+`MarkActionDispatchStarted` requeues the same attempt. That one-shot CAS is the+sole pre-send linearization point, increments `dispatchCount`, and removes the+outbox row. Once reached, restart recovery may accept only a correlated receipt+or query a transport reconciler by attempt ID; it cannot claim or send again.+When a correlated response includes the existing `ExecutionResult`, SQLite and+MemoryStore commit the receipt, `receipt_recorded` attempt, terminal audit, and+lifecycle event atomically. Standalone callbacks without a result remain+transport-only receipts and do not invent terminal truth.+Queued, claimed, forged, conflicting, duplicate, late, and out-of-order receipt+handling is monotonic and tenant-scoped, and the in-memory store mirrors the+SQLite crash-boundary behavior.It also mirrors the durable decision contract: approval/rejection writes musttarget an existing pending action and must fail rather than creating adecision-only record or overwriting an already decided action.diff --git a/internal/actionlifecycle/dispatch_context.go b/internal/actionlifecycle/dispatch_context.gonew file mode 100644index 0000000000..243dd4f610--- /dev/null+++ b/internal/actionlifecycle/dispatch_context.go@@ -0,0 +1,27 @@+package actionlifecycle++import (+ "context"++ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++type dispatchAttemptContextKey struct{}++func withDispatchAttempt(ctx context.Context, attempt unified.ActionDispatchAttempt) context.Context {+ return context.WithValue(ctx, dispatchAttemptContextKey{}, attempt)+}++// ContextWithCommittedDispatchAttempt is exposed for executor conformance+// tests and transport adapters. Production callers must obtain attempt from a+// successful lifecycle-store admission before using it.+func ContextWithCommittedDispatchAttempt(ctx context.Context, attempt unified.ActionDispatchAttempt) context.Context {+ return withDispatchAttempt(ctx, attempt)+}++// DispatchAttemptFromContext returns the committed transport authority for an+// executor call. Executors must use its ID as the transport request identity.+func DispatchAttemptFromContext(ctx context.Context) (unified.ActionDispatchAttempt, bool) {+ attempt, ok := ctx.Value(dispatchAttemptContextKey{}).(unified.ActionDispatchAttempt)+ return attempt, ok+}diff --git a/internal/actionlifecycle/service.go b/internal/actionlifecycle/service.goindex d2805e36db..e0677cc5e0 100644--- a/internal/actionlifecycle/service.go+++ b/internal/actionlifecycle/service.go@@ -14,6 +14,7 @@ import ("fmt""strings""sync"+ "sync/atomic""time""github.com/rcourtman/pulse-go-rewrite/internal/actionplanner"@@ -26,6 +27,13 @@ type Executor interface {ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error)}+// DispatchReconciler queries a transport by durable attempt identity. It must+// never send or re-send the mutation. found is true only for an authenticated,+// correlated transport response.+type DispatchReconciler interface {+ ReconcileActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (result *unified.ExecutionResult, receipt unified.ActionDispatchReceipt, found bool, err error)+}+// AvailabilityChecker lets an executor contribute live readiness checks// before Pulse advertises or persists an executable action plan.type AvailabilityChecker interface {@@ -39,12 +47,25 @@ type Store interface {CreateActionAudit(record unified.ActionAuditRecord, initialEvents []unified.ActionLifecycleEvent) (unified.ActionAuditRecord, bool, error)GetActionAudit(actionID string) (unified.ActionAuditRecord, bool, error)RecordActionDecision(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) error+ RecordActionExpiry(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) errorRecordActionExecutionStart(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) errorRecordActionPolicyExecutionStart(record unified.ActionAuditRecord, approvalEvent, executionEvent unified.ActionLifecycleEvent) error+ RecordActionExecutionAdmission(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent, attempt unified.ActionDispatchAttempt) error+ RecordActionPolicyExecutionAdmission(record unified.ActionAuditRecord, approvalEvent, executionEvent unified.ActionLifecycleEvent, attempt unified.ActionDispatchAttempt) errorRecordActionExecutionResult(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) errorRecordActionExecutionRefusal(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) errorRecordActionLifecycleEvent(event unified.ActionLifecycleEvent) errorGetActionLifecycleEvents(actionID string, since time.Time, limit int) ([]unified.ActionLifecycleEvent, error)+ GetActionDispatchAttempt(actionID string) (unified.ActionDispatchAttempt, bool, error)+ GetActionDispatchReceipt(attemptID string) (unified.ActionDispatchReceipt, bool, error)+ ClaimActionDispatch(actionID, owner string, now time.Time, lease time.Duration) (unified.ActionDispatchAttempt, bool, error)+ MarkActionDispatchStarted(attemptID, owner string, now time.Time) (unified.ActionDispatchAttempt, error)+ RecordActionDispatchReceipt(receipt unified.ActionDispatchReceipt) (unified.ActionDispatchAttempt, error)+ RecordActionDispatchCompletion(receipt unified.ActionDispatchReceipt, record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) error+ RecoverActionDispatch(actionID string, now time.Time) (unified.ActionDispatchAttempt, bool, error)+ ExpireActionAudits(now time.Time, limit int) ([]unified.ActionAuditRecord, error)+ GetActionAuditsByStates(states []unified.ActionState, limit int) ([]unified.ActionAuditRecord, error)+ GetPendingActionAudits(limit int) ([]unified.ActionAuditRecord, error)GetResourceOperatorState(canonicalID string) (unified.ResourceOperatorState, bool, error)}@@ -74,8 +95,24 @@ type Service struct {PolicyAdmission *PolicyAdmissionCoordinator}+type ActionDetail struct {+ Audit unified.ActionAuditRecord `json:"audit"`+ Events []unified.ActionLifecycleEvent `json:"events"`+ Attempt *unified.ActionDispatchAttempt `json:"attempt,omitempty"`+ Receipt *unified.ActionDispatchReceipt `json:"receipt,omitempty"`+}++type ActionListView string++const (+ ActionListPending ActionListView = "pending"+ ActionListSettled ActionListView = "settled"+)+type PolicyAdmissionCoordinator struct{ mu sync.RWMutex }+var dispatchWorkerSequence atomic.Uint64+func (s *Service) admissionCoordinator() *PolicyAdmissionCoordinator {if s.PolicyAdmission == nil {s.PolicyAdmission = &PolicyAdmissionCoordinator{}@@ -315,7 +352,85 @@ func (s *Service) Get(orgID, actionID string) (unified.ActionAuditRecord, bool,if err != nil {return unified.ActionAuditRecord{}, false, &QueryError{Op: "action audit", Err: err}}- return record, found, nil+ if !found {+ return record, false, nil+ }+ record, err = s.materializeExpiry(store, orgID, record)+ if err != nil {+ return unified.ActionAuditRecord{}, false, err+ }+ return record, true, nil+}++// Detail returns the authoritative lifecycle record together with its durable+// transport correlation. It never infers result truth from dispatch state.+func (s *Service) Detail(orgID, actionID string) (ActionDetail, bool, error) {+ record, found, err := s.Get(orgID, actionID)+ if err != nil || !found {+ return ActionDetail{}, found, err+ }+ store, err := s.store(orgID)+ if err != nil {+ return ActionDetail{}, false, err+ }+ events, err := store.GetActionLifecycleEvents(record.ID, time.Time{}, 500)+ if err != nil {+ return ActionDetail{}, false, &QueryError{Op: "action lifecycle events", Err: err}+ }+ detail := ActionDetail{Audit: record, Events: events}+ if attempt, ok, queryErr := store.GetActionDispatchAttempt(record.ID); queryErr != nil {+ return ActionDetail{}, false, &QueryError{Op: "action dispatch attempt", Err: queryErr}+ } else if ok {+ detail.Attempt = &attempt+ if receipt, receiptOK, receiptErr := store.GetActionDispatchReceipt(attempt.ID); receiptErr != nil {+ return ActionDetail{}, false, &QueryError{Op: "action dispatch receipt", Err: receiptErr}+ } else if receiptOK {+ detail.Receipt = &receipt+ }+ }+ return detail, true, nil+}++// List returns the canonical pending or settled inbox projection.+func (s *Service) List(orgID string, view ActionListView, limit int) ([]unified.ActionAuditRecord, error) {+ store, err := s.store(orgID)+ if err != nil {+ return nil, err+ }+ if _, err := store.ExpireActionAudits(s.now(), 500); err != nil {+ return nil, &PersistError{Op: "action expiry sweep", Err: err}+ }+ var states []unified.ActionState+ switch view {+ case ActionListPending:+ states = []unified.ActionState{unified.ActionStatePlanned, unified.ActionStatePending, unified.ActionStateApproved, unified.ActionStateExecuting}+ case ActionListSettled:+ states = []unified.ActionState{unified.ActionStateRejected, unified.ActionStateExpired, unified.ActionStateCompleted, unified.ActionStateFailed}+ default:+ return nil, fmt.Errorf("unsupported action list view %q", view)+ }+ records, err := store.GetActionAuditsByStates(states, limit)+ if err != nil {+ return nil, &QueryError{Op: "action inbox", Err: err}+ }+ return records, nil+}++// DecisionQueue preserves the legacy oldest-first pending-approval projection+// while sharing the canonical expiry sweep.+func (s *Service) DecisionQueue(orgID string, limit int) ([]unified.ActionAuditRecord, error) {+ store, err := s.store(orgID)+ if err != nil {+ return nil, err+ }+ if _, err := store.ExpireActionAudits(s.now(), 500); err != nil {+ return nil, &PersistError{Op: "action expiry sweep", Err: err}+ }+ records, err := store.GetPendingActionAudits(limit)+ if err != nil {+ return nil, &QueryError{Op: "pending action queue", Err: err}+ }+ return records, nil}// ResourceOperatorState returns the authoritative per-resource policy used by@@ -425,6 +540,13 @@ func (s *Service) Decide(ctx context.Context, orgID, actionID string, approval uif !ok {return unified.ActionAuditRecord{}, &ActionNotFoundError{ActionID: actionID}}+ record, err = s.materializeExpiry(store, orgID, record)+ if err != nil {+ return unified.ActionAuditRecord{}, err+ }+ if record.State == unified.ActionStateExpired {+ return record, unified.ErrActionPlanExpired+ }if record.State != unified.ActionStatePending {for _, existing := range record.Approvals {if existing.Outcome == approval.Outcome {@@ -482,11 +604,21 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason stif !ok {return unified.ActionAuditRecord{}, &ActionNotFoundError{ActionID: actionID}}- if record.State == unified.ActionStateExecuting || record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed {+ if record.State == unified.ActionStateExecuting {+ return s.dispatchCommitted(ctx, orgID, store, record, actor)+ }+ if record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed {return record, nil}now := s.now()+ record, err = s.materializeExpiry(store, orgID, record)+ if err != nil {+ return unified.ActionAuditRecord{}, err+ }+ if record.State == unified.ActionStateExpired {+ return record, unified.ErrActionPlanExpired+ }if stopped, stopErr := s.emergencyStopped(orgID); stopErr != nil || stopped {if stopErr != nil {return unified.ActionAuditRecord{}, &PolicyCheckError{Err: stopErr}@@ -546,31 +678,24 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason stif reason != "" {startEvent.Message = "Action execution started: " + reason}- if err := store.RecordActionExecutionStart(started, startEvent); err != nil {+ attempt, err := unified.NewActionDispatchAttempt(started.ID, now)+ if err != nil {+ return unified.ActionAuditRecord{}, err+ }+ if err := store.RecordActionExecutionAdmission(started, startEvent, attempt); err != nil {if errors.Is(err, unified.ErrActionAlreadyExecuting) || errors.Is(err, unified.ErrActionExecutionFinal) {current, found, queryErr := store.GetActionAudit(actionID)if queryErr == nil && found {+ if current.State == unified.ActionStateExecuting {+ return s.dispatchCommitted(ctx, orgID, store, current, actor)+ }return current, nil}}return unified.ActionAuditRecord{}, &PersistError{Op: "action execution start", Err: err}}s.publishTransition(orgID, started)-- result, execErr := s.Executor.ExecuteAction(ctx, started)- if execErr != nil {- result = &unified.ExecutionResult{Success: false, ErrorMessage: execErr.Error()}- }- completed, doneEvent, err := unified.CompleteActionExecution(started, result, actor, s.now())- if err != nil {- return unified.ActionAuditRecord{}, err- }- if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {- return unified.ActionAuditRecord{}, &PersistError{Op: "action execution result", Err: err}- }- s.publishTransition(orgID, completed)- s.publishCompleted(completed)- return completed, nil+ return s.dispatchCommitted(ctx, orgID, store, started, actor)}// ExecuteUnderPolicy is the only automatic dispatch boundary. It revalidates@@ -584,23 +709,7 @@ func (s *Service) ExecuteUnderPolicy(ctx context.Context, orgID, actionID, actorif !admitted {return started, admissionErr}- // The executing transition is the authorization linearization point.- // Later emergency-stop changes may request best-effort cancellation but- // cannot claim that an external mutation was rolled back.- result, execErr := s.Executor.ExecuteAction(ctx, started)- if execErr != nil {- result = &unified.ExecutionResult{Success: false, ErrorMessage: execErr.Error()}- }- completed, doneEvent, err := unified.CompleteActionExecution(started, result, actor, s.now())- if err != nil {- return unified.ActionAuditRecord{}, err- }- if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {- return unified.ActionAuditRecord{}, &PersistError{Op: "action execution result", Err: err}- }- s.publishTransition(orgID, completed)- s.publishCompleted(completed)- return completed, nil+ return s.dispatchCommitted(ctx, orgID, store, started, actor)}func (s *Service) beginPolicyExecution(ctx context.Context, orgID, actionID, actor string, authorize PolicyAuthorizer) (unified.ActionAuditRecord, Store, bool, error) {@@ -616,10 +725,20 @@ func (s *Service) beginPolicyExecution(ctx context.Context, orgID, actionID, actif !found {return unified.ActionAuditRecord{}, store, false, &ActionNotFoundError{ActionID: actionID}}- if record.State == unified.ActionStateExecuting || record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed {+ if record.State == unified.ActionStateExecuting {+ return record, store, true, nil+ }+ if record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed {return record, store, false, nil}now := s.now()+ record, err = s.materializeExpiry(store, orgID, record)+ if err != nil {+ return unified.ActionAuditRecord{}, store, false, err+ }+ if record.State == unified.ActionStateExpired {+ return record, store, false, unified.ErrActionPlanExpired+ }if record.State == unified.ActionStateApproved {for _, approval := range record.Approvals {if approval.Method == unified.MethodPolicy && approval.PolicyLease == nil {@@ -671,7 +790,11 @@ func (s *Service) beginPolicyExecution(ctx context.Context, orgID, actionID, actfailed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, err)return failed, store, false, refuseErr}- if err := store.RecordActionPolicyExecutionStart(started, approvedEvent, startEvent); err != nil {+ attempt, err := unified.NewActionDispatchAttempt(started.ID, now)+ if err != nil {+ return unified.ActionAuditRecord{}, store, false, err+ }+ if err := store.RecordActionPolicyExecutionAdmission(started, approvedEvent, startEvent, attempt); err != nil {if errors.Is(err, unified.ErrActionAlreadyExecuting) || errors.Is(err, unified.ErrActionExecutionFinal) {current, ok, queryErr := store.GetActionAudit(actionID)if queryErr == nil && ok {@@ -684,6 +807,140 @@ func (s *Service) beginPolicyExecution(ctx context.Context, orgID, actionID, actreturn started, store, true, nil}+func (s *Service) materializeExpiry(store Store, orgID string, record unified.ActionAuditRecord) (unified.ActionAuditRecord, error) {+ if record.State == unified.ActionStateExpired || record.State == unified.ActionStateExecuting || record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed || record.State == unified.ActionStateRejected {+ return record, nil+ }+ now := s.now()+ if record.Plan.ExpiresAt.IsZero() || now.Before(record.Plan.ExpiresAt) {+ return record, nil+ }+ expired, event, err := unified.ExpireAction(record, "system:expiry", now)+ if err != nil {+ return unified.ActionAuditRecord{}, err+ }+ if err := store.RecordActionExpiry(expired, event); err != nil {+ current, found, queryErr := store.GetActionAudit(record.ID)+ if queryErr == nil && found {+ return current, nil+ }+ return unified.ActionAuditRecord{}, &PersistError{Op: "action expiry", Err: err}+ }+ s.publishTransition(orgID, expired)+ return expired, nil+}++func (s *Service) dispatchCommitted(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, actor string) (unified.ActionAuditRecord, error) {+ attempt, found, err := store.GetActionDispatchAttempt(record.ID)+ if err != nil {+ return unified.ActionAuditRecord{}, &QueryError{Op: "action dispatch attempt", Err: err}+ }+ if !found {+ // Legacy executing rows predate durable dispatch authority. They must+ // remain observable, but can never be readmitted or blindly resent.+ return record, nil+ }+ if attempt.State == unified.ActionDispatchReceiptPending || attempt.State == unified.ActionDispatchReceiptRecorded {+ return s.reconcileCommitted(ctx, orgID, store, record, attempt, actor)+ }+ owner := fmt.Sprintf("action-lifecycle:%s:%d", attempt.ID, dispatchWorkerSequence.Add(1))+ attempt, claimed, err := store.ClaimActionDispatch(record.ID, owner, s.now(), 30*time.Second)+ if err != nil {+ return unified.ActionAuditRecord{}, &PersistError{Op: "action dispatch claim", Err: err}+ }+ if !claimed {+ return record, nil+ }+ attempt, err = store.MarkActionDispatchStarted(attempt.ID, owner, s.now())+ if err != nil {+ return unified.ActionAuditRecord{}, &PersistError{Op: "action dispatch start", Err: err}+ }+ result, execErr := s.Executor.ExecuteAction(withDispatchAttempt(ctx, attempt), record)+ if execErr != nil {+ // A timeout, disconnect, cancellation, or generic executor error is not+ // proof that the transport answered. Preserve receipt_pending so a+ // reconciler can query by attempt ID without resending.+ return record, execErr+ }+ receipt := unified.ActionDispatchReceipt{+ AttemptID: attempt.ID, ActionID: record.ID, TransportRequestID: attempt.ID, ReceivedAt: s.now(),+ }+ return s.completeCorrelatedDispatch(orgID, store, record, receipt, result, actor)+}++func (s *Service) reconcileCommitted(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt, actor string) (unified.ActionAuditRecord, error) {+ reconciler, ok := s.Executor.(DispatchReconciler)+ if !ok {+ return record, nil+ }+ result, receipt, found, err := reconciler.ReconcileActionDispatch(ctx, record, attempt)+ if err != nil || !found {+ return record, err+ }+ if receipt.AttemptID == "" {+ receipt = unified.ActionDispatchReceipt{AttemptID: attempt.ID, ActionID: record.ID, TransportRequestID: attempt.ID, ReceivedAt: s.now()}+ }+ if receipt.AttemptID != attempt.ID || receipt.ActionID != record.ID {+ return unified.ActionAuditRecord{}, unified.ErrActionDispatchReceiptConflict+ }+ return s.completeCorrelatedDispatch(orgID, store, record, receipt, result, actor)+}++func (s *Service) completeCorrelatedDispatch(orgID string, store Store, record unified.ActionAuditRecord, receipt unified.ActionDispatchReceipt, result *unified.ExecutionResult, actor string) (unified.ActionAuditRecord, error) {+ completed, doneEvent, err := unified.CompleteActionExecution(record, result, actor, s.now())+ if err != nil {+ return unified.ActionAuditRecord{}, err+ }+ if err := store.RecordActionDispatchCompletion(receipt, completed, doneEvent); err != nil {+ if errors.Is(err, unified.ErrActionExecutionFinal) {+ if current, found, queryErr := store.GetActionAudit(record.ID); queryErr == nil && found {+ return current, nil+ }+ }+ return unified.ActionAuditRecord{}, &PersistError{Op: "correlated action dispatch completion", Err: err}+ }+ s.publishTransition(orgID, completed)+ s.publishCompleted(completed)+ return completed, nil+}++// RecordDispatchReceipt persists a late authenticated callback correlation.+// It does not infer or mutate terminal execution truth.+func (s *Service) RecordDispatchReceipt(orgID string, receipt unified.ActionDispatchReceipt) (unified.ActionDispatchAttempt, error) {+ store, err := s.store(orgID)+ if err != nil {+ return unified.ActionDispatchAttempt{}, err+ }+ attempt, err := store.RecordActionDispatchReceipt(receipt)+ if err != nil {+ return unified.ActionDispatchAttempt{}, &PersistError{Op: "late action dispatch receipt", Err: err}+ }+ return attempt, nil+}++// RecoverExecutingActions drives restart recovery without blind re-execution.+// Queued or pre-send expired claims may dispatch once; post-start attempts are+// reconciled by durable attempt identity only.+func (s *Service) RecoverExecutingActions(ctx context.Context, orgID, actor string, limit int) ([]unified.ActionAuditRecord, error) {+ store, err := s.store(orgID)+ if err != nil {+ return nil, err+ }+ records, err := store.GetActionAuditsByStates([]unified.ActionState{unified.ActionStateExecuting}, limit)+ if err != nil {+ return nil, &QueryError{Op: "executing action recovery", Err: err}+ }+ recovered := make([]unified.ActionAuditRecord, 0, len(records))+ for _, record := range records {+ current, recoverErr := s.dispatchCommitted(ctx, orgID, store, record, actor)+ if recoverErr != nil {+ continue+ }+ recovered = append(recovered, current)+ }+ return recovered, nil+}+func (s *Service) emergencyStopped(orgID string) (bool, error) {if s == nil || s.EmergencyStop == nil {return false, nildiff --git a/internal/actionlifecycle/service_test.go b/internal/actionlifecycle/service_test.goindex 13b0a80014..1ad5b313c3 100644--- a/internal/actionlifecycle/service_test.go+++ b/internal/actionlifecycle/service_test.go@@ -32,6 +32,22 @@ type blockingExecutor struct {release chan struct{}}+type claimBoundaryStore struct {+ unified.ResourceStore+ entered chan struct{}+ release chan struct{}+ once atomic.Bool+}++func (s *claimBoundaryStore) ClaimActionDispatch(actionID, owner string, now time.Time, lease time.Duration) (unified.ActionDispatchAttempt, bool, error) {+ attempt, claimed, err := s.ResourceStore.ClaimActionDispatch(actionID, owner, now, lease)+ if claimed && s.once.CompareAndSwap(false, true) {+ close(s.entered)+ <-s.release+ }+ return attempt, claimed, err+}+func (e *blockingExecutor) ExecuteAction(_ context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {if e.calls.Add(1) == 1 {close(e.entered)@@ -138,6 +154,47 @@ func TestConcurrentExecuteAdmitsExecutorExactlyOnceSQLiteStore(t *testing.T) {runConcurrentExecuteAdmitsExecutorExactlyOnce(t, store)}+func runConcurrentDuplicateExecuteAtClaimBoundaryCallsExecutorOnce(t *testing.T, store unified.ResourceStore) {+ t.Helper()+ blocked := &claimBoundaryStore{ResourceStore: store, entered: make(chan struct{}), release: make(chan struct{})}+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}}+ service := serviceForStore(t, blocked, testResource(time.Now().UTC(), unified.ApprovalNone), executor)+ plan, err := service.Plan(context.Background(), "default", restartRequest())+ if err != nil {+ t.Fatal(err)+ }+ first := make(chan error, 1)+ go func() {+ _, executeErr := service.Execute(context.Background(), "default", plan.ActionID, "operator", "first")+ first <- executeErr+ }()+ <-blocked.entered+ second, err := service.Execute(context.Background(), "default", plan.ActionID, "operator", "duplicate")+ if err != nil || second.State != unified.ActionStateExecuting {+ t.Fatalf("duplicate=%#v err=%v", second, err)+ }+ close(blocked.release)+ if err := <-first; err != nil {+ t.Fatal(err)+ }+ if executor.calls != 1 {+ t.Fatalf("executor calls=%d, want 1", executor.calls)+ }+}++func TestMemoryStoreConcurrentDuplicateExecuteAtClaimBoundaryCallsExecutorOnce(t *testing.T) {+ runConcurrentDuplicateExecuteAtClaimBoundaryCallsExecutorOnce(t, unified.NewMemoryStore())+}++func TestSQLiteConcurrentDuplicateExecuteAtClaimBoundaryCallsExecutorOnce(t *testing.T) {+ store, err := unified.NewSQLiteResourceStore(t.TempDir(), "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ runConcurrentDuplicateExecuteAtClaimBoundaryCallsExecutorOnce(t, store)+}+func TestPlanReplayReturnsAuthoritativeApprovedExecutingAndTerminalRecords(t *testing.T) {states := []unified.ActionState{unified.ActionStateApproved, unified.ActionStateExecuting, unified.ActionStateRejected, unified.ActionStateCompleted, unified.ActionStateFailed}for _, state := range states {@@ -253,6 +310,109 @@ func TestExecuteAfterSQLiteRestartDoesNotReadmitExecutingAction(t *testing.T) {}}+func TestExecuteTimeoutAfterSendWaitsForCorrelatedLateResponseWithoutResend(t *testing.T) {+ store := unified.NewMemoryStore()+ executor := &reconcilingExecutor{executeErr: context.DeadlineExceeded, result: &unified.ExecutionResult{Success: true}}+ service := serviceForStore(t, store, testResource(time.Now().UTC(), unified.ApprovalNone), executor)+ plan, err := service.Plan(context.Background(), "default", restartRequest())+ if err != nil {+ t.Fatal(err)+ }+ current, err := service.Execute(context.Background(), "default", plan.ActionID, "operator", "timeout proof")+ if !errors.Is(err, context.DeadlineExceeded) || current.State != unified.ActionStateExecuting {+ t.Fatalf("current=%#v err=%v", current, err)+ }+ attempt, found, err := store.GetActionDispatchAttempt(plan.ActionID)+ if err != nil || !found || attempt.State != unified.ActionDispatchReceiptPending || attempt.DispatchCount != 1 {+ t.Fatalf("attempt=%#v found=%v err=%v", attempt, found, err)+ }+ if _, found, err := store.GetActionDispatchReceipt(attempt.ID); err != nil || found {+ t.Fatalf("receipt found=%v err=%v", found, err)+ }+ // Duplicate execute is a query-only resume and cannot call ExecuteAction.+ current, err = service.Execute(context.Background(), "default", plan.ActionID, "operator", "duplicate resume")+ if err != nil || current.State != unified.ActionStateExecuting || executor.executeCalls != 1 || executor.reconcileCalls != 1 {+ t.Fatalf("current=%#v err=%v execute=%d reconcile=%d", current, err, executor.executeCalls, executor.reconcileCalls)+ }+ executor.found = true+ current, err = service.Execute(context.Background(), "default", plan.ActionID, "operator", "late response")+ if err != nil || current.State != unified.ActionStateCompleted || executor.executeCalls != 1 || executor.reconcileCalls != 2 {+ t.Fatalf("current=%#v err=%v execute=%d reconcile=%d", current, err, executor.executeCalls, executor.reconcileCalls)+ }+ if receipt, found, err := store.GetActionDispatchReceipt(attempt.ID); err != nil || !found || receipt.AttemptID != attempt.ID {+ t.Fatalf("receipt=%#v found=%v err=%v", receipt, found, err)+ }+}++func TestSQLiteRestartRecoveryReconcilesReceiptPendingWithoutResend(t *testing.T) {+ dir := t.TempDir()+ now := time.Now().UTC()+ first, err := unified.NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ executor := &reconcilingExecutor{executeErr: context.DeadlineExceeded, result: &unified.ExecutionResult{Success: true}}+ service := serviceForStore(t, first, testResource(now, unified.ApprovalNone), executor)+ plan, err := service.Plan(context.Background(), "default", restartRequest())+ if err != nil {+ t.Fatal(err)+ }+ if _, err := service.Execute(context.Background(), "default", plan.ActionID, "operator", "before restart"); !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("Execute error=%v", err)+ }+ if err := first.Close(); err != nil {+ t.Fatal(err)+ }+ second, err := unified.NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ defer second.Close()+ executor.found = true+ service = serviceForStore(t, second, testResource(now, unified.ApprovalNone), executor)+ recovered, err := service.RecoverExecutingActions(context.Background(), "default", "system:restart-recovery", 100)+ if err != nil || len(recovered) != 1 || recovered[0].State != unified.ActionStateCompleted {+ t.Fatalf("recovered=%#v err=%v", recovered, err)+ }+ if executor.executeCalls != 1 || executor.reconcileCalls != 1 {+ t.Fatalf("execute=%d reconcile=%d", executor.executeCalls, executor.reconcileCalls)+ }+ current, err := service.Execute(context.Background(), "default", plan.ActionID, "operator", "duplicate after recovery")+ if err != nil || current.State != unified.ActionStateCompleted || executor.executeCalls != 1 {+ t.Fatalf("current=%#v err=%v execute=%d", current, err, executor.executeCalls)+ }+}++func TestActionDetailAndInboxMaterializeExplicitExpiry(t *testing.T) {+ now := time.Date(2026, 7, 11, 14, 0, 0, 0, time.UTC)+ store := unified.NewMemoryStore()+ service := serviceForStore(t, store, testResource(now, unified.ApprovalAdmin), &stubExecutor{})+ service.Now = func() time.Time { return now }+ plan, err := service.Plan(context.Background(), "default", restartRequest())+ if err != nil {+ t.Fatal(err)+ }+ service.Now = func() time.Time { return plan.ExpiresAt.Add(time.Second) }+ detail, found, err := service.Detail("default", plan.ActionID)+ if err != nil || !found || detail.Audit.State != unified.ActionStateExpired {+ t.Fatalf("detail=%#v found=%v err=%v", detail, found, err)+ }+ if len(detail.Events) == 0 || detail.Events[0].State != unified.ActionStateExpired {+ t.Fatalf("events=%#v", detail.Events)+ }+ pending, err := service.List("default", ActionListPending, 100)+ if err != nil || len(pending) != 0 {+ t.Fatalf("pending=%#v err=%v", pending, err)+ }+ settled, err := service.List("default", ActionListSettled, 100)+ if err != nil || len(settled) != 1 || settled[0].State != unified.ActionStateExpired {+ t.Fatalf("settled=%#v err=%v", settled, err)+ }+ if _, err := service.Decide(context.Background(), "default", plan.ActionID, unified.ActionApprovalRecord{Actor: "operator", Outcome: unified.OutcomeApproved}); !errors.Is(err, unified.ErrActionPlanExpired) {+ t.Fatalf("Decide error=%v", err)+ }+}+func policyTestLease(record unified.ActionAuditRecord, now time.Time) unified.ActionPolicyAuthorizationLease {lease := unified.ActionPolicyAuthorizationLease{Version: 1, OrgID: "default", ActionID: record.ID, ResourceID: record.Request.ResourceID,@@ -564,6 +724,29 @@ type stubExecutor struct {readiness *unified.ResourceActionReadiness}+type reconcilingExecutor struct {+ executeCalls int+ reconcileCalls int+ executeErr error+ found bool+ result *unified.ExecutionResult+}++func (e *reconcilingExecutor) ExecuteAction(_ context.Context, _ unified.ActionAuditRecord) (*unified.ExecutionResult, error) {+ e.executeCalls+++ return nil, e.executeErr+}++func (e *reconcilingExecutor) ReconcileActionDispatch(_ context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {+ e.reconcileCalls+++ if !e.found {+ return nil, unified.ActionDispatchReceipt{}, false, nil+ }+ return e.result, unified.ActionDispatchReceipt{+ AttemptID: attempt.ID, ActionID: record.ID, TransportRequestID: attempt.ID, ReceivedAt: time.Now().UTC(),+ }, true, nil+}+func (s *stubExecutor) ExecuteAction(_ context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {s.calls++s.received = recorddiff --git a/internal/agentcapabilities/errors.go b/internal/agentcapabilities/errors.goindex 48e7ab217b..f0d4d9c694 100644--- a/internal/agentcapabilities/errors.go+++ b/internal/agentcapabilities/errors.go@@ -32,6 +32,12 @@ const (AgentErrCodeActionQueueUnavailable = "action_queue_unavailable"AgentErrCodeActionQueueQueryFailed = "action_queue_query_failed"AgentErrCodeActionQueueEncodeFailed = "action_queue_encode_failed"+ AgentErrCodeInvalidActionListLimit = "invalid_action_list_limit"+ AgentErrCodeInvalidActionListView = "invalid_action_list_view"+ AgentErrCodeActionListFailed = "action_list_failed"+ AgentErrCodeActionListEncodeFailed = "action_list_encode_failed"+ AgentErrCodeActionDetailFailed = "action_detail_failed"+ AgentErrCodeActionDetailEncodeFailed = "action_detail_encode_failed"AgentErrCodeRawCommandRetired = "raw_command_retired")diff --git a/internal/api/action_dispatch_test.go b/internal/api/action_dispatch_test.gonew file mode 100644index 0000000000..513a5adbd1--- /dev/null+++ b/internal/api/action_dispatch_test.go@@ -0,0 +1,19 @@+package api++import (+ "context"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++func actionDispatchTestContext(t *testing.T, actionID string) context.Context {+ t.Helper()+ attempt, err := unified.NewActionDispatchAttempt(actionID, time.Now())+ if err != nil {+ t.Fatalf("NewActionDispatchAttempt: %v", err)+ }+ return actionlifecycle.ContextWithCommittedDispatchAttempt(context.Background(), attempt)+}diff --git a/internal/api/actions.go b/internal/api/actions.goindex 8286482511..7984ebda34 100644--- a/internal/api/actions.go+++ b/internal/api/actions.go@@ -5,6 +5,7 @@ import ("errors""io""net/http"+ "strconv""strings""github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"@@ -55,6 +56,12 @@ type pendingActionsResponse struct {Count int `json:"count"`}+type actionInboxResponse struct {+ View actionlifecycle.ActionListView `json:"view"`+ Actions []unified.ActionAuditRecord `json:"actions"`+ Count int `json:"count"`+}+// ActionLifecycle returns the shared transport-independent action lifecycle// service bound to this handler set's registry, store, executor, and// completion publisher. The REST handlers below and any in-process broker@@ -116,17 +123,7 @@ func (h *ResourceHandlers) HandleListPendingActions(w http.ResponseWriter, r *hthttp.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- store, err := h.getStore(GetOrgID(r.Context()))- if err != nil || store == nil {- writeJSONError(w, http.StatusServiceUnavailable, "action_audit_unavailable", "Action decision queue is not available")- return- }- reader, ok := store.(unified.PendingActionAuditReader)- if !ok {- writeJSONError(w, http.StatusServiceUnavailable, agentcapabilities.AgentErrCodeActionQueueUnavailable, "Action decision queue is not available")- return- }- actions, err := reader.GetPendingActionAudits(maxPendingActionAudits)+ actions, err := h.ActionLifecycle().DecisionQueue(GetOrgID(r.Context()), maxPendingActionAudits)if err != nil {writeJSONError(w, http.StatusInternalServerError, agentcapabilities.AgentErrCodeActionQueueQueryFailed, "Failed to query pending actions")return@@ -140,6 +137,65 @@ func (h *ResourceHandlers) HandleListPendingActions(w http.ResponseWriter, r *ht}}+// HandleListActions returns the global active or settled action projection.+func (h *ResourceHandlers) HandleListActions(w http.ResponseWriter, r *http.Request) {+ view := actionlifecycle.ActionListView(strings.TrimSpace(r.URL.Query().Get("view")))+ if view == "" {+ view = actionlifecycle.ActionListPending+ }+ limit := maxPendingActionAudits+ if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" {+ parsed, err := strconv.Atoi(raw)+ if err != nil || parsed < 1 || parsed > 500 {+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionListLimit, "Action list limit must be between 1 and 500")+ return+ }+ limit = parsed+ }+ actions, err := h.ActionLifecycle().List(GetOrgID(r.Context()), view, limit)+ if err != nil {+ if strings.Contains(err.Error(), "unsupported action list view") {+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionListView, "Action list view must be pending or settled")+ return+ }+ writeActionLifecycleReadError(w, err, func() {+ writeJSONError(w, http.StatusInternalServerError, agentcapabilities.AgentErrCodeActionListFailed, "Failed to query actions")+ })+ return+ }+ if actions == nil {+ actions = []unified.ActionAuditRecord{}+ }+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(actionInboxResponse{View: view, Actions: actions, Count: len(actions)}); err != nil {+ writeJSONError(w, http.StatusInternalServerError, agentcapabilities.AgentErrCodeActionListEncodeFailed, "Failed to encode actions")+ }+}++// HandleGetAction returns authoritative lifecycle and durable dispatch detail.+func (h *ResourceHandlers) HandleGetAction(w http.ResponseWriter, r *http.Request) {+ actionID := strings.TrimSpace(r.PathValue("id"))+ if actionID == "" || !validAuditEventID.MatchString(actionID) || len(actionID) > 128 {+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidID, "Invalid action ID format")+ return+ }+ detail, found, err := h.ActionLifecycle().Detail(GetOrgID(r.Context()), actionID)+ if err != nil {+ writeActionLifecycleReadError(w, err, func() {+ writeJSONError(w, http.StatusInternalServerError, agentcapabilities.AgentErrCodeActionDetailFailed, "Failed to query action detail")+ })+ return+ }+ if !found {+ writeJSONErrorWithDetails(w, http.StatusNotFound, agentcapabilities.AgentErrCodeActionNotFound, "Action not found", map[string]string{"actionId": actionID})+ return+ }+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(detail); err != nil {+ writeJSONError(w, http.StatusInternalServerError, agentcapabilities.AgentErrCodeActionDetailEncodeFailed, "Failed to encode action detail")+ }+}+func writeActionPlanError(w http.ResponseWriter, err error) {var validationErr *actionplanner.ValidationErrorvar notFound *actionlifecycle.ResourceNotFoundErrordiff --git a/internal/api/actions_test.go b/internal/api/actions_test.goindex 234d87fb53..6041413586 100644--- a/internal/api/actions_test.go+++ b/internal/api/actions_test.go@@ -258,6 +258,70 @@ func TestHandleListPendingActionsReturnsOnlyCanonicalDecisionQueue(t *testing.T)}}+func TestHandleGetActionAndInboxAreTenantScoped(t *testing.T) {+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})+ now := time.Now().UTC()+ store, err := h.getStore("org-a")+ if err != nil {+ t.Fatal(err)+ }+ record := unified.ActionAuditRecord{+ ID: "act-org-a", CreatedAt: now, UpdatedAt: now, State: unified.ActionStatePending,+ Request: unified.ActionRequest{RequestID: "req-org-a", ResourceID: "vm:42", CapabilityName: "restart", RequestedBy: "operator"},+ Plan: unified.ActionPlan{ActionID: "act-org-a", RequestID: "req-org-a", Allowed: true, RequiresApproval: true, ApprovalPolicy: unified.ApprovalAdmin, PlannedAt: now, ExpiresAt: now.Add(time.Hour), ResourceVersion: "v1", PolicyVersion: "p1", PlanHash: "sha256:org-a"},+ }+ if _, _, err := store.CreateActionAudit(record, []unified.ActionLifecycleEvent{{ActionID: record.ID, Timestamp: now, State: unified.ActionStatePending, Actor: "operator", Message: "Pending approval."}}); err != nil {+ t.Fatal(err)+ }++ for _, orgID := range []string{"org-b", "default"} {+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/actions/act-org-a", nil)+ req.SetPathValue("id", "act-org-a")+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, orgID))+ h.HandleGetAction(rec, req)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("cross-org detail status for %s=%d body=%s", orgID, rec.Code, rec.Body.String())+ }+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/actions/act-org-a", nil)+ req.SetPathValue("id", "act-org-a")+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))+ h.HandleGetAction(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("owner detail status=%d body=%s", rec.Code, rec.Body.String())+ }+ var detail actionlifecycle.ActionDetail+ if err := json.Unmarshal(rec.Body.Bytes(), &detail); err != nil || detail.Audit.ID != record.ID {+ t.Fatalf("detail=%#v err=%v", detail, err)+ }++ rec = httptest.NewRecorder()+ req = httptest.NewRequest(http.MethodGet, "/api/actions?view=pending", nil)+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-b"))+ h.HandleListActions(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("cross-org list status=%d body=%s", rec.Code, rec.Body.String())+ }+ var inbox actionInboxResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &inbox); err != nil || inbox.Count != 0 {+ t.Fatalf("cross-org inbox=%#v err=%v", inbox, err)+ }+}++func TestHandleListActionsRejectsUnknownViewAndUnsafeLimit(t *testing.T) {+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})+ for _, target := range []string{"/api/actions?view=unknown", "/api/actions?limit=501", "/api/actions?limit=-1"} {+ rec := httptest.NewRecorder()+ h.HandleListActions(rec, httptest.NewRequest(http.MethodGet, target, nil))+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("target=%s status=%d body=%s", target, rec.Code, rec.Body.String())+ }+ }+}+func TestHandleDecideActionApprovesPendingPlanWithoutExecution(t *testing.T) {now := time.Date(2026, 5, 4, 14, 0, 0, 0, time.UTC)h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})@@ -795,7 +859,7 @@ func TestHandleExecuteActionRejectsDryRunOnlyPlan(t *testing.T) {}}-func TestHandleExecuteActionRejectsExpiredPlanAsFailedAudit(t *testing.T) {+func TestHandleExecuteActionMaterializesExplicitExpiredState(t *testing.T) {now := time.Now().UTC().Truncate(time.Second)h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "should not run"}}@@ -866,23 +930,20 @@ func TestHandleExecuteActionRejectsExpiredPlanAsFailedAudit(t *testing.T) {if err != nil {t.Fatalf("GetActionAudit: %v", err)}- if !ok || got.State != unified.ActionStateFailed || got.Result == nil || got.Result.Success || !strings.HasPrefix(got.Result.ErrorMessage, "action_plan_expired:") {+ if !ok || got.State != unified.ActionStateExpired || got.Result != nil {t.Fatalf("expired-plan audit = %#v, ok=%v", got, ok)}select {case eventRecord := <-published:- if eventRecord.ID != "act_expired" || eventRecord.State != unified.ActionStateFailed {- t.Fatalf("published expired-plan completion = %#v", eventRecord)- }+ t.Fatalf("expiry must not publish fabricated completion truth: %#v", eventRecord)default:- t.Fatal("expected expired-plan refusal to publish a terminal action completion event")}events, err := store.GetActionLifecycleEvents("act_expired", time.Time{}, 10)if err != nil {t.Fatalf("GetActionLifecycleEvents: %v", err)}- if len(events) != 1 || events[0].State != unified.ActionStateFailed || !strings.HasPrefix(events[0].Message, "action_plan_expired:") {- t.Fatalf("expected one failed expired-plan lifecycle event, got %#v", events)+ if len(events) != 1 || events[0].State != unified.ActionStateExpired || events[0].Message != "Action plan expired before dispatch." {+ t.Fatalf("expected one explicit expiry lifecycle event, got %#v", events)}}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 2fca5b45c4..7b2d36481f 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -80,16 +80,18 @@ func TestContract_ActionLifecycleReplayIsCreateOnceAndMonotonic(t *testing.T) {}}-func TestContract_ActionExecutorAdmissionRequiresExecutingCASWinner(t *testing.T) {+func TestContract_ActionExecutorAdmissionRequiresDurableAttemptAndSendCAS(t *testing.T) {service, err := os.ReadFile("../actionlifecycle/service.go")if err != nil {t.Fatal(err)}src := string(service)- start := strings.Index(src, "store.RecordActionExecutionStart(started, startEvent)")- dispatch := strings.Index(src, "s.Executor.ExecuteAction(ctx, started)")- if start < 0 || dispatch < 0 || start > dispatch {- t.Fatal("executor dispatch must occur only after the executing-state CAS")+ admission := strings.Index(src, "store.RecordActionExecutionAdmission(started, startEvent, attempt)")+ policyAdmission := strings.Index(src, "store.RecordActionPolicyExecutionAdmission(started, approvedEvent, startEvent, attempt)")+ started := strings.Index(src, "store.MarkActionDispatchStarted(attempt.ID, owner, s.now())")+ dispatch := strings.Index(src, "s.Executor.ExecuteAction(withDispatchAttempt(ctx, attempt), record)")+ if admission < 0 || policyAdmission < 0 || started < 0 || dispatch < 0 || admission > started || started > dispatch {+ t.Fatal("executor dispatch must follow atomic attempt admission and the one-shot pre-send CAS")}}@@ -19679,25 +19681,31 @@ func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T)// 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_queue_unavailable": true,- "action_queue_query_failed": true,- "action_queue_encode_failed": true,- "action_not_executing": true,- "action_policy_validation_failed": true,- "action_plan_validation_failed": true,- "resource_registry_unavailable": true,- agentcapabilities.AgentErrCodeRawCommandRetired: true,+ "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_queue_unavailable": true,+ "action_queue_query_failed": true,+ "action_queue_encode_failed": true,+ agentcapabilities.AgentErrCodeInvalidActionListLimit: true,+ agentcapabilities.AgentErrCodeInvalidActionListView: true,+ agentcapabilities.AgentErrCodeActionListFailed: true,+ agentcapabilities.AgentErrCodeActionListEncodeFailed: true,+ agentcapabilities.AgentErrCodeActionDetailFailed: true,+ agentcapabilities.AgentErrCodeActionDetailEncodeFailed: true,+ "action_not_executing": true,+ "action_policy_validation_failed": true,+ "action_plan_validation_failed": true,+ "resource_registry_unavailable": true,+ agentcapabilities.AgentErrCodeRawCommandRetired: true,}agentErrorConstantValues := map[string]string{@@ -19728,6 +19736,12 @@ func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T)"AgentErrCodeActionQueueUnavailable": agentcapabilities.AgentErrCodeActionQueueUnavailable,"AgentErrCodeActionQueueQueryFailed": agentcapabilities.AgentErrCodeActionQueueQueryFailed,"AgentErrCodeActionQueueEncodeFailed": agentcapabilities.AgentErrCodeActionQueueEncodeFailed,+ "AgentErrCodeInvalidActionListLimit": agentcapabilities.AgentErrCodeInvalidActionListLimit,+ "AgentErrCodeInvalidActionListView": agentcapabilities.AgentErrCodeInvalidActionListView,+ "AgentErrCodeActionListFailed": agentcapabilities.AgentErrCodeActionListFailed,+ "AgentErrCodeActionListEncodeFailed": agentcapabilities.AgentErrCodeActionListEncodeFailed,+ "AgentErrCodeActionDetailFailed": agentcapabilities.AgentErrCodeActionDetailFailed,+ "AgentErrCodeActionDetailEncodeFailed": agentcapabilities.AgentErrCodeActionDetailEncodeFailed,"AgentErrCodeRawCommandRetired": agentcapabilities.AgentErrCodeRawCommandRetired,}diff --git a/internal/api/docker_container_action_executor.go b/internal/api/docker_container_action_executor.goindex 08d206681b..bb08b7b8c4 100644--- a/internal/api/docker_container_action_executor.go+++ b/internal/api/docker_container_action_executor.go@@ -6,6 +6,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/safety"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -30,6 +31,10 @@ func (e dockerContainerActionExecutor) ActionHandlerNames() []string {}func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {+ attempt, ok := actionlifecycle.DispatchAttemptFromContext(ctx)+ if !ok || attempt.ActionID != record.ID {+ return nil, fmt.Errorf("committed action dispatch authority is required")+ }record, err := unified.NormalizeActionAuditRecord(record)if err != nil {return nil, err@@ -58,7 +63,7 @@ func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, recordcommand := fmt.Sprintf("%s %s %s", runtime, operation, shellQuote(containerRef))result, err := e.agents.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{- RequestID: record.ID,+ RequestID: attempt.ID,Command: command,ApprovalID: record.ID,TargetType: "agent",diff --git a/internal/api/docker_container_action_executor_test.go b/internal/api/docker_container_action_executor_test.goindex f09b93b1ce..e4f8af797d 100644--- a/internal/api/docker_container_action_executor_test.go+++ b/internal/api/docker_container_action_executor_test.go@@ -83,7 +83,7 @@ func TestDockerContainerActionExecutorDispatchesPodmanRestartAndVerification(t *}}executor := newDockerContainerActionExecutor(h, agents)- result, err := executor.ExecuteAction(context.Background(), dockerContainerActionRecord("act_container", "app-container:api", "restart"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_container"), dockerContainerActionRecord("act_container", "app-container:api", "restart"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -99,6 +99,9 @@ func TestDockerContainerActionExecutorDispatchesPodmanRestartAndVerification(t *if agents.calls[0].ApprovalID != "act_container" || !agents.calls[0].Trusted {t.Fatalf("dispatch approval/trust = %q/%v", agents.calls[0].ApprovalID, agents.calls[0].Trusted)}+ if agents.calls[0].RequestID != "act_container.dispatch.1" {+ t.Fatalf("dispatch request identity = %q", agents.calls[0].RequestID)+ }if got := agents.calls[1].Command; got != "podman inspect -f '{{.State.Status}} {{.State.Running}}' 'container-123'" {t.Fatalf("verification command = %q", got)}@@ -141,7 +144,7 @@ func TestDockerContainerActionExecutorResolvesCommandAgentByDockerHostname(t *tet.Fatalf("CheckActionAvailable readiness = %#v, want available through hostname-resolved command agent", readiness)}- result, err := executor.ExecuteAction(context.Background(), dockerContainerActionRecord("act_container", "app-container:api", "restart"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_container"), dockerContainerActionRecord("act_container", "app-container:api", "restart"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -170,7 +173,7 @@ func TestDockerContainerActionExecutorFailsWhenCapabilityNoLongerAdvertised(t *tagents := &fakeDockerActionAgentCommander{}executor := newDockerContainerActionExecutor(h, agents)- result, err := executor.ExecuteAction(context.Background(), dockerContainerActionRecord("act_container", "app-container:api", "restart"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_container"), dockerContainerActionRecord("act_container", "app-container:api", "restart"))if err == nil || !strings.Contains(err.Error(), "does not currently advertise restart capability") {t.Fatalf("ExecuteAction err = %v, result = %#v", err, result)}diff --git a/internal/api/host_storage_cleanup_action_executor.go b/internal/api/host_storage_cleanup_action_executor.goindex 239843d318..08fc1793d2 100644--- a/internal/api/host_storage_cleanup_action_executor.go+++ b/internal/api/host_storage_cleanup_action_executor.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -60,6 +61,10 @@ func (e hostStorageCleanupActionExecutor) CheckActionAvailable(_ context.Context}func (e hostStorageCleanupActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {+ attempt, ok := actionlifecycle.DispatchAttemptFromContext(ctx)+ if !ok || attempt.ActionID != record.ID {+ return nil, fmt.Errorf("committed action dispatch authority is required")+ }record, err := unified.NormalizeActionAuditRecord(record)if err != nil {return nil, err@@ -72,7 +77,7 @@ func (e hostStorageCleanupActionExecutor) ExecuteAction(ctx context.Context, recreturn nil, err}result, err := e.agents.ExecuteHostStorageCleanup(ctx, strings.TrimSpace(resource.Agent.AgentID), agentexec.HostStorageCleanupPayload{- RequestID: record.ID,+ RequestID: attempt.ID,ActionID: record.ID,Operation: agentexec.HostStorageCleanupOperationPackageCache,ExpectedFingerprint: resource.Agent.StorageCleanup.Fingerprint,diff --git a/internal/api/host_storage_cleanup_action_executor_test.go b/internal/api/host_storage_cleanup_action_executor_test.goindex d72f18d70a..921320ed31 100644--- a/internal/api/host_storage_cleanup_action_executor_test.go+++ b/internal/api/host_storage_cleanup_action_executor_test.go@@ -38,7 +38,7 @@ func TestHostStorageCleanupActionExecutorDispatchesFingerprintBoundOperation(t *h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{hostStorageCleanupActionResource(now)}})agents := verifiedHostStorageCleanupAgent()- result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(context.Background(), hostStorageCleanupActionRecord("action-cleanup"))+ result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(actionDispatchTestContext(t, "action-cleanup"), hostStorageCleanupActionRecord("action-cleanup"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -68,7 +68,7 @@ func TestHostStorageCleanupActionExecutorDoesNotExposeAgentErrorText(t *testing.Error: "private repository package path and token",}}- result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(context.Background(), hostStorageCleanupActionRecord("action-cleanup"))+ result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(actionDispatchTestContext(t, "action-cleanup"), hostStorageCleanupActionRecord("action-cleanup"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}diff --git a/internal/api/host_update_action_executor.go b/internal/api/host_update_action_executor.goindex 4dd5b8609d..2e7ed18b50 100644--- a/internal/api/host_update_action_executor.go+++ b/internal/api/host_update_action_executor.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -60,6 +61,10 @@ func (e hostUpdateActionExecutor) CheckActionAvailable(ctx context.Context, req}func (e hostUpdateActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {+ attempt, ok := actionlifecycle.DispatchAttemptFromContext(ctx)+ if !ok || attempt.ActionID != record.ID {+ return nil, fmt.Errorf("committed action dispatch authority is required")+ }record, err := unified.NormalizeActionAuditRecord(record)if err != nil {return nil, err@@ -73,7 +78,7 @@ func (e hostUpdateActionExecutor) ExecuteAction(ctx context.Context, record unif}agentID := strings.TrimSpace(resource.Agent.AgentID)result, err := e.agents.ExecuteHostUpdate(ctx, agentID, agentexec.HostUpdatePayload{- RequestID: record.ID,+ RequestID: attempt.ID,ActionID: record.ID,Operation: agentexec.HostUpdateOperationInstall,ExpectedInventoryHash: resource.Agent.PackageUpdates.InventoryHash,diff --git a/internal/api/host_update_action_executor_test.go b/internal/api/host_update_action_executor_test.goindex 6e903c8f50..71bb0ef85e 100644--- a/internal/api/host_update_action_executor_test.go+++ b/internal/api/host_update_action_executor_test.go@@ -48,7 +48,7 @@ func TestHostUpdateActionExecutorDispatchesTypedOperationAndProjectsVerification}}executor := newHostUpdateActionExecutor(h, agents)- result, err := executor.ExecuteAction(context.Background(), hostUpdateActionRecord("action-host-update"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "action-host-update"), hostUpdateActionRecord("action-host-update"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -62,7 +62,7 @@ func TestHostUpdateActionExecutorDispatchesTypedOperationAndProjectsVerificationt.Fatalf("agent calls = %#v, agentID=%q", agents.requests, agents.agentID)}request := agents.requests[0]- if request.ActionID != "action-host-update" || request.RequestID != "action-host-update" || request.Operation != agentexec.HostUpdateOperationInstall || request.ExpectedInventoryHash != testHostPackageInventoryHash || request.Timeout != 900 {+ if request.ActionID != "action-host-update" || request.RequestID != "action-host-update.dispatch.1" || request.Operation != agentexec.HostUpdateOperationInstall || request.ExpectedInventoryHash != testHostPackageInventoryHash || request.Timeout != 900 {t.Fatalf("typed request = %#v", request)}}@@ -79,7 +79,7 @@ func TestHostUpdateActionExecutorReportsInconclusiveVerificationHonestly(t *testError: "package installation completed but verification was inconclusive",}}- result, err := newHostUpdateActionExecutor(h, agents).ExecuteAction(context.Background(), hostUpdateActionRecord("action-host-update"))+ result, err := newHostUpdateActionExecutor(h, agents).ExecuteAction(actionDispatchTestContext(t, "action-host-update"), hostUpdateActionRecord("action-host-update"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}diff --git a/internal/api/proxmox_guest_action_executor.go b/internal/api/proxmox_guest_action_executor.goindex fe8108669a..13a8093f22 100644--- a/internal/api/proxmox_guest_action_executor.go+++ b/internal/api/proxmox_guest_action_executor.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -40,6 +41,10 @@ func (e proxmoxGuestActionExecutor) ActionHandlerNames() []string {}func (e proxmoxGuestActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {+ attempt, ok := actionlifecycle.DispatchAttemptFromContext(ctx)+ if !ok || attempt.ActionID != record.ID {+ return nil, fmt.Errorf("committed action dispatch authority is required")+ }record, err := unified.NormalizeActionAuditRecord(record)if err != nil {return nil, err@@ -61,7 +66,7 @@ func (e proxmoxGuestActionExecutor) ExecuteAction(ctx context.Context, record uncommand := proxmoxGuestLifecycleCommand(kind, operation, vmid)result, err := e.agents.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{- RequestID: record.ID,+ RequestID: attempt.ID,Command: command,ApprovalID: record.ID,TargetType: "agent",diff --git a/internal/api/proxmox_guest_action_executor_test.go b/internal/api/proxmox_guest_action_executor_test.goindex 8d4c16b871..f7665d3292 100644--- a/internal/api/proxmox_guest_action_executor_test.go+++ b/internal/api/proxmox_guest_action_executor_test.go@@ -31,7 +31,7 @@ func TestProxmoxGuestActionExecutorDispatchesVMShutdownAndVerification(t *testin}}executor := newProxmoxGuestActionExecutor(h, agents)- result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_vm", "vm:160", "shutdown"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_vm"), proxmoxGuestActionRecord("act_vm", "vm:160", "shutdown"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -47,6 +47,9 @@ func TestProxmoxGuestActionExecutorDispatchesVMShutdownAndVerification(t *testinif agents.calls[0].ApprovalID != "act_vm" || !agents.calls[0].Trusted || agents.calls[0].Timeout != 180 {t.Fatalf("dispatch approval/trust/timeout = %q/%v/%d", agents.calls[0].ApprovalID, agents.calls[0].Trusted, agents.calls[0].Timeout)}+ if agents.calls[0].RequestID != "act_vm.dispatch.1" {+ t.Fatalf("dispatch request identity = %q", agents.calls[0].RequestID)+ }if got := agents.calls[1].Command; got != "qm status 160" {t.Fatalf("verification command = %q", got)}@@ -72,7 +75,7 @@ func TestProxmoxGuestActionExecutorDispatchesLXCStartAndVerification(t *testing.}}executor := newProxmoxGuestActionExecutor(h, agents)- result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_ct", "system-container:101", "start"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_ct"), proxmoxGuestActionRecord("act_ct", "system-container:101", "start"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -120,7 +123,7 @@ func TestProxmoxGuestActionExecutorResolvesCommandAgentByNodeHostname(t *testingt.Fatalf("CheckActionAvailable readiness = %#v, want available through node hostname fallback", readiness)}- result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_vm", "vm:160", "reboot"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_vm"), proxmoxGuestActionRecord("act_vm", "vm:160", "reboot"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -153,7 +156,7 @@ func TestProxmoxGuestActionExecutorVerificationFailureFailsAction(t *testing.T)}}executor := newProxmoxGuestActionExecutor(h, agents)- result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_vm", "vm:160", "shutdown"))+ result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_vm"), proxmoxGuestActionRecord("act_vm", "vm:160", "shutdown"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}diff --git a/internal/api/relay_mobile_capability.go b/internal/api/relay_mobile_capability.goindex 25464048c3..ee85158ff0 100644--- a/internal/api/relay_mobile_capability.go+++ b/internal/api/relay_mobile_capability.go@@ -30,6 +30,8 @@ const (relayMobileRouteApprovalApprove relayMobileRuntimeRouteID = "approval-approve"relayMobileRouteApprovalDeny relayMobileRuntimeRouteID = "approval-deny"relayMobileRoutePendingActions relayMobileRuntimeRouteID = "pending-actions"+ relayMobileRouteActionsList relayMobileRuntimeRouteID = "actions-list"+ relayMobileRouteActionDetail relayMobileRuntimeRouteID = "action-detail"relayMobileRouteActionDecision relayMobileRuntimeRouteID = "action-decision"relayMobileRouteActionExecute relayMobileRuntimeRouteID = "action-execute"relayMobileRouteChatSend relayMobileRuntimeRouteID = "chat-send"@@ -55,6 +57,8 @@ var relayMobileRuntimeRouteOrder = []relayMobileRuntimeRouteID{relayMobileRouteApprovalApprove,relayMobileRouteApprovalDeny,relayMobileRoutePendingActions,+ relayMobileRouteActionsList,+ relayMobileRouteActionDetail,relayMobileRouteActionDecision,relayMobileRouteActionExecute,relayMobileRouteChatSend,@@ -145,6 +149,18 @@ var relayMobileRuntimeRouteSpecs = map[relayMobileRuntimeRouteID]relayMobileRuntpath: "/api/actions/pending",requiredScope: config.ScopeAIExecute,},+ relayMobileRouteActionsList: {+ id: relayMobileRouteActionsList,+ method: http.MethodGet,+ path: "/api/actions",+ requiredScope: config.ScopeAIExecute,+ },+ relayMobileRouteActionDetail: {+ id: relayMobileRouteActionDetail,+ method: http.MethodGet,+ path: "/api/actions/{action_id}",+ requiredScope: config.ScopeAIExecute,+ },relayMobileRouteActionDecision: {id: relayMobileRouteActionDecision,method: http.MethodPost,diff --git a/internal/api/relay_mobile_capability_test.go b/internal/api/relay_mobile_capability_test.goindex 464268ea37..1d8e63dfc9 100644--- a/internal/api/relay_mobile_capability_test.go+++ b/internal/api/relay_mobile_capability_test.go@@ -52,6 +52,8 @@ func TestRelayMobileRuntimeRouteInventory(t *testing.T) {"POST /api/ai/approvals/{approval_id}/approve => ai:execute","POST /api/ai/approvals/{approval_id}/deny => ai:execute","GET /api/actions/pending => ai:execute",+ "GET /api/actions => ai:execute",+ "GET /api/actions/{action_id} => ai:execute","POST /api/actions/{action_id}/decision => ai:execute","POST /api/actions/{action_id}/execute => ai:execute","POST /api/ai/chat => ai:chat",diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex e8feca4c4a..99a5014620 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -430,6 +430,8 @@ var allRouteAllowlist = []string{"/api/agent/events","POST /api/actions/plan","GET /api/actions/pending",+ "GET /api/actions",+ "GET /api/actions/{id}","POST /api/actions/{id}/decision","POST /api/actions/{id}/execute","/api/guests/metadata",diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.goindex 070278e56b..dd4ce614e6 100644--- a/internal/api/router_routes_monitoring.go+++ b/internal/api/router_routes_monitoring.go@@ -143,6 +143,12 @@ func (r *Router) registerMonitoringResourceRoutes(r.mux.HandleFunc("GET /api/actions/pending", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRoutePendingActions,r.resourceHandlers.HandleListPendingActions,)))+ r.mux.HandleFunc("GET /api/actions", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRouteActionsList,+ r.resourceHandlers.HandleListActions,+ )))+ r.mux.HandleFunc("GET /api/actions/{id}", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRouteActionDetail,+ r.resourceHandlers.HandleGetAction,+ )))r.mux.HandleFunc("POST /api/actions/{id}/decision", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRouteActionDecision, r.withExternalAgentCapabilityActivity(agentcapabilities.DecideActionCapabilityName,r.resourceHandlers.HandleDecideAction,diff --git a/internal/unifiedresources/action_dispatch.go b/internal/unifiedresources/action_dispatch.gonew file mode 100644index 0000000000..7ad720a113--- /dev/null+++ b/internal/unifiedresources/action_dispatch.go@@ -0,0 +1,126 @@+package unifiedresources++import (+ "errors"+ "fmt"+ "strings"+ "time"+)++// ActionDispatchState records transport authority only. It deliberately does+// not describe execution success, verification, evidence, or compensation.+type ActionDispatchState string++const (+ ActionDispatchQueued ActionDispatchState = "queued"+ ActionDispatchClaimed ActionDispatchState = "claimed"+ ActionDispatchReceiptPending ActionDispatchState = "receipt_pending"+ ActionDispatchReceiptRecorded ActionDispatchState = "receipt_recorded"+)++// ActionDispatchAttempt is the create-once durable identity for sending one+// canonical action to its mutation transport.+type ActionDispatchAttempt struct {+ ID string `json:"id"`+ ActionID string `json:"actionId"`+ State ActionDispatchState `json:"state"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ LeaseOwner string `json:"leaseOwner,omitempty"`+ LeaseExpiresAt time.Time `json:"leaseExpiresAt,omitempty"`+ DispatchCount int `json:"dispatchCount"`+}++// ActionDispatchReceipt proves only that the transport answered the committed+// attempt. It intentionally contains no result or verification truth.+type ActionDispatchReceipt struct {+ AttemptID string `json:"attemptId"`+ ActionID string `json:"actionId"`+ TransportRequestID string `json:"transportRequestId"`+ ReceivedAt time.Time `json:"receivedAt"`+}++var (+ ErrActionDispatchNotFound = errors.New("action dispatch attempt not found")+ ErrActionDispatchNotClaimable = errors.New("action dispatch attempt is not claimable")+ ErrActionDispatchLeaseMismatch = errors.New("action dispatch lease owner mismatch")+ ErrActionDispatchReceiptConflict = errors.New("action dispatch receipt conflicts with persisted correlation")+)++func ActionDispatchAttemptID(actionID string) string {+ actionID = strings.TrimSpace(actionID)+ if actionID == "" {+ return ""+ }+ return actionID + ".dispatch.1"+}++func NewActionDispatchAttempt(actionID string, now time.Time) (ActionDispatchAttempt, error) {+ if now.IsZero() {+ now = time.Now().UTC()+ } else {+ now = now.UTC()+ }+ return NormalizeActionDispatchAttempt(ActionDispatchAttempt{+ ID: ActionDispatchAttemptID(actionID), ActionID: strings.TrimSpace(actionID),+ State: ActionDispatchQueued, CreatedAt: now, UpdatedAt: now,+ })+}++func NormalizeActionDispatchAttempt(attempt ActionDispatchAttempt) (ActionDispatchAttempt, error) {+ attempt.ID = strings.TrimSpace(attempt.ID)+ attempt.ActionID = strings.TrimSpace(attempt.ActionID)+ attempt.LeaseOwner = strings.TrimSpace(attempt.LeaseOwner)+ if attempt.ActionID == "" {+ return ActionDispatchAttempt{}, fmt.Errorf("action dispatch action id required")+ }+ if attempt.ID == "" {+ attempt.ID = ActionDispatchAttemptID(attempt.ActionID)+ }+ if attempt.ID != ActionDispatchAttemptID(attempt.ActionID) {+ return ActionDispatchAttempt{}, fmt.Errorf("action dispatch attempt id %q does not match action %q", attempt.ID, attempt.ActionID)+ }+ switch attempt.State {+ case ActionDispatchQueued, ActionDispatchClaimed, ActionDispatchReceiptPending, ActionDispatchReceiptRecorded:+ default:+ return ActionDispatchAttempt{}, fmt.Errorf("unsupported action dispatch state %q", attempt.State)+ }+ if attempt.CreatedAt.IsZero() {+ return ActionDispatchAttempt{}, fmt.Errorf("action dispatch createdAt required")+ }+ attempt.CreatedAt = attempt.CreatedAt.UTC()+ if attempt.UpdatedAt.IsZero() {+ attempt.UpdatedAt = attempt.CreatedAt+ } else {+ attempt.UpdatedAt = attempt.UpdatedAt.UTC()+ }+ if !attempt.LeaseExpiresAt.IsZero() {+ attempt.LeaseExpiresAt = attempt.LeaseExpiresAt.UTC()+ }+ if attempt.State != ActionDispatchClaimed {+ attempt.LeaseOwner = ""+ attempt.LeaseExpiresAt = time.Time{}+ }+ if attempt.DispatchCount < 0 {+ return ActionDispatchAttempt{}, fmt.Errorf("action dispatch count cannot be negative")+ }+ return attempt, nil+}++func NormalizeActionDispatchReceipt(receipt ActionDispatchReceipt) (ActionDispatchReceipt, error) {+ receipt.AttemptID = strings.TrimSpace(receipt.AttemptID)+ receipt.ActionID = strings.TrimSpace(receipt.ActionID)+ receipt.TransportRequestID = strings.TrimSpace(receipt.TransportRequestID)+ if receipt.ActionID == "" || receipt.AttemptID != ActionDispatchAttemptID(receipt.ActionID) {+ return ActionDispatchReceipt{}, fmt.Errorf("action dispatch receipt identity is invalid")+ }+ if receipt.TransportRequestID == "" {+ receipt.TransportRequestID = receipt.AttemptID+ }+ if receipt.ReceivedAt.IsZero() {+ receipt.ReceivedAt = time.Now().UTC()+ } else {+ receipt.ReceivedAt = receipt.ReceivedAt.UTC()+ }+ return receipt, nil+}diff --git a/internal/unifiedresources/action_dispatch_store.go b/internal/unifiedresources/action_dispatch_store.gonew file mode 100644index 0000000000..0839bc83de--- /dev/null+++ b/internal/unifiedresources/action_dispatch_store.go@@ -0,0 +1,822 @@+package unifiedresources++import (+ "database/sql"+ "errors"+ "fmt"+ "strings"+ "time"+)++func insertActionDispatchSQL(exec sqlExecutor, attempt ActionDispatchAttempt) error {+ attempt, err := NormalizeActionDispatchAttempt(attempt)+ if err != nil {+ return err+ }+ if _, err := exec.Exec(`+ INSERT INTO action_dispatch_attempts+ (attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count)+ VALUES (?, ?, ?, ?, ?, NULL, NULL, ?)+ `, attempt.ID, attempt.ActionID, string(attempt.State), attempt.CreatedAt, attempt.UpdatedAt, attempt.DispatchCount); err != nil {+ return fmt.Errorf("insert action dispatch attempt: %w", err)+ }+ if _, err := exec.Exec(`+ INSERT INTO action_dispatch_outbox (attempt_id, action_id, available_at)+ VALUES (?, ?, ?)+ `, attempt.ID, attempt.ActionID, attempt.CreatedAt); err != nil {+ return fmt.Errorf("insert action dispatch outbox: %w", err)+ }+ return nil+}++func scanActionDispatch(scanner interface{ Scan(...any) error }) (ActionDispatchAttempt, error) {+ var attempt ActionDispatchAttempt+ var state string+ var owner sql.NullString+ var lease sql.NullTime+ if err := scanner.Scan(&attempt.ID, &attempt.ActionID, &state, &attempt.CreatedAt, &attempt.UpdatedAt, &owner, &lease, &attempt.DispatchCount); err != nil {+ return ActionDispatchAttempt{}, err+ }+ attempt.State = ActionDispatchState(state)+ attempt.LeaseOwner = owner.String+ if lease.Valid {+ attempt.LeaseExpiresAt = lease.Time+ }+ return NormalizeActionDispatchAttempt(attempt)+}++func getActionDispatchFrom(queryer actionAuditQueryRower, actionID string) (ActionDispatchAttempt, bool, error) {+ row := queryer.QueryRow(`+ SELECT attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count+ FROM action_dispatch_attempts WHERE action_id = ?+ `, strings.TrimSpace(actionID))+ attempt, err := scanActionDispatch(row)+ if errors.Is(err, sql.ErrNoRows) {+ return ActionDispatchAttempt{}, false, nil+ }+ return attempt, err == nil, err+}++func getActionDispatchByAttemptFrom(queryer actionAuditQueryRower, attemptID string) (ActionDispatchAttempt, bool, error) {+ row := queryer.QueryRow(`+ SELECT attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count+ FROM action_dispatch_attempts WHERE attempt_id = ?+ `, strings.TrimSpace(attemptID))+ attempt, err := scanActionDispatch(row)+ if errors.Is(err, sql.ErrNoRows) {+ return ActionDispatchAttempt{}, false, nil+ }+ return attempt, err == nil, err+}++func validateExecutionAdmission(record ActionAuditRecord, event ActionLifecycleEvent, attempt ActionDispatchAttempt) (ActionAuditRecord, ActionLifecycleEvent, ActionDispatchAttempt, error) {+ record, err := NormalizeActionAuditRecord(record)+ if err != nil {+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionDispatchAttempt{}, err+ }+ event, err = NormalizeActionLifecycleEvent(event)+ if err != nil {+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionDispatchAttempt{}, err+ }+ attempt, err = NormalizeActionDispatchAttempt(attempt)+ if err != nil {+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionDispatchAttempt{}, err+ }+ if record.State != ActionStateExecuting || event.State != ActionStateExecuting || event.ActionID != record.ID || attempt.ActionID != record.ID || attempt.State != ActionDispatchQueued {+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionDispatchAttempt{}, errors.New("action dispatch admission identities or states do not match")+ }+ return RedactAuditRecord(record), event, attempt, nil+}++func (s *SQLiteResourceStore) RecordActionExecutionAdmission(record ActionAuditRecord, event ActionLifecycleEvent, attempt ActionDispatchAttempt) error {+ record, event, attempt, err := validateExecutionAdmission(record, event, attempt)+ if err != nil {+ return err+ }+ expected := []ActionState{ActionStateApproved}+ if record.Plan.Allowed && !record.Plan.RequiresApproval {+ expected = append(expected, ActionStatePlanned)+ }+ return s.recordActionAdmission(record, []ActionLifecycleEvent{event}, attempt, expected)+}++func (s *SQLiteResourceStore) RecordActionPolicyExecutionAdmission(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent, attempt ActionDispatchAttempt) error {+ record, executionEvent, attempt, err := validateExecutionAdmission(record, executionEvent, attempt)+ if err != nil {+ return err+ }+ approvalEvent, err = NormalizeActionLifecycleEvent(approvalEvent)+ if err != nil {+ return err+ }+ if approvalEvent.State != ActionStateApproved || approvalEvent.ActionID != record.ID || len(record.Approvals) == 0 || record.Approvals[len(record.Approvals)-1].PolicyLease == nil {+ return ErrActionPolicyAuthorizationInvalid+ }+ return s.recordActionAdmission(record, []ActionLifecycleEvent{approvalEvent, executionEvent}, attempt, []ActionState{ActionStatePlanned, ActionStatePending})+}++func (s *SQLiteResourceStore) recordActionAdmission(record ActionAuditRecord, events []ActionLifecycleEvent, attempt ActionDispatchAttempt, expected []ActionState) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ tx, err := s.db.Begin()+ if err != nil {+ return fmt.Errorf("begin action dispatch admission transaction: %w", err)+ }+ committed := false+ defer func() {+ if !committed {+ _ = tx.Rollback()+ }+ }()+ updated, err := updateActionAuditSQL(tx, record, expected...)+ if err != nil {+ return err+ }+ if !updated {+ current, found, queryErr := getActionAuditFrom(tx, record.ID)+ if queryErr != nil {+ return queryErr+ }+ if !found {+ return fmt.Errorf("action audit %q not found", record.ID)+ }+ return actionTransitionConflict(current, record, ErrActionNotApproved)+ }+ for _, event := range events {+ if err := recordActionLifecycleEventSQL(tx, event); err != nil {+ return err+ }+ }+ if err := insertActionDispatchSQL(tx, attempt); err != nil {+ return err+ }+ if err := tx.Commit(); err != nil {+ return fmt.Errorf("commit action dispatch admission transaction: %w", err)+ }+ committed = true+ return nil+}++func (s *SQLiteResourceStore) RecordActionExpiry(record ActionAuditRecord, event ActionLifecycleEvent) error {+ record, err := NormalizeActionAuditRecord(record)+ if err != nil {+ return err+ }+ event, err = NormalizeActionLifecycleEvent(event)+ if err != nil {+ return err+ }+ if record.State != ActionStateExpired || event.State != ActionStateExpired || event.ActionID != record.ID {+ return errors.New("action expiry must persist matching expired state")+ }+ return s.recordActionTransition(record, event, []ActionState{ActionStatePlanned, ActionStatePending, ActionStateApproved}, ErrActionExecutionFinal)+}++func (s *SQLiteResourceStore) GetActionDispatchAttempt(actionID string) (ActionDispatchAttempt, bool, error) {+ return getActionDispatchFrom(s.db, actionID)+}++func (s *SQLiteResourceStore) GetActionDispatchReceipt(attemptID string) (ActionDispatchReceipt, bool, error) {+ row := s.db.QueryRow(`SELECT attempt_id, action_id, transport_request_id, received_at FROM action_dispatch_receipts WHERE attempt_id = ?`, strings.TrimSpace(attemptID))+ var receipt ActionDispatchReceipt+ if err := row.Scan(&receipt.AttemptID, &receipt.ActionID, &receipt.TransportRequestID, &receipt.ReceivedAt); errors.Is(err, sql.ErrNoRows) {+ return ActionDispatchReceipt{}, false, nil+ } else if err != nil {+ return ActionDispatchReceipt{}, false, err+ }+ receipt, err := NormalizeActionDispatchReceipt(receipt)+ return receipt, err == nil, err+}++func (s *SQLiteResourceStore) ClaimActionDispatch(actionID, owner string, now time.Time, lease time.Duration) (ActionDispatchAttempt, bool, error) {+ owner = strings.TrimSpace(owner)+ if owner == "" || lease <= 0 {+ return ActionDispatchAttempt{}, false, ErrActionDispatchNotClaimable+ }+ if now.IsZero() {+ now = time.Now().UTC()+ } else {+ now = now.UTC()+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ tx, err := s.db.Begin()+ if err != nil {+ return ActionDispatchAttempt{}, false, err+ }+ committed := false+ defer func() {+ if !committed {+ _ = tx.Rollback()+ }+ }()+ attempt, found, err := getActionDispatchFrom(tx, actionID)+ if err != nil || !found {+ if err == nil {+ err = ErrActionDispatchNotFound+ }+ return ActionDispatchAttempt{}, false, err+ }+ if attempt.State == ActionDispatchClaimed {+ if attempt.LeaseOwner == owner && now.Before(attempt.LeaseExpiresAt) {+ _ = tx.Rollback()+ committed = true+ return attempt, false, nil+ }+ if !attempt.LeaseExpiresAt.IsZero() && !now.Before(attempt.LeaseExpiresAt) {+ // Claiming does not authorize transport. Until MarkActionDispatchStarted+ // commits the pre-send boundary, an expired lease is safe to requeue.+ attempt.State, attempt.UpdatedAt, attempt.LeaseOwner, attempt.LeaseExpiresAt = ActionDispatchQueued, now, "", time.Time{}+ if _, err = tx.Exec(`UPDATE action_dispatch_attempts SET state=?, updated_at=?, lease_owner=NULL, lease_expires_at=NULL WHERE attempt_id=?`, string(attempt.State), now, attempt.ID); err != nil {+ return ActionDispatchAttempt{}, false, err+ }+ if _, err = tx.Exec(`INSERT OR IGNORE INTO action_dispatch_outbox (attempt_id, action_id, available_at) VALUES (?, ?, ?)`, attempt.ID, attempt.ActionID, now); err != nil {+ return ActionDispatchAttempt{}, false, err+ }+ attempt.State, attempt.UpdatedAt, attempt.LeaseOwner, attempt.LeaseExpiresAt = ActionDispatchClaimed, now, owner, now.Add(lease)+ if _, err = tx.Exec(`UPDATE action_dispatch_attempts SET state=?, updated_at=?, lease_owner=?, lease_expires_at=? WHERE attempt_id=? AND state=?`, string(attempt.State), now, owner, attempt.LeaseExpiresAt, attempt.ID, string(ActionDispatchQueued)); err != nil {+ return ActionDispatchAttempt{}, false, err+ }+ if err = tx.Commit(); err != nil {+ return ActionDispatchAttempt{}, false, err+ }+ committed = true+ return attempt, true, nil+ }+ return attempt, false, nil+ }+ if attempt.State != ActionDispatchQueued {+ _ = tx.Rollback()+ committed = true+ return attempt, false, nil+ }+ attempt.State, attempt.UpdatedAt, attempt.LeaseOwner, attempt.LeaseExpiresAt = ActionDispatchClaimed, now, owner, now.Add(lease)+ result, err := tx.Exec(`UPDATE action_dispatch_attempts SET state=?, updated_at=?, lease_owner=?, lease_expires_at=? WHERE attempt_id=? AND state=?`, string(attempt.State), now, owner, attempt.LeaseExpiresAt, attempt.ID, string(ActionDispatchQueued))+ if err != nil {+ return ActionDispatchAttempt{}, false, err+ }+ rows, _ := result.RowsAffected()+ if rows != 1 {+ return ActionDispatchAttempt{}, false, ErrActionDispatchNotClaimable+ }+ if err = tx.Commit(); err != nil {+ return ActionDispatchAttempt{}, false, err+ }+ committed = true+ return attempt, true, nil+}++func (s *SQLiteResourceStore) MarkActionDispatchStarted(attemptID, owner string, now time.Time) (ActionDispatchAttempt, error) {+ if now.IsZero() {+ now = time.Now().UTC()+ } else {+ now = now.UTC()+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ tx, err := s.db.Begin()+ if err != nil {+ return ActionDispatchAttempt{}, err+ }+ committed := false+ defer func() {+ if !committed {+ _ = tx.Rollback()+ }+ }()+ attempt, found, err := getActionDispatchByAttemptFrom(tx, attemptID)+ if err != nil || !found {+ if err == nil {+ err = ErrActionDispatchNotFound+ }+ return ActionDispatchAttempt{}, err+ }+ if attempt.State != ActionDispatchClaimed {+ return ActionDispatchAttempt{}, ErrActionDispatchNotClaimable+ }+ if attempt.LeaseOwner != strings.TrimSpace(owner) {+ return ActionDispatchAttempt{}, ErrActionDispatchLeaseMismatch+ }+ attempt.State, attempt.UpdatedAt, attempt.DispatchCount, attempt.LeaseOwner, attempt.LeaseExpiresAt = ActionDispatchReceiptPending, now, attempt.DispatchCount+1, "", time.Time{}+ result, err := tx.Exec(`UPDATE action_dispatch_attempts SET state=?, updated_at=?, lease_owner=NULL, lease_expires_at=NULL, dispatch_count=? WHERE attempt_id=? AND state=? AND lease_owner=?`, string(attempt.State), now, attempt.DispatchCount, attempt.ID, string(ActionDispatchClaimed), owner)+ if err != nil {+ return ActionDispatchAttempt{}, err+ }+ if rows, rowsErr := result.RowsAffected(); rowsErr != nil || rows != 1 {+ return ActionDispatchAttempt{}, ErrActionDispatchNotClaimable+ }+ if _, err = tx.Exec(`DELETE FROM action_dispatch_outbox WHERE attempt_id=?`, attempt.ID); err != nil {+ return ActionDispatchAttempt{}, err+ }+ if err = tx.Commit(); err != nil {+ return ActionDispatchAttempt{}, err+ }+ committed = true+ return attempt, nil+}++func (s *SQLiteResourceStore) RecordActionDispatchReceipt(receipt ActionDispatchReceipt) (ActionDispatchAttempt, error) {+ receipt, err := NormalizeActionDispatchReceipt(receipt)+ if err != nil {+ return ActionDispatchAttempt{}, err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ tx, err := s.db.Begin()+ if err != nil {+ return ActionDispatchAttempt{}, err+ }+ committed := false+ defer func() {+ if !committed {+ _ = tx.Rollback()+ }+ }()+ attempt, found, err := getActionDispatchByAttemptFrom(tx, receipt.AttemptID)+ if err != nil || !found {+ if err == nil {+ err = ErrActionDispatchNotFound+ }+ return ActionDispatchAttempt{}, err+ }+ var existingID, transportID string+ var received time.Time+ scanErr := tx.QueryRow(`SELECT attempt_id, transport_request_id, received_at FROM action_dispatch_receipts WHERE attempt_id=?`, receipt.AttemptID).Scan(&existingID, &transportID, &received)+ if scanErr == nil {+ if transportID != receipt.TransportRequestID {+ return ActionDispatchAttempt{}, ErrActionDispatchReceiptConflict+ }+ _ = tx.Rollback()+ committed = true+ return attempt, nil+ }+ if !errors.Is(scanErr, sql.ErrNoRows) {+ return ActionDispatchAttempt{}, scanErr+ }+ if attempt.State != ActionDispatchReceiptPending {+ return ActionDispatchAttempt{}, ErrActionDispatchReceiptConflict+ }+ if _, err = tx.Exec(`INSERT INTO action_dispatch_receipts (attempt_id, action_id, transport_request_id, received_at) VALUES (?, ?, ?, ?)`, receipt.AttemptID, receipt.ActionID, receipt.TransportRequestID, receipt.ReceivedAt); err != nil {+ return ActionDispatchAttempt{}, err+ }+ attempt.State, attempt.UpdatedAt, attempt.LeaseOwner, attempt.LeaseExpiresAt = ActionDispatchReceiptRecorded, receipt.ReceivedAt, "", time.Time{}+ if _, err = tx.Exec(`UPDATE action_dispatch_attempts SET state=?, updated_at=?, lease_owner=NULL, lease_expires_at=NULL WHERE attempt_id=?`, string(attempt.State), attempt.UpdatedAt, attempt.ID); err != nil {+ return ActionDispatchAttempt{}, err+ }+ if _, err = tx.Exec(`DELETE FROM action_dispatch_outbox WHERE attempt_id=?`, attempt.ID); err != nil {+ return ActionDispatchAttempt{}, err+ }+ if err = tx.Commit(); err != nil {+ return ActionDispatchAttempt{}, err+ }+ committed = true+ return attempt, nil+}++func normalizeActionDispatchCompletion(receipt ActionDispatchReceipt, record ActionAuditRecord, event ActionLifecycleEvent) (ActionDispatchReceipt, ActionAuditRecord, ActionLifecycleEvent, error) {+ receipt, err := NormalizeActionDispatchReceipt(receipt)+ if err != nil {+ return ActionDispatchReceipt{}, ActionAuditRecord{}, ActionLifecycleEvent{}, err+ }+ record, err = NormalizeActionAuditRecord(record)+ if err != nil {+ return ActionDispatchReceipt{}, ActionAuditRecord{}, ActionLifecycleEvent{}, err+ }+ event, err = NormalizeActionLifecycleEvent(event)+ if err != nil {+ return ActionDispatchReceipt{}, ActionAuditRecord{}, ActionLifecycleEvent{}, err+ }+ if receipt.ActionID != record.ID || event.ActionID != record.ID || event.State != record.State || (record.State != ActionStateCompleted && record.State != ActionStateFailed) {+ return ActionDispatchReceipt{}, ActionAuditRecord{}, ActionLifecycleEvent{}, errors.New("correlated dispatch completion identities or terminal states do not match")+ }+ return receipt, RedactAuditRecord(record), event, nil+}++// RecordActionDispatchCompletion atomically persists the correlated transport+// receipt and today's canonical terminal audit/event. It adds no new result+// truth; it only prevents a crash from separating an existing result from its+// receipt correlation.+func (s *SQLiteResourceStore) RecordActionDispatchCompletion(receipt ActionDispatchReceipt, record ActionAuditRecord, event ActionLifecycleEvent) error {+ receipt, record, event, err := normalizeActionDispatchCompletion(receipt, record, event)+ if err != nil {+ return err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ tx, err := s.db.Begin()+ if err != nil {+ return err+ }+ committed := false+ defer func() {+ if !committed {+ _ = tx.Rollback()+ }+ }()+ attempt, found, err := getActionDispatchByAttemptFrom(tx, receipt.AttemptID)+ if err != nil || !found {+ if err == nil {+ err = ErrActionDispatchNotFound+ }+ return err+ }+ var existingTransportID string+ receiptErr := tx.QueryRow(`SELECT transport_request_id FROM action_dispatch_receipts WHERE attempt_id=?`, receipt.AttemptID).Scan(&existingTransportID)+ switch {+ case receiptErr == nil:+ if existingTransportID != receipt.TransportRequestID || attempt.State != ActionDispatchReceiptRecorded {+ return ErrActionDispatchReceiptConflict+ }+ case errors.Is(receiptErr, sql.ErrNoRows):+ if attempt.State != ActionDispatchReceiptPending {+ return ErrActionDispatchReceiptConflict+ }+ if _, err = tx.Exec(`INSERT INTO action_dispatch_receipts (attempt_id, action_id, transport_request_id, received_at) VALUES (?, ?, ?, ?)`, receipt.AttemptID, receipt.ActionID, receipt.TransportRequestID, receipt.ReceivedAt); err != nil {+ return err+ }+ result, updateErr := tx.Exec(`UPDATE action_dispatch_attempts SET state=?, updated_at=?, lease_owner=NULL, lease_expires_at=NULL WHERE attempt_id=? AND state=?`, string(ActionDispatchReceiptRecorded), receipt.ReceivedAt, attempt.ID, string(ActionDispatchReceiptPending))+ if updateErr != nil {+ return updateErr+ }+ if rows, rowsErr := result.RowsAffected(); rowsErr != nil || rows != 1 {+ return ErrActionDispatchReceiptConflict+ }+ case receiptErr != nil:+ return receiptErr+ }+ updated, err := updateActionAuditSQL(tx, record, ActionStateExecuting)+ if err != nil {+ return err+ }+ if !updated {+ current, currentFound, queryErr := getActionAuditFrom(tx, record.ID)+ if queryErr != nil {+ return queryErr+ }+ if !currentFound {+ return fmt.Errorf("action audit %q not found", record.ID)+ }+ return actionTransitionConflict(current, record, ErrActionNotExecuting)+ }+ if err := recordActionLifecycleEventSQL(tx, event); err != nil {+ return err+ }+ if _, err := tx.Exec(`DELETE FROM action_dispatch_outbox WHERE attempt_id=?`, attempt.ID); err != nil {+ return err+ }+ if err := tx.Commit(); err != nil {+ return err+ }+ committed = true+ return nil+}++func (s *SQLiteResourceStore) RecoverActionDispatch(actionID string, now time.Time) (ActionDispatchAttempt, bool, error) {+ attempt, found, err := s.GetActionDispatchAttempt(actionID)+ if err != nil || !found {+ return attempt, found, err+ }+ if attempt.State != ActionDispatchClaimed || attempt.LeaseExpiresAt.IsZero() || now.Before(attempt.LeaseExpiresAt) {+ return attempt, false, nil+ }+ return s.ClaimActionDispatch(actionID, "recovery", now, time.Second)+}++func (s *SQLiteResourceStore) ExpireActionAudits(now time.Time, limit int) ([]ActionAuditRecord, error) {+ if now.IsZero() {+ now = time.Now().UTC()+ } else {+ now = now.UTC()+ }+ if limit <= 0 || limit > 500 {+ limit = 100+ }+ rows, err := s.db.Query(`SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json, origin_json FROM action_audits WHERE state IN (?, ?, ?) ORDER BY updated_at ASC LIMIT ?`, ActionStatePlanned, ActionStatePending, ActionStateApproved, limit)+ if err != nil {+ return nil, err+ }+ var candidates []ActionAuditRecord+ for rows.Next() {+ record, scanErr := scanActionAuditRecord(rows)+ if scanErr != nil {+ rows.Close()+ return nil, scanErr+ }+ if !record.Plan.ExpiresAt.IsZero() && !now.Before(record.Plan.ExpiresAt) {+ candidates = append(candidates, record)+ }+ }+ if err = rows.Close(); err != nil {+ return nil, err+ }+ var expired []ActionAuditRecord+ for _, record := range candidates {+ updated, event, applyErr := ExpireAction(record, "system:expiry", now)+ if applyErr != nil {+ continue+ }+ if persistErr := s.RecordActionExpiry(updated, event); persistErr == nil {+ expired = append(expired, updated)+ } else if !errors.Is(persistErr, ErrActionExecutionFinal) {+ return expired, persistErr+ }+ }+ return expired, nil+}++func (s *SQLiteResourceStore) GetActionAuditsByStates(states []ActionState, limit int) ([]ActionAuditRecord, error) {+ if len(states) == 0 {+ return []ActionAuditRecord{}, nil+ }+ if limit <= 0 || limit > 500 {+ limit = 100+ }+ marks := make([]string, len(states))+ args := make([]any, 0, len(states)+1)+ for i, state := range states {+ if !isValidActionState(state) {+ return nil, fmt.Errorf("unsupported action state %q", state)+ }+ marks[i] = "?"+ args = append(args, string(state))+ }+ args = append(args, limit)+ rows, err := s.db.Query(`SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json, origin_json FROM action_audits WHERE state IN (`+strings.Join(marks, ",")+`) ORDER BY updated_at DESC, created_at DESC LIMIT ?`, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []ActionAuditRecord+ for rows.Next() {+ record, scanErr := scanActionAuditRecord(rows)+ if scanErr != nil {+ return nil, scanErr+ }+ out = append(out, record)+ }+ return out, rows.Err()+}++// MemoryStore mirrors the durable transport authority contract for unit tests.+func (m *MemoryStore) RecordActionExecutionAdmission(record ActionAuditRecord, event ActionLifecycleEvent, attempt ActionDispatchAttempt) error {+ record, event, attempt, err := validateExecutionAdmission(record, event, attempt)+ if err != nil {+ return err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ for i := range m.actionAudits {+ if m.actionAudits[i].ID == record.ID {+ if err := ValidateActionExecutionStart(m.actionAudits[i], event.Timestamp); err != nil {+ return err+ }+ m.actionAudits[i] = record+ m.actionLifecycleEvents = append(m.actionLifecycleEvents, event)+ m.actionDispatchAttempts[record.ID] = attempt+ return nil+ }+ }+ return fmt.Errorf("action audit %q not found", record.ID)+}++func (m *MemoryStore) RecordActionPolicyExecutionAdmission(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent, attempt ActionDispatchAttempt) error {+ record, executionEvent, attempt, err := validateExecutionAdmission(record, executionEvent, attempt)+ if err != nil {+ return err+ }+ approvalEvent, err = NormalizeActionLifecycleEvent(approvalEvent)+ if err != nil {+ return err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ for i := range m.actionAudits {+ if m.actionAudits[i].ID == record.ID {+ current := m.actionAudits[i]+ if current.State != ActionStatePlanned && current.State != ActionStatePending {+ return actionTransitionConflict(current, record, ErrActionNotApproved)+ }+ m.actionAudits[i] = record+ m.actionLifecycleEvents = append(m.actionLifecycleEvents, approvalEvent, executionEvent)+ m.actionDispatchAttempts[record.ID] = attempt+ return nil+ }+ }+ return fmt.Errorf("action audit %q not found", record.ID)+}++func (m *MemoryStore) RecordActionExpiry(record ActionAuditRecord, event ActionLifecycleEvent) error {+ record, err := NormalizeActionAuditRecord(record)+ if err != nil {+ return err+ }+ event, err = NormalizeActionLifecycleEvent(event)+ if err != nil {+ return err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ for i := range m.actionAudits {+ if m.actionAudits[i].ID == record.ID {+ current := m.actionAudits[i]+ switch current.State {+ case ActionStatePlanned, ActionStatePending, ActionStateApproved:+ m.actionAudits[i] = record+ m.actionLifecycleEvents = append(m.actionLifecycleEvents, event)+ return nil+ default:+ return actionTransitionConflict(current, record, ErrActionExecutionFinal)+ }+ }+ }+ return fmt.Errorf("action audit %q not found", record.ID)+}++func (m *MemoryStore) GetActionDispatchAttempt(actionID string) (ActionDispatchAttempt, bool, error) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ a, ok := m.actionDispatchAttempts[strings.TrimSpace(actionID)]+ return a, ok, nil+}+func (m *MemoryStore) GetActionDispatchReceipt(attemptID string) (ActionDispatchReceipt, bool, error) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ r, ok := m.actionDispatchReceipts[strings.TrimSpace(attemptID)]+ return r, ok, nil+}++func (m *MemoryStore) ClaimActionDispatch(actionID, owner string, now time.Time, lease time.Duration) (ActionDispatchAttempt, bool, error) {+ owner = strings.TrimSpace(owner)+ if owner == "" || lease <= 0 {+ return ActionDispatchAttempt{}, false, ErrActionDispatchNotClaimable+ }+ if now.IsZero() {+ now = time.Now().UTC()+ } else {+ now = now.UTC()+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ a, ok := m.actionDispatchAttempts[actionID]+ if !ok {+ return a, false, ErrActionDispatchNotFound+ }+ if a.State == ActionDispatchClaimed && !a.LeaseExpiresAt.IsZero() && !now.Before(a.LeaseExpiresAt) {+ a.State, a.UpdatedAt, a.LeaseOwner, a.LeaseExpiresAt = ActionDispatchQueued, now, "", time.Time{}+ m.actionDispatchAttempts[actionID] = a+ }+ if a.State == ActionDispatchClaimed && a.LeaseOwner == owner && now.Before(a.LeaseExpiresAt) {+ return a, false, nil+ }+ if a.State != ActionDispatchQueued {+ return a, false, nil+ }+ a.State, a.UpdatedAt, a.LeaseOwner, a.LeaseExpiresAt = ActionDispatchClaimed, now, owner, now.Add(lease)+ m.actionDispatchAttempts[actionID] = a+ return a, true, nil+}++func (m *MemoryStore) MarkActionDispatchStarted(attemptID, owner string, now time.Time) (ActionDispatchAttempt, error) {+ if now.IsZero() {+ now = time.Now().UTC()+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ for actionID, a := range m.actionDispatchAttempts {+ if a.ID != attemptID {+ continue+ }+ if a.State != ActionDispatchClaimed {+ return a, ErrActionDispatchNotClaimable+ }+ if a.LeaseOwner != strings.TrimSpace(owner) {+ return a, ErrActionDispatchLeaseMismatch+ }+ a.State, a.UpdatedAt, a.DispatchCount, a.LeaseOwner, a.LeaseExpiresAt = ActionDispatchReceiptPending, now, a.DispatchCount+1, "", time.Time{}+ m.actionDispatchAttempts[actionID] = a+ return a, nil+ }+ return ActionDispatchAttempt{}, ErrActionDispatchNotFound+}++func (m *MemoryStore) RecordActionDispatchReceipt(receipt ActionDispatchReceipt) (ActionDispatchAttempt, error) {+ receipt, err := NormalizeActionDispatchReceipt(receipt)+ if err != nil {+ return ActionDispatchAttempt{}, err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ a, ok := m.actionDispatchAttempts[receipt.ActionID]+ if !ok {+ return a, ErrActionDispatchNotFound+ }+ if current, exists := m.actionDispatchReceipts[receipt.AttemptID]; exists {+ if current.TransportRequestID != receipt.TransportRequestID {+ return a, ErrActionDispatchReceiptConflict+ }+ return a, nil+ }+ if a.State != ActionDispatchReceiptPending {+ return a, ErrActionDispatchReceiptConflict+ }+ a.State, a.UpdatedAt, a.LeaseOwner, a.LeaseExpiresAt = ActionDispatchReceiptRecorded, receipt.ReceivedAt, "", time.Time{}+ m.actionDispatchAttempts[receipt.ActionID] = a+ m.actionDispatchReceipts[receipt.AttemptID] = receipt+ return a, nil+}++func (m *MemoryStore) RecordActionDispatchCompletion(receipt ActionDispatchReceipt, record ActionAuditRecord, event ActionLifecycleEvent) error {+ receipt, record, event, err := normalizeActionDispatchCompletion(receipt, record, event)+ if err != nil {+ return err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ attempt, found := m.actionDispatchAttempts[record.ID]+ if !found || attempt.ID != receipt.AttemptID {+ return ErrActionDispatchNotFound+ }+ existingReceipt, receiptExists := m.actionDispatchReceipts[receipt.AttemptID]+ if receiptExists {+ if existingReceipt.TransportRequestID != receipt.TransportRequestID || attempt.State != ActionDispatchReceiptRecorded {+ return ErrActionDispatchReceiptConflict+ }+ } else if attempt.State != ActionDispatchReceiptPending {+ return ErrActionDispatchReceiptConflict+ }+ auditIndex := -1+ for i := range m.actionAudits {+ if m.actionAudits[i].ID == record.ID {+ auditIndex = i+ break+ }+ }+ if auditIndex < 0 {+ return fmt.Errorf("action audit %q not found", record.ID)+ }+ current := m.actionAudits[auditIndex]+ if current.State != ActionStateExecuting {+ return actionTransitionConflict(current, record, ErrActionNotExecuting)+ }+ if !ActionAuditIdentityMatches(current, record) {+ return ErrActionIdentityConflict+ }+ attempt.State = ActionDispatchReceiptRecorded+ attempt.UpdatedAt = receipt.ReceivedAt+ attempt.LeaseOwner = ""+ attempt.LeaseExpiresAt = time.Time{}+ m.actionDispatchAttempts[record.ID] = attempt+ m.actionDispatchReceipts[receipt.AttemptID] = receipt+ m.actionAudits[auditIndex] = record+ m.actionLifecycleEvents = append(m.actionLifecycleEvents, event)+ return nil+}++func (m *MemoryStore) RecoverActionDispatch(actionID string, now time.Time) (ActionDispatchAttempt, bool, error) {+ a, ok, err := m.GetActionDispatchAttempt(actionID)+ if err != nil || !ok || a.State != ActionDispatchClaimed || a.LeaseExpiresAt.IsZero() || now.Before(a.LeaseExpiresAt) {+ return a, false, err+ }+ return m.ClaimActionDispatch(actionID, "recovery", now, time.Second)+}++func (m *MemoryStore) ExpireActionAudits(now time.Time, limit int) ([]ActionAuditRecord, error) {+ m.mu.RLock()+ var candidates []ActionAuditRecord+ for _, r := range m.actionAudits {+ if (r.State == ActionStatePlanned || r.State == ActionStatePending || r.State == ActionStateApproved) && !r.Plan.ExpiresAt.IsZero() && !now.Before(r.Plan.ExpiresAt) {+ candidates = append(candidates, r)+ }+ }+ m.mu.RUnlock()+ if limit > 0 && len(candidates) > limit {+ candidates = candidates[:limit]+ }+ var out []ActionAuditRecord+ for _, r := range candidates {+ expired, event, err := ExpireAction(r, "system:expiry", now)+ if err == nil && m.RecordActionExpiry(expired, event) == nil {+ out = append(out, expired)+ }+ }+ return out, nil+}++func (m *MemoryStore) GetActionAuditsByStates(states []ActionState, limit int) ([]ActionAuditRecord, error) {+ set := map[ActionState]bool{}+ for _, s := range states {+ set[s] = true+ }+ m.mu.RLock()+ defer m.mu.RUnlock()+ var out []ActionAuditRecord+ for i := len(m.actionAudits) - 1; i >= 0; i-- {+ if set[m.actionAudits[i].State] {+ out = append(out, m.actionAudits[i])+ if limit > 0 && len(out) >= limit {+ break+ }+ }+ }+ return out, nil+}diff --git a/internal/unifiedresources/action_dispatch_store_test.go b/internal/unifiedresources/action_dispatch_store_test.gonew file mode 100644index 0000000000..be8e134390--- /dev/null+++ b/internal/unifiedresources/action_dispatch_store_test.go@@ -0,0 +1,291 @@+package unifiedresources++import (+ "errors"+ "sync"+ "testing"+ "time"+)++func admitDispatchTestAction(t *testing.T, store ResourceStore, id string, now time.Time) ActionDispatchAttempt {+ t.Helper()+ record := atomicLifecycleTestRecord(id, ActionStatePlanned)+ record.CreatedAt = now+ record.UpdatedAt = now+ record.Plan.PlannedAt = now+ record.Plan.ExpiresAt = now.Add(time.Hour)+ record.Plan.RequiresApproval = false+ record.Plan.ApprovalPolicy = ApprovalNone+ if _, _, err := store.CreateActionAudit(record, atomicLifecycleInitialEvents(record)); err != nil {+ t.Fatal(err)+ }+ started, event, err := BeginActionExecution(record, "operator", now)+ if err != nil {+ t.Fatal(err)+ }+ attempt, err := NewActionDispatchAttempt(id, now)+ if err != nil {+ t.Fatal(err)+ }+ if err := store.RecordActionExecutionAdmission(started, event, attempt); err != nil {+ t.Fatal(err)+ }+ return attempt+}++func runActionDispatchCrashBoundaries(t *testing.T, store ResourceStore) {+ t.Helper()+ now := time.Date(2026, 7, 11, 14, 0, 0, 0, time.UTC)+ attempt := admitDispatchTestAction(t, store, "act_dispatch_crash", now)+ claimed, ok, err := store.ClaimActionDispatch(attempt.ActionID, "worker-a", now, time.Second)+ if err != nil || !ok || claimed.DispatchCount != 0 {+ t.Fatalf("initial claim=%#v ok=%v err=%v", claimed, ok, err)+ }+ // Crash after claim but before MarkActionDispatchStarted: the same durable+ // attempt is safely reclaimed and dispatch count remains zero.+ reclaimed, ok, err := store.ClaimActionDispatch(attempt.ActionID, "worker-b", now.Add(2*time.Second), time.Second)+ if err != nil || !ok || reclaimed.ID != attempt.ID || reclaimed.DispatchCount != 0 {+ t.Fatalf("reclaim=%#v ok=%v err=%v", reclaimed, ok, err)+ }+ started, err := store.MarkActionDispatchStarted(attempt.ID, "worker-b", now.Add(2*time.Second))+ if err != nil || started.State != ActionDispatchReceiptPending || started.DispatchCount != 1 {+ t.Fatalf("started=%#v err=%v", started, err)+ }+ if _, err := store.MarkActionDispatchStarted(attempt.ID, "worker-b", now.Add(3*time.Second)); !errors.Is(err, ErrActionDispatchNotClaimable) {+ t.Fatalf("duplicate pre-send boundary error=%v", err)+ }+ // Crash after the pre-send boundary: recovery cannot claim or resend.+ resumed, ok, err := store.RecoverActionDispatch(attempt.ActionID, now.Add(time.Hour))+ if err != nil || ok || resumed.State != ActionDispatchReceiptPending || resumed.DispatchCount != 1 {+ t.Fatalf("post-start recovery=%#v ok=%v err=%v", resumed, ok, err)+ }+}++func TestMemoryStoreActionDispatchCrashBoundaries(t *testing.T) {+ runActionDispatchCrashBoundaries(t, NewMemoryStore())+}++func TestSQLiteActionDispatchCrashBoundaries(t *testing.T) {+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ runActionDispatchCrashBoundaries(t, store)+}++func runConcurrentActionDispatchClaimHasOneWinner(t *testing.T, store ResourceStore) {+ t.Helper()+ now := time.Now().UTC()+ attempt := admitDispatchTestAction(t, store, "act_dispatch_claim", now)+ start := make(chan struct{})+ var wg sync.WaitGroup+ var mu sync.Mutex+ winners := 0+ for _, owner := range []string{"worker-a", "worker-b"} {+ wg.Add(1)+ go func(owner string) {+ defer wg.Done()+ <-start+ _, claimed, claimErr := store.ClaimActionDispatch(attempt.ActionID, owner, now, time.Minute)+ if claimErr != nil {+ t.Errorf("ClaimActionDispatch: %v", claimErr)+ }+ if claimed {+ mu.Lock()+ winners+++ mu.Unlock()+ }+ }(owner)+ }+ close(start)+ wg.Wait()+ if winners != 1 {+ t.Fatalf("claim winners=%d, want 1", winners)+ }+}++func TestMemoryStoreConcurrentActionDispatchClaimHasOneWinner(t *testing.T) {+ runConcurrentActionDispatchClaimHasOneWinner(t, NewMemoryStore())+}++func TestSQLiteConcurrentActionDispatchClaimHasOneWinner(t *testing.T) {+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ runConcurrentActionDispatchClaimHasOneWinner(t, store)+}++func TestSQLiteActionDispatchAdmissionRollsBackAuditAndOutboxTogether(t *testing.T) {+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ now := time.Now().UTC()+ record := atomicLifecycleTestRecord("act_dispatch_rollback", ActionStatePlanned)+ record.Plan.RequiresApproval = false+ record.Plan.ApprovalPolicy = ApprovalNone+ if _, _, err := store.CreateActionAudit(record, atomicLifecycleInitialEvents(record)); err != nil {+ t.Fatal(err)+ }+ if _, err := store.db.Exec(`CREATE TRIGGER fail_dispatch_outbox BEFORE INSERT ON action_dispatch_outbox BEGIN SELECT RAISE(FAIL, 'outbox failure'); END`); err != nil {+ t.Fatal(err)+ }+ started, event, _ := BeginActionExecution(record, "operator", now)+ attempt, _ := NewActionDispatchAttempt(record.ID, now)+ if err := store.RecordActionExecutionAdmission(started, event, attempt); err == nil {+ t.Fatal("expected admission failure")+ }+ current, found, err := store.GetActionAudit(record.ID)+ if err != nil || !found || current.State != ActionStatePlanned {+ t.Fatalf("current=%#v found=%v err=%v", current, found, err)+ }+ if _, found, err := store.GetActionDispatchAttempt(record.ID); err != nil || found {+ t.Fatalf("attempt found=%v err=%v", found, err)+ }+}++func TestSQLiteActionDispatchReceiptIsIdempotentAndCorrelatedAcrossRestart(t *testing.T) {+ dir := t.TempDir()+ now := time.Now().UTC()+ store, err := NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ attempt := admitDispatchTestAction(t, store, "act_dispatch_receipt", now)+ if _, ok, err := store.ClaimActionDispatch(attempt.ActionID, "worker", now, time.Minute); err != nil || !ok {+ t.Fatalf("claim ok=%v err=%v", ok, err)+ }+ if _, err := store.MarkActionDispatchStarted(attempt.ID, "worker", now); err != nil {+ t.Fatal(err)+ }+ if err := store.Close(); err != nil {+ t.Fatal(err)+ }+ store, err = NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ receipt := ActionDispatchReceipt{AttemptID: attempt.ID, ActionID: attempt.ActionID, TransportRequestID: attempt.ID, ReceivedAt: now.Add(time.Minute)}+ if _, err := store.RecordActionDispatchReceipt(receipt); err != nil {+ t.Fatal(err)+ }+ if _, err := store.RecordActionDispatchReceipt(receipt); err != nil {+ t.Fatalf("duplicate receipt: %v", err)+ }+ receipt.TransportRequestID = "different"+ if _, err := store.RecordActionDispatchReceipt(receipt); !errors.Is(err, ErrActionDispatchReceiptConflict) {+ t.Fatalf("conflicting receipt error=%v", err)+ }+}++func runEarlyActionDispatchReceiptIsRejected(t *testing.T, store ResourceStore) {+ t.Helper()+ now := time.Now().UTC()+ attempt := admitDispatchTestAction(t, store, "act_dispatch_early_receipt", now)+ if _, ok, err := store.ClaimActionDispatch(attempt.ActionID, "worker", now, time.Minute); err != nil || !ok {+ t.Fatalf("claim ok=%v err=%v", ok, err)+ }+ receipt := ActionDispatchReceipt{AttemptID: attempt.ID, ActionID: attempt.ActionID, TransportRequestID: attempt.ID, ReceivedAt: now}+ if _, err := store.RecordActionDispatchReceipt(receipt); !errors.Is(err, ErrActionDispatchReceiptConflict) {+ t.Fatalf("early receipt error=%v", err)+ }+ current, found, err := store.GetActionDispatchAttempt(attempt.ActionID)+ if err != nil || !found || current.State != ActionDispatchClaimed || current.DispatchCount != 0 {+ t.Fatalf("current=%#v found=%v err=%v", current, found, err)+ }+}++func TestMemoryStoreEarlyActionDispatchReceiptIsRejected(t *testing.T) {+ runEarlyActionDispatchReceiptIsRejected(t, NewMemoryStore())+}++func TestSQLiteEarlyActionDispatchReceiptIsRejected(t *testing.T) {+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ runEarlyActionDispatchReceiptIsRejected(t, store)+}++func prepareCorrelatedDispatchCompletion(t *testing.T, store ResourceStore, id string, now time.Time) (ActionDispatchAttempt, ActionAuditRecord, ActionLifecycleEvent, ActionDispatchReceipt) {+ t.Helper()+ attempt := admitDispatchTestAction(t, store, id, now)+ if _, claimed, err := store.ClaimActionDispatch(id, "worker", now, time.Minute); err != nil || !claimed {+ t.Fatalf("claim claimed=%v err=%v", claimed, err)+ }+ if _, err := store.MarkActionDispatchStarted(attempt.ID, "worker", now); err != nil {+ t.Fatal(err)+ }+ executing, found, err := store.GetActionAudit(id)+ if err != nil || !found {+ t.Fatalf("executing found=%v err=%v", found, err)+ }+ completed, event, err := CompleteActionExecution(executing, &ExecutionResult{Success: true, Output: "correlated"}, "operator", now.Add(time.Second))+ if err != nil {+ t.Fatal(err)+ }+ receipt := ActionDispatchReceipt{AttemptID: attempt.ID, ActionID: id, TransportRequestID: attempt.ID, ReceivedAt: now.Add(time.Second)}+ return attempt, completed, event, receipt+}++func TestSQLiteCorrelatedDispatchCompletionRollsBackReceiptOnTerminalWriteFailure(t *testing.T) {+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ now := time.Now().UTC()+ attempt, completed, event, receipt := prepareCorrelatedDispatchCompletion(t, store, "act_dispatch_atomic_rollback", now)+ if _, err := store.db.Exec(`CREATE TRIGGER fail_terminal_event BEFORE INSERT ON action_lifecycle_events WHEN NEW.state IN ('completed', 'failed') BEGIN SELECT RAISE(FAIL, 'terminal event failure'); END`); err != nil {+ t.Fatal(err)+ }+ if err := store.RecordActionDispatchCompletion(receipt, completed, event); err == nil {+ t.Fatal("expected atomic completion failure")+ }+ if _, found, err := store.GetActionDispatchReceipt(attempt.ID); err != nil || found {+ t.Fatalf("receipt found=%v err=%v", found, err)+ }+ currentAttempt, found, err := store.GetActionDispatchAttempt(attempt.ActionID)+ if err != nil || !found || currentAttempt.State != ActionDispatchReceiptPending {+ t.Fatalf("attempt=%#v found=%v err=%v", currentAttempt, found, err)+ }+ currentAudit, found, err := store.GetActionAudit(attempt.ActionID)+ if err != nil || !found || currentAudit.State != ActionStateExecuting || currentAudit.Result != nil {+ t.Fatalf("audit=%#v found=%v err=%v", currentAudit, found, err)+ }+}++func TestSQLiteCorrelatedDispatchCompletionSurvivesRestartWithoutReceiptOnlyState(t *testing.T) {+ dir := t.TempDir()+ now := time.Now().UTC()+ store, err := NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ attempt, completed, event, receipt := prepareCorrelatedDispatchCompletion(t, store, "act_dispatch_atomic_restart", now)+ if err := store.RecordActionDispatchCompletion(receipt, completed, event); err != nil {+ t.Fatal(err)+ }+ if err := store.Close(); err != nil {+ t.Fatal(err)+ }+ store, err = NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ storedReceipt, found, err := store.GetActionDispatchReceipt(attempt.ID)+ if err != nil || !found || storedReceipt.AttemptID != attempt.ID {+ t.Fatalf("receipt=%#v found=%v err=%v", storedReceipt, found, err)+ }+ storedAudit, found, err := store.GetActionAudit(attempt.ActionID)+ if err != nil || !found || storedAudit.State != ActionStateCompleted || storedAudit.Result == nil || !storedAudit.Result.Success {+ t.Fatalf("audit=%#v found=%v err=%v", storedAudit, found, err)+ }+}diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.goindex f6942e8ee3..bbfadd800b 100644--- a/internal/unifiedresources/actions.go+++ b/internal/unifiedresources/actions.go@@ -18,6 +18,7 @@ const (ActionStatePending ActionState = "pending_approval"ActionStateApproved ActionState = "approved"ActionStateRejected ActionState = "rejected"+ ActionStateExpired ActionState = "expired"ActionStateExecuting ActionState = "executing"ActionStateCompleted ActionState = "completed"ActionStateFailed ActionState = "failed"@@ -382,6 +383,7 @@ var (ErrActionAlreadyExecuting = errors.New("action is already executing")ErrActionExecutionFinal = errors.New("action execution is already final")ErrActionPlanExpired = errors.New("action plan expired")+ ErrActionPlanNotExpired = errors.New("action plan has not expired")ErrActionDryRunOnly = errors.New("action plan is dry-run only")ErrActionExecutionRefusal = errors.New("action execution refusal is not a permanent terminal refusal")ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")@@ -510,6 +512,41 @@ func ApplyActionDecision(record ActionAuditRecord, approval ActionApprovalRecordreturn normalized, normalizedEvent, nil}+// ExpireAction materializes plan expiry as an explicit monotonic lifecycle+// state. Expiry is admission truth, not an execution-result classification.+func ExpireAction(record ActionAuditRecord, actor string, now time.Time) (ActionAuditRecord, ActionLifecycleEvent, error) {+ if now.IsZero() {+ now = time.Now().UTC()+ } else {+ now = now.UTC()+ }+ if record.State == ActionStateExpired {+ return record, ActionLifecycleEvent{}, nil+ }+ switch record.State {+ case ActionStatePlanned, ActionStatePending, ActionStateApproved:+ default:+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ErrActionExecutionFinal+ }+ if record.Plan.ExpiresAt.IsZero() || now.Before(record.Plan.ExpiresAt) {+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ErrActionPlanNotExpired+ }+ record.State = ActionStateExpired+ record.UpdatedAt = now+ normalized, err := NormalizeActionAuditRecord(record)+ if err != nil {+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err+ }+ event, err := NormalizeActionLifecycleEvent(ActionLifecycleEvent{+ ActionID: normalized.ID,+ Timestamp: now,+ State: ActionStateExpired,+ Actor: strings.TrimSpace(actor),+ Message: "Action plan expired before dispatch.",+ })+ return normalized, event, err+}+// BeginActionExecution moves an explicitly executable action into executing.// Approval remains separate from execution: approval-required plans must be// approved first, while approval-free plans may start from planned only through@@ -683,7 +720,7 @@ func ValidateActionExecutionStart(record ActionAuditRecord, now time.Time) errorswitch record.State {case ActionStateExecuting:return ErrActionAlreadyExecuting- case ActionStateCompleted, ActionStateFailed:+ case ActionStateExpired, ActionStateCompleted, ActionStateFailed:return ErrActionExecutionFinal}if !record.Plan.ExpiresAt.IsZero() && !now.Before(record.Plan.ExpiresAt) {@@ -700,7 +737,7 @@ func ValidateActionExecutionStart(record ActionAuditRecord, now time.Time) errorreturn nil}return ErrActionNotApproved- case ActionStatePending, ActionStateRejected:+ case ActionStatePending, ActionStateRejected, ActionStateExpired:return ErrActionNotApproveddefault:return fmt.Errorf("unsupported action state %q", record.State)@@ -905,7 +942,7 @@ func NormalizeActionPreflight(preflight *ActionPreflight, request ActionRequest,func isValidActionState(state ActionState) bool {switch state {- case ActionStatePlanned, ActionStatePending, ActionStateApproved, ActionStateRejected, ActionStateExecuting, ActionStateCompleted, ActionStateFailed:+ case ActionStatePlanned, ActionStatePending, ActionStateApproved, ActionStateRejected, ActionStateExpired, ActionStateExecuting, ActionStateCompleted, ActionStateFailed:return truedefault:return falsediff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex 27fd5294f1..3fefd1336f 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -674,8 +674,10 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {// publishes only after the corresponding store write."OnActionTransition func(orgID string, record unified.ActionAuditRecord)","func (s *Service) publishTransition(orgID string, record unified.ActionAuditRecord)",- "store.RecordActionExecutionStart(started, startEvent)",- "store.RecordActionExecutionResult(completed, doneEvent)",+ "store.RecordActionExecutionAdmission(started, startEvent, attempt)",+ "store.MarkActionDispatchStarted(attempt.ID, owner, s.now())",+ "s.Executor.ExecuteAction(withDispatchAttempt(ctx, attempt), record)",+ "store.RecordActionDispatchCompletion(receipt, completed, doneEvent)",},filepath.Join("..", "api", "actions.go"): {// The REST layer is a thin adapter over the shared lifecyclediff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.goindex e3e5d232f3..211c259f36 100644--- a/internal/unifiedresources/store.go+++ b/internal/unifiedresources/store.go@@ -46,12 +46,25 @@ type ResourceStore interface {GetActionAudit(actionID string) (ActionAuditRecord, bool, error)GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error)RecordActionDecision(record ActionAuditRecord, event ActionLifecycleEvent) error+ RecordActionExpiry(record ActionAuditRecord, event ActionLifecycleEvent) errorRecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) errorRecordActionPolicyExecutionStart(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent) error+ RecordActionExecutionAdmission(record ActionAuditRecord, event ActionLifecycleEvent, attempt ActionDispatchAttempt) error+ RecordActionPolicyExecutionAdmission(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent, attempt ActionDispatchAttempt) errorRecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) errorRecordActionExecutionRefusal(record ActionAuditRecord, event ActionLifecycleEvent) errorRecordActionLifecycleEvent(event ActionLifecycleEvent) errorGetActionLifecycleEvents(actionID string, since time.Time, limit int) ([]ActionLifecycleEvent, error)+ GetActionDispatchAttempt(actionID string) (ActionDispatchAttempt, bool, error)+ GetActionDispatchReceipt(attemptID string) (ActionDispatchReceipt, bool, error)+ ClaimActionDispatch(actionID, owner string, now time.Time, lease time.Duration) (ActionDispatchAttempt, bool, error)+ MarkActionDispatchStarted(attemptID, owner string, now time.Time) (ActionDispatchAttempt, error)+ RecordActionDispatchReceipt(receipt ActionDispatchReceipt) (ActionDispatchAttempt, error)+ RecordActionDispatchCompletion(receipt ActionDispatchReceipt, record ActionAuditRecord, event ActionLifecycleEvent) error+ RecoverActionDispatch(actionID string, now time.Time) (ActionDispatchAttempt, bool, error)+ ExpireActionAudits(now time.Time, limit int) ([]ActionAuditRecord, error)+ GetActionAuditsByStates(states []ActionState, limit int) ([]ActionAuditRecord, error)+ GetPendingActionAudits(limit int) ([]ActionAuditRecord, error)RecordExportAudit(record ExportAuditRecord) errorGetExportAudits(since time.Time, limit int) ([]ExportAuditRecord, error)// Operator-set per-resource state. See ResourceOperatorState.@@ -461,6 +474,30 @@ func (s *SQLiteResourceStore) initSchema() error {message TEXT);CREATE INDEX IF NOT EXISTS idx_action_lifecycle_events_action ON action_lifecycle_events(action_id, timestamp DESC);+ CREATE TABLE IF NOT EXISTS action_dispatch_attempts (+ attempt_id TEXT PRIMARY KEY,+ action_id TEXT NOT NULL UNIQUE,+ state TEXT NOT NULL,+ created_at DATETIME NOT NULL,+ updated_at DATETIME NOT NULL,+ lease_owner TEXT,+ lease_expires_at DATETIME,+ dispatch_count INTEGER NOT NULL DEFAULT 0+ );+ CREATE INDEX IF NOT EXISTS idx_action_dispatch_attempts_state_updated ON action_dispatch_attempts(state, updated_at);+ CREATE TABLE IF NOT EXISTS action_dispatch_outbox (+ attempt_id TEXT PRIMARY KEY,+ action_id TEXT NOT NULL UNIQUE,+ available_at DATETIME NOT NULL,+ FOREIGN KEY(attempt_id) REFERENCES action_dispatch_attempts(attempt_id)+ );+ CREATE TABLE IF NOT EXISTS action_dispatch_receipts (+ attempt_id TEXT PRIMARY KEY,+ action_id TEXT NOT NULL UNIQUE,+ transport_request_id TEXT NOT NULL,+ received_at DATETIME NOT NULL,+ FOREIGN KEY(attempt_id) REFERENCES action_dispatch_attempts(attempt_id)+ );CREATE TABLE IF NOT EXISTS export_audits (id TEXT PRIMARY KEY,@@ -2120,6 +2157,8 @@ func actionTransitionConflict(current ActionAuditRecord, desired ActionAuditRecoswitch current.State {case ActionStateRejected, ActionStateCompleted, ActionStateFailed:return ErrActionExecutionFinal+ case ActionStateExpired:+ return ErrActionPlanExpiredcase ActionStateExecuting:if desired.State == ActionStateExecuting {return ErrActionAlreadyExecuting@@ -2778,23 +2817,27 @@ func (s *SQLiteResourceStore) ClearResourceOperatorStateWithMaintenanceLifecycle// MemoryStore is an in-memory implementation for tests.type MemoryStore struct {- mu sync.RWMutex- links []ResourceLink- exclusions []ResourceExclusion- changes []ResourceChange- actionAudits []ActionAuditRecord- actionLifecycleEvents []ActionLifecycleEvent- exportAudits []ExportAuditRecord- resourceOperatorState map[string]ResourceOperatorState- loopReports map[string]LoopReport- identityPins map[string]ResourceIdentityPin+ mu sync.RWMutex+ links []ResourceLink+ exclusions []ResourceExclusion+ changes []ResourceChange+ actionAudits []ActionAuditRecord+ actionLifecycleEvents []ActionLifecycleEvent+ actionDispatchAttempts map[string]ActionDispatchAttempt+ actionDispatchReceipts map[string]ActionDispatchReceipt+ exportAudits []ExportAuditRecord+ resourceOperatorState map[string]ResourceOperatorState+ loopReports map[string]LoopReport+ identityPins map[string]ResourceIdentityPin}func NewMemoryStore() *MemoryStore {return &MemoryStore{- resourceOperatorState: make(map[string]ResourceOperatorState),- loopReports: make(map[string]LoopReport),- identityPins: make(map[string]ResourceIdentityPin),+ resourceOperatorState: make(map[string]ResourceOperatorState),+ loopReports: make(map[string]LoopReport),+ identityPins: make(map[string]ResourceIdentityPin),+ actionDispatchAttempts: make(map[string]ActionDispatchAttempt),+ actionDispatchReceipts: make(map[string]ActionDispatchReceipt),}}diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.goindex 671430733d..dab7d08a2c 100644--- a/internal/unifiedresources/store_test.go+++ b/internal/unifiedresources/store_test.go@@ -786,6 +786,22 @@ func TestNewSQLiteResourceStore_InitializesCanonicalAuditSchemas(t *testing.T) {columns: []string{"id", "action_id", "timestamp", "state", "actor", "message"},indexes: []string{"idx_action_lifecycle_events_action"},},+ {+ name: "action_dispatch_attempts",+ columns: []string{+ "attempt_id", "action_id", "state", "created_at", "updated_at",+ "lease_owner", "lease_expires_at", "dispatch_count",+ },+ indexes: []string{"idx_action_dispatch_attempts_state_updated"},+ },+ {+ name: "action_dispatch_outbox",+ columns: []string{"attempt_id", "action_id", "available_at"},+ },+ {+ name: "action_dispatch_receipts",+ columns: []string{"attempt_id", "action_id", "transport_request_id", "received_at"},+ },{name: "export_audits",columns: []string{"id", "timestamp", "actor", "envelope_hash", "decision", "destination", "redactions_json"},