Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Add canonical action result truth

rcourtmanb7b897651b6e
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index e1af19f66b..1e080e4b28 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -4341,6 +4341,95 @@
"kind": "file"
}
]
+ },
+ {
+ "id": "RA38",
+ "summary": "Canonical terminal action truth preserves execution and verification as independent axes: no terminal consumer may collapse one into the other, no nil or unknown-effect executor tuple may infer success, and no result may claim independent verification without bounded durable evidence from a distinct trust domain.",
+ "kind": "invariant",
+ "blocking_level": "repo-ready",
+ "proof_type": "automated",
+ "lane_ids": [
+ "L6",
+ "L7",
+ "L13",
+ "L15",
+ "L16",
+ "L20"
+ ],
+ "subsystem_ids": [
+ "agent-lifecycle",
+ "ai-runtime",
+ "api-contracts",
+ "patrol-intelligence",
+ "relay-runtime",
+ "storage-recovery",
+ "unified-resources"
+ ],
+ "release_gate_ids": [],
+ "proof_commands": [
+ {
+ "id": "ra38-action-result-truth-and-persistence",
+ "run": [
+ "go",
+ "test",
+ "./internal/unifiedresources",
+ "-run",
+ "TestNormalizeActionResultTruthMatrix48|TestValidateActionResultEvidenceClassMatrix|TestActionResultLegacyProjectionMatrix48|TestCompleteActionExecutionRequiresExplicitResult|TestKnownPreDispatchRefusalIsNotRunAndNotVerified|TestLegacyTimeoutAndDisconnectMigrateInconclusive|TestMalformedStoredActionResultV2FailsClosed|TestActionResultV2MemoryStoreRoundTrip|TestActionResultV2SQLiteRoundTrip|TestActionResultV2SurvivesSQLiteReopen|TestCompensationFailureSurvivesSQLiteReopen|TestCompensationSucceededRestoredStateSurvivesSQLiteReopen|TestMalformedActionResultV2PersistsFailClosed|TestLegacyCompletedNilResultMigratesInconclusive|TestLegacyMissingVerificationMigratesNotAttempted|TestActionEvidenceCanonicalDigestStable|TestActionEvidenceCanonicalDigestChangesWithRetainedSemanticFields|TestActionEvidenceRedactionPreservesTruthAndCanonicalDigest|TestActionEvidenceRejectsUnboundedPayload|TestActionEvidenceBoundsApplyBeforeSecretRedaction|TestActionResultRedactionDeepCopiesAndRecomputesDigest|TestActionResultRedactionFailsClosedOnMalformedEvidence|TestCompensationNeverRewritesPrimaryResult|TestCompensationSucceededRequiresRestorationVerification|TestCompensationStateShapeValidationMatrix|TestActionTruthTypesStayUnifiedResourceOwned",
+ "-count=1"
+ ]
+ },
+ {
+ "id": "ra38-executor-and-terminal-consumer-projections",
+ "run": [
+ "go",
+ "test",
+ "./internal/actionlifecycle",
+ "./internal/api",
+ "./internal/relay",
+ "./pkg/aicontracts",
+ "-run",
+ "TestExecutorTupleNilNilPersistsInconclusiveContractViolation|TestExecutorTupleResultAndErrorIsContractViolation|TestExecutorTuplePostDispatchErrorPreservesReceiptPending|TestActionResultV2EventFindingContextTelemetryProjectionMatrix|TestActionResultV2JSONContractSnapshot|TestMalformedStoredActionResultV2CannotProjectSuccessOrVerification|TestPatrolActionBrokerTerminalReplayPreservesAuditAndEvents|TestPatrolActionReconciliationHydratesTerminalAuditAfterRestart|TestPatrolActionReconciliationCannotRegressFromOutOfOrderCallback|TestCanonicalActionOutcomeNotificationMatrix|TestActionBrokerPolicyMetadataCarriesNoAuthorizationMethod",
+ "-count=1"
+ ]
+ }
+ ],
+ "evidence": [
+ {
+ "repo": "pulse",
+ "path": "internal/actionlifecycle/service_action_result_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/api/action_result_v2_contract_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/relay/push_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/action_result_store_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/action_result_v2.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/action_result_v2_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ }
+ ]
}
],
"evidence_reference_policy": {
@@ -5898,7 +5987,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 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. Task 08 Phase B1 also makes requester and decision authority server-owned, binds actor and approval requirement into plan identity, rechecks current tenant/RBAC/token scope, and records multi-actor approvals through revision-CAS append-only decision facts plus atomic lifecycle transitions. MFA-required decisions remain explicitly unavailable until a core verifier validates and consumes action-bound cryptographic evidence; labels and local biometrics are not MFA. 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 UI and MSP delegation/inheritance, device-key/WebAuthn enrollment and verifier integration, 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. Task 08 Phase B1 also makes requester and decision authority server-owned, binds actor and approval requirement into plan identity, rechecks current tenant/RBAC/token scope, and records multi-actor approvals through revision-CAS append-only decision facts plus atomic lifecycle transitions. MFA-required decisions remain explicitly unavailable until a core verifier validates and consumes action-bound cryptographic evidence; labels and local biometrics are not MFA. Task 10 Phase B1 now owns one versioned ActionResultV2 with separate execution and verification axes, bounded trust-domain evidence, fail-closed redaction and stable digesting, nested compensation truth, durable Memory/SQLite compatibility persistence, executor tuple enforcement, and non-collapsing event, finding, context, telemetry, and relay projections. M4, M6, and claim 19 remain open pending Task 05 producer migration, Task 07 recovery, Tasks 06/09 workflow lab observations, Task 11 browser presentation, and Task 12 certification against the final SHA. Remaining post-RC hardening also includes mobile/relay inbox and push-dedup consumption, broader tenant defaults/inheritance and automation rate budgets, richer dry-run providers, multi-actor UI and MSP delegation/inheritance, device-key/WebAuthn enrollment and verifier integration, 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",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e2cd20e6b9..596279f110 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4327,3 +4327,11 @@ The preview copy affordances must use the shared accessible action-button
primitive, carry localized names for the exact value being copied, and retain
a 40-pixel mobile touch floor. The setup surface must not reintroduce raw,
unlabelled icon buttons or a phone-only copy-control fork.
+
+Agent-facing action completion events and resource-context history now expose
+the canonical `ActionResultV2` alongside bounded legacy projections. Consumers
+must branch on execution and verification separately: a completed transport is
+not a verified postcondition, and an independently verified label is valid only
+when the canonical evidence identifies a distinct trust domain. Agent-side
+producer migration and UI wording are downstream governed work, not permission
+to add an agent-local truth model.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 90e9dbb7ed..ba9c255eb0 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -5772,3 +5772,12 @@ compatibility window. AI-facing method labels, model assertions, and local
biometric claims never satisfy an MFA floor. Until the core step-up verifier
accepts action-bound cryptographic evidence, the honest runtime outcome is
step-up unavailable, not MFA approved.
+
+AI and Patrol projections consume `unifiedresources.ActionResultV2`; they do
+not own action-result enums. Finding reconciliation maps confirmed,
+contradicted, and inconclusive verification independently from execution, and
+therefore cannot treat terminal audit state as proof of the postcondition.
+Legacy investigation outcome strings remain projections for compatibility and
+must be derived from canonical truth rather than reconstructed locally. The
+typed disposition retains the serialized canonical two-axis result so the
+legacy single outcome is never the sole durable/read-model truth.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d5f0988cb1..4cc4b34a89 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7391,3 +7391,19 @@ CAS loss. Legacy nonterminal records without canonical actor/approval binding
are replan-required. MFA is not implemented by labels: until a server verifier
can validate and consume action-bound cryptographic evidence, MFA-required
decisions remain unavailable and no API or product surface may claim otherwise.
+
+Action completion now carries the unified-resource-owned `ActionResultV2`
+through canonical completion events and agent resource context while retaining
+legacy fields for one compatibility window. Lifecycle executors may return a
+result or an error, never both. `nil,nil` is persisted as an inconclusive
+executor contract violation. A post-dispatch timeout or disconnect preserves
+the Task 07 durable receipt-pending attempt for reconciliation and is never
+converted into execution failure or success. Patrol reconciliation and Pulse
+Intelligence telemetry derive verification from the V2 verification axis and
+do not infer it from audit terminal state. Patrol `ActionDisposition` carries
+the canonical result as a neutral serialized V2 envelope alongside a derived
+legacy verification string; `pkg/aicontracts` declares no competing truth
+enums. Malformed stored V2 fails closed across events, context, findings,
+telemetry, dispositions, and relay wording. Producer migration remains Task 05;
+receipt/verification-attempt recovery remains Task 07; browser presentation
+remains Task 11; final-SHA certification remains Task 12.
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index be1ce41f35..306cf9dc82 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -1967,3 +1967,10 @@ and offers an Assistant handoff. Collapsed-row attention state must consult the
same investigation action reference, so it cannot claim there is no approval
while the expanded panel has one. Browser proof must exercise pending,
terminal-verified, and legacy-history states rather than judging only source.
+
+Backend Patrol finding reconciliation now reads `ActionResultV2`: execution
+failed or known-not-run maps to fix failure; confirmed verification maps to
+verified; contradicted verification maps to verification failure; and
+not-attempted or inconclusive verification remains verification unknown. A
+successful execution never overwrites contradictory verification. Task 11
+still owns browser wording and proof for the distinct terminal states.
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 66b2007870..06c0de9205 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -1867,3 +1867,11 @@ Publication remains an O(1) wakeup keyed by org and action id; reconciliation
and read-time recovery use indexed action-audit lookups rather than scanning
findings or audit history. SQLite keeps dedicated state and valid-origin JSON
indexes for pending queues and missed-callback hydration.
+
+The `action.completed` projection reads the already-loaded
+`ActionAuditRecord` and derives canonical `ActionResultV2` plus the bounded
+legacy compatibility fields in process. Projection adds no action-store
+lookup, polling loop, provider call, or evidence fetch. Canonical evidence and
+reference counts, text, and identity fields remain bounded by the
+unified-resource-owned `ActionResultV2` contract, so event publication cannot
+turn terminal action evidence into an unbounded payload or hot-path query.
diff --git a/docs/release-control/v6/internal/subsystems/relay-runtime.md b/docs/release-control/v6/internal/subsystems/relay-runtime.md
index 1351e79178..ff9bccec4d 100644
--- a/docs/release-control/v6/internal/subsystems/relay-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/relay-runtime.md
@@ -154,3 +154,14 @@ binding. Detached relay/service tokens fail closed. A mobile-local biometric
label is not server-verifiable MFA evidence, so device-key enrollment and
cryptographic mobile step-up remain a later governed slice and relay must not
claim that local biometric success satisfied the core MFA floor.
+
+The canonical relay notification projection accepts `ActionResultV2` and uses
+wording that names execution separately from verification: not run, execution
+failed, execution inconclusive, executed and confirmed, executed but
+contradicted, verification not attempted, or verification inconclusive.
+Every canonical notification states both execution and verification even when
+one axis is failed, not run, or inconclusive, and confirmed/contradicted copy
+names agent-attested versus independent evidence.
+Legacy status-string notification input remains a compatibility boundary; new
+workflow producers must not use it as a competing truth model. Task 11 owns
+client presentation and Task 12 owns final-SHA certification.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 5deb112441..f3a8915f1a 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1327,3 +1327,14 @@ biometric, or UI method labels are not MFA evidence. MFA-required actions fail
closed unless the core verifier validates and single-use consumes evidence
bound to the actor, credential, organization, action, plan, outcome, and
challenge.
+
+Action completion and resource-context projections expose only normalized and
+redacted canonical evidence plus legacy compatibility fields derived from that
+truth. A present but malformed `ActionResultV2` fails closed to bounded
+inconclusive truth; it cannot fall back to legacy success or verified labels.
+Independent verification requires durable evidence from a trust domain
+distinct from the executor. Raw commands, provider stderr, credentials, and
+secret-bearing text do not enter `ActionResultV2` projections. Stable bounded
+refusal reason codes such as `resource_remediation_locked:` and `plan_drift:`
+may remain visible so authorized consumers can branch without receiving raw
+provider output.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 2fa1ceab44..8f9d3098e7 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -2032,6 +2032,13 @@ while storage detail drawers and filter controls must route summary series IDs,
source tones, and disk metrics through the shared storage helpers instead of
reconstructing them from local table state.
+Storage and recovery consumers of action events and resource history inherit
+the unified-resource-owned `ActionResultV2`. They must preserve execution,
+verification, evidence class, and nested compensation independently and must
+not turn a successful mutation plus contradicted readback into generic failure
+or success. Task 10 defines the schema only; restart compensation recovery and
+workflow rollback algorithms remain with their declared downstream owners.
+
The adjacent unified action store migration now adds a durable action decision
revision plus typed lifecycle-event kind, decision revision, and bound decision
JSON. Migration retains duplicate historical state rows as typed legacy facts,
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 287a438715..1df046bead 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1688,6 +1688,29 @@ through the canonical resource model, but unified-resource consumers must not
reintroduce removed workload aliases or feature-local resource-type shims just
to satisfy one table, drawer, or badge surface.
+### Canonical action-result truth
+
+`internal/unifiedresources/action_result_v2.go` is the sole schema authority
+for terminal action truth. `ActionResultV2` versions execution, verification,
+evidence trust, and nested compensation as independent facts. Independent
+verification requires durable bounded evidence from a trust domain distinct
+from the executor; evidence identifies observer kind as well as observer and
+trust domain, and an agent readback remains agent-attested. Nil executor
+results, legacy completed rows without results, timeouts with unknown effect,
+and malformed evidence remain explicitly inconclusive. Legacy `Success` and
+`VerificationOutcome` fields are derived compatibility projections only.
+Canonical evidence is bounded before redaction and digested as SHA-256 over
+the canonical redacted envelope. Redaction deep-copies nested evidence and
+fails closed to `redaction_contract_violation`; it never preserves invalid or
+unredacted input. A present but malformed stored V2 also fails closed to
+`result_v2_invalid`; legacy booleans can never override it. Compensation truth
+never rewrites the primary result and carries declared trigger, durable
+attempt/step identity, timing, nested execution and verification, and restored
+state digest identity for downstream recovery without implementing recovery.
+Workflow, API, AI, agent, Docker, host-agent, and relay packages must not
+declare competing truth enums. Generated wire mirrors remain a bounded later
+presentation concern, not a second source of semantics.
+
The canonical action resource contract now owns immutable `ActionActor` and
versioned `ApprovalRequirement` bindings. Actor subject/kind/credential/org and
requirement floor/quorum/separation are part of deterministic action identity
diff --git a/internal/actionlifecycle/service.go b/internal/actionlifecycle/service.go
index 6ba14ccc92..0e14b7d02d 100644
--- a/internal/actionlifecycle/service.go
+++ b/internal/actionlifecycle/service.go
@@ -1088,6 +1088,9 @@ func (s *Service) dispatchCommitted(ctx context.Context, orgID string, store Sto
}
result, execErr := s.Executor.ExecuteAction(withDispatchAttempt(ctx, attempt), record)
if execErr != nil {
+ if result != nil {
+ return record, fmt.Errorf("%w: executor returned both result and error", unified.ErrExecutorResultContract)
+ }
// 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.
@@ -1105,7 +1108,13 @@ func (s *Service) reconcileCommitted(ctx context.Context, orgID string, store St
return record, nil
}
result, receipt, found, err := reconciler.ReconcileActionDispatch(ctx, record, attempt)
- if err != nil || !found {
+ if err != nil {
+ if result != nil {
+ return record, fmt.Errorf("%w: reconciler returned both result and error", unified.ErrExecutorResultContract)
+ }
+ return record, err
+ }
+ if !found {
return record, err
}
if receipt.AttemptID == "" {
diff --git a/internal/actionlifecycle/service_action_result_test.go b/internal/actionlifecycle/service_action_result_test.go
new file mode 100644
index 0000000000..182bb87e08
--- /dev/null
+++ b/internal/actionlifecycle/service_action_result_test.go
@@ -0,0 +1,67 @@
+package actionlifecycle
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func TestExecutorTupleNilNilPersistsInconclusiveContractViolation(t *testing.T) {
+ store := unified.NewMemoryStore()
+ service := serviceForStore(t, store, testResource(time.Now().UTC(), unified.ApprovalNone), &stubExecutor{})
+ plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ record, err := service.Execute(context.Background(), "default", plan.ActionID, testActionActor("operator", "default"), "nil tuple")
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := unified.CanonicalActionResultV2(record)
+ if record.State != unified.ActionStateFailed || truth.Execution.Status != unified.ActionExecutionInconclusive || truth.Execution.ReasonCode != "executor_nil_result" {
+ t.Fatalf("record=%#v truth=%#v", record, truth)
+ }
+ stored, found, err := store.GetActionAudit(plan.ActionID)
+ if err != nil || !found || unified.CanonicalActionResultV2(stored).Execution.Status != unified.ActionExecutionInconclusive {
+ t.Fatalf("stored=%#v found=%v err=%v", stored, found, err)
+ }
+}
+
+func TestExecutorTupleResultAndErrorIsContractViolation(t *testing.T) {
+ store := unified.NewMemoryStore()
+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}, err: context.DeadlineExceeded}
+ service := serviceForStore(t, store, testResource(time.Now().UTC(), unified.ApprovalNone), executor)
+ plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ record, err := service.Execute(context.Background(), "default", plan.ActionID, testActionActor("operator", "default"), "invalid tuple")
+ if !errors.Is(err, unified.ErrExecutorResultContract) || record.State != unified.ActionStateExecuting {
+ t.Fatalf("record=%#v err=%v", record, err)
+ }
+ attempt, found, getErr := store.GetActionDispatchAttempt(plan.ActionID)
+ if getErr != nil || !found || attempt.State != unified.ActionDispatchReceiptPending {
+ t.Fatalf("attempt=%#v found=%v err=%v", attempt, found, getErr)
+ }
+}
+
+func TestExecutorTuplePostDispatchErrorPreservesReceiptPending(t *testing.T) {
+ store := unified.NewMemoryStore()
+ executor := &stubExecutor{err: context.DeadlineExceeded}
+ service := serviceForStore(t, store, testResource(time.Now().UTC(), unified.ApprovalNone), executor)
+ plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ record, err := service.Execute(context.Background(), "default", plan.ActionID, testActionActor("operator", "default"), "timeout")
+ if !errors.Is(err, context.DeadlineExceeded) || record.State != unified.ActionStateExecuting {
+ t.Fatalf("record=%#v err=%v", record, err)
+ }
+ attempt, found, getErr := store.GetActionDispatchAttempt(plan.ActionID)
+ if getErr != nil || !found || attempt.State != unified.ActionDispatchReceiptPending {
+ t.Fatalf("attempt=%#v found=%v err=%v", attempt, found, getErr)
+ }
+}
diff --git a/internal/api/action_result_v2_contract_test.go b/internal/api/action_result_v2_contract_test.go
new file mode 100644
index 0000000000..1ba56c96d9
--- /dev/null
+++ b/internal/api/action_result_v2_contract_test.go
@@ -0,0 +1,183 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/relay"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
+)
+
+func apiActionResultTruth(t *testing.T, execution unified.ActionExecutionStatus, verification unified.ActionVerificationStatus, class unified.ActionEvidenceClass) unified.ActionResultV2 {
+ t.Helper()
+ now := time.Date(2026, 7, 11, 16, 0, 0, 0, time.UTC)
+ truth := unified.ActionResultV2{
+ Version: unified.ActionResultV2Version,
+ Execution: unified.ActionExecutionTruth{Status: execution},
+ Verification: unified.ActionVerificationTruth{
+ Status: verification, EvidenceClass: class,
+ },
+ Compensation: unified.ActionCompensationTruth{Support: unified.ActionCompensationUnavailable, Status: unified.ActionCompensationNotAvailable},
+ }
+ if execution != unified.ActionExecutionSucceeded {
+ truth.Execution.ReasonCode = "execution_reason"
+ }
+ if verification == unified.ActionVerificationInconclusive {
+ truth.Verification.ReasonCode = "observer_timeout"
+ }
+ if class != unified.ActionEvidenceNone {
+ observerDomain := "agent:node-1"
+ observerKind := "agent"
+ if class == unified.ActionEvidenceIndependent {
+ observerDomain = "provider:api"
+ observerKind = "provider_api"
+ }
+ truth.Verification.Evidence = []unified.ActionEvidence{{
+ Version: unified.ActionEvidenceVersion, ID: "provider-read-1", ObserverID: "provider-api",
+ ObserverKind: observerKind, ObserverTrustDomain: observerDomain, ExecutorTrustDomain: "agent:node-1",
+ Method: "generation_read", SubjectID: "vm:42", ObservedAt: now, ReceivedAt: now.Add(time.Second),
+ }}
+ }
+ normalized, err := unified.NormalizeActionResultV2(truth)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return normalized
+}
+
+func TestActionResultV2EventFindingContextTelemetryProjectionMatrix(t *testing.T) {
+ executions := []unified.ActionExecutionStatus{unified.ActionExecutionNotRun, unified.ActionExecutionSucceeded, unified.ActionExecutionFailed, unified.ActionExecutionInconclusive}
+ verificationClasses := map[unified.ActionVerificationStatus][]unified.ActionEvidenceClass{
+ unified.ActionVerificationNotAttempted: {unified.ActionEvidenceNone},
+ unified.ActionVerificationConfirmed: {unified.ActionEvidenceAgentAttested, unified.ActionEvidenceIndependent},
+ unified.ActionVerificationContradicted: {unified.ActionEvidenceAgentAttested, unified.ActionEvidenceIndependent},
+ unified.ActionVerificationInconclusive: {unified.ActionEvidenceNone, unified.ActionEvidenceAgentAttested, unified.ActionEvidenceIndependent},
+ }
+ cases := 0
+ for _, execution := range executions {
+ for verification, classes := range verificationClasses {
+ for _, class := range classes {
+ cases++
+ t.Run(fmt.Sprintf("%s/%s/%s", execution, verification, class), func(t *testing.T) {
+ truth := apiActionResultTruth(t, execution, verification, class)
+ state := unified.ActionStateFailed
+ if execution == unified.ActionExecutionSucceeded {
+ state = unified.ActionStateCompleted
+ }
+ record := unified.ActionAuditRecord{
+ ID: "action-1", State: state, UpdatedAt: time.Now().UTC(),
+ Request: unified.ActionRequest{ResourceID: "vm:42", CapabilityName: "restart"},
+ Result: &unified.ExecutionResult{ActionResultV2: &truth},
+ Approvals: []unified.ActionApprovalRecord{{Outcome: unified.OutcomeApproved}},
+ }
+ event, ok := projectAgentActionCompletedPayload(record)
+ if !ok || event.ActionResultV2 == nil || event.ActionResultV2.Execution.Status != execution || event.ActionResultV2.Verification.Status != verification || event.Success != (execution == unified.ActionExecutionSucceeded) {
+ t.Fatalf("event=%#v ok=%v", event, ok)
+ }
+ contexts := projectAgentResourceActions([]unified.ActionAuditRecord{record})
+ if len(contexts) != 1 || contexts[0].ActionResultV2 == nil || contexts[0].ActionResultV2.Execution.Status != execution || contexts[0].ActionResultV2.Verification.Status != verification || contexts[0].Success != (execution == unified.ActionExecutionSucceeded) {
+ t.Fatalf("contexts=%#v", contexts)
+ }
+ expectedOutcome := aicontracts.OutcomeFixVerificationUnknown
+ if execution == unified.ActionExecutionFailed || execution == unified.ActionExecutionNotRun {
+ expectedOutcome = aicontracts.OutcomeFixFailed
+ } else if execution == unified.ActionExecutionSucceeded && verification == unified.ActionVerificationConfirmed {
+ expectedOutcome = aicontracts.OutcomeFixVerified
+ } else if execution == unified.ActionExecutionSucceeded && verification == unified.ActionVerificationContradicted {
+ expectedOutcome = aicontracts.OutcomeFixVerificationFailed
+ }
+ if got := patrolOutcomeForActionAudit(record); got != expectedOutcome {
+ t.Fatalf("finding outcome=%q want=%q", got, expectedOutcome)
+ }
+ if got := pulseIntelligenceActionVerifiedOutcome(record); got != (execution == unified.ActionExecutionSucceeded && verification == unified.ActionVerificationConfirmed) {
+ t.Fatalf("telemetry verified=%v", got)
+ }
+ disposition := dispositionFromRecord(record)
+ var dispositionTruth unified.ActionResultV2
+ if err := json.Unmarshal(disposition.ActionResultV2, &dispositionTruth); err != nil || dispositionTruth.Execution.Status != execution || dispositionTruth.Verification.Status != verification {
+ t.Fatalf("disposition=%#v truth=%#v err=%v", disposition, dispositionTruth, err)
+ }
+ notification := relay.NewCanonicalActionOutcomeNotification("finding-1", "Action", truth)
+ if !strings.Contains(notification.Body, "Execution ") || !strings.Contains(notification.Body, "verification ") {
+ t.Fatalf("notification collapsed axes: %#v", notification)
+ }
+ })
+ }
+ }
+ }
+ if cases != 32 {
+ t.Fatalf("legal consumer projection cases=%d, want 32", cases)
+ }
+}
+
+func TestActionResultV2JSONContractSnapshot(t *testing.T) {
+ truth := apiActionResultTruth(t, unified.ActionExecutionSucceeded, unified.ActionVerificationConfirmed, unified.ActionEvidenceIndependent)
+ payload, err := json.Marshal(AgentEventActionCompletedPayload{ActionID: "action-1", State: "completed", ActionResultV2: &truth})
+ if err != nil {
+ t.Fatal(err)
+ }
+ jsonText := string(payload)
+ for _, required := range []string{`"actionResultV2":{"version":2`, `"execution":{"status":"succeeded"`, `"verification":{"status":"confirmed","evidenceClass":"independent"`, `"compensation":{"support":"unavailable","status":"not_available"`} {
+ if !strings.Contains(jsonText, required) {
+ t.Fatalf("JSON contract missing %s: %s", required, jsonText)
+ }
+ }
+}
+
+func TestMalformedStoredActionResultV2CannotProjectSuccessOrVerification(t *testing.T) {
+ base := apiActionResultTruth(t, unified.ActionExecutionSucceeded, unified.ActionVerificationConfirmed, unified.ActionEvidenceIndependent)
+ tests := []struct {
+ name string
+ mutate func(*unified.ActionResultV2)
+ }{
+ {"false_independence", func(result *unified.ActionResultV2) {
+ result.Verification.Evidence[0].ObserverTrustDomain = result.Verification.Evidence[0].ExecutorTrustDomain
+ }},
+ {"bad_digest", func(result *unified.ActionResultV2) {
+ result.Verification.Evidence[0].Digest = "sha256:" + strings.Repeat("0", 64)
+ }},
+ {"invalid_status", func(result *unified.ActionResultV2) { result.Execution.Status = "successful" }},
+ {"invalid_version", func(result *unified.ActionResultV2) { result.Version = 99 }},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ malicious := base
+ malicious.Verification.Evidence = append([]unified.ActionEvidence(nil), base.Verification.Evidence...)
+ test.mutate(&malicious)
+ record := unified.ActionAuditRecord{
+ ID: "malicious", State: unified.ActionStateCompleted, UpdatedAt: time.Now().UTC(),
+ Result: &unified.ExecutionResult{Success: true, ActionResultV2: &malicious, Verification: &unified.ActionVerificationResult{Ran: true, Success: true}},
+ VerificationOutcome: unified.VerificationOutcome{Status: unified.VerificationVerified},
+ Approvals: []unified.ActionApprovalRecord{{Outcome: unified.OutcomeApproved}},
+ }
+ event, ok := projectAgentActionCompletedPayload(record)
+ contexts := projectAgentResourceActions([]unified.ActionAuditRecord{record})
+ disposition := dispositionFromRecord(record)
+ var dispositionTruth unified.ActionResultV2
+ unmarshalErr := json.Unmarshal(disposition.ActionResultV2, &dispositionTruth)
+ if !ok || event.Success || event.ActionResultV2 == nil || event.ActionResultV2.Execution.Status != unified.ActionExecutionInconclusive || event.ActionResultV2.Verification.Status != unified.ActionVerificationInconclusive {
+ t.Fatalf("event failed open: %#v", event)
+ }
+ if len(contexts) != 1 || contexts[0].Success || contexts[0].ActionResultV2.Execution.Status != unified.ActionExecutionInconclusive || contexts[0].ActionResultV2.Verification.Status != unified.ActionVerificationInconclusive {
+ t.Fatalf("context failed open: %#v", contexts)
+ }
+ if got := patrolOutcomeForActionAudit(record); got != aicontracts.OutcomeFixVerificationUnknown {
+ t.Fatalf("finding failed open: %q", got)
+ }
+ if pulseIntelligenceActionVerifiedOutcome(record) {
+ t.Fatal("telemetry projected malformed V2 as verified")
+ }
+ if unmarshalErr != nil || dispositionTruth.Execution.Status != unified.ActionExecutionInconclusive || dispositionTruth.Verification.Status != unified.ActionVerificationInconclusive || disposition.VerificationStatus == string(unified.VerificationVerified) {
+ t.Fatalf("disposition failed open: %#v truth=%#v err=%v", disposition, dispositionTruth, unmarshalErr)
+ }
+ notification := relay.NewCanonicalActionOutcomeNotification("finding-1", "Action", dispositionTruth)
+ if strings.Contains(notification.Body, "succeeded") || strings.Contains(notification.Body, "confirmed") {
+ t.Fatalf("push failed open: %#v", notification)
+ }
+ })
+ }
+}
diff --git a/internal/api/agent_events.go b/internal/api/agent_events.go
index 00189a924e..d8a0a67ed7 100644
--- a/internal/api/agent_events.go
+++ b/internal/api/agent_events.go
@@ -127,6 +127,7 @@ type AgentEventActionCompletedPayload struct {
State string `json:"state"`
Success bool `json:"success"`
ErrorMessage string `json:"errorMessage,omitempty"`
+ ActionResultV2 *unifiedresources.ActionResultV2 `json:"actionResultV2,omitempty"`
Verification *AgentResourceActionVerification `json:"verification,omitempty"`
RequestedBy string `json:"requestedBy,omitempty"`
CompletedAt time.Time `json:"completedAt"`
@@ -373,10 +374,11 @@ func (b *AgentEventBroadcaster) PublishActionCompletedRecord(record unifiedresou
if cmd, ok := record.Request.Params["command"].(string); ok {
payload.Command = cmd
}
- if record.Result != nil {
- payload.Success = record.Result.Success
- payload.ErrorMessage = record.Result.ErrorMessage
- }
+ canonical := unifiedresources.CanonicalActionResultV2(record)
+ payload.ActionResultV2 = &canonical
+ legacy := unifiedresources.LegacyActionResultProjection(record)
+ payload.Success = legacy.Success
+ payload.ErrorMessage = legacy.ErrorMessage
if v := projectAgentResourceVerification(unifiedresources.CanonicalActionVerification(record)); v != nil {
payload.Verification = v
}
diff --git a/internal/api/agent_resource_context.go b/internal/api/agent_resource_context.go
index 1d7027e855..7b5293dab4 100644
--- a/internal/api/agent_resource_context.go
+++ b/internal/api/agent_resource_context.go
@@ -72,6 +72,7 @@ type AgentResourceActionSummary struct {
State string `json:"state"`
Success bool `json:"success"`
ErrorMessage string `json:"errorMessage,omitempty"`
+ ActionResultV2 *unified.ActionResultV2 `json:"actionResultV2,omitempty"`
Verification *AgentResourceActionVerification `json:"verification,omitempty"`
RequestedBy string `json:"requestedBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
@@ -1354,8 +1355,12 @@ func projectAgentResourceActions(
if cmd, ok := audit.Request.Params["command"].(string); ok {
summary.Command = cmd
}
- if audit.Result != nil {
- summary.Success = audit.Result.Success
+ canonical := unified.CanonicalActionResultV2(audit)
+ summary.ActionResultV2 = &canonical
+ legacy := unified.LegacyActionResultProjection(audit)
+ summary.Success = legacy.Success
+ summary.ErrorMessage = legacy.ErrorMessage
+ if audit.Result != nil && (strings.HasPrefix(audit.Result.ErrorMessage, "resource_remediation_locked:") || strings.HasPrefix(audit.Result.ErrorMessage, "plan_drift:")) {
summary.ErrorMessage = audit.Result.ErrorMessage
}
if v := projectAgentResourceVerification(unified.CanonicalActionVerification(audit)); v != nil {
diff --git a/internal/api/ai_handlers_investigation_additional_test.go b/internal/api/ai_handlers_investigation_additional_test.go
index 77d7ad99a6..d39629d708 100644
--- a/internal/api/ai_handlers_investigation_additional_test.go
+++ b/internal/api/ai_handlers_investigation_additional_test.go
@@ -237,6 +237,7 @@ func TestPatrolActionReconciliationCannotRegressFromOutOfOrderCallback(t *testin
completed := pending
completed.State = unifiedresources.ActionStateCompleted
completed.UpdatedAt = now.Add(time.Second)
+ completed.Result = &unifiedresources.ExecutionResult{Success: true}
completed.VerificationOutcome = unifiedresources.VerificationOutcome{Status: unifiedresources.VerificationVerified}
if _, _, err := audits.CreateActionAudit(completed, nil); err != nil {
t.Fatalf("CreateActionAudit(completed): %v", err)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 57d4aecffc..35f79e1fe5 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -14181,7 +14181,13 @@ func TestContract_ActionExecutionJSONSnapshot(t *testing.T) {
"state":"completed",
"result":{
"success":true,
- "output":"restart dispatched"
+ "output":"restart dispatched",
+ "actionResultV2":{
+ "version":2,
+ "execution":{"status":"succeeded","summary":"restart dispatched"},
+ "verification":{"status":"not_attempted","evidenceClass":"none"},
+ "compensation":{"support":"unavailable","status":"not_available"}
+ }
},
"audit":{
"id":"act_execution_contract",
@@ -14239,7 +14245,13 @@ func TestContract_ActionExecutionJSONSnapshot(t *testing.T) {
],
"result":{
"success":true,
- "output":"restart dispatched"
+ "output":"restart dispatched",
+ "actionResultV2":{
+ "version":2,
+ "execution":{"status":"succeeded","summary":"restart dispatched"},
+ "verification":{"status":"not_attempted","evidenceClass":"none"},
+ "compensation":{"support":"unavailable","status":"not_available"}
+ }
},
"verificationOutcome":{
"status":"unknown"
@@ -19592,10 +19604,9 @@ func TestContract_PulseIntelligenceApprovedSuccessTelemetryRequiresVerifiedOutco
`if record.State != unifiedresources.ActionStateCompleted`,
`return pulseIntelligenceActionVerifiedOutcome(record)`,
`func pulseIntelligenceActionVerifiedOutcome(record unifiedresources.ActionAuditRecord) bool`,
- `outcome := unifiedresources.NormalizeVerificationOutcome(record.VerificationOutcome)`,
- `outcome.Status == unifiedresources.VerificationVerified`,
- `verification := unifiedresources.CanonicalActionVerification(record)`,
- `return verification != nil && verification.Ran && verification.Success`,
+ `truth := unifiedresources.CanonicalActionResultV2(record)`,
+ `truth.Execution.Status == unifiedresources.ActionExecutionSucceeded`,
+ `truth.Verification.Status == unifiedresources.ActionVerificationConfirmed`,
} {
if !strings.Contains(telemetrySrc, fragment) {
t.Errorf("Pulse Intelligence approved-success telemetry must require verified outcome proof; missing %s", fragment)
diff --git a/internal/api/patrol_action_broker.go b/internal/api/patrol_action_broker.go
index f837cfede2..59152d5c11 100644
--- a/internal/api/patrol_action_broker.go
+++ b/internal/api/patrol_action_broker.go
@@ -246,10 +246,14 @@ func policySnapshotVersion(snapshot PatrolActionPolicySnapshot) string {
}
func dispositionFromRecord(record unified.ActionAuditRecord) aicontracts.ActionDisposition {
+ canonical := unified.CanonicalActionResultV2(record)
+ resultJSON, _ := json.Marshal(canonical)
+ _, legacyVerification, _ := unified.ApplyActionResultV2(nil, canonical)
return aicontracts.ActionDisposition{
ActionID: record.ID,
State: string(record.State),
- VerificationStatus: string(record.VerificationOutcome.Status),
+ ActionResultV2: resultJSON,
+ VerificationStatus: string(legacyVerification.Status),
Plan: *approvalPlanRequestToInfo(&record.Plan),
}
}
diff --git a/internal/api/patrol_action_reconciliation.go b/internal/api/patrol_action_reconciliation.go
index 593de23909..e01edae541 100644
--- a/internal/api/patrol_action_reconciliation.go
+++ b/internal/api/patrol_action_reconciliation.go
@@ -148,13 +148,18 @@ func patrolOutcomeForActionAudit(audit unifiedresources.ActionAuditRecord) aicon
return aicontracts.OutcomeFixQueued
case unifiedresources.ActionStateRejected:
return aicontracts.OutcomeFixRejected
- case unifiedresources.ActionStateFailed:
- return aicontracts.OutcomeFixFailed
- case unifiedresources.ActionStateCompleted:
- switch unifiedresources.NormalizeVerificationOutcome(audit.VerificationOutcome).Status {
- case unifiedresources.VerificationVerified:
+ case unifiedresources.ActionStateFailed, unifiedresources.ActionStateCompleted:
+ truth := unifiedresources.CanonicalActionResultV2(audit)
+ if truth.Execution.Status == unifiedresources.ActionExecutionFailed || truth.Execution.Status == unifiedresources.ActionExecutionNotRun {
+ return aicontracts.OutcomeFixFailed
+ }
+ if truth.Execution.Status != unifiedresources.ActionExecutionSucceeded {
+ return aicontracts.OutcomeFixVerificationUnknown
+ }
+ switch truth.Verification.Status {
+ case unifiedresources.ActionVerificationConfirmed:
return aicontracts.OutcomeFixVerified
- case unifiedresources.VerificationFailed:
+ case unifiedresources.ActionVerificationContradicted:
return aicontracts.OutcomeFixVerificationFailed
default:
return aicontracts.OutcomeFixVerificationUnknown
diff --git a/internal/api/router.go b/internal/api/router.go
index 75f23a018c..361954d573 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -3186,10 +3186,11 @@ func projectAgentActionCompletedPayload(record unifiedresources.ActionAuditRecor
if cmd, ok := record.Request.Params["command"].(string); ok {
payload.Command = cmd
}
- if record.Result != nil {
- payload.Success = record.Result.Success
- payload.ErrorMessage = record.Result.ErrorMessage
- }
+ canonical := unifiedresources.CanonicalActionResultV2(record)
+ payload.ActionResultV2 = &canonical
+ legacy := unifiedresources.LegacyActionResultProjection(record)
+ payload.Success = legacy.Success
+ payload.ErrorMessage = legacy.ErrorMessage
if v := projectAgentResourceVerification(unifiedresources.CanonicalActionVerification(record)); v != nil {
payload.Verification = v
}
diff --git a/internal/api/telemetry_pulse_intelligence.go b/internal/api/telemetry_pulse_intelligence.go
index 0e4ecc9ae6..fa1dabc5fe 100644
--- a/internal/api/telemetry_pulse_intelligence.go
+++ b/internal/api/telemetry_pulse_intelligence.go
@@ -232,12 +232,8 @@ func pulseIntelligenceActionVerifiedOutcome(record unifiedresources.ActionAuditR
if !pulseIntelligenceActionWasApproved(record) {
return false
}
- outcome := unifiedresources.NormalizeVerificationOutcome(record.VerificationOutcome)
- if outcome.Status == unifiedresources.VerificationVerified {
- return true
- }
- verification := unifiedresources.CanonicalActionVerification(record)
- return verification != nil && verification.Ran && verification.Success
+ truth := unifiedresources.CanonicalActionResultV2(record)
+ return truth.Execution.Status == unifiedresources.ActionExecutionSucceeded && truth.Verification.Status == unifiedresources.ActionVerificationConfirmed
}
func pulseIntelligenceActionLifecycleIndicatesAttempt(event unifiedresources.ActionLifecycleEvent) bool {
diff --git a/internal/api/telemetry_pulse_intelligence_test.go b/internal/api/telemetry_pulse_intelligence_test.go
index f0970b7d1d..f4e19f9bdd 100644
--- a/internal/api/telemetry_pulse_intelligence_test.go
+++ b/internal/api/telemetry_pulse_intelligence_test.go
@@ -115,11 +115,10 @@ func TestGetPulseIntelligenceActionTelemetry_CountsApprovedLifecycleAttemptsInsi
if err := store.RecordActionExecutionStart(started, startEvent); err != nil {
t.Fatalf("RecordActionExecutionStart(currentApproved): %v", err)
}
- completed, doneEvent, err := unifiedresources.CompleteActionExecution(started, &unifiedresources.ExecutionResult{Success: true}, "operator", now.Add(-80*time.Minute))
+ completed, doneEvent, err := unifiedresources.CompleteActionExecution(started, &unifiedresources.ExecutionResult{Success: true, Verification: &unifiedresources.ActionVerificationResult{Ran: true, Success: true, RanAt: now.Add(-80 * time.Minute)}}, "operator", now.Add(-80*time.Minute))
if err != nil {
t.Fatalf("CompleteActionExecution(currentApproved): %v", err)
}
- completed.VerificationOutcome = unifiedresources.VerificationOutcome{Status: unifiedresources.VerificationVerified}
if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {
t.Fatalf("RecordActionExecutionResult(currentApproved): %v", err)
}
diff --git a/internal/relay/push.go b/internal/relay/push.go
index 9987b2ad5b..505d3ec725 100644
--- a/internal/relay/push.go
+++ b/internal/relay/push.go
@@ -4,6 +4,8 @@ import (
"fmt"
"regexp"
"strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
// Notification type constants
@@ -180,3 +182,45 @@ func NewActionOutcomeNotification(findingID, title, verificationStatus string) P
ActionID: findingID,
}
}
+
+// NewCanonicalActionOutcomeNotification projects both canonical truth axes
+// without calling unknown execution or verification a success or failure.
+func NewCanonicalActionOutcomeNotification(findingID, title string, result unifiedresources.ActionResultV2) PushNotificationPayload {
+ execution := "Execution outcome is inconclusive"
+ priority := PushPriorityNormal
+ switch result.Execution.Status {
+ case unifiedresources.ActionExecutionNotRun:
+ execution = "Execution was not run"
+ priority = PushPriorityHigh
+ case unifiedresources.ActionExecutionFailed:
+ execution = "Execution failed"
+ priority = PushPriorityHigh
+ case unifiedresources.ActionExecutionSucceeded:
+ execution = "Execution succeeded"
+ }
+ verification := "verification was inconclusive"
+ source := ""
+ switch result.Verification.EvidenceClass {
+ case unifiedresources.ActionEvidenceAgentAttested:
+ source = " with agent-attested evidence"
+ case unifiedresources.ActionEvidenceIndependent:
+ source = " with independent evidence"
+ }
+ switch result.Verification.Status {
+ case unifiedresources.ActionVerificationNotAttempted:
+ verification = "verification was not attempted"
+ case unifiedresources.ActionVerificationConfirmed:
+ verification = "verification confirmed the expected result" + source
+ case unifiedresources.ActionVerificationContradicted:
+ verification = "verification contradicted the expected result" + source
+ priority = PushPriorityHigh
+ case unifiedresources.ActionVerificationInconclusive:
+ verification = "verification was inconclusive" + source
+ }
+ body := execution + "; " + verification
+ return PushNotificationPayload{
+ Type: PushTypeFixCompleted, Priority: priority,
+ Title: truncate(sanitizeTitle(title), maxPushTitleLen), Body: truncate(body, maxPushBodyLen),
+ ActionType: PushActionViewFixResult, ActionID: findingID,
+ }
+}
diff --git a/internal/relay/push_test.go b/internal/relay/push_test.go
index faec881322..e6699a8d6d 100644
--- a/internal/relay/push_test.go
+++ b/internal/relay/push_test.go
@@ -1,10 +1,47 @@
package relay
import (
+ "fmt"
"strings"
"testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
+func TestCanonicalActionOutcomeNotificationMatrix(t *testing.T) {
+ executions := []unifiedresources.ActionExecutionStatus{unifiedresources.ActionExecutionNotRun, unifiedresources.ActionExecutionSucceeded, unifiedresources.ActionExecutionFailed, unifiedresources.ActionExecutionInconclusive}
+ verificationClasses := map[unifiedresources.ActionVerificationStatus][]unifiedresources.ActionEvidenceClass{
+ unifiedresources.ActionVerificationNotAttempted: {unifiedresources.ActionEvidenceNone},
+ unifiedresources.ActionVerificationConfirmed: {unifiedresources.ActionEvidenceAgentAttested, unifiedresources.ActionEvidenceIndependent},
+ unifiedresources.ActionVerificationContradicted: {unifiedresources.ActionEvidenceAgentAttested, unifiedresources.ActionEvidenceIndependent},
+ unifiedresources.ActionVerificationInconclusive: {unifiedresources.ActionEvidenceNone, unifiedresources.ActionEvidenceAgentAttested, unifiedresources.ActionEvidenceIndependent},
+ }
+ cases := 0
+ for _, execution := range executions {
+ for verification, classes := range verificationClasses {
+ for _, class := range classes {
+ cases++
+ t.Run(fmt.Sprintf("%s/%s/%s", execution, verification, class), func(t *testing.T) {
+ result := unifiedresources.ActionResultV2{Execution: unifiedresources.ActionExecutionTruth{Status: execution}, Verification: unifiedresources.ActionVerificationTruth{Status: verification, EvidenceClass: class}}
+ got := NewCanonicalActionOutcomeNotification("finding-1", "Action", result)
+ if !strings.Contains(got.Body, "Execution ") || !strings.Contains(got.Body, "verification ") {
+ t.Fatalf("notification collapsed an axis: %#v", got)
+ }
+ if class == unifiedresources.ActionEvidenceAgentAttested && !strings.Contains(got.Body, "agent-attested") {
+ t.Fatalf("agent evidence source omitted: %#v", got)
+ }
+ if class == unifiedresources.ActionEvidenceIndependent && !strings.Contains(got.Body, "independent") {
+ t.Fatalf("independent evidence source omitted: %#v", got)
+ }
+ })
+ }
+ }
+ }
+ if cases != 32 {
+ t.Fatalf("legal notification cases=%d, want 32", cases)
+ }
+}
+
func TestNewPatrolFindingNotification(t *testing.T) {
t.Run("warning finding", func(t *testing.T) {
n := NewPatrolFindingNotification("finding-123", "warning", "performance", "High CPU usage detected")
diff --git a/internal/unifiedresources/action_result_store_test.go b/internal/unifiedresources/action_result_store_test.go
new file mode 100644
index 0000000000..051b582ba8
--- /dev/null
+++ b/internal/unifiedresources/action_result_store_test.go
@@ -0,0 +1,230 @@
+package unifiedresources
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+func actionResultStoreRecord(id string) ActionAuditRecord {
+ record := atomicLifecycleTestRecord(id, ActionStatePlanned)
+ record.Plan.RequiresApproval = false
+ record.Plan.ApprovalPolicy = ApprovalNone
+ record.Plan.ApprovalRequirement = ApprovalRequirementForFloor(ApprovalNone)
+ return record
+}
+
+func persistedActionResultV2(t *testing.T, store ResourceStore, id string) ActionResultV2 {
+ canonical := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded, Summary: "mutation returned success"},
+ Verification: ActionVerificationTruth{Status: ActionVerificationContradicted, EvidenceClass: ActionEvidenceAgentAttested, Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested)},
+ Compensation: ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore_backup", Trigger: "verification_contradicted", Status: ActionCompensationNotAttempted},
+ }
+ return persistedActionResultV2WithTruth(t, store, id, canonical)
+}
+
+func persistedActionResultV2WithTruth(t *testing.T, store ResourceStore, id string, canonical ActionResultV2) ActionResultV2 {
+ t.Helper()
+ record := actionResultStoreRecord(id)
+ if _, created, err := store.CreateActionAudit(record, atomicLifecycleInitialEvents(record)); err != nil || !created {
+ t.Fatalf("CreateActionAudit created=%v err=%v", created, err)
+ }
+ started, startEvent, err := BeginActionExecution(record, "operator", record.CreatedAt.Add(time.Minute))
+ if err != nil || store.RecordActionExecutionStart(started, startEvent) != nil {
+ t.Fatalf("start action: %v", err)
+ }
+ result, _, err := ApplyActionResultV2(&ExecutionResult{Output: "mutation returned success"}, canonical)
+ if err != nil {
+ t.Fatal(err)
+ }
+ completed, doneEvent, err := CompleteActionExecution(started, result, "operator", record.CreatedAt.Add(2*time.Minute))
+ if err != nil || store.RecordActionExecutionResult(completed, doneEvent) != nil {
+ t.Fatalf("complete action: %v", err)
+ }
+ got, found, err := store.GetActionAudit(id)
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit found=%v err=%v", found, err)
+ }
+ return CanonicalActionResultV2(got)
+}
+
+func TestCompensationFailureSurvivesSQLiteReopen(t *testing.T) {
+ dir := t.TempDir()
+ store, err := NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded},
+ Verification: ActionVerificationTruth{Status: ActionVerificationContradicted, EvidenceClass: ActionEvidenceAgentAttested, Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested)},
+ Compensation: ActionCompensationTruth{
+ Support: ActionCompensationDeclared, Strategy: "restore_backup", Trigger: "verification_contradicted", Status: ActionCompensationFailed,
+ AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(time.Now().UTC().Add(-time.Minute)), CompletedAt: actionResultTestTime(time.Now().UTC()),
+ Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested),
+ ReasonCode: "restore_failed", Execution: &ActionExecutionTruth{Status: ActionExecutionFailed, ReasonCode: "provider_error"},
+ },
+ }
+ want := persistedActionResultV2WithTruth(t, store, "act-compensation-failed", truth)
+ if err := store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ reopened, err := NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reopened.Close()
+ record, found, err := reopened.GetActionAudit("act-compensation-failed")
+ if err != nil || !found {
+ t.Fatalf("reopen found=%v err=%v", found, err)
+ }
+ got := CanonicalActionResultV2(record)
+ if !reflect.DeepEqual(got, want) || got.Compensation.Status != ActionCompensationFailed || got.Execution.Status != ActionExecutionSucceeded {
+ t.Fatalf("reopened compensation truth\n got: %#v\nwant: %#v", got, want)
+ }
+}
+
+func TestCompensationSucceededRestoredStateSurvivesSQLiteReopen(t *testing.T) {
+ dir := t.TempDir()
+ store, err := NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ digest := "sha256:" + strings.Repeat("c", 64)
+ verification := ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceIndependent, Evidence: actionResultTestEvidence(ActionEvidenceIndependent)}
+ truth := ActionResultV2{
+ Version: ActionResultV2Version, Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded},
+ Verification: ActionVerificationTruth{Status: ActionVerificationContradicted, EvidenceClass: ActionEvidenceAgentAttested, Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested)},
+ Compensation: ActionCompensationTruth{
+ Support: ActionCompensationDeclared, Strategy: "restore_backup", Trigger: "verification_contradicted", Status: ActionCompensationSucceeded,
+ AttemptID: "comp-2", StepID: "restore", StartedAt: actionResultTestTime(now.Add(-time.Minute)), CompletedAt: actionResultTestTime(now),
+ Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested),
+ Execution: &ActionExecutionTruth{Status: ActionExecutionSucceeded}, Verification: &verification,
+ RestoredState: &ActionRestoredStateTruth{SubjectID: "vm:42", ExpectedDigest: digest, ObservedDigest: digest, ObservedAt: now},
+ },
+ }
+ want := persistedActionResultV2WithTruth(t, store, "act-compensation-succeeded", truth)
+ if err := store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ reopened, err := NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reopened.Close()
+ record, found, err := reopened.GetActionAudit("act-compensation-succeeded")
+ if err != nil || !found {
+ t.Fatalf("reopen found=%v err=%v", found, err)
+ }
+ got := CanonicalActionResultV2(record)
+ if !reflect.DeepEqual(got, want) || len(got.Compensation.Evidence) != 1 || got.Compensation.RestoredState == nil || got.Compensation.RestoredState.ExpectedDigest != digest {
+ t.Fatalf("reopened restored state\n got: %#v\nwant: %#v", got, want)
+ }
+}
+
+func TestMalformedActionResultV2PersistsFailClosed(t *testing.T) {
+ stores := []struct {
+ name string
+ store ResourceStore
+ }{
+ {"memory", NewMemoryStore()},
+ }
+ sqliteStore, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sqliteStore.Close()
+ stores = append(stores, struct {
+ name string
+ store ResourceStore
+ }{"sqlite", sqliteStore})
+ for _, test := range stores {
+ t.Run(test.name, func(t *testing.T) {
+ record := actionResultStoreRecord("act-malformed-" + test.name)
+ if _, created, err := test.store.CreateActionAudit(record, atomicLifecycleInitialEvents(record)); err != nil || !created {
+ t.Fatalf("create created=%v err=%v", created, err)
+ }
+ started, startEvent, err := BeginActionExecution(record, "operator", record.CreatedAt.Add(time.Minute))
+ if err != nil || test.store.RecordActionExecutionStart(started, startEvent) != nil {
+ t.Fatalf("start: %v", err)
+ }
+ malicious := ActionResultV2{Version: 99, Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded}, Verification: ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceIndependent, Evidence: actionResultTestEvidence(ActionEvidenceIndependent)}, Compensation: actionResultTestCompensation()}
+ completed, event, err := CompleteActionExecution(started, &ExecutionResult{Success: true, ActionResultV2: &malicious}, "operator", record.CreatedAt.Add(2*time.Minute))
+ if err != nil || test.store.RecordActionExecutionResult(completed, event) != nil {
+ t.Fatalf("complete: %v", err)
+ }
+ stored, found, err := test.store.GetActionAudit(record.ID)
+ truth := CanonicalActionResultV2(stored)
+ if err != nil || !found || truth.Execution.Status != ActionExecutionInconclusive || truth.Verification.Status != ActionVerificationInconclusive || stored.Result.Success {
+ t.Fatalf("stored=%#v truth=%#v found=%v err=%v", stored, truth, found, err)
+ }
+ })
+ }
+}
+
+func TestActionResultV2MemoryStoreRoundTrip(t *testing.T) {
+ truth := persistedActionResultV2(t, NewMemoryStore(), "act-result-memory")
+ if truth.Execution.Status != ActionExecutionSucceeded || truth.Verification.Status != ActionVerificationContradicted || truth.Compensation.Status != ActionCompensationNotAttempted {
+ t.Fatalf("round-trip truth=%#v", truth)
+ }
+}
+
+func TestActionResultV2SQLiteRoundTrip(t *testing.T) {
+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+ truth := persistedActionResultV2(t, store, "act-result-sqlite")
+ if truth.Execution.Status != ActionExecutionSucceeded || truth.Verification.Status != ActionVerificationContradicted || truth.Verification.EvidenceClass != ActionEvidenceAgentAttested {
+ t.Fatalf("round-trip truth=%#v", truth)
+ }
+}
+
+func TestActionResultV2SurvivesSQLiteReopen(t *testing.T) {
+ dir := t.TempDir()
+ store, err := NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := persistedActionResultV2(t, store, "act-result-reopen")
+ if err := store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ reopened, err := NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reopened.Close()
+ record, found, err := reopened.GetActionAudit("act-result-reopen")
+ if err != nil || !found {
+ t.Fatalf("reopen found=%v err=%v", found, err)
+ }
+ got := CanonicalActionResultV2(record)
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("reopened truth\n got: %#v\nwant: %#v", got, want)
+ }
+}
+
+func TestLegacyCompletedNilResultMigratesInconclusive(t *testing.T) {
+ record := actionResultStoreRecord("act-legacy-nil")
+ record.State = ActionStateCompleted
+ record.UpdatedAt = record.CreatedAt.Add(time.Minute)
+ truth := CanonicalActionResultV2(record)
+ if truth.Execution.Status != ActionExecutionInconclusive || truth.Execution.ReasonCode != "legacy_missing_result" {
+ t.Fatalf("legacy nil truth=%#v", truth)
+ }
+}
+
+func TestLegacyMissingVerificationMigratesNotAttempted(t *testing.T) {
+ record := actionResultStoreRecord("act-legacy-no-verification")
+ record.State = ActionStateCompleted
+ record.Result = &ExecutionResult{Success: true, Output: "done"}
+ truth := CanonicalActionResultV2(record)
+ if truth.Execution.Status != ActionExecutionSucceeded || truth.Verification.Status != ActionVerificationNotAttempted || truth.Verification.EvidenceClass != ActionEvidenceNone {
+ t.Fatalf("legacy missing verification truth=%#v", truth)
+ }
+}
diff --git a/internal/unifiedresources/action_result_v2.go b/internal/unifiedresources/action_result_v2.go
new file mode 100644
index 0000000000..21920114e6
--- /dev/null
+++ b/internal/unifiedresources/action_result_v2.go
@@ -0,0 +1,759 @@
+package unifiedresources
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+const (
+ ActionResultV2Version = 2
+ ActionEvidenceVersion = 1
+ ActionEvidenceMaxItems = 16
+ ActionEvidenceMaxRefs = 16
+ ActionEvidenceMaxTextBytes = 2048
+ ActionEvidenceMaxReasonBytes = 256
+)
+
+// ActionExecutionStatus is the executor-owned outcome of the requested
+// mutation. It is deliberately independent from postcondition verification.
+type ActionExecutionStatus string
+
+const (
+ ActionExecutionNotRun ActionExecutionStatus = "not_run"
+ ActionExecutionSucceeded ActionExecutionStatus = "succeeded"
+ ActionExecutionFailed ActionExecutionStatus = "failed"
+ ActionExecutionInconclusive ActionExecutionStatus = "inconclusive"
+)
+
+// ActionVerificationStatus is the evidence-owned verdict about the intended
+// postcondition. A contradicted postcondition does not rewrite execution.
+type ActionVerificationStatus string
+
+const (
+ ActionVerificationNotAttempted ActionVerificationStatus = "not_attempted"
+ ActionVerificationConfirmed ActionVerificationStatus = "confirmed"
+ ActionVerificationContradicted ActionVerificationStatus = "contradicted"
+ ActionVerificationInconclusive ActionVerificationStatus = "inconclusive"
+)
+
+// ActionEvidenceClass records the trust relationship between the executor and
+// observer. A second read through the mutating agent remains agent-attested.
+type ActionEvidenceClass string
+
+const (
+ ActionEvidenceNone ActionEvidenceClass = "none"
+ ActionEvidenceAgentAttested ActionEvidenceClass = "agent_attested"
+ ActionEvidenceIndependent ActionEvidenceClass = "independent"
+)
+
+// ActionEvidenceRef is a bounded durable reference to supporting evidence.
+type ActionEvidenceRef struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Digest string `json:"digest"`
+}
+
+// ActionEvidence is a redacted, bounded and digest-bound observation. Digest
+// is calculated over the canonical redacted envelope with Digest cleared.
+type ActionEvidence struct {
+ Version int `json:"version"`
+ ID string `json:"id"`
+ ObserverID string `json:"observerId"`
+ ObserverKind string `json:"observerKind"`
+ ObserverTrustDomain string `json:"observerTrustDomain"`
+ ExecutorTrustDomain string `json:"executorTrustDomain"`
+ Method string `json:"method"`
+ SubjectID string `json:"subjectId"`
+ ObservedAt time.Time `json:"observedAt"`
+ ReceivedAt time.Time `json:"receivedAt"`
+ ReasonCode string `json:"reasonCode,omitempty"`
+ Summary string `json:"summary,omitempty"`
+ Refs []ActionEvidenceRef `json:"refs,omitempty"`
+ Digest string `json:"digest"`
+}
+
+type ActionExecutionTruth struct {
+ Status ActionExecutionStatus `json:"status"`
+ ReasonCode string `json:"reasonCode,omitempty"`
+ Summary string `json:"summary,omitempty"`
+}
+
+type ActionVerificationTruth struct {
+ Status ActionVerificationStatus `json:"status"`
+ EvidenceClass ActionEvidenceClass `json:"evidenceClass"`
+ ReasonCode string `json:"reasonCode,omitempty"`
+ Summary string `json:"summary,omitempty"`
+ Evidence []ActionEvidence `json:"evidence,omitempty"`
+}
+
+type ActionCompensationSupport string
+
+const (
+ ActionCompensationUnavailable ActionCompensationSupport = "unavailable"
+ ActionCompensationDeclared ActionCompensationSupport = "declared"
+)
+
+type ActionCompensationStatus string
+
+const (
+ ActionCompensationNotAvailable ActionCompensationStatus = "not_available"
+ ActionCompensationNotNeeded ActionCompensationStatus = "not_needed"
+ ActionCompensationNotAttempted ActionCompensationStatus = "not_attempted"
+ ActionCompensationRunning ActionCompensationStatus = "running"
+ ActionCompensationSucceeded ActionCompensationStatus = "succeeded"
+ ActionCompensationFailed ActionCompensationStatus = "failed"
+ ActionCompensationInconclusive ActionCompensationStatus = "inconclusive"
+)
+
+// ActionCompensationTruth describes declared recovery and its outcome without
+// rewriting the primary execution or verification truth.
+type ActionCompensationTruth struct {
+ Support ActionCompensationSupport `json:"support"`
+ Strategy string `json:"strategy,omitempty"`
+ Trigger string `json:"trigger,omitempty"`
+ Status ActionCompensationStatus `json:"status"`
+ ReasonCode string `json:"reasonCode,omitempty"`
+ Summary string `json:"summary,omitempty"`
+ AttemptID string `json:"attemptId,omitempty"`
+ StepID string `json:"stepId,omitempty"`
+ StartedAt *time.Time `json:"startedAt,omitempty"`
+ CompletedAt *time.Time `json:"completedAt,omitempty"`
+ Evidence []ActionEvidence `json:"evidence,omitempty"`
+ Execution *ActionExecutionTruth `json:"execution,omitempty"`
+ Verification *ActionVerificationTruth `json:"verification,omitempty"`
+ RestoredState *ActionRestoredStateTruth `json:"restoredState,omitempty"`
+}
+
+// ActionRestoredStateTruth binds a successful compensation to the exact
+// durable state identity that independent verification observed.
+type ActionRestoredStateTruth struct {
+ SubjectID string `json:"subjectId"`
+ ExpectedDigest string `json:"expectedDigest"`
+ ObservedDigest string `json:"observedDigest"`
+ ObservedAt time.Time `json:"observedAt"`
+}
+
+// ActionResultV2 is the sole canonical terminal truth contract. Legacy result
+// booleans and VerificationOutcome are compatibility projections derived from
+// this structure during the migration window.
+type ActionResultV2 struct {
+ Version int `json:"version"`
+ Execution ActionExecutionTruth `json:"execution"`
+ Verification ActionVerificationTruth `json:"verification"`
+ Compensation ActionCompensationTruth `json:"compensation"`
+}
+
+var (
+ ErrInvalidActionResultV2 = errors.New("invalid action result v2")
+ ErrInvalidActionEvidence = errors.New("invalid action evidence")
+ ErrFalseIndependentEvidence = errors.New("independent evidence must use a distinct trust domain")
+ ErrActionEvidenceBounds = errors.New("action evidence exceeds bounded contract")
+ ErrExecutorResultContract = errors.New("executor result contract violation")
+)
+
+func validActionExecutionStatus(status ActionExecutionStatus) bool {
+ switch status {
+ case ActionExecutionNotRun, ActionExecutionSucceeded, ActionExecutionFailed, ActionExecutionInconclusive:
+ return true
+ default:
+ return false
+ }
+}
+
+func validActionVerificationStatus(status ActionVerificationStatus) bool {
+ switch status {
+ case ActionVerificationNotAttempted, ActionVerificationConfirmed, ActionVerificationContradicted, ActionVerificationInconclusive:
+ return true
+ default:
+ return false
+ }
+}
+
+func validActionEvidenceClass(class ActionEvidenceClass) bool {
+ switch class {
+ case ActionEvidenceNone, ActionEvidenceAgentAttested, ActionEvidenceIndependent:
+ return true
+ default:
+ return false
+ }
+}
+
+func boundedAuditText(value string, limit int) (string, error) {
+ value = strings.TrimSpace(value)
+ if len(value) > limit {
+ return "", ErrActionEvidenceBounds
+ }
+ value = strings.TrimSpace(RedactAuditText(value))
+ if len(value) > limit {
+ return "", ErrActionEvidenceBounds
+ }
+ return value, nil
+}
+
+// ActionEvidenceDigest returns the stable SHA-256 digest of the canonical,
+// redacted evidence envelope.
+func ActionEvidenceDigest(evidence ActionEvidence) (string, error) {
+ evidence.Digest = ""
+ normalized, err := normalizeActionEvidenceFields(evidence)
+ if err != nil {
+ return "", err
+ }
+ payload, err := json.Marshal(normalized)
+ if err != nil {
+ return "", fmt.Errorf("marshal canonical action evidence: %w", err)
+ }
+ sum := sha256.Sum256(payload)
+ return "sha256:" + hex.EncodeToString(sum[:]), nil
+}
+
+func normalizeActionEvidenceFields(evidence ActionEvidence) (ActionEvidence, error) {
+ if evidence.Version == 0 {
+ evidence.Version = ActionEvidenceVersion
+ }
+ if evidence.Version != ActionEvidenceVersion {
+ return ActionEvidence{}, fmt.Errorf("%w: unsupported version %d", ErrInvalidActionEvidence, evidence.Version)
+ }
+ var err error
+ for _, field := range []*string{&evidence.ID, &evidence.ObserverID, &evidence.ObserverKind, &evidence.ObserverTrustDomain, &evidence.ExecutorTrustDomain, &evidence.Method, &evidence.SubjectID} {
+ *field, err = boundedAuditText(*field, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionEvidence{}, err
+ }
+ }
+ evidence.ReasonCode, err = boundedAuditText(evidence.ReasonCode, ActionEvidenceMaxReasonBytes)
+ if err != nil {
+ return ActionEvidence{}, err
+ }
+ evidence.Summary, err = boundedAuditText(evidence.Summary, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionEvidence{}, err
+ }
+ if len(evidence.Refs) > ActionEvidenceMaxRefs {
+ return ActionEvidence{}, ErrActionEvidenceBounds
+ }
+ for i := range evidence.Refs {
+ evidence.Refs[i].ID, err = boundedAuditText(evidence.Refs[i].ID, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionEvidence{}, err
+ }
+ evidence.Refs[i].Kind, err = boundedAuditText(evidence.Refs[i].Kind, ActionEvidenceMaxReasonBytes)
+ if err != nil {
+ return ActionEvidence{}, err
+ }
+ evidence.Refs[i].Digest = strings.TrimSpace(evidence.Refs[i].Digest)
+ if !validSHA256Digest(evidence.Refs[i].Digest) {
+ return ActionEvidence{}, fmt.Errorf("%w: invalid evidence reference digest", ErrInvalidActionEvidence)
+ }
+ }
+ if evidence.ObservedAt.IsZero() || evidence.ReceivedAt.IsZero() {
+ return ActionEvidence{}, fmt.Errorf("%w: observation timestamps required", ErrInvalidActionEvidence)
+ }
+ evidence.ObservedAt = evidence.ObservedAt.UTC()
+ evidence.ReceivedAt = evidence.ReceivedAt.UTC()
+ if evidence.ReceivedAt.Before(evidence.ObservedAt) {
+ return ActionEvidence{}, fmt.Errorf("%w: receivedAt predates observedAt", ErrInvalidActionEvidence)
+ }
+ if evidence.ID == "" || evidence.ObserverID == "" || evidence.ObserverKind == "" || evidence.ObserverTrustDomain == "" || evidence.ExecutorTrustDomain == "" || evidence.Method == "" || evidence.SubjectID == "" {
+ return ActionEvidence{}, fmt.Errorf("%w: evidence identity, observer kind, trust domains, method, and subject required", ErrInvalidActionEvidence)
+ }
+ return evidence, nil
+}
+
+func validSHA256Digest(value string) bool {
+ if !strings.HasPrefix(value, "sha256:") || len(value) != len("sha256:")+64 {
+ return false
+ }
+ _, err := hex.DecodeString(strings.TrimPrefix(value, "sha256:"))
+ return err == nil
+}
+
+func NormalizeActionEvidence(evidence ActionEvidence) (ActionEvidence, error) {
+ providedDigest := strings.TrimSpace(evidence.Digest)
+ evidence.Digest = ""
+ normalized, err := normalizeActionEvidenceFields(evidence)
+ if err != nil {
+ return ActionEvidence{}, err
+ }
+ digest, err := ActionEvidenceDigest(normalized)
+ if err != nil {
+ return ActionEvidence{}, err
+ }
+ if providedDigest != "" && providedDigest != digest {
+ return ActionEvidence{}, fmt.Errorf("%w: digest mismatch", ErrInvalidActionEvidence)
+ }
+ normalized.Digest = digest
+ return normalized, nil
+}
+
+func normalizeExecutionTruth(truth ActionExecutionTruth) (ActionExecutionTruth, error) {
+ if !validActionExecutionStatus(truth.Status) {
+ return ActionExecutionTruth{}, fmt.Errorf("%w: unsupported execution status %q", ErrInvalidActionResultV2, truth.Status)
+ }
+ var err error
+ truth.ReasonCode, err = boundedAuditText(truth.ReasonCode, ActionEvidenceMaxReasonBytes)
+ if err != nil {
+ return ActionExecutionTruth{}, err
+ }
+ truth.Summary, err = boundedAuditText(truth.Summary, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionExecutionTruth{}, err
+ }
+ if (truth.Status == ActionExecutionFailed || truth.Status == ActionExecutionInconclusive || truth.Status == ActionExecutionNotRun) && truth.ReasonCode == "" {
+ return ActionExecutionTruth{}, fmt.Errorf("%w: non-success execution requires reasonCode", ErrInvalidActionResultV2)
+ }
+ return truth, nil
+}
+
+func normalizeVerificationTruth(truth ActionVerificationTruth) (ActionVerificationTruth, error) {
+ if !validActionVerificationStatus(truth.Status) || !validActionEvidenceClass(truth.EvidenceClass) {
+ return ActionVerificationTruth{}, fmt.Errorf("%w: unsupported verification status or evidence class", ErrInvalidActionResultV2)
+ }
+ var err error
+ truth.ReasonCode, err = boundedAuditText(truth.ReasonCode, ActionEvidenceMaxReasonBytes)
+ if err != nil {
+ return ActionVerificationTruth{}, err
+ }
+ truth.Summary, err = boundedAuditText(truth.Summary, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionVerificationTruth{}, err
+ }
+ if len(truth.Evidence) > ActionEvidenceMaxItems {
+ return ActionVerificationTruth{}, ErrActionEvidenceBounds
+ }
+ if truth.Status == ActionVerificationNotAttempted {
+ if truth.EvidenceClass != ActionEvidenceNone || len(truth.Evidence) != 0 {
+ return ActionVerificationTruth{}, fmt.Errorf("%w: not-attempted verification cannot carry evidence", ErrInvalidActionResultV2)
+ }
+ return truth, nil
+ }
+ if truth.Status == ActionVerificationInconclusive && truth.ReasonCode == "" {
+ return ActionVerificationTruth{}, fmt.Errorf("%w: inconclusive verification requires reasonCode", ErrInvalidActionResultV2)
+ }
+ if (truth.Status == ActionVerificationConfirmed || truth.Status == ActionVerificationContradicted) && (truth.EvidenceClass == ActionEvidenceNone || len(truth.Evidence) == 0) {
+ return ActionVerificationTruth{}, fmt.Errorf("%w: conclusive verification requires evidence", ErrInvalidActionResultV2)
+ }
+ if truth.EvidenceClass == ActionEvidenceNone && len(truth.Evidence) != 0 {
+ return ActionVerificationTruth{}, fmt.Errorf("%w: evidence class none cannot carry evidence", ErrInvalidActionResultV2)
+ }
+ if truth.EvidenceClass != ActionEvidenceNone && len(truth.Evidence) == 0 {
+ return ActionVerificationTruth{}, fmt.Errorf("%w: declared evidence class requires evidence", ErrInvalidActionResultV2)
+ }
+ for i := range truth.Evidence {
+ truth.Evidence[i], err = NormalizeActionEvidence(truth.Evidence[i])
+ if err != nil {
+ return ActionVerificationTruth{}, err
+ }
+ if truth.EvidenceClass == ActionEvidenceIndependent && truth.Evidence[i].ObserverTrustDomain == truth.Evidence[i].ExecutorTrustDomain {
+ return ActionVerificationTruth{}, ErrFalseIndependentEvidence
+ }
+ }
+ return truth, nil
+}
+
+func normalizeCompensationTruth(truth ActionCompensationTruth) (ActionCompensationTruth, error) {
+ var err error
+ truth.Strategy, err = boundedAuditText(truth.Strategy, ActionEvidenceMaxReasonBytes)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.Trigger, err = boundedAuditText(truth.Trigger, ActionEvidenceMaxReasonBytes)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.ReasonCode, err = boundedAuditText(truth.ReasonCode, ActionEvidenceMaxReasonBytes)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.Summary, err = boundedAuditText(truth.Summary, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.AttemptID, err = boundedAuditText(truth.AttemptID, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.StepID, err = boundedAuditText(truth.StepID, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ if truth.StartedAt != nil {
+ startedAt := truth.StartedAt.UTC()
+ truth.StartedAt = &startedAt
+ }
+ if truth.CompletedAt != nil {
+ completedAt := truth.CompletedAt.UTC()
+ truth.CompletedAt = &completedAt
+ }
+ if len(truth.Evidence) > ActionEvidenceMaxItems {
+ return ActionCompensationTruth{}, ErrActionEvidenceBounds
+ }
+ for i := range truth.Evidence {
+ truth.Evidence[i], err = NormalizeActionEvidence(truth.Evidence[i])
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ }
+ if truth.Support == ActionCompensationUnavailable {
+ if truth.Status != ActionCompensationNotAvailable || truth.Strategy != "" || truth.Trigger != "" || compensationHasRuntimeOutcome(truth) {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: unavailable compensation cannot carry runtime outcome", ErrInvalidActionResultV2)
+ }
+ return truth, nil
+ }
+ if truth.Support != ActionCompensationDeclared || truth.Strategy == "" || truth.Trigger == "" {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: declared compensation strategy and trigger required", ErrInvalidActionResultV2)
+ }
+ switch truth.Status {
+ case ActionCompensationNotNeeded, ActionCompensationNotAttempted, ActionCompensationRunning, ActionCompensationSucceeded, ActionCompensationFailed, ActionCompensationInconclusive:
+ default:
+ return ActionCompensationTruth{}, fmt.Errorf("%w: unsupported compensation status %q", ErrInvalidActionResultV2, truth.Status)
+ }
+ if truth.Status == ActionCompensationNotNeeded || truth.Status == ActionCompensationNotAttempted {
+ if compensationHasRuntimeOutcome(truth) {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: unattempted compensation cannot carry runtime outcome", ErrInvalidActionResultV2)
+ }
+ return truth, nil
+ }
+ if truth.AttemptID == "" || truth.StepID == "" || truth.StartedAt == nil {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: compensation runtime requires attempt, step, and start identity", ErrInvalidActionResultV2)
+ }
+ if truth.Status == ActionCompensationRunning {
+ if truth.CompletedAt != nil || truth.Execution != nil || truth.Verification != nil || truth.RestoredState != nil {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: running compensation cannot carry terminal outcome", ErrInvalidActionResultV2)
+ }
+ return truth, nil
+ }
+ if truth.CompletedAt == nil || truth.CompletedAt.Before(*truth.StartedAt) {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: terminal compensation requires coherent completion time", ErrInvalidActionResultV2)
+ }
+ if (truth.Status == ActionCompensationFailed || truth.Status == ActionCompensationInconclusive) && truth.ReasonCode == "" {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: failed or inconclusive compensation requires reasonCode", ErrInvalidActionResultV2)
+ }
+ if truth.Execution != nil {
+ normalized, err := normalizeExecutionTruth(*truth.Execution)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.Execution = &normalized
+ }
+ if truth.Verification != nil {
+ normalized, err := normalizeVerificationTruth(*truth.Verification)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.Verification = &normalized
+ }
+ if truth.Execution == nil {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: terminal compensation requires execution truth", ErrInvalidActionResultV2)
+ }
+ if truth.RestoredState != nil {
+ restored, err := normalizeRestoredStateTruth(*truth.RestoredState)
+ if err != nil {
+ return ActionCompensationTruth{}, err
+ }
+ truth.RestoredState = &restored
+ }
+ if truth.Status == ActionCompensationSucceeded {
+ if truth.Execution.Status != ActionExecutionSucceeded || truth.Verification == nil || truth.Verification.Status != ActionVerificationConfirmed || truth.RestoredState == nil {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: compensation success requires successful execution and confirmed restoration", ErrInvalidActionResultV2)
+ }
+ } else if truth.Status == ActionCompensationFailed {
+ if truth.Execution.Status != ActionExecutionFailed && (truth.Verification == nil || truth.Verification.Status != ActionVerificationContradicted) {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: failed compensation requires failed execution or contradicted restoration", ErrInvalidActionResultV2)
+ }
+ } else if truth.Status == ActionCompensationInconclusive {
+ if truth.Execution.Status != ActionExecutionInconclusive && (truth.Verification == nil || truth.Verification.Status != ActionVerificationInconclusive) {
+ return ActionCompensationTruth{}, fmt.Errorf("%w: inconclusive compensation requires an inconclusive axis", ErrInvalidActionResultV2)
+ }
+ }
+ return truth, nil
+}
+
+func compensationHasRuntimeOutcome(truth ActionCompensationTruth) bool {
+ return truth.AttemptID != "" || truth.StepID != "" || truth.StartedAt != nil || truth.CompletedAt != nil || len(truth.Evidence) != 0 || truth.Execution != nil || truth.Verification != nil || truth.RestoredState != nil
+}
+
+func normalizeRestoredStateTruth(truth ActionRestoredStateTruth) (ActionRestoredStateTruth, error) {
+ var err error
+ truth.SubjectID, err = boundedAuditText(truth.SubjectID, ActionEvidenceMaxTextBytes)
+ if err != nil {
+ return ActionRestoredStateTruth{}, err
+ }
+ truth.ExpectedDigest = strings.TrimSpace(truth.ExpectedDigest)
+ truth.ObservedDigest = strings.TrimSpace(truth.ObservedDigest)
+ if truth.SubjectID == "" || !validSHA256Digest(truth.ExpectedDigest) || truth.ExpectedDigest != truth.ObservedDigest || truth.ObservedAt.IsZero() {
+ return ActionRestoredStateTruth{}, fmt.Errorf("%w: restored state requires matching durable digests and timestamp", ErrInvalidActionResultV2)
+ }
+ truth.ObservedAt = truth.ObservedAt.UTC()
+ return truth, nil
+}
+
+func NormalizeActionResultV2(result ActionResultV2) (ActionResultV2, error) {
+ if result.Version == 0 {
+ result.Version = ActionResultV2Version
+ }
+ if result.Version != ActionResultV2Version {
+ return ActionResultV2{}, fmt.Errorf("%w: unsupported version %d", ErrInvalidActionResultV2, result.Version)
+ }
+ var err error
+ result.Execution, err = normalizeExecutionTruth(result.Execution)
+ if err != nil {
+ return ActionResultV2{}, err
+ }
+ result.Verification, err = normalizeVerificationTruth(result.Verification)
+ if err != nil {
+ return ActionResultV2{}, err
+ }
+ result.Compensation, err = normalizeCompensationTruth(result.Compensation)
+ if err != nil {
+ return ActionResultV2{}, err
+ }
+ return result, nil
+}
+
+func defaultCompensationTruth(rollbackAvailable bool) ActionCompensationTruth {
+ if rollbackAvailable {
+ return ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "legacy_declared", Trigger: "legacy_rollback_declared", Status: ActionCompensationNotAttempted}
+ }
+ return ActionCompensationTruth{Support: ActionCompensationUnavailable, Status: ActionCompensationNotAvailable}
+}
+
+func legacyVerificationEvidence(verification *ActionVerificationResult, outcome VerificationOutcome, subjectID string, observedAt time.Time) ActionEvidence {
+ summary := strings.TrimSpace(outcome.EvidenceSummary)
+ method := "legacy_verification_outcome"
+ if verification != nil {
+ method = "agent_readback"
+ if strings.TrimSpace(verification.Note) != "" {
+ summary = verification.Note
+ } else if strings.TrimSpace(verification.Output) != "" {
+ summary = verification.Output
+ }
+ if !verification.RanAt.IsZero() {
+ observedAt = verification.RanAt
+ }
+ }
+ if observedAt.IsZero() {
+ observedAt = time.Unix(1, 0).UTC()
+ }
+ evidence := ActionEvidence{
+ Version: ActionEvidenceVersion, ID: "legacy-verification", ObserverID: "legacy-agent",
+ ObserverKind: "agent",
+ ObserverTrustDomain: "legacy-agent", ExecutorTrustDomain: "legacy-agent", Method: method,
+ SubjectID: strings.TrimSpace(subjectID), ObservedAt: observedAt.UTC(), ReceivedAt: observedAt.UTC(), Summary: summary,
+ }
+ if evidence.SubjectID == "" {
+ evidence.SubjectID = "legacy-action"
+ }
+ normalized, err := NormalizeActionEvidence(evidence)
+ if err == nil {
+ return normalized
+ }
+ return evidence
+}
+
+func legacyReadbackContradiction(result *ExecutionResult) bool {
+ if result == nil || result.Success || result.Verification == nil || !result.Verification.Ran || result.Verification.Success {
+ return false
+ }
+ message := strings.ToLower(strings.TrimSpace(result.ErrorMessage))
+ return strings.Contains(message, "completed but verification did not confirm")
+}
+
+func legacyUnknownEffect(result *ExecutionResult) bool {
+ if result == nil || result.Success {
+ return false
+ }
+ message := strings.ToLower(strings.TrimSpace(result.ErrorMessage))
+ for _, marker := range []string{"context deadline exceeded", "deadline exceeded", "timed out", "timeout", "connection reset", "connection closed", "disconnected", "disconnect", "broken pipe", "unexpected eof"} {
+ if strings.Contains(message, marker) {
+ return true
+ }
+ }
+ return false
+}
+
+// ActionResultV2FromLegacy converts the compatibility execution result and
+// verification projection into canonical truth without inventing independence.
+func ActionResultV2FromLegacy(result *ExecutionResult, outcome VerificationOutcome, rollbackAvailable bool, subjectID string, completedAt time.Time) ActionResultV2 {
+ canonical := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionInconclusive, ReasonCode: "legacy_missing_result", Summary: "Legacy action recorded no executor result."},
+ Verification: ActionVerificationTruth{Status: ActionVerificationNotAttempted, EvidenceClass: ActionEvidenceNone},
+ Compensation: defaultCompensationTruth(rollbackAvailable),
+ }
+ if result == nil {
+ normalized, _ := NormalizeActionResultV2(canonical)
+ return normalized
+ }
+ if result.Success {
+ canonical.Execution = ActionExecutionTruth{Status: ActionExecutionSucceeded, Summary: strings.TrimSpace(result.Output)}
+ } else if legacyReadbackContradiction(result) {
+ canonical.Execution = ActionExecutionTruth{Status: ActionExecutionSucceeded, Summary: strings.TrimSpace(result.Output)}
+ } else if legacyUnknownEffect(result) {
+ canonical.Execution = ActionExecutionTruth{Status: ActionExecutionInconclusive, ReasonCode: "legacy_unknown_effect", Summary: strings.TrimSpace(result.ErrorMessage)}
+ } else {
+ canonical.Execution = ActionExecutionTruth{Status: ActionExecutionFailed, ReasonCode: "legacy_execution_failed", Summary: strings.TrimSpace(result.ErrorMessage)}
+ }
+ rawVerificationNote := ""
+ if result.Verification != nil {
+ rawVerificationNote = strings.TrimSpace(result.Verification.Note)
+ }
+ verification := NormalizeActionVerificationResult(result.Verification)
+ if verification != nil {
+ if !verification.Ran {
+ canonical.Verification = ActionVerificationTruth{Status: ActionVerificationInconclusive, EvidenceClass: ActionEvidenceNone, ReasonCode: "legacy_verification_inconclusive", Summary: rawVerificationNote}
+ } else {
+ status := ActionVerificationContradicted
+ if verification.Success {
+ status = ActionVerificationConfirmed
+ }
+ canonical.Verification = ActionVerificationTruth{Status: status, EvidenceClass: ActionEvidenceAgentAttested, Evidence: []ActionEvidence{legacyVerificationEvidence(verification, outcome, subjectID, completedAt)}}
+ }
+ } else {
+ switch NormalizeVerificationOutcome(outcome).Status {
+ case VerificationVerified:
+ canonical.Verification = ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceAgentAttested, Evidence: []ActionEvidence{legacyVerificationEvidence(nil, outcome, subjectID, completedAt)}}
+ case VerificationFailed:
+ canonical.Verification = ActionVerificationTruth{Status: ActionVerificationContradicted, EvidenceClass: ActionEvidenceAgentAttested, Evidence: []ActionEvidence{legacyVerificationEvidence(nil, outcome, subjectID, completedAt)}}
+ case VerificationUnverified:
+ canonical.Verification = ActionVerificationTruth{Status: ActionVerificationInconclusive, EvidenceClass: ActionEvidenceNone, ReasonCode: "legacy_verification_inconclusive", Summary: outcome.EvidenceSummary}
+ }
+ }
+ normalized, err := NormalizeActionResultV2(canonical)
+ if err != nil {
+ fallback := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionInconclusive, ReasonCode: "legacy_result_invalid", Summary: err.Error()},
+ Verification: ActionVerificationTruth{Status: ActionVerificationInconclusive, EvidenceClass: ActionEvidenceNone, ReasonCode: "legacy_result_invalid"},
+ Compensation: defaultCompensationTruth(rollbackAvailable),
+ }
+ normalized, _ = NormalizeActionResultV2(fallback)
+ }
+ return normalized
+}
+
+// CanonicalActionResultV2 returns normalized stored truth or derives it from
+// the compatibility fields for older rows.
+func CanonicalActionResultV2(record ActionAuditRecord) ActionResultV2 {
+ if record.Result != nil && record.Result.ActionResultV2 != nil {
+ if normalized, err := NormalizeActionResultV2(*record.Result.ActionResultV2); err == nil {
+ return normalized
+ }
+ return invalidStoredActionResultV2(record.Plan.RollbackAvailable)
+ }
+ return ActionResultV2FromLegacy(record.Result, record.VerificationOutcome, record.Plan.RollbackAvailable, record.ID, record.UpdatedAt)
+}
+
+func invalidStoredActionResultV2(rollbackAvailable bool) ActionResultV2 {
+ result := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionInconclusive, ReasonCode: "result_v2_invalid", Summary: "Stored action result violated the canonical contract."},
+ Verification: ActionVerificationTruth{Status: ActionVerificationInconclusive, EvidenceClass: ActionEvidenceNone, ReasonCode: "result_v2_invalid"},
+ Compensation: defaultCompensationTruth(rollbackAvailable),
+ }
+ normalized, err := NormalizeActionResultV2(result)
+ if err != nil {
+ panic("canonical invalid-result fallback is invalid: " + err.Error())
+ }
+ return normalized
+}
+
+// ApplyActionResultV2 derives compatibility fields from canonical truth.
+func ApplyActionResultV2(result *ExecutionResult, canonical ActionResultV2) (*ExecutionResult, VerificationOutcome, error) {
+ normalized, err := NormalizeActionResultV2(canonical)
+ if err != nil {
+ return nil, VerificationOutcome{}, err
+ }
+ if result == nil {
+ result = &ExecutionResult{}
+ } else {
+ clone := *result
+ result = &clone
+ }
+ result.ActionResultV2 = &normalized
+ result.Success = normalized.Execution.Status == ActionExecutionSucceeded
+ if normalized.Execution.Status != ActionExecutionSucceeded && strings.TrimSpace(result.ErrorMessage) == "" {
+ result.ErrorMessage = strings.TrimSpace(normalized.Execution.Summary)
+ if result.ErrorMessage == "" {
+ result.ErrorMessage = normalized.Execution.ReasonCode
+ }
+ }
+ legacy := VerificationOutcome{Status: VerificationUnknown}
+ switch normalized.Verification.Status {
+ case ActionVerificationConfirmed:
+ legacy.Status = VerificationVerified
+ case ActionVerificationContradicted:
+ legacy.Status = VerificationFailed
+ case ActionVerificationInconclusive:
+ legacy.Status = VerificationUnverified
+ }
+ legacy.EvidenceSummary = normalized.Verification.Summary
+ if legacy.EvidenceSummary == "" && len(normalized.Verification.Evidence) > 0 {
+ legacy.EvidenceSummary = normalized.Verification.Evidence[0].Summary
+ }
+ return result, legacy, nil
+}
+
+// LegacyActionVerificationFromV2 derives the bounded compatibility readback
+// projection without allowing legacy fields to override canonical truth.
+func LegacyActionVerificationFromV2(canonical ActionResultV2) *ActionVerificationResult {
+ switch canonical.Verification.Status {
+ case ActionVerificationConfirmed:
+ return &ActionVerificationResult{Ran: true, Success: true, Note: canonical.Verification.Summary}
+ case ActionVerificationContradicted:
+ return &ActionVerificationResult{Ran: true, Success: false, Note: canonical.Verification.Summary}
+ case ActionVerificationInconclusive:
+ return &ActionVerificationResult{Ran: false, Success: false}
+ default:
+ return nil
+ }
+}
+
+// LegacyActionResultProjection derives the one-window compatibility result
+// from canonical truth, including fail-closed handling of malformed stored V2.
+func LegacyActionResultProjection(record ActionAuditRecord) *ExecutionResult {
+ canonical := CanonicalActionResultV2(record)
+ projected, _, err := ApplyActionResultV2(record.Result, canonical)
+ if err != nil {
+ projected, _, _ = ApplyActionResultV2(nil, invalidStoredActionResultV2(record.Plan.RollbackAvailable))
+ }
+ projected.Verification = LegacyActionVerificationFromV2(canonical)
+ return projected
+}
+
+// ExecutorContractViolationResult returns durable inconclusive truth for an
+// executor tuple that cannot be trusted.
+func ExecutorContractViolationResult(reasonCode, summary string, rollbackAvailable bool) *ExecutionResult {
+ canonical := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionInconclusive, ReasonCode: strings.TrimSpace(reasonCode), Summary: strings.TrimSpace(summary)},
+ Verification: ActionVerificationTruth{Status: ActionVerificationInconclusive, EvidenceClass: ActionEvidenceNone, ReasonCode: "execution_outcome_inconclusive"},
+ Compensation: defaultCompensationTruth(rollbackAvailable),
+ }
+ result, _, err := ApplyActionResultV2(nil, canonical)
+ if err != nil {
+ return &ExecutionResult{Success: false, ErrorMessage: ErrExecutorResultContract.Error()}
+ }
+ return result
+}
+
+// KnownNoEffectResult records a typed refusal that is known to have stopped
+// before dispatch. It is failed lifecycle admission with execution not_run,
+// not an executor failure and not an unknown-effect attempt.
+func KnownNoEffectResult(reasonCode, summary string, rollbackAvailable bool) *ExecutionResult {
+ canonical := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionNotRun, ReasonCode: strings.TrimSpace(reasonCode), Summary: strings.TrimSpace(summary)},
+ Verification: ActionVerificationTruth{Status: ActionVerificationNotAttempted, EvidenceClass: ActionEvidenceNone},
+ Compensation: defaultCompensationTruth(rollbackAvailable),
+ }
+ result, _, err := ApplyActionResultV2(&ExecutionResult{ErrorMessage: strings.TrimSpace(summary)}, canonical)
+ if err != nil {
+ return ExecutorContractViolationResult("known_no_effect_result_invalid", "Known-no-effect result violated its canonical contract.", rollbackAvailable)
+ }
+ return result
+}
diff --git a/internal/unifiedresources/action_result_v2_test.go b/internal/unifiedresources/action_result_v2_test.go
new file mode 100644
index 0000000000..564cb033f0
--- /dev/null
+++ b/internal/unifiedresources/action_result_v2_test.go
@@ -0,0 +1,429 @@
+package unifiedresources
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+)
+
+func actionResultTestEvidence(class ActionEvidenceClass) []ActionEvidence {
+ if class == ActionEvidenceNone {
+ return nil
+ }
+ observerDomain := "agent:node-1"
+ if class == ActionEvidenceIndependent {
+ observerDomain = "provider:proxmox-api"
+ }
+ now := time.Date(2026, 7, 11, 15, 0, 0, 0, time.UTC)
+ return []ActionEvidence{{
+ Version: ActionEvidenceVersion, ID: "evidence-1", ObserverID: "observer-1",
+ ObserverKind: "agent",
+ ObserverTrustDomain: observerDomain, ExecutorTrustDomain: "agent:node-1",
+ Method: "resource_status", SubjectID: "vm:42", ObservedAt: now, ReceivedAt: now.Add(time.Second),
+ Summary: "resource reached expected state",
+ }}
+}
+
+func actionResultTestCompensation() ActionCompensationTruth {
+ return ActionCompensationTruth{Support: ActionCompensationUnavailable, Status: ActionCompensationNotAvailable}
+}
+
+func actionResultTestTime(value time.Time) *time.Time {
+ value = value.UTC()
+ return &value
+}
+
+func TestNormalizeActionResultTruthMatrix48(t *testing.T) {
+ executions := []ActionExecutionStatus{ActionExecutionNotRun, ActionExecutionSucceeded, ActionExecutionFailed, ActionExecutionInconclusive}
+ verifications := []ActionVerificationStatus{ActionVerificationNotAttempted, ActionVerificationConfirmed, ActionVerificationContradicted, ActionVerificationInconclusive}
+ classes := []ActionEvidenceClass{ActionEvidenceNone, ActionEvidenceAgentAttested, ActionEvidenceIndependent}
+ cases := 0
+ for _, execution := range executions {
+ for _, verification := range verifications {
+ for _, class := range classes {
+ cases++
+ name := fmt.Sprintf("%s/%s/%s", execution, verification, class)
+ t.Run(name, func(t *testing.T) {
+ result := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: execution},
+ Verification: ActionVerificationTruth{Status: verification, EvidenceClass: class, Evidence: actionResultTestEvidence(class)},
+ Compensation: actionResultTestCompensation(),
+ }
+ if execution != ActionExecutionSucceeded {
+ result.Execution.ReasonCode = "execution_reason"
+ }
+ if verification == ActionVerificationInconclusive {
+ result.Verification.ReasonCode = "verification_reason"
+ }
+ valid := false
+ switch verification {
+ case ActionVerificationNotAttempted:
+ valid = class == ActionEvidenceNone
+ case ActionVerificationConfirmed, ActionVerificationContradicted:
+ valid = class == ActionEvidenceAgentAttested || class == ActionEvidenceIndependent
+ case ActionVerificationInconclusive:
+ valid = true
+ }
+ normalized, err := NormalizeActionResultV2(result)
+ if valid && err != nil {
+ t.Fatalf("NormalizeActionResultV2: %v", err)
+ }
+ if !valid && err == nil {
+ t.Fatalf("invalid combination normalized: %#v", normalized)
+ }
+ if valid && (normalized.Execution.Status != execution || normalized.Verification.Status != verification || normalized.Verification.EvidenceClass != class) {
+ t.Fatalf("truth collapsed: %#v", normalized)
+ }
+ })
+ }
+ }
+ }
+ if cases != 48 {
+ t.Fatalf("matrix cases=%d, want 48", cases)
+ }
+}
+
+func TestValidateActionResultEvidenceClassMatrix(t *testing.T) {
+ base := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded},
+ Verification: ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceIndependent, Evidence: actionResultTestEvidence(ActionEvidenceIndependent)},
+ Compensation: actionResultTestCompensation(),
+ }
+ if _, err := NormalizeActionResultV2(base); err != nil {
+ t.Fatalf("valid independent evidence: %v", err)
+ }
+ sameDomain := base
+ sameDomain.Verification.Evidence = actionResultTestEvidence(ActionEvidenceIndependent)
+ sameDomain.Verification.Evidence[0].ObserverTrustDomain = sameDomain.Verification.Evidence[0].ExecutorTrustDomain
+ if _, err := NormalizeActionResultV2(sameDomain); !errors.Is(err, ErrFalseIndependentEvidence) {
+ t.Fatalf("same trust domain error=%v", err)
+ }
+ missing := base
+ missing.Verification.Evidence = nil
+ if _, err := NormalizeActionResultV2(missing); err == nil {
+ t.Fatal("independent verification without evidence accepted")
+ }
+}
+
+func TestActionResultLegacyProjectionMatrix48(t *testing.T) {
+ executions := []ActionExecutionStatus{ActionExecutionNotRun, ActionExecutionSucceeded, ActionExecutionFailed, ActionExecutionInconclusive}
+ verifications := []ActionVerificationStatus{ActionVerificationNotAttempted, ActionVerificationConfirmed, ActionVerificationContradicted, ActionVerificationInconclusive}
+ classes := []ActionEvidenceClass{ActionEvidenceNone, ActionEvidenceAgentAttested, ActionEvidenceIndependent}
+ for _, execution := range executions {
+ for _, verification := range verifications {
+ for _, class := range classes {
+ result := ActionResultV2{Version: ActionResultV2Version, Execution: ActionExecutionTruth{Status: execution}, Verification: ActionVerificationTruth{Status: verification, EvidenceClass: class, Evidence: actionResultTestEvidence(class)}, Compensation: actionResultTestCompensation()}
+ if execution != ActionExecutionSucceeded {
+ result.Execution.ReasonCode = "execution_reason"
+ }
+ if verification == ActionVerificationInconclusive {
+ result.Verification.ReasonCode = "verification_reason"
+ }
+ if _, err := NormalizeActionResultV2(result); err != nil {
+ continue
+ }
+ legacy, outcome, err := ApplyActionResultV2(nil, result)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if legacy.Success != (execution == ActionExecutionSucceeded) {
+ t.Fatalf("execution %q legacy success=%v", execution, legacy.Success)
+ }
+ wantOutcome := map[ActionVerificationStatus]VerificationStatus{
+ ActionVerificationNotAttempted: VerificationUnknown,
+ ActionVerificationConfirmed: VerificationVerified,
+ ActionVerificationContradicted: VerificationFailed,
+ ActionVerificationInconclusive: VerificationUnverified,
+ }[verification]
+ if outcome.Status != wantOutcome {
+ t.Fatalf("verification %q legacy outcome=%q want=%q", verification, outcome.Status, wantOutcome)
+ }
+ }
+ }
+ }
+}
+
+func TestCompleteActionExecutionRequiresExplicitResult(t *testing.T) {
+ record := atomicLifecycleTestRecord("act-nil-result", ActionStateExecuting)
+ completed, _, err := CompleteActionExecution(record, nil, "operator", record.CreatedAt.Add(time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := CanonicalActionResultV2(completed)
+ if completed.State != ActionStateFailed || completed.Result == nil || completed.Result.Success || truth.Execution.Status != ActionExecutionInconclusive || truth.Execution.ReasonCode != "executor_nil_result" {
+ t.Fatalf("nil result truth=%#v record=%#v", truth, completed)
+ }
+}
+
+func TestKnownPreDispatchRefusalIsNotRunAndNotVerified(t *testing.T) {
+ record := atomicLifecycleTestRecord("action-refused", ActionStateExecuting)
+ refused, _, err := RefuseActionExecution(record, ErrActionPlanDrift, "operator", time.Now().UTC())
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := CanonicalActionResultV2(refused)
+ if truth.Execution.Status != ActionExecutionNotRun || truth.Verification.Status != ActionVerificationNotAttempted {
+ t.Fatalf("refusal truth=%#v", truth)
+ }
+}
+
+func TestLegacyDockerAndProxmoxReadbackFailureMigratesSucceededContradicted(t *testing.T) {
+ legacy := &ExecutionResult{Success: false, ErrorMessage: "container lifecycle action completed but verification did not confirm the expected state", Verification: &ActionVerificationResult{Ran: true, Success: false, RanAt: time.Now().UTC(), Note: "expected running=true"}}
+ truth := ActionResultV2FromLegacy(legacy, VerificationOutcome{Status: VerificationUnknown}, false, "app-container:42", time.Now().UTC())
+ if truth.Execution.Status != ActionExecutionSucceeded || truth.Verification.Status != ActionVerificationContradicted || truth.Verification.EvidenceClass != ActionEvidenceAgentAttested {
+ t.Fatalf("legacy contradiction=%#v", truth)
+ }
+}
+
+func TestLegacyVerifiedDefaultsToAgentAttested(t *testing.T) {
+ truth := ActionResultV2FromLegacy(&ExecutionResult{Success: true}, VerificationOutcome{Status: VerificationVerified, EvidenceSummary: "healthy"}, false, "vm:42", time.Now().UTC())
+ if truth.Verification.Status != ActionVerificationConfirmed || truth.Verification.EvidenceClass != ActionEvidenceAgentAttested {
+ t.Fatalf("legacy verified=%#v", truth.Verification)
+ }
+}
+
+func TestLegacyTimeoutAndDisconnectMigrateInconclusive(t *testing.T) {
+ for _, message := range []string{"context deadline exceeded", "transport timed out after dispatch", "agent disconnected before receipt", "connection reset by peer"} {
+ t.Run(message, func(t *testing.T) {
+ truth := ActionResultV2FromLegacy(&ExecutionResult{Success: false, ErrorMessage: message}, VerificationOutcome{Status: VerificationFailed}, false, "vm:42", time.Now().UTC())
+ if truth.Execution.Status != ActionExecutionInconclusive || truth.Execution.ReasonCode != "legacy_unknown_effect" {
+ t.Fatalf("legacy unknown effect=%#v", truth)
+ }
+ })
+ }
+}
+
+func TestMalformedStoredActionResultV2FailsClosed(t *testing.T) {
+ valid := ActionResultV2{
+ Version: ActionResultV2Version, Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded},
+ Verification: ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceIndependent, Evidence: actionResultTestEvidence(ActionEvidenceIndependent)},
+ Compensation: actionResultTestCompensation(),
+ }
+ tests := []struct {
+ name string
+ mutate func(*ActionResultV2)
+ }{
+ {"false_independence", func(result *ActionResultV2) {
+ result.Verification.Evidence[0].ObserverTrustDomain = result.Verification.Evidence[0].ExecutorTrustDomain
+ }},
+ {"bad_digest", func(result *ActionResultV2) {
+ result.Verification.Evidence[0].Digest = "sha256:" + strings.Repeat("0", 64)
+ }},
+ {"invalid_execution", func(result *ActionResultV2) { result.Execution.Status = "successful" }},
+ {"invalid_version", func(result *ActionResultV2) { result.Version = 99 }},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ malicious := cloneActionResultV2(valid)
+ test.mutate(&malicious)
+ record := ActionAuditRecord{
+ ID: "malicious", State: ActionStateCompleted,
+ Result: &ExecutionResult{Success: true, ActionResultV2: &malicious, Verification: &ActionVerificationResult{Ran: true, Success: true}},
+ VerificationOutcome: VerificationOutcome{Status: VerificationVerified},
+ }
+ truth := CanonicalActionResultV2(record)
+ legacy := LegacyActionResultProjection(record)
+ if truth.Execution.Status != ActionExecutionInconclusive || truth.Execution.ReasonCode != "result_v2_invalid" || truth.Verification.Status != ActionVerificationInconclusive || legacy.Success || legacy.Verification == nil || legacy.Verification.Ran || legacy.Verification.Success {
+ t.Fatalf("malformed stored V2 failed open: truth=%#v legacy=%#v", truth, legacy)
+ }
+ })
+ }
+}
+
+func TestInconclusiveEvidenceReasonSurvivesNormalization(t *testing.T) {
+ verification := &ActionVerificationResult{Ran: false, Note: "agent disconnected after dispatch"}
+ legacy := NormalizeActionVerificationResult(verification)
+ if legacy == nil || legacy.Note != "" {
+ t.Fatalf("legacy unrun verification was not scrubbed: %#v", legacy)
+ }
+ truth := ActionResultV2FromLegacy(&ExecutionResult{Success: true, Verification: verification}, VerificationOutcome{}, false, "vm:42", time.Now().UTC())
+ if truth.Verification.Status != ActionVerificationInconclusive || truth.Verification.Summary != "agent disconnected after dispatch" {
+ t.Fatalf("inconclusive truth=%#v", truth.Verification)
+ }
+}
+
+func TestActionEvidenceCanonicalDigestStable(t *testing.T) {
+ evidence := actionResultTestEvidence(ActionEvidenceIndependent)[0]
+ first, err := NormalizeActionEvidence(evidence)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := NormalizeActionEvidence(first)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if first.Digest != second.Digest || !strings.HasPrefix(first.Digest, "sha256:") {
+ t.Fatalf("unstable digest first=%q second=%q", first.Digest, second.Digest)
+ }
+}
+
+func TestActionEvidenceCanonicalDigestChangesWithRetainedSemanticFields(t *testing.T) {
+ evidence := actionResultTestEvidence(ActionEvidenceIndependent)[0]
+ first, err := NormalizeActionEvidence(evidence)
+ if err != nil {
+ t.Fatal(err)
+ }
+ evidence.Method = "provider_generation"
+ second, err := NormalizeActionEvidence(evidence)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if first.Digest == second.Digest {
+ t.Fatalf("digest did not bind retained semantic method: %q", first.Digest)
+ }
+}
+
+func TestActionEvidenceRedactionPreservesTruthAndCanonicalDigest(t *testing.T) {
+ evidence := actionResultTestEvidence(ActionEvidenceAgentAttested)[0]
+ evidence.Summary = "Authorization: Bearer secret-token"
+ normalized, err := NormalizeActionEvidence(evidence)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(normalized.Summary, "secret-token") || normalized.Digest == "" {
+ t.Fatalf("evidence not safely canonicalized: %#v", normalized)
+ }
+}
+
+func TestActionEvidenceRejectsUnboundedPayload(t *testing.T) {
+ evidence := actionResultTestEvidence(ActionEvidenceAgentAttested)[0]
+ evidence.Summary = strings.Repeat("x", ActionEvidenceMaxTextBytes+1)
+ if _, err := NormalizeActionEvidence(evidence); !errors.Is(err, ErrActionEvidenceBounds) {
+ t.Fatalf("unbounded evidence error=%v", err)
+ }
+}
+
+func TestActionEvidenceBoundsApplyBeforeSecretRedaction(t *testing.T) {
+ oversizedSecret := "Authorization: Bearer " + strings.Repeat("x", ActionEvidenceMaxTextBytes+1)
+ tests := []struct {
+ name string
+ mutate func(*ActionEvidence)
+ }{
+ {name: "summary", mutate: func(e *ActionEvidence) { e.Summary = oversizedSecret }},
+ {name: "reason", mutate: func(e *ActionEvidence) { e.ReasonCode = "token=" + strings.Repeat("x", ActionEvidenceMaxReasonBytes+1) }},
+ {name: "ref_id", mutate: func(e *ActionEvidence) {
+ e.Refs = []ActionEvidenceRef{{ID: oversizedSecret, Kind: "audit", Digest: "sha256:" + strings.Repeat("a", 64)}}
+ }},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ evidence := actionResultTestEvidence(ActionEvidenceAgentAttested)[0]
+ test.mutate(&evidence)
+ if _, err := NormalizeActionEvidence(evidence); !errors.Is(err, ErrActionEvidenceBounds) {
+ t.Fatalf("pre-redaction bound error=%v", err)
+ }
+ })
+ }
+}
+
+func TestActionResultRedactionDeepCopiesAndRecomputesDigest(t *testing.T) {
+ evidence := actionResultTestEvidence(ActionEvidenceAgentAttested)[0]
+ evidence.Summary = "Authorization: Bearer secret-token"
+ evidence.Digest = "not-a-valid-digest"
+ result := &ExecutionResult{ActionResultV2: &ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded, Summary: "token=execution-secret"},
+ Verification: ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceAgentAttested, Evidence: []ActionEvidence{evidence}},
+ Compensation: actionResultTestCompensation(),
+ }}
+ redacted := redactActionExecutionResult(result)
+ got := redacted.ActionResultV2.Verification.Evidence[0]
+ if strings.Contains(got.Summary, "secret-token") || !validSHA256Digest(got.Digest) {
+ t.Fatalf("redacted evidence=%#v", got)
+ }
+ if result.ActionResultV2.Verification.Evidence[0].Summary != "Authorization: Bearer secret-token" || result.ActionResultV2.Verification.Evidence[0].Digest != "not-a-valid-digest" {
+ t.Fatalf("redaction mutated input: %#v", result.ActionResultV2.Verification.Evidence[0])
+ }
+}
+
+func TestActionResultRedactionFailsClosedOnMalformedEvidence(t *testing.T) {
+ evidence := actionResultTestEvidence(ActionEvidenceAgentAttested)[0]
+ evidence.Summary = "Authorization: Bearer must-not-leak"
+ evidence.Refs = []ActionEvidenceRef{{ID: "token=ref-secret", Kind: "audit", Digest: "malformed"}}
+ result := &ExecutionResult{ActionResultV2: &ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded, Summary: "token=execution-secret"},
+ Verification: ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceAgentAttested, Evidence: []ActionEvidence{evidence}},
+ Compensation: actionResultTestCompensation(),
+ }}
+ redacted := redactActionExecutionResult(result)
+ truth := redacted.ActionResultV2
+ if truth.Execution.Status != ActionExecutionInconclusive || truth.Execution.ReasonCode != "redaction_contract_violation" || len(truth.Verification.Evidence) != 0 {
+ t.Fatalf("malformed evidence did not fail closed: %#v", truth)
+ }
+ payload := fmt.Sprintf("%#v", redacted)
+ if strings.Contains(payload, "must-not-leak") || strings.Contains(payload, "execution-secret") || strings.Contains(payload, "ref-secret") {
+ t.Fatalf("redaction fallback leaked original content: %s", payload)
+ }
+ if result.ActionResultV2.Verification.Evidence[0].Refs[0].Digest != "malformed" {
+ t.Fatalf("redaction mutated original ref graph: %#v", result.ActionResultV2.Verification.Evidence[0].Refs)
+ }
+}
+
+func TestCompensationNeverRewritesPrimaryResult(t *testing.T) {
+ failedCompensation := ActionCompensationTruth{
+ Support: ActionCompensationDeclared, Strategy: "restore_snapshot", Trigger: "verification_contradicted", Status: ActionCompensationFailed, ReasonCode: "restore_failed",
+ AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(time.Now().UTC().Add(-time.Minute)), CompletedAt: actionResultTestTime(time.Now().UTC()),
+ Execution: &ActionExecutionTruth{Status: ActionExecutionFailed, ReasonCode: "provider_failed"},
+ }
+ result := ActionResultV2{Version: ActionResultV2Version, Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded}, Verification: ActionVerificationTruth{Status: ActionVerificationContradicted, EvidenceClass: ActionEvidenceAgentAttested, Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested)}, Compensation: failedCompensation}
+ normalized, err := NormalizeActionResultV2(result)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if normalized.Execution.Status != ActionExecutionSucceeded || normalized.Verification.Status != ActionVerificationContradicted || normalized.Compensation.Status != ActionCompensationFailed {
+ t.Fatalf("truth axes collapsed: %#v", normalized)
+ }
+}
+
+func TestCompensationSucceededRequiresRestorationVerification(t *testing.T) {
+ now := time.Now().UTC()
+ result := ActionResultV2{Version: ActionResultV2Version, Execution: ActionExecutionTruth{Status: ActionExecutionFailed, ReasonCode: "update_failed"}, Verification: ActionVerificationTruth{Status: ActionVerificationContradicted, EvidenceClass: ActionEvidenceAgentAttested, Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested)}, Compensation: ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore_backup", Trigger: "verification_contradicted", Status: ActionCompensationSucceeded, AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(now.Add(-time.Minute)), CompletedAt: actionResultTestTime(now), Execution: &ActionExecutionTruth{Status: ActionExecutionSucceeded}}}
+ if _, err := NormalizeActionResultV2(result); err == nil {
+ t.Fatal("compensation success without restoration verification accepted")
+ }
+ verification := ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceIndependent, Evidence: actionResultTestEvidence(ActionEvidenceIndependent)}
+ result.Compensation.Verification = &verification
+ digest := "sha256:" + strings.Repeat("a", 64)
+ result.Compensation.RestoredState = &ActionRestoredStateTruth{SubjectID: "vm:42", ExpectedDigest: digest, ObservedDigest: digest, ObservedAt: now}
+ if _, err := NormalizeActionResultV2(result); err != nil {
+ t.Fatalf("verified compensation rejected: %v", err)
+ }
+}
+
+func TestCompensationStateShapeValidationMatrix(t *testing.T) {
+ now := time.Now().UTC()
+ digest := "sha256:" + strings.Repeat("b", 64)
+ confirmed := ActionVerificationTruth{Status: ActionVerificationConfirmed, EvidenceClass: ActionEvidenceIndependent, Evidence: actionResultTestEvidence(ActionEvidenceIndependent)}
+ tests := []struct {
+ name string
+ truth ActionCompensationTruth
+ valid bool
+ }{
+ {"unavailable_empty", ActionCompensationTruth{Support: ActionCompensationUnavailable, Status: ActionCompensationNotAvailable}, true},
+ {"unavailable_with_strategy", ActionCompensationTruth{Support: ActionCompensationUnavailable, Status: ActionCompensationNotAvailable, Strategy: "restore"}, false},
+ {"not_needed_empty", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "no_change", Status: ActionCompensationNotNeeded}, true},
+ {"not_needed_with_attempt", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "no_change", Status: ActionCompensationNotNeeded, AttemptID: "comp-1"}, false},
+ {"not_attempted_with_evidence", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "manual", Status: ActionCompensationNotAttempted, Evidence: actionResultTestEvidence(ActionEvidenceAgentAttested)}, false},
+ {"not_attempted_with_execution", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "manual", Status: ActionCompensationNotAttempted, Execution: &ActionExecutionTruth{Status: ActionExecutionSucceeded}}, false},
+ {"running", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "contradicted", Status: ActionCompensationRunning, AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(now)}, true},
+ {"running_with_terminal_axis", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "contradicted", Status: ActionCompensationRunning, AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(now), Execution: &ActionExecutionTruth{Status: ActionExecutionSucceeded}}, false},
+ {"failed_without_axis", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "contradicted", Status: ActionCompensationFailed, ReasonCode: "failed", AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(now), CompletedAt: actionResultTestTime(now.Add(time.Second))}, false},
+ {"inconclusive_with_success_axis", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "timeout", Status: ActionCompensationInconclusive, ReasonCode: "unknown", AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(now), CompletedAt: actionResultTestTime(now.Add(time.Second)), Execution: &ActionExecutionTruth{Status: ActionExecutionSucceeded}}, false},
+ {"succeeded_without_restored_state", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "contradicted", Status: ActionCompensationSucceeded, AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(now), CompletedAt: actionResultTestTime(now.Add(time.Second)), Execution: &ActionExecutionTruth{Status: ActionExecutionSucceeded}, Verification: &confirmed}, false},
+ {"succeeded", ActionCompensationTruth{Support: ActionCompensationDeclared, Strategy: "restore", Trigger: "contradicted", Status: ActionCompensationSucceeded, AttemptID: "comp-1", StepID: "restore", StartedAt: actionResultTestTime(now), CompletedAt: actionResultTestTime(now.Add(time.Second)), Execution: &ActionExecutionTruth{Status: ActionExecutionSucceeded}, Verification: &confirmed, RestoredState: &ActionRestoredStateTruth{SubjectID: "vm:42", ExpectedDigest: digest, ObservedDigest: digest, ObservedAt: now.Add(time.Second)}}, true},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ result := ActionResultV2{Version: ActionResultV2Version, Execution: ActionExecutionTruth{Status: ActionExecutionSucceeded}, Verification: ActionVerificationTruth{Status: ActionVerificationNotAttempted, EvidenceClass: ActionEvidenceNone}, Compensation: test.truth}
+ _, err := NormalizeActionResultV2(result)
+ if (err == nil) != test.valid {
+ t.Fatalf("valid=%v err=%v truth=%#v", test.valid, err, test.truth)
+ }
+ })
+ }
+}
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index d37e511867..2d283bc125 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -303,10 +303,11 @@ type ActionPlan struct {
// ExecutionResult captures the output of the native capability driver.
type ExecutionResult struct {
- Success bool `json:"success"`
- Output string `json:"output,omitempty"`
- ErrorMessage string `json:"errorMessage,omitempty"`
- Verification *ActionVerificationResult `json:"verification,omitempty"`
+ Success bool `json:"success"`
+ Output string `json:"output,omitempty"`
+ ErrorMessage string `json:"errorMessage,omitempty"`
+ Verification *ActionVerificationResult `json:"verification,omitempty"`
+ ActionResultV2 *ActionResultV2 `json:"actionResultV2,omitempty"`
}
// ActionVerificationResult records the outcome of a post-execution
@@ -389,9 +390,10 @@ func VerificationOutcomeFromExecutionResult(result *ExecutionResult) Verificatio
if result == nil || !result.Success || result.Verification == nil {
return VerificationOutcome{Status: VerificationUnknown}
}
+ note := strings.TrimSpace(result.Verification.Note)
verification := NormalizeActionVerificationResult(result.Verification)
if verification == nil || !verification.Ran {
- return VerificationOutcome{Status: VerificationUnverified, EvidenceSummary: strings.TrimSpace(verification.Note)}
+ return VerificationOutcome{Status: VerificationUnverified, EvidenceSummary: note}
}
if verification.Success {
return VerificationOutcome{Status: VerificationVerified, EvidenceSummary: strings.TrimSpace(verification.Note)}
@@ -417,9 +419,9 @@ func NormalizeActionVerificationResult(result *ActionVerificationResult) *Action
if !normalized.Ran {
normalized.Command = ""
normalized.Output = ""
+ normalized.Note = ""
normalized.Success = false
normalized.RanAt = time.Time{}
- normalized.Note = ""
}
return &normalized
}
@@ -436,6 +438,20 @@ func cloneActionVerificationResult(result *ActionVerificationResult) *ActionVeri
// an audit record, falling back to legacy result.verification records while
// older persisted rows are still being read.
func CanonicalActionVerification(record ActionAuditRecord) *ActionVerificationResult {
+ if record.Result != nil && record.Result.ActionResultV2 != nil {
+ canonical := CanonicalActionResultV2(record)
+ projected := LegacyActionVerificationFromV2(canonical)
+ if projected == nil || !projected.Ran {
+ return NormalizeActionVerificationResult(projected)
+ }
+ for _, candidate := range []*ActionVerificationResult{record.Verification, record.Result.Verification} {
+ compatibility := NormalizeActionVerificationResult(candidate)
+ if compatibility != nil && compatibility.Ran && compatibility.Success == projected.Success {
+ return compatibility
+ }
+ }
+ return NormalizeActionVerificationResult(projected)
+ }
if result := NormalizeActionVerificationResult(record.Verification); result != nil {
return result
}
@@ -937,10 +953,16 @@ func CompleteActionExecution(record ActionAuditRecord, result *ExecutionResult,
actor = "api:authenticated"
}
if result == nil {
- result = &ExecutionResult{Success: true}
+ result = ExecutorContractViolationResult("executor_nil_result", "Executor returned no result.", record.Plan.RollbackAvailable)
}
result.Output = strings.TrimSpace(result.Output)
result.ErrorMessage = strings.TrimSpace(result.ErrorMessage)
+ canonical := CanonicalActionResultV2(ActionAuditRecord{ID: record.ID, UpdatedAt: now, Plan: record.Plan, Result: result, VerificationOutcome: VerificationOutcomeFromExecutionResult(result)})
+ var err error
+ result, record.VerificationOutcome, err = ApplyActionResultV2(result, canonical)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
nextState := ActionStateCompleted
message := "Action execution completed."
@@ -955,7 +977,6 @@ func CompleteActionExecution(record ActionAuditRecord, result *ExecutionResult,
record.State = nextState
record.UpdatedAt = now
record.Result = result
- record.VerificationOutcome = VerificationOutcomeFromExecutionResult(result)
normalized, err := NormalizeActionAuditRecord(record)
if err != nil {
return ActionAuditRecord{}, ActionLifecycleEvent{}, err
@@ -993,10 +1014,7 @@ func RefuseActionExecution(record ActionAuditRecord, reason error, actor string,
record.State = ActionStateFailed
record.UpdatedAt = now
- record.Result = &ExecutionResult{
- Success: false,
- ErrorMessage: message,
- }
+ record.Result = KnownNoEffectResult("pre_dispatch_refused", message, record.Plan.RollbackAvailable)
normalized, err := NormalizeActionAuditRecord(record)
if err != nil {
return ActionAuditRecord{}, ActionLifecycleEvent{}, err
@@ -1241,7 +1259,12 @@ func NormalizeActionAuditRecord(record ActionAuditRecord) (ActionAuditRecord, er
result := *record.Result
result.Output = strings.TrimSpace(result.Output)
result.ErrorMessage = strings.TrimSpace(result.ErrorMessage)
+ if result.Verification == nil {
+ result.Verification = cloneActionVerificationResult(record.Verification)
+ }
+ canonical := CanonicalActionResultV2(ActionAuditRecord{ID: record.ID, UpdatedAt: record.UpdatedAt, Plan: record.Plan, Result: &result, VerificationOutcome: record.VerificationOutcome})
result.Verification = NormalizeActionVerificationResult(result.Verification)
+ result.ActionResultV2 = &canonical
record.Result = &result
}
record.Verification = NormalizeActionVerificationResult(record.Verification)
@@ -1252,6 +1275,14 @@ func NormalizeActionAuditRecord(record ActionAuditRecord) (ActionAuditRecord, er
record.Result.Verification = cloneActionVerificationResult(record.Verification)
}
record.VerificationOutcome = NormalizeVerificationOutcome(record.VerificationOutcome)
+ if record.Result != nil {
+ result, legacy, err := ApplyActionResultV2(record.Result, CanonicalActionResultV2(record))
+ if err != nil {
+ return ActionAuditRecord{}, err
+ }
+ record.Result = result
+ record.VerificationOutcome = legacy
+ }
for i := range record.Approvals {
record.Approvals[i].Actor = strings.TrimSpace(record.Approvals[i].Actor)
diff --git a/internal/unifiedresources/audit_redaction.go b/internal/unifiedresources/audit_redaction.go
index 1eb689c4d3..3a27cd1c9f 100644
--- a/internal/unifiedresources/audit_redaction.go
+++ b/internal/unifiedresources/audit_redaction.go
@@ -98,9 +98,88 @@ func redactActionExecutionResult(result *ExecutionResult) *ExecutionResult {
redacted.Output = RedactAuditText(redacted.Output)
redacted.ErrorMessage = RedactAuditText(redacted.ErrorMessage)
redacted.Verification = redactActionVerificationResult(redacted.Verification)
+ if redacted.ActionResultV2 != nil {
+ canonical := cloneActionResultV2(*redacted.ActionResultV2)
+ clearActionEvidenceDigests(canonical.Verification.Evidence)
+ clearActionEvidenceDigests(canonical.Compensation.Evidence)
+ if canonical.Compensation.Verification != nil {
+ clearActionEvidenceDigests(canonical.Compensation.Verification.Evidence)
+ }
+ if normalized, err := NormalizeActionResultV2(canonical); err == nil {
+ redacted.ActionResultV2 = &normalized
+ } else {
+ fallback := redactionContractViolationResult()
+ redacted.ActionResultV2 = &fallback
+ }
+ }
return &redacted
}
+func cloneActionResultV2(result ActionResultV2) ActionResultV2 {
+ result.Verification.Evidence = cloneActionEvidence(result.Verification.Evidence)
+ result.Compensation.Evidence = cloneActionEvidence(result.Compensation.Evidence)
+ if result.Compensation.StartedAt != nil {
+ startedAt := *result.Compensation.StartedAt
+ result.Compensation.StartedAt = &startedAt
+ }
+ if result.Compensation.CompletedAt != nil {
+ completedAt := *result.Compensation.CompletedAt
+ result.Compensation.CompletedAt = &completedAt
+ }
+ if result.Compensation.Execution != nil {
+ execution := *result.Compensation.Execution
+ result.Compensation.Execution = &execution
+ }
+ if result.Compensation.Verification != nil {
+ verification := *result.Compensation.Verification
+ verification.Evidence = cloneActionEvidence(verification.Evidence)
+ result.Compensation.Verification = &verification
+ }
+ if result.Compensation.RestoredState != nil {
+ restored := *result.Compensation.RestoredState
+ result.Compensation.RestoredState = &restored
+ }
+ return result
+}
+
+func cloneActionEvidence(evidence []ActionEvidence) []ActionEvidence {
+ if evidence == nil {
+ return nil
+ }
+ cloned := make([]ActionEvidence, len(evidence))
+ copy(cloned, evidence)
+ for i := range cloned {
+ cloned[i].Refs = append([]ActionEvidenceRef(nil), evidence[i].Refs...)
+ }
+ return cloned
+}
+
+func clearActionEvidenceDigests(evidence []ActionEvidence) {
+ for i := range evidence {
+ evidence[i].Digest = ""
+ }
+}
+
+func redactionContractViolationResult() ActionResultV2 {
+ fallback := ActionResultV2{
+ Version: ActionResultV2Version,
+ Execution: ActionExecutionTruth{
+ Status: ActionExecutionInconclusive, ReasonCode: "redaction_contract_violation",
+ Summary: "Action result was rejected by the audit redaction contract.",
+ },
+ Verification: ActionVerificationTruth{
+ Status: ActionVerificationInconclusive, EvidenceClass: ActionEvidenceNone,
+ ReasonCode: "redaction_contract_violation",
+ },
+ Compensation: ActionCompensationTruth{Support: ActionCompensationUnavailable, Status: ActionCompensationNotAvailable},
+ }
+ normalized, err := NormalizeActionResultV2(fallback)
+ if err != nil {
+ panic("canonical redaction fallback is invalid: " + err.Error())
+ }
+ return normalized
+}
+
// RedactAuditRecord returns a copy of the input ActionAuditRecord with
// known secret shapes scrubbed from the operator-authored reason, the
// params map's string values, execution output, and error text. Verification
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 03a84ed5ec..192201549a 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -69,6 +69,45 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
+func TestActionTruthTypesStayUnifiedResourceOwned(t *testing.T) {
+ repoRoot := filepath.Join("..", "..")
+ roots := []string{"internal/api", "internal/ai", "internal/agentexec", "internal/hostagent", "internal/dockeragent", "internal/relay", "internal/workflow", "internal/workflows"}
+ forbidden := []*regexp.Regexp{
+ regexp.MustCompile(`(?m)^type\s+ActionExecutionStatus\b`),
+ regexp.MustCompile(`(?m)^type\s+ActionVerificationStatus\b`),
+ regexp.MustCompile(`(?m)^type\s+ActionEvidenceClass\b`),
+ regexp.MustCompile(`(?m)^type\s+ActionCompensationStatus\b`),
+ regexp.MustCompile(`(?m)^type\s+ActionResultV2\b`),
+ }
+ for _, root := range roots {
+ path := filepath.Join(repoRoot, root)
+ if _, err := os.Stat(path); os.IsNotExist(err) {
+ continue
+ }
+ err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if info.IsDir() || filepath.Ext(path) != ".go" || strings.HasSuffix(path, "_test.go") {
+ return nil
+ }
+ source, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ for _, pattern := range forbidden {
+ if pattern.Match(source) {
+ t.Errorf("%s declares workflow-local action truth; use unifiedresources.ActionResultV2", filepath.ToSlash(path))
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("scan %s: %v", path, err)
+ }
+ }
+}
+
func TestProductionActionLifecycleDoesNotUseRecordActionAuditAsUpsert(t *testing.T) {
paths := []string{"../actionlifecycle/service.go", "../ai/tools/action_audit.go", "../api/patrol_action_broker.go"}
for _, path := range paths {
@@ -620,7 +659,7 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
// shape stable across refactors so frontend audit surfaces and
// any other consumers can rely on it.
"type ActionVerificationResult struct",
- "Verification *ActionVerificationResult `json:\"verification,omitempty\"`",
+ "Verification *ActionVerificationResult `json:\"verification,omitempty\"`",
},
filepath.Join(".", "store.go"): {
"RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error",
diff --git a/pkg/aicontracts/action_broker.go b/pkg/aicontracts/action_broker.go
index 56d2455e3f..e3bcc49841 100644
--- a/pkg/aicontracts/action_broker.go
+++ b/pkg/aicontracts/action_broker.go
@@ -2,6 +2,7 @@ package aicontracts
import (
"context"
+ "encoding/json"
"errors"
)
@@ -72,10 +73,11 @@ type ActionCapabilityParamInfo struct {
// the existing safe ActionPlanInfo projection shared with approval
// surfaces (see fix_execution.go).
type ActionDisposition struct {
- ActionID string `json:"action_id"`
- State string `json:"state"`
- VerificationStatus string `json:"verification_status,omitempty"`
- Plan ActionPlanInfo `json:"plan"`
+ ActionID string `json:"action_id"`
+ State string `json:"state"`
+ ActionResultV2 json.RawMessage `json:"action_result_v2,omitempty"`
+ VerificationStatus string `json:"verification_status,omitempty"`
+ Plan ActionPlanInfo `json:"plan"`
}
// ActionReference links an investigation to its canonical action lifecycle
diff --git a/pkg/aicontracts/contracts_test.go b/pkg/aicontracts/contracts_test.go
index fdc1770c11..76afbeed7a 100644
--- a/pkg/aicontracts/contracts_test.go
+++ b/pkg/aicontracts/contracts_test.go
@@ -279,6 +279,7 @@ func TestActionBrokerPolicyMetadataCarriesNoAuthorizationMethod(t *testing.T) {
dispositionPayload, err := json.Marshal(ActionDisposition{
ActionID: "act-1",
State: "completed",
+ ActionResultV2: json.RawMessage(`{"version":2,"execution":{"status":"succeeded"},"verification":{"status":"confirmed","evidenceClass":"independent"},"compensation":{"support":"unavailable","status":"not_available"}}`),
VerificationStatus: "verified",
})
if err != nil {
@@ -287,6 +288,9 @@ func TestActionBrokerPolicyMetadataCarriesNoAuthorizationMethod(t *testing.T) {
if !strings.Contains(string(dispositionPayload), `"verification_status":"verified"`) {
t.Fatalf("disposition must carry terminal verification: %s", dispositionPayload)
}
+ if !strings.Contains(string(dispositionPayload), `"action_result_v2":{"version":2`) {
+ t.Fatalf("disposition must carry canonical two-axis result: %s", dispositionPayload)
+ }
for _, forbidden := range []string{"authorize", "approve", "execute"} {
if strings.Contains(string(catalogPayload), forbidden) || strings.Contains(string(dispositionPayload), forbidden) {
t.Fatalf("broker wire metadata must not carry a %s authority field", forbidden)