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 durable Docker restart lifecycle proof

rcourtman00621284140e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index d6ba95ff39..cf5b7ca7b8 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1078,6 +1078,16 @@ the intentionally sparse public response.
Patrol run across agentic turns.
2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.
3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.
+ Local real-lab journey harnesses under `scripts/intelligence_lab/` belong to
+ this lifecycle boundary. They must be explicitly authorized, use ignored
+ artifacts, bind every mutation to an exact disposable run label, preserve
+ pre-existing resources, redact bounded evidence, prove idempotent cleanup,
+ and distinguish lab compensation from product rollback.
+ The artifact-backed current-build browser contract for the Docker restart
+ journey is `tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts`.
+ It may render only the strict redacted projection produced by the matching
+ managed-runtime run and must reject missing or mismatched proposal, action,
+ attempt, receipt, finding, and evidence identities.
Proxmox host-agent setup must treat local `proxmox-registered` markers as a cache, not authority: before skipping token setup or node repair, `internal/hostagent/proxmox_setup.go` must revalidate the current type and candidate hosts against Pulse through the canonical auto-register contract.
Runtime-side PVE token setup must also keep the same permission shape as the
generated setup script: Pulse-managed PVE monitor tokens are
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f84d4c528e..05b659fac0 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7358,6 +7358,27 @@ consumption remain separate work; no mobile or relay-local workaround may
compensate for a missing core API. Claims 16 and 17 remain open pending Task 09
resumption, real browser/lab evidence, and Task 12 certification.
+Typed Docker / Podman container start, stop, and restart operations extend that
+same durable boundary rather than creating a provider-local action protocol.
+The agent wire request is closed and binds the exact action, dispatch attempt,
+operation kind/version, request digest, agent, and immutable container identity.
+Its result is a bounded observation envelope only: workflow phase, whether a
+mutation started and completed, whether readback ran, before/after snapshots,
+bounded operation/transport error facts, and timestamps. The agent and
+`internal/agentexec` must not author success, verification, evidence-class, or
+compensation truth. The server rejects cross-operation identity reuse and any
+result or durable receipt that does not match the complete pending identity.
+Only the API-owned Docker lifecycle executor projects those facts into the
+unified-resource-owned `ActionResultV2`: a completed mutation remains execution
+`succeeded` even when readback contradicts, while preflight-proven no-effect is
+`not_run` and partial or unknown post-dispatch effect is `inconclusive`.
+Fresh same-agent readback is `agent_attested`; absent, invalid, or stale
+readback is inconclusive with a stable reason. A direct daemon observation may
+be classified `independent` only when a distinct observer trust domain binds
+the action, subject, observation and receipt times, before/after facts, and
+canonical evidence digest. It is independent operational evidence, not a
+cryptographic attestation.
+
### Canonical mutation plane
`internal/mutationregistry/manifest.json` is the generated closed registry for
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 965cd31b7f..bc0f433df6 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -1046,7 +1046,8 @@
"owned_prefixes": [
"internal/agentexec/",
"internal/agentupdate/",
- "internal/hostagent/"
+ "internal/hostagent/",
+ "scripts/intelligence_lab/"
],
"owned_files": [
".github/workflows/unified-agent-native.yml",
@@ -1114,7 +1115,8 @@
"scripts/install.ps1",
"scripts/install.sh",
"scripts/installtests/windows_agent_lifecycle.ps1",
- "scripts/installtests/windowslifecycleserver/main.go"
+ "scripts/installtests/windowslifecycleserver/main.go",
+ "tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts"
],
"verification": {
"allow_same_subsystem_tests": false,
@@ -1122,6 +1124,23 @@
"exact_files": [],
"require_explicit_path_policy_coverage": true,
"path_policies": [
+ {
+ "id": "docker-restart-intelligence-lab",
+ "label": "Docker restart managed-runtime and artifact-backed browser proof",
+ "match_prefixes": [
+ "scripts/intelligence_lab/"
+ ],
+ "match_files": [
+ "tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "internal/api/docker_restart_colima_real_lab_test.go",
+ "scripts/intelligence_lab/test_artifact_redaction.py",
+ "tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts"
+ ]
+ },
{
"id": "pulse-agent-cli-entrypoint",
"label": "pulse-agent CLI entrypoint proof",
@@ -1228,6 +1247,7 @@
"internal/hostagent/commands_deploy_test.go",
"internal/hostagent/commands_host_update_test.go",
"internal/hostagent/commands_storage_cleanup_test.go",
+ "internal/hostagent/docker_lifecycle_test.go",
"internal/hostagent/package_updates_test.go",
"internal/hostagent/send_report_test.go",
"internal/hostagent/storage_cleanup_test.go"
@@ -1488,6 +1508,7 @@
"exact_files": [
"internal/agentexec/approval_grant_test.go",
"internal/agentexec/deploy_test.go",
+ "internal/agentexec/docker_lifecycle_contract_test.go",
"internal/agentexec/policy_test.go",
"internal/agentexec/server_coverage_test.go",
"internal/agentexec/server_test.go",
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index d2540bb6a9..b43b57634c 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -421,6 +421,18 @@ host name and dispatches a trusted internal container command after action
approval, storage and recovery consumers may observe only the resulting action
audit and verification evidence; they must not reinterpret that trusted command
path as recovery authority or a storage-owned action transport.
+Container restart declares rollback unavailable. Its canonical
+`ActionResultV2.compensation` therefore records support `unavailable` and status
+`not_available`; neither same-agent readback nor a distinct direct-daemon
+observation creates rollback authority. Removing an exactly labelled disposable
+lab fixture is test-environment cleanup compensation only, never product
+rollback or evidence that Pulse can restore the restarted process. Dispatch,
+callback loss, and process-restart recovery remain on the shared action attempt
+and operation-receipt journal: reconciliation queries the bound attempt/receipt
+without blind redispatch, and an interrupted, missing, conflicting, or
+tombstoned receipt cannot authorize another mutation. Storage/recovery code must
+not add a Docker-specific receipt journal, infer restore readiness from a
+terminal container action, or represent cleanup as recovery compensation.
Disconnected command-agent readiness for those lifecycle actions remains an
API/runtime fail-closed condition; storage/recovery consumers may observe that
an action is unavailable, but must not reinterpret it as recovery degradation
diff --git a/internal/agentexec/apt_codec.go b/internal/agentexec/apt_codec.go
index 918d28d442..cd564de72b 100644
--- a/internal/agentexec/apt_codec.go
+++ b/internal/agentexec/apt_codec.go
@@ -156,6 +156,21 @@ func ValidateOperationQueryResultForIdentity(result operationreceipt.QueryResult
return err
}
return validateDurableAPTObservation(payload.Before.CheckedAt, payload.After.CheckedAt, result.Record.TerminalAt)
+ case DockerContainerOperationStart, DockerContainerOperationStop, DockerContainerOperationRestart:
+ if result.Record.ResultKind != DockerContainerLifecycleReceiptKind || result.Record.ResultVersion != DockerContainerLifecycleReceiptVersion {
+ return fmt.Errorf("docker container lifecycle query result envelope mismatch")
+ }
+ payload, err := DecodeDockerContainerLifecycleResultPayload(result.Record.Result)
+ if err != nil {
+ return err
+ }
+ if payload.RequestID != identity.AttemptID || payload.ActionID != identity.ActionID || payload.Operation != identity.OperationKind || payload.OperationVersion != identity.OperationVersion || payload.RequestDigest != identity.RequestDigest {
+ return operationreceipt.ErrBindingConflict
+ }
+ if payload.ReadbackRan && (payload.After.ObservedAt.IsZero() || result.Record.TerminalAt.Before(payload.After.ObservedAt)) {
+ return fmt.Errorf("docker container lifecycle readback has invalid terminal chronology")
+ }
+ return nil
default:
return fmt.Errorf("unsupported operation query kind %q", identity.OperationKind)
}
diff --git a/internal/agentexec/docker_lifecycle_codec.go b/internal/agentexec/docker_lifecycle_codec.go
new file mode 100644
index 0000000000..3232599e94
--- /dev/null
+++ b/internal/agentexec/docker_lifecycle_codec.go
@@ -0,0 +1,201 @@
+package agentexec
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
+)
+
+const (
+ DockerContainerLifecycleOperationVersion = 1
+ DockerContainerLifecycleReceiptKind = "pulse.docker_container_lifecycle_result"
+ DockerContainerLifecycleReceiptVersion = 1
+)
+
+var dockerContainerIDPattern = regexp.MustCompile(`^[a-f0-9]{12,64}$`)
+
+func decodeStrictDockerLifecycle(data []byte, target any) error {
+ if len(bytes.TrimSpace(data)) == 0 {
+ return fmt.Errorf("docker lifecycle payload is empty")
+ }
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(target); err != nil {
+ return err
+ }
+ if err := decoder.Decode(&struct{}{}); err != io.EOF {
+ if err == nil {
+ return fmt.Errorf("docker lifecycle payload contains trailing JSON")
+ }
+ return fmt.Errorf("docker lifecycle payload contains trailing data: %w", err)
+ }
+ return nil
+}
+
+func DecodeDockerContainerLifecyclePayload(data []byte) (DockerContainerLifecyclePayload, error) {
+ var payload DockerContainerLifecyclePayload
+ if err := decodeStrictDockerLifecycle(data, &payload); err != nil {
+ return DockerContainerLifecyclePayload{}, err
+ }
+ if err := ValidateDockerContainerLifecyclePayload(&payload); err != nil {
+ return DockerContainerLifecyclePayload{}, err
+ }
+ return payload, nil
+}
+
+func DecodeDockerContainerLifecycleResultPayload(data []byte) (DockerContainerLifecycleResultPayload, error) {
+ var payload DockerContainerLifecycleResultPayload
+ if err := decodeStrictDockerLifecycle(data, &payload); err != nil {
+ return DockerContainerLifecycleResultPayload{}, err
+ }
+ if err := ValidateDockerContainerLifecycleResultPayload(&payload); err != nil {
+ return DockerContainerLifecycleResultPayload{}, err
+ }
+ return payload, nil
+}
+
+func BindDockerContainerLifecyclePayload(payload *DockerContainerLifecyclePayload) error {
+ if payload == nil {
+ return fmt.Errorf("docker container lifecycle payload is required")
+ }
+ payload.OperationVersion = DockerContainerLifecycleOperationVersion
+ digest, err := dockerContainerLifecycleRequestDigest(*payload)
+ if err != nil {
+ return err
+ }
+ payload.RequestDigest = digest
+ return nil
+}
+
+func dockerContainerLifecycleRequestDigest(payload DockerContainerLifecyclePayload) (string, error) {
+ return operationreceipt.DigestCanonicalJSON(struct {
+ ActionID string `json:"action_id"`
+ Operation string `json:"operation"`
+ OperationVersion int `json:"operation_version"`
+ Runtime string `json:"runtime"`
+ ContainerID string `json:"container_id"`
+ ExpectedState string `json:"expected_state"`
+ ExpectedStartedAt time.Time `json:"expected_started_at,omitempty"`
+ }{
+ strings.TrimSpace(payload.ActionID), strings.TrimSpace(payload.Operation), payload.OperationVersion,
+ strings.ToLower(strings.TrimSpace(payload.Runtime)), strings.ToLower(strings.TrimSpace(payload.ContainerID)),
+ strings.ToLower(strings.TrimSpace(payload.ExpectedState)), payload.ExpectedStartedAt.UTC(),
+ })
+}
+
+func ValidateDockerContainerLifecyclePayload(payload *DockerContainerLifecyclePayload) error {
+ if payload == nil {
+ return fmt.Errorf("docker container lifecycle payload is required")
+ }
+ payload.RequestID = strings.TrimSpace(payload.RequestID)
+ payload.ActionID = strings.TrimSpace(payload.ActionID)
+ payload.Operation = strings.TrimSpace(payload.Operation)
+ payload.Runtime = strings.ToLower(strings.TrimSpace(payload.Runtime))
+ payload.ContainerID = strings.ToLower(strings.TrimSpace(payload.ContainerID))
+ payload.ExpectedState = strings.ToLower(strings.TrimSpace(payload.ExpectedState))
+ payload.ExpectedStartedAt = payload.ExpectedStartedAt.UTC()
+ if payload.RequestID == "" || len(payload.RequestID) > maxRequestIDLength || payload.ActionID == "" || len(payload.ActionID) > maxRequestIDLength {
+ return fmt.Errorf("invalid docker lifecycle request or action id")
+ }
+ if payload.Operation != DockerContainerOperationStart && payload.Operation != DockerContainerOperationStop && payload.Operation != DockerContainerOperationRestart {
+ return fmt.Errorf("unsupported docker container lifecycle operation %q", payload.Operation)
+ }
+ if payload.OperationVersion != DockerContainerLifecycleOperationVersion {
+ return fmt.Errorf("unsupported docker container lifecycle operation version %d", payload.OperationVersion)
+ }
+ if payload.Runtime != "docker" && payload.Runtime != "podman" {
+ return fmt.Errorf("unsupported container runtime %q", payload.Runtime)
+ }
+ if !dockerContainerIDPattern.MatchString(payload.ContainerID) {
+ return fmt.Errorf("container id must be an immutable hexadecimal id")
+ }
+ if payload.ExpectedState == "" || len(payload.ExpectedState) > 32 {
+ return fmt.Errorf("expected container state is required")
+ }
+ expectedDigest, err := dockerContainerLifecycleRequestDigest(*payload)
+ if err != nil {
+ return err
+ }
+ if payload.RequestDigest != expectedDigest {
+ return fmt.Errorf("docker container lifecycle request digest mismatch")
+ }
+ if payload.Timeout < 0 || payload.Timeout > 300 {
+ return fmt.Errorf("docker container lifecycle timeout must be between 0 and 300 seconds")
+ }
+ if payload.Timeout == 0 {
+ payload.Timeout = 120
+ }
+ return nil
+}
+
+func ValidateDockerContainerLifecycleResultPayload(result *DockerContainerLifecycleResultPayload) error {
+ if result == nil {
+ return fmt.Errorf("docker container lifecycle result is required")
+ }
+ result.RequestID = strings.TrimSpace(result.RequestID)
+ result.ActionID = strings.TrimSpace(result.ActionID)
+ result.Operation = strings.TrimSpace(result.Operation)
+ result.RequestDigest = strings.TrimSpace(result.RequestDigest)
+ result.ContainerID = strings.ToLower(strings.TrimSpace(result.ContainerID))
+ result.ExecutionPhase = strings.TrimSpace(result.ExecutionPhase)
+ result.Error = strings.TrimSpace(result.Error)
+ if result.RequestID == "" || len(result.RequestID) > maxRequestIDLength || result.ActionID == "" || len(result.ActionID) > maxRequestIDLength {
+ return fmt.Errorf("invalid docker lifecycle result identity")
+ }
+ if result.Operation != DockerContainerOperationStart && result.Operation != DockerContainerOperationStop && result.Operation != DockerContainerOperationRestart {
+ return fmt.Errorf("unsupported docker lifecycle result operation %q", result.Operation)
+ }
+ if result.OperationVersion != DockerContainerLifecycleOperationVersion || !dockerContainerIDPattern.MatchString(result.ContainerID) || !hostUpdateInventoryHashPattern.MatchString(result.RequestDigest) {
+ return fmt.Errorf("invalid docker lifecycle result binding")
+ }
+ if result.ExecutionPhase != DockerContainerPhasePreflight && result.ExecutionPhase != DockerContainerPhaseMutate && result.ExecutionPhase != DockerContainerPhaseVerify && result.ExecutionPhase != DockerContainerPhaseComplete {
+ return fmt.Errorf("unsupported docker lifecycle execution phase %q", result.ExecutionPhase)
+ }
+ if len(result.Error) > 1024 || result.Before.RestartCount < 0 || result.After.RestartCount < 0 {
+ return fmt.Errorf("docker lifecycle result exceeds bounded contract")
+ }
+ for _, snapshot := range []DockerContainerLifecycleSnapshot{result.Before, result.After} {
+ if snapshot.ContainerID != "" && !dockerContainerIDPattern.MatchString(strings.ToLower(strings.TrimSpace(snapshot.ContainerID))) {
+ return fmt.Errorf("docker lifecycle result has invalid container id")
+ }
+ if !snapshot.ObservedAt.IsZero() && snapshot.ObservedAt.Location() != time.UTC {
+ return fmt.Errorf("docker lifecycle observation timestamp must be UTC")
+ }
+ }
+ if result.MutationCompleted && !result.MutationStarted {
+ return fmt.Errorf("completed docker lifecycle mutation requires mutation start")
+ }
+ if result.ReadbackRan && result.After.ObservedAt.IsZero() {
+ return fmt.Errorf("docker lifecycle readback requires an observation")
+ }
+ return nil
+}
+
+func DockerContainerLifecycleOperationIdentity(agentID string, payload DockerContainerLifecyclePayload) operationreceipt.Identity {
+ return operationreceipt.Identity{AttemptID: payload.RequestID, ActionID: payload.ActionID, OperationKind: payload.Operation, OperationVersion: payload.OperationVersion, RequestDigest: payload.RequestDigest, AgentID: strings.TrimSpace(agentID)}
+}
+
+func ValidateDockerContainerLifecycleResultForRequest(req DockerContainerLifecyclePayload, result DockerContainerLifecycleResultPayload) error {
+ if err := ValidateDockerContainerLifecyclePayload(&req); err != nil {
+ return err
+ }
+ if err := ValidateDockerContainerLifecycleResultPayload(&result); err != nil {
+ return err
+ }
+ if result.RequestID != req.RequestID || result.ActionID != req.ActionID || result.Operation != req.Operation || result.OperationVersion != req.OperationVersion || result.RequestDigest != req.RequestDigest || result.ContainerID != req.ContainerID {
+ return fmt.Errorf("docker lifecycle result identity mismatch")
+ }
+ if result.Before.ContainerID != "" && !strings.EqualFold(result.Before.ContainerID, req.ContainerID) {
+ return fmt.Errorf("docker lifecycle before-state container mismatch")
+ }
+ if result.After.ContainerID != "" && !strings.EqualFold(result.After.ContainerID, req.ContainerID) {
+ return fmt.Errorf("docker lifecycle after-state container mismatch")
+ }
+ return nil
+}
diff --git a/internal/agentexec/docker_lifecycle_contract_test.go b/internal/agentexec/docker_lifecycle_contract_test.go
new file mode 100644
index 0000000000..ba3efd8d2f
--- /dev/null
+++ b/internal/agentexec/docker_lifecycle_contract_test.go
@@ -0,0 +1,74 @@
+package agentexec
+
+import (
+ "encoding/json"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
+)
+
+func TestDockerContainerLifecycleWireCarriesFactsNotActionTruth(t *testing.T) {
+ typeOf := reflect.TypeOf(DockerContainerLifecycleResultPayload{})
+ for _, forbidden := range []string{"Success", "Verification", "Evidence", "EvidenceClass", "Compensation", "Independent"} {
+ if _, ok := typeOf.FieldByName(forbidden); ok {
+ t.Fatalf("Docker lifecycle wire result declares canonical action truth field %q", forbidden)
+ }
+ }
+ payload, err := json.Marshal(DockerContainerLifecycleResultPayload{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, forbidden := range []string{`"success"`, `"verification"`, `"evidence"`, `"evidence_class"`, `"compensation"`, `"independent"`} {
+ if jsonContains(payload, forbidden) {
+ t.Fatalf("Docker lifecycle wire result exposes canonical action truth key %s: %s", forbidden, payload)
+ }
+ }
+}
+
+func TestDockerAgentWireAndRuntimeDeclareNoLocalActionTruthModel(t *testing.T) {
+ paths := []string{"docker_lifecycle_codec.go", "../hostagent/docker_lifecycle.go"}
+ for _, path := range paths {
+ source, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, forbidden := range []string{"DockerContainerVerification", "ActionResultV2", "ActionVerificationTruth", "ActionEvidenceClass", "ActionCompensationTruth", `json:"verification`, `json:"evidence`, `json:"independent`} {
+ if strings.Contains(string(source), forbidden) {
+ t.Fatalf("%s declares server-owned action truth token %q", path, forbidden)
+ }
+ }
+ }
+}
+
+func TestPendingDockerOperationBindsFullIdentityAndRejectsCrossTypeReuse(t *testing.T) {
+ server := NewServer(func(string, string, string) bool { return true })
+ identity := operationreceipt.Identity{AttemptID: "action.dispatch.1", ActionID: "action", OperationKind: DockerContainerOperationRestart, OperationVersion: DockerContainerLifecycleOperationVersion, RequestDigest: "sha256:" + strings.Repeat("a", 64), AgentID: "agent-1"}
+ key, err := server.claimPendingDockerOperation(identity, "0123456789ab")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer server.releasePendingHostOperation(key)
+ if _, err := server.claimPendingHostOperation(identity.AgentID, identity.AttemptID, identity.ActionID, HostUpdateOperationInstall); err == nil {
+ t.Fatal("same attempt identity was reused across operation kinds")
+ }
+ exact := DockerContainerLifecycleResultPayload{RequestID: identity.AttemptID, ActionID: identity.ActionID, Operation: identity.OperationKind, OperationVersion: identity.OperationVersion, RequestDigest: identity.RequestDigest, ContainerID: "0123456789ab"}
+ if !server.matchesPendingDockerOperation(identity.AgentID, exact) {
+ t.Fatal("exact durable identity did not match")
+ }
+ exact.RequestDigest = "sha256:" + strings.Repeat("b", 64)
+ if server.matchesPendingDockerOperation(identity.AgentID, exact) {
+ t.Fatal("request digest drift reached the waiter")
+ }
+}
+
+func jsonContains(payload []byte, value string) bool {
+ for i := 0; i+len(value) <= len(payload); i++ {
+ if string(payload[i:i+len(value)]) == value {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index fdec3fa2e3..3e78a70b52 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -61,24 +61,25 @@ var hostStorageCleanupFingerprintPattern = regexp.MustCompile(`^sha256:[a-f0-9]{
// Server manages WebSocket connections from agents
type Server struct {
- mu sync.RWMutex
- agents map[string]*agentConn // agentID -> connection
- pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
- pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup response
- pendingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update response
- pendingHostOperations map[string]pendingHostOperation // scoped request key -> exact typed APT operation/query identity
- pendingOperationQueries map[string]pendingOperationQuery
- deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber
- validateToken func(token string, agentID string, hostname string) bool
- commandPolicy *CommandPolicy
- ipConnCounts map[string]int
- maxConnsPerIP int
- shutdown chan struct{}
- shutdownOnce sync.Once
- pingInterval time.Duration
- commandAuthorizationVerifier func(CommandAuthorizationRequest) error
- newCommandApprovalGrant func([]byte, string, ExecuteCommandPayload, time.Time, time.Duration) (*CommandApprovalGrant, error)
- now func() time.Time
+ mu sync.RWMutex
+ agents map[string]*agentConn // agentID -> connection
+ pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
+ pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup response
+ pendingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update response
+ pendingDockerContainerLifecycles map[string]chan DockerContainerLifecycleResultPayload
+ pendingHostOperations map[string]pendingHostOperation // scoped request key -> exact typed APT operation/query identity
+ pendingOperationQueries map[string]pendingOperationQuery
+ deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber
+ validateToken func(token string, agentID string, hostname string) bool
+ commandPolicy *CommandPolicy
+ ipConnCounts map[string]int
+ maxConnsPerIP int
+ shutdown chan struct{}
+ shutdownOnce sync.Once
+ pingInterval time.Duration
+ commandAuthorizationVerifier func(CommandAuthorizationRequest) error
+ newCommandApprovalGrant func([]byte, string, ExecuteCommandPayload, time.Time, time.Duration) (*CommandApprovalGrant, error)
+ now func() time.Time
}
// CommandAuthorizationRequest is the complete server-side approval scope
@@ -105,6 +106,8 @@ type agentConn struct {
type pendingHostOperation struct {
actionID string
operation string
+ identity operationreceipt.Identity
+ subjectID string
}
type pendingOperationQuery struct {
@@ -139,21 +142,22 @@ func NewServer(validateToken func(token string, agentID string, hostname string)
}
return &Server{
- agents: make(map[string]*agentConn),
- pendingReqs: make(map[string]chan CommandResultPayload),
- pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),
- pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),
- pendingHostOperations: make(map[string]pendingHostOperation),
- pendingOperationQueries: make(map[string]pendingOperationQuery),
- deploySubs: make(map[string]chan DeployProgressPayload),
- validateToken: validateToken,
- commandPolicy: DefaultPolicy(),
- ipConnCounts: make(map[string]int),
- maxConnsPerIP: defaultMaxWebSocketConnectionsPerIP,
- shutdown: make(chan struct{}),
- pingInterval: defaultPingInterval,
- newCommandApprovalGrant: NewCommandApprovalGrant,
- now: time.Now,
+ agents: make(map[string]*agentConn),
+ pendingReqs: make(map[string]chan CommandResultPayload),
+ pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),
+ pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),
+ pendingDockerContainerLifecycles: make(map[string]chan DockerContainerLifecycleResultPayload),
+ pendingHostOperations: make(map[string]pendingHostOperation),
+ pendingOperationQueries: make(map[string]pendingOperationQuery),
+ deploySubs: make(map[string]chan DeployProgressPayload),
+ validateToken: validateToken,
+ commandPolicy: DefaultPolicy(),
+ ipConnCounts: make(map[string]int),
+ maxConnsPerIP: defaultMaxWebSocketConnectionsPerIP,
+ shutdown: make(chan struct{}),
+ pingInterval: defaultPingInterval,
+ newCommandApprovalGrant: NewCommandApprovalGrant,
+ now: time.Now,
}
}
@@ -201,6 +205,30 @@ func (s *Server) matchesPendingHostOperation(agentID, requestID, actionID, opera
return ok && expected.actionID == strings.TrimSpace(actionID) && expected.operation == strings.TrimSpace(operation)
}
+func (s *Server) claimPendingDockerOperation(identity operationreceipt.Identity, containerID string) (string, error) {
+ identity, err := operationreceipt.NormalizeIdentity(identity)
+ if err != nil {
+ return "", err
+ }
+ key := pendingRequestKey(identity.AgentID, identity.AttemptID)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if _, exists := s.pendingHostOperations[key]; exists {
+ return "", fmt.Errorf("typed operation request %q is already pending", identity.AttemptID)
+ }
+ s.pendingHostOperations[key] = pendingHostOperation{actionID: identity.ActionID, operation: identity.OperationKind, identity: identity, subjectID: strings.ToLower(strings.TrimSpace(containerID))}
+ return key, nil
+}
+
+func (s *Server) matchesPendingDockerOperation(agentID string, result DockerContainerLifecycleResultPayload) bool {
+ key := pendingRequestKey(agentID, result.RequestID)
+ s.mu.RLock()
+ expected, ok := s.pendingHostOperations[key]
+ s.mu.RUnlock()
+ actual := operationreceipt.Identity{AttemptID: result.RequestID, ActionID: result.ActionID, OperationKind: result.Operation, OperationVersion: result.OperationVersion, RequestDigest: result.RequestDigest, AgentID: strings.TrimSpace(agentID)}
+ return ok && expected.identity == actual && expected.subjectID == strings.ToLower(strings.TrimSpace(result.ContainerID))
+}
+
func (s *Server) releasePendingHostOperation(key string) {
s.mu.Lock()
delete(s.pendingHostOperations, key)
@@ -936,6 +964,27 @@ func (s *Server) readLoop(ac *agentConn) {
}
}
+ case MsgTypeDockerContainerLifecycleResult:
+ result, decodeErr := DecodeDockerContainerLifecycleResultPayload(msg.Payload)
+ if decodeErr != nil {
+ log.Warn().Err(decodeErr).Str("agent_id", ac.agent.AgentID).Msg("Dropping invalid docker container lifecycle result")
+ continue
+ }
+ if !s.matchesPendingDockerOperation(ac.agent.AgentID, result) {
+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Dropping uncorrelated docker lifecycle result")
+ continue
+ }
+ s.mu.RLock()
+ ch, ok := s.pendingDockerContainerLifecycles[pendingRequestKey(ac.agent.AgentID, result.RequestID)]
+ s.mu.RUnlock()
+ if ok {
+ select {
+ case ch <- result:
+ default:
+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Docker lifecycle result channel full, dropping")
+ }
+ }
+
case MsgTypeOperationQueryResult:
result, decodeErr := operationreceipt.DecodeQueryResult(msg.Payload)
if decodeErr != nil {
@@ -1439,6 +1488,86 @@ func (s *Server) ExecuteHostStorageCleanup(ctx context.Context, agentID string,
}
}
+// ExecuteDockerContainerLifecycle dispatches one closed typed container
+// operation. The Unified Agent owns the fixed runtime command catalog and
+// performs preflight plus read-after-write inside this single dispatch.
+func (s *Server) ExecuteDockerContainerLifecycle(ctx context.Context, agentID string, req DockerContainerLifecyclePayload) (*DockerContainerLifecycleResultPayload, error) {
+ if s == nil {
+ return nil, fmt.Errorf("agent execution server is unavailable")
+ }
+ agentID = strings.TrimSpace(agentID)
+ if agentID == "" {
+ return nil, fmt.Errorf("agent id is required")
+ }
+ if strings.TrimSpace(req.RequestID) == "" {
+ req.RequestID = uuid.NewString()
+ }
+ if err := BindDockerContainerLifecyclePayload(&req); err != nil {
+ return nil, err
+ }
+ if err := ValidateDockerContainerLifecyclePayload(&req); err != nil {
+ return nil, err
+ }
+ s.mu.RLock()
+ ac, ok := s.agents[agentID]
+ s.mu.RUnlock()
+ if !ok {
+ return nil, fmt.Errorf("agent %s not connected", agentID)
+ }
+ if ac.agent.OperationReceiptVersion != operationreceipt.ProtocolVersion {
+ return nil, fmt.Errorf("agent does not support durable operation receipts")
+ }
+
+ respCh := make(chan DockerContainerLifecycleResultPayload, 1)
+ reqKey := pendingRequestKey(agentID, req.RequestID)
+ identity := DockerContainerLifecycleOperationIdentity(agentID, req)
+ hostOperationKey, err := s.claimPendingDockerOperation(identity, req.ContainerID)
+ if err != nil {
+ return nil, err
+ }
+ defer s.releasePendingHostOperation(hostOperationKey)
+ s.mu.Lock()
+ if _, exists := s.pendingDockerContainerLifecycles[reqKey]; exists {
+ s.mu.Unlock()
+ return nil, fmt.Errorf("docker container lifecycle request %q is already pending", req.RequestID)
+ }
+ s.pendingDockerContainerLifecycles[reqKey] = respCh
+ s.mu.Unlock()
+ defer func() {
+ s.mu.Lock()
+ delete(s.pendingDockerContainerLifecycles, reqKey)
+ s.mu.Unlock()
+ }()
+
+ msg, err := NewMessage(MsgTypeDockerContainerLifecycle, req.RequestID, req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encode docker container lifecycle request: %w", err)
+ }
+ ac.writeMu.Lock()
+ err = s.sendMessage(ac.conn, msg)
+ ac.writeMu.Unlock()
+ if err != nil {
+ return nil, fmt.Errorf("failed to send docker container lifecycle request: %w", err)
+ }
+ timer := time.NewTimer(time.Duration(req.Timeout) * time.Second)
+ defer timer.Stop()
+ select {
+ case result := <-respCh:
+ if err := ValidateDockerContainerLifecycleResultForRequest(req, result); err != nil {
+ return nil, fmt.Errorf("docker container lifecycle result validation failed: %w", err)
+ }
+ return &result, nil
+ case <-timer.C:
+ return nil, fmt.Errorf("docker container lifecycle timed out after %s", time.Duration(req.Timeout)*time.Second)
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-ac.done:
+ return nil, fmt.Errorf("agent %s disconnected before docker container lifecycle receipt", agentID)
+ case <-s.shutdown:
+ return nil, errServerShuttingDown
+ }
+}
+
func (s *Server) currentTime() time.Time {
if s != nil && s.now != nil {
return s.now().UTC()
diff --git a/internal/agentexec/types.go b/internal/agentexec/types.go
index e3bda967d6..b3736a2060 100644
--- a/internal/agentexec/types.go
+++ b/internal/agentexec/types.go
@@ -12,24 +12,26 @@ type MessageType string
const (
// Agent -> Server messages
- MsgTypeAgentRegister MessageType = "agent_register"
- MsgTypeAgentPing MessageType = "agent_ping"
- MsgTypeCommandResult MessageType = "command_result"
- MsgTypeHostStorageCleanupResult MessageType = "host_storage_cleanup_result"
- MsgTypeHostUpdateResult MessageType = "host_update_result"
- MsgTypeOperationQueryResult MessageType = "agent_operation_query_result"
+ MsgTypeAgentRegister MessageType = "agent_register"
+ MsgTypeAgentPing MessageType = "agent_ping"
+ MsgTypeCommandResult MessageType = "command_result"
+ MsgTypeHostStorageCleanupResult MessageType = "host_storage_cleanup_result"
+ MsgTypeHostUpdateResult MessageType = "host_update_result"
+ MsgTypeDockerContainerLifecycleResult MessageType = "docker_container_lifecycle_result"
+ MsgTypeOperationQueryResult MessageType = "agent_operation_query_result"
// Server -> Agent messages
- MsgTypeRegistered MessageType = "registered"
- MsgTypePong MessageType = "pong"
- MsgTypeExecuteCmd MessageType = "execute_command"
- MsgTypeHostStorageCleanup MessageType = "host_storage_cleanup"
- MsgTypeReadFile MessageType = "read_file"
- MsgTypeHostUpdate MessageType = "host_update"
- MsgTypeOperationQuery MessageType = "agent_operation_query"
- MsgTypeDeployPreflight MessageType = "deploy_preflight"
- MsgTypeDeployInstall MessageType = "deploy_install"
- MsgTypeDeployCancelJob MessageType = "deploy_cancel"
+ MsgTypeRegistered MessageType = "registered"
+ MsgTypePong MessageType = "pong"
+ MsgTypeExecuteCmd MessageType = "execute_command"
+ MsgTypeHostStorageCleanup MessageType = "host_storage_cleanup"
+ MsgTypeReadFile MessageType = "read_file"
+ MsgTypeHostUpdate MessageType = "host_update"
+ MsgTypeDockerContainerLifecycle MessageType = "docker_container_lifecycle"
+ MsgTypeOperationQuery MessageType = "agent_operation_query"
+ MsgTypeDeployPreflight MessageType = "deploy_preflight"
+ MsgTypeDeployInstall MessageType = "deploy_install"
+ MsgTypeDeployCancelJob MessageType = "deploy_cancel"
// Agent -> Server messages (deploy)
MsgTypeDeployProgress MessageType = "deploy_progress"
@@ -156,6 +158,61 @@ type CommandResultPayload struct {
const HostUpdateOperationInstall = "install_os_updates"
+const (
+ DockerContainerOperationStart = "start_container"
+ DockerContainerOperationStop = "stop_container"
+ DockerContainerOperationRestart = "restart_container"
+)
+
+// DockerContainerLifecyclePayload is a closed container lifecycle operation.
+// It carries an immutable container ID and request-bound before state, never
+// command text, flags, a shell fragment, or a user-controlled container name.
+type DockerContainerLifecyclePayload struct {
+ RequestID string `json:"request_id"`
+ ActionID string `json:"action_id"`
+ Operation string `json:"operation"`
+ OperationVersion int `json:"operation_version"`
+ RequestDigest string `json:"request_digest"`
+ Runtime string `json:"runtime"`
+ ContainerID string `json:"container_id"`
+ ExpectedState string `json:"expected_state"`
+ ExpectedStartedAt time.Time `json:"expected_started_at,omitempty"`
+ Timeout int `json:"timeout,omitempty"`
+}
+
+type DockerContainerLifecycleSnapshot struct {
+ ContainerID string `json:"container_id"`
+ State string `json:"state"`
+ Running bool `json:"running"`
+ StartedAt time.Time `json:"started_at,omitempty"`
+ RestartCount int `json:"restart_count"`
+ ObservedAt time.Time `json:"observed_at"`
+}
+
+type DockerContainerLifecycleResultPayload struct {
+ RequestID string `json:"request_id"`
+ ActionID string `json:"action_id"`
+ Operation string `json:"operation"`
+ OperationVersion int `json:"operation_version"`
+ RequestDigest string `json:"request_digest"`
+ ContainerID string `json:"container_id"`
+ ExecutionPhase string `json:"execution_phase"`
+ MutationStarted bool `json:"mutation_started"`
+ MutationCompleted bool `json:"mutation_completed"`
+ ReadbackRan bool `json:"readback_ran"`
+ Before DockerContainerLifecycleSnapshot `json:"before"`
+ After DockerContainerLifecycleSnapshot `json:"after"`
+ Error string `json:"error,omitempty"`
+ Duration int64 `json:"duration_ms"`
+}
+
+const (
+ DockerContainerPhasePreflight = "preflight"
+ DockerContainerPhaseMutate = "mutate"
+ DockerContainerPhaseVerify = "verify"
+ DockerContainerPhaseComplete = "complete"
+)
+
// HostUpdatePayload is the closed, typed host-package operation sent to a
// Unified Agent. It intentionally has no command or package-name fields: the
// agent owns the package-manager command catalog and always updates the whole
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 8b6ebfea04..5f9608cac0 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -19946,7 +19946,7 @@ func TestContract_ResourceActionReadinessPayloadShape(t *testing.T) {
}
}
-func TestContract_DockerLifecycleActionsResolveCommandAgentAndDispatchTrusted(t *testing.T) {
+func TestContract_DockerLifecycleActionsResolveCommandAgentAndDispatchOneTypedOperation(t *testing.T) {
source, err := os.ReadFile("docker_container_action_executor.go")
if err != nil {
t.Fatalf("read docker_container_action_executor.go: %v", err)
@@ -19961,12 +19961,18 @@ func TestContract_DockerLifecycleActionsResolveCommandAgentAndDispatchTrusted(t
"func (e dockerContainerActionExecutor) connectedDockerCommandAgentID(resource unified.Resource) (string, error)",
"resource.Docker.AgentID",
"e.agents.GetAgentForHost(strings.TrimSpace(resource.Docker.Hostname))",
- "Trusted: true",
+ "ExecuteDockerContainerLifecycle(context.Context, string, agentexec.DockerContainerLifecyclePayload)",
+ "BindActionDispatch",
+ "ReconcileActionDispatch",
+ "dockerContainerExecutionResult",
} {
if !strings.Contains(src, snippet) {
- t.Fatalf("docker lifecycle executor must pin command-agent/trusted dispatch snippet %q", snippet)
+ t.Fatalf("docker lifecycle executor must pin durable typed dispatch snippet %q", snippet)
}
}
+ if strings.Contains(src, "ExecuteCommand(ctx, agentID") || strings.Contains(src, "docker inspect -f") || strings.Contains(src, "podman inspect -f") {
+ t.Fatal("docker lifecycle executor regressed to raw command dispatch or server-authored agent inspect")
+ }
if !strings.Contains(sharedSrc, "GetAgentForHost(hostname string) (string, bool)") {
t.Fatal("shared action command interface must keep hostname-based command-agent resolution available")
}
diff --git a/internal/api/docker_container_action_executor.go b/internal/api/docker_container_action_executor.go
index bb08b7b8c4..0eb922684b 100644
--- a/internal/api/docker_container_action_executor.go
+++ b/internal/api/docker_container_action_executor.go
@@ -9,6 +9,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/safety"
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
@@ -17,6 +18,47 @@ const dockerContainerLifecycleHandler = "docker.container.lifecycle"
type dockerContainerActionExecutor struct {
resources *ResourceHandlers
agents actionAgentCommander
+ observer dockerContainerPostconditionObserver
+}
+
+type dockerContainerPostconditionObservation struct {
+ ObserverID string
+ TrustDomain string
+ Method string
+ Snapshot agentexec.DockerContainerLifecycleSnapshot
+ ReceivedAt time.Time
+}
+
+type dockerContainerPostconditionObserver interface {
+ ObserveDockerContainer(context.Context, string, string) (dockerContainerPostconditionObservation, error)
+}
+
+type dockerContainerLifecycleAgentCommander interface {
+ ExecuteDockerContainerLifecycle(context.Context, string, agentexec.DockerContainerLifecyclePayload) (*agentexec.DockerContainerLifecycleResultPayload, error)
+}
+
+func (e dockerContainerActionExecutor) BindActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {
+ operation, err := dockerAgentLifecycleOperation(record.Request.CapabilityName)
+ if err != nil {
+ return unified.ActionDispatchAttempt{}, err
+ }
+ resource, err := e.currentDockerContainerResource(ctx, record.Request.ResourceID, record.Request.CapabilityName)
+ if err != nil {
+ return unified.ActionDispatchAttempt{}, err
+ }
+ runtime, err := dockerContainerRuntime(resource)
+ if err != nil {
+ return unified.ActionDispatchAttempt{}, err
+ }
+ agentID, err := e.connectedDockerCommandAgentID(resource)
+ if err != nil {
+ return unified.ActionDispatchAttempt{}, err
+ }
+ req := dockerContainerLifecycleRequest(attempt.ID, record.ID, operation, runtime, resource)
+ if err := agentexec.BindDockerContainerLifecyclePayload(&req); err != nil {
+ return unified.ActionDispatchAttempt{}, err
+ }
+ return unified.BindActionDispatchAttempt(attempt, unified.ActionDispatchBinding{OperationKind: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, AgentID: agentID})
}
func newDockerContainerActionExecutor(resources *ResourceHandlers, agents actionAgentCommander) ActionExecutor {
@@ -52,8 +94,7 @@ func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, record
if err != nil {
return nil, err
}
- containerRef := dockerContainerRef(resource)
- if containerRef == "" {
+ if dockerContainerRef(resource) == "" {
return nil, fmt.Errorf("docker container resource %q has no executable container id", record.Request.ResourceID)
}
agentID, err := e.connectedDockerCommandAgentID(resource)
@@ -61,36 +102,75 @@ func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, record
return nil, err
}
- command := fmt.Sprintf("%s %s %s", runtime, operation, shellQuote(containerRef))
- result, err := e.agents.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
- RequestID: attempt.ID,
- Command: command,
- ApprovalID: record.ID,
- TargetType: "agent",
- Timeout: 120,
- Trusted: true,
- })
+ typedAgents, ok := e.agents.(dockerContainerLifecycleAgentCommander)
+ if !ok {
+ return nil, fmt.Errorf("typed docker container lifecycle agent is unavailable")
+ }
+ agentOperation, err := dockerAgentLifecycleOperation(operation)
if err != nil {
return nil, err
}
-
- output := redactActionOutput(commandOutput(result))
- execution := &unified.ExecutionResult{
- Success: result.ExitCode == 0,
- Output: output,
+ req := dockerContainerLifecycleRequest(attempt.ID, record.ID, agentOperation, runtime, resource)
+ if err := agentexec.BindDockerContainerLifecyclePayload(&req); err != nil {
+ return nil, err
+ }
+ if agentexec.DockerContainerLifecycleOperationIdentity(agentID, req) != (operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}) {
+ return nil, fmt.Errorf("docker container lifecycle dispatch binding drift")
+ }
+ result, err := typedAgents.ExecuteDockerContainerLifecycle(ctx, agentID, req)
+ if err != nil {
+ return nil, err
}
- if result.ExitCode != 0 {
- execution.ErrorMessage = strings.TrimSpace(firstNonEmpty(result.Error, output, fmt.Sprintf("container %s exited with status %d", operation, result.ExitCode)))
- return execution, nil
+ if result == nil {
+ return nil, fmt.Errorf("docker container lifecycle agent returned no result")
+ }
+ receivedAt := time.Now().UTC()
+ if err := agentexec.ValidateDockerContainerLifecycleResultForRequest(req, *result); err != nil {
+ return nil, fmt.Errorf("invalid docker container lifecycle agent result: %w", err)
+ }
+ var independent *dockerContainerPostconditionObservation
+ if e.observer != nil {
+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, req.ContainerID); observeErr == nil {
+ independent = &observation
+ }
}
+ return dockerContainerExecutionResult(record.Request.ResourceID, agentID, req, *result, independent, receivedAt)
+}
- verification := e.verifyContainerState(ctx, agentID, record.ID, runtime, containerRef, operation)
- execution.Verification = verification
- if verification != nil && verification.Ran && !verification.Success {
- execution.Success = false
- execution.ErrorMessage = "container lifecycle action completed but verification did not confirm the expected state"
+func (e dockerContainerActionExecutor) ReconcileActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {
+ querier, ok := e.agents.(operationReceiptQuerier)
+ if !ok {
+ return nil, unified.ActionDispatchReceipt{}, false, nil
+ }
+ identity := operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}
+ query, err := querier.QueryAgentOperation(ctx, attempt.AgentID, identity)
+ if err != nil {
+ return nil, unified.ActionDispatchReceipt{}, false, err
+ }
+ if query.Status != operationreceipt.QueryFoundTerminal {
+ return nil, unified.ActionDispatchReceipt{}, false, nil
+ }
+ receivedAt := time.Now().UTC()
+ if err := agentexec.ValidateOperationQueryResultForIdentity(query, identity, receivedAt); err != nil {
+ return nil, unified.ActionDispatchReceipt{}, false, err
+ }
+ result, err := agentexec.DecodeDockerContainerLifecycleResultPayload(query.Record.Result)
+ if err != nil {
+ return nil, unified.ActionDispatchReceipt{}, false, err
+ }
+ req := agentexec.DockerContainerLifecyclePayload{RequestID: attempt.ID, ActionID: record.ID, Operation: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, Runtime: "docker", ContainerID: result.ContainerID, ExpectedState: result.Before.State, ExpectedStartedAt: result.Before.StartedAt}
+ var independent *dockerContainerPostconditionObservation
+ if e.observer != nil {
+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, result.ContainerID); observeErr == nil {
+ independent = &observation
+ }
}
- return execution, nil
+ execution, err := dockerContainerExecutionResult(record.Request.ResourceID, attempt.AgentID, req, result, independent, receivedAt)
+ if err != nil {
+ return nil, unified.ActionDispatchReceipt{}, false, err
+ }
+ receipt := unified.ActionDispatchReceipt{AttemptID: attempt.ID, ActionID: record.ID, TransportRequestID: attempt.ID, ReceivedAt: receivedAt}
+ return execution, receipt, true, nil
}
func (e dockerContainerActionExecutor) CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {
@@ -103,12 +183,20 @@ func (e dockerContainerActionExecutor) CheckActionAvailable(ctx context.Context,
if e.agents == nil {
return unavailableDockerActionReadiness(operation, "command_agent_unavailable", "Docker / Podman command execution is not available.")
}
+ if _, ok := e.agents.(dockerContainerLifecycleAgentCommander); !ok {
+ return unavailableDockerActionReadiness(operation, "typed_operation_unavailable", "Typed Docker / Podman lifecycle execution is not available.")
+ }
if _, err := e.executableDockerContainerResource(ctx, resource, operation); err != nil {
return unavailableDockerActionReadiness(operation, dockerActionUnavailableReasonCode(err), dockerActionUnavailableReason(err))
}
if _, err := e.connectedDockerCommandAgentID(resource); err != nil {
return unavailableDockerActionReadiness(operation, "command_agent_disconnected", "Docker / Podman command agent is not connected.")
}
+ agentID, _ := e.connectedDockerCommandAgentID(resource)
+ liveCapability, supported := e.agents.(agentOperationReceiptCapability)
+ if !supported || liveCapability.AgentOperationReceiptVersion(agentID) != operationreceipt.ProtocolVersion {
+ return unavailableDockerActionReadiness(operation, "operation_receipt_unsupported", "This agent does not support durable typed-operation receipts.")
+ }
return readiness
}
@@ -246,69 +334,31 @@ func dockerContainerRef(resource unified.Resource) string {
if ref := strings.TrimSpace(resource.Docker.ContainerID); ref != "" {
return ref
}
- return strings.TrimSpace(resource.Name)
+ return ""
}
-func (e dockerContainerActionExecutor) verifyContainerState(ctx context.Context, agentID, actionID, runtime, containerRef, operation string) *unified.ActionVerificationResult {
- expectRunning := operation == "start" || operation == "restart"
- command := fmt.Sprintf("%s inspect -f '{{.State.Status}} {{.State.Running}}' %s", runtime, shellQuote(containerRef))
-
- var lastOutput string
- for attempt := 0; attempt < 3; attempt++ {
- if attempt > 0 {
- timer := time.NewTimer(500 * time.Millisecond)
- select {
- case <-ctx.Done():
- timer.Stop()
- return &unified.ActionVerificationResult{Ran: false}
- case <-timer.C:
- }
- }
-
- result, err := e.agents.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
- RequestID: actionID + "-verify",
- Command: command,
- ApprovalID: actionID,
- TargetType: "agent",
- Timeout: 30,
- Trusted: true,
- })
- if err != nil {
- return &unified.ActionVerificationResult{Ran: false}
- }
- lastOutput = redactActionOutput(commandOutput(result))
- status, running := parseDockerInspectState(lastOutput)
- if result.ExitCode == 0 && status != "" && running == expectRunning {
- return &unified.ActionVerificationResult{
- Ran: true,
- Command: command,
- Output: lastOutput,
- Success: true,
- RanAt: time.Now().UTC(),
- }
- }
- }
-
- return &unified.ActionVerificationResult{
- Ran: true,
- Command: command,
- Output: lastOutput,
- Success: false,
- RanAt: time.Now().UTC(),
- Note: fmt.Sprintf("expected running=%t", expectRunning),
+func dockerAgentLifecycleOperation(operation string) (string, error) {
+ switch strings.TrimSpace(operation) {
+ case "start", agentexec.DockerContainerOperationStart:
+ return agentexec.DockerContainerOperationStart, nil
+ case "stop", agentexec.DockerContainerOperationStop:
+ return agentexec.DockerContainerOperationStop, nil
+ case "restart", agentexec.DockerContainerOperationRestart:
+ return agentexec.DockerContainerOperationRestart, nil
+ default:
+ return "", fmt.Errorf("unsupported docker container lifecycle capability %q", operation)
}
}
-func parseDockerInspectState(output string) (string, bool) {
- fields := strings.Fields(strings.ToLower(strings.TrimSpace(output)))
- if len(fields) == 0 {
- return "", false
+func dockerContainerLifecycleRequest(attemptID, actionID, operation, runtime string, resource unified.Resource) agentexec.DockerContainerLifecyclePayload {
+ startedAt := time.Time{}
+ if resource.Docker != nil && resource.Docker.StartedAt != nil {
+ startedAt = resource.Docker.StartedAt.UTC()
}
- running := false
- if len(fields) > 1 {
- running = fields[1] == "true"
+ return agentexec.DockerContainerLifecyclePayload{
+ RequestID: attemptID, ActionID: actionID, Operation: operation, Runtime: runtime,
+ ContainerID: dockerContainerRef(resource), ExpectedState: strings.ToLower(strings.TrimSpace(resource.Docker.ContainerState)), ExpectedStartedAt: startedAt, Timeout: 120,
}
- return fields[0], running
}
func isDockerContainerLifecycleOperation(operation string) bool {
diff --git a/internal/api/docker_container_action_executor_test.go b/internal/api/docker_container_action_executor_test.go
index da6102a810..b33aa4ba63 100644
--- a/internal/api/docker_container_action_executor_test.go
+++ b/internal/api/docker_container_action_executor_test.go
@@ -10,9 +10,11 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -21,8 +23,43 @@ type fakeDockerActionAgentCommander struct {
results []*agentexec.CommandResultPayload
calls []agentexec.ExecuteCommandPayload
callAgents []string
+ typedCalls []agentexec.DockerContainerLifecyclePayload
connected map[string]bool
agentByHost map[string]string
+ queryResult operationreceipt.QueryResult
+ queries []operationreceipt.Identity
+}
+
+func dockerActionDispatchContext(t *testing.T, executor dockerContainerActionExecutor, record unified.ActionAuditRecord) context.Context {
+ t.Helper()
+ attempt, err := unified.NewActionDispatchAttempt(record.ID, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ attempt, err = executor.BindActionDispatch(context.Background(), record, attempt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return actionlifecycle.ContextWithCommittedDispatchAttempt(context.Background(), attempt)
+}
+
+func (f *fakeDockerActionAgentCommander) AgentOperationReceiptVersion(string) int { return 1 }
+
+func (f *fakeDockerActionAgentCommander) QueryAgentOperation(_ context.Context, _ string, identity operationreceipt.Identity) (operationreceipt.QueryResult, error) {
+ f.queries = append(f.queries, identity)
+ return f.queryResult, nil
+}
+
+func (f *fakeDockerActionAgentCommander) ExecuteDockerContainerLifecycle(_ context.Context, agentID string, req agentexec.DockerContainerLifecyclePayload) (*agentexec.DockerContainerLifecycleResultPayload, error) {
+ f.callAgents = append(f.callAgents, agentID)
+ f.typedCalls = append(f.typedCalls, req)
+ now := time.Now().UTC()
+ return &agentexec.DockerContainerLifecycleResultPayload{
+ RequestID: req.RequestID, ActionID: req.ActionID, Operation: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, ContainerID: req.ContainerID,
+ ExecutionPhase: agentexec.DockerContainerPhaseComplete, MutationStarted: true, MutationCompleted: true, ReadbackRan: true,
+ Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: req.ExpectedState, Running: true, StartedAt: req.ExpectedStartedAt, ObservedAt: now.Add(-time.Second)},
+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, StartedAt: now, ObservedAt: now},
+ }, nil
}
func (f *fakeDockerActionAgentCommander) ExecuteCommand(_ context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {
@@ -77,36 +114,28 @@ func TestDockerContainerActionExecutorDispatchesPodmanRestartAndVerification(t *
dockerContainerActionResource("app-container:api", "podman", "running", now),
},
})
- agents := &fakeDockerActionAgentCommander{results: []*agentexec.CommandResultPayload{
- {RequestID: "act_container", Success: true, ExitCode: 0, Stdout: "api restarted"},
- {RequestID: "act_container-verify", Success: true, ExitCode: 0, Stdout: "running true"},
- }}
- executor := newDockerContainerActionExecutor(h, agents)
+ agents := &fakeDockerActionAgentCommander{}
+ executor := newDockerContainerActionExecutor(h, agents).(dockerContainerActionExecutor)
+ record := dockerContainerActionRecord("act_container", "app-container:api", "restart")
- result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_container"), dockerContainerActionRecord("act_container", "app-container:api", "restart"))
+ result, err := executor.ExecuteAction(dockerActionDispatchContext(t, executor, record), record)
if err != nil {
t.Fatalf("ExecuteAction: %v", err)
}
if result == nil || !result.Success || result.Verification == nil || !result.Verification.Success {
t.Fatalf("result = %#v, want successful execution and verification", result)
}
- if len(agents.calls) != 2 {
- t.Fatalf("agent calls = %d, want dispatch and verification", len(agents.calls))
- }
- if got := agents.calls[0].Command; got != "podman restart 'container-123'" {
- t.Fatalf("dispatch command = %q", got)
- }
- if agents.calls[0].ApprovalID != "act_container" || !agents.calls[0].Trusted {
- t.Fatalf("dispatch approval/trust = %q/%v", agents.calls[0].ApprovalID, agents.calls[0].Trusted)
+ if len(agents.typedCalls) != 1 || len(agents.calls) != 0 {
+ t.Fatalf("typed/raw agent calls = %d/%d, want one typed dispatch and zero raw commands", len(agents.typedCalls), len(agents.calls))
}
- if agents.calls[0].RequestID != "act_container.dispatch.1" {
- t.Fatalf("dispatch request identity = %q", agents.calls[0].RequestID)
+ if got := agents.typedCalls[0].Operation; got != agentexec.DockerContainerOperationRestart {
+ t.Fatalf("typed operation = %q", got)
}
- if got := agents.calls[1].Command; got != "podman inspect -f '{{.State.Status}} {{.State.Running}}' 'container-123'" {
- t.Fatalf("verification command = %q", got)
+ if agents.typedCalls[0].Runtime != "podman" {
+ t.Fatalf("runtime = %q", agents.typedCalls[0].Runtime)
}
- if !agents.calls[1].Trusted {
- t.Fatalf("verification command should be trusted")
+ if agents.typedCalls[0].RequestID != "act_container.dispatch.1" {
+ t.Fatalf("dispatch request identity = %q", agents.typedCalls[0].RequestID)
}
}
@@ -121,10 +150,6 @@ func TestDockerContainerActionExecutorResolvesCommandAgentByDockerHostname(t *te
resources: []unified.Resource{resource},
})
agents := &fakeDockerActionAgentCommander{
- results: []*agentexec.CommandResultPayload{
- {RequestID: "act_container", Success: true, ExitCode: 0, Stdout: "api restarted"},
- {RequestID: "act_container-verify", Success: true, ExitCode: 0, Stdout: "running true"},
- },
connected: map[string]bool{
"docker-source-1": false,
"command-agent-1": true,
@@ -144,15 +169,16 @@ func TestDockerContainerActionExecutorResolvesCommandAgentByDockerHostname(t *te
t.Fatalf("CheckActionAvailable readiness = %#v, want available through hostname-resolved command agent", readiness)
}
- result, err := executor.ExecuteAction(actionDispatchTestContext(t, "act_container"), dockerContainerActionRecord("act_container", "app-container:api", "restart"))
+ record := dockerContainerActionRecord("act_container", "app-container:api", "restart")
+ result, err := executor.ExecuteAction(dockerActionDispatchContext(t, executor, record), record)
if err != nil {
t.Fatalf("ExecuteAction: %v", err)
}
if result == nil || !result.Success {
t.Fatalf("result = %#v, want successful execution", result)
}
- if len(agents.callAgents) != 2 {
- t.Fatalf("call agents = %#v, want dispatch and verification through hostname-resolved agent", agents.callAgents)
+ if len(agents.callAgents) != 1 {
+ t.Fatalf("call agents = %#v, want one typed dispatch through hostname-resolved agent", agents.callAgents)
}
for _, agentID := range agents.callAgents {
if agentID != "command-agent-1" {
@@ -208,6 +234,53 @@ func TestDockerContainerActionExecutorAvailabilityRequiresConnectedAgent(t *test
}
}
+func TestDockerContainerActionExecutorStaleFixtureIsTripleZero(t *testing.T) {
+ now := time.Now().UTC()
+ resource := dockerContainerActionResource("app-container:api", "docker", "running", now)
+ resource.SourceStatus[unified.SourceDocker] = unified.SourceStatus{Status: "stale", LastSeen: now.Add(-time.Hour)}
+ h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{resource}})
+ agents := &fakeDockerActionAgentCommander{}
+ executor := newDockerContainerActionExecutor(h, agents).(dockerContainerActionExecutor)
+ readiness := executor.CheckActionAvailable(context.Background(), unified.ActionRequest{ResourceID: resource.ID, CapabilityName: "restart"}, resource)
+ if readiness.Available || readiness.ReasonCode != "stale_inventory" || len(agents.typedCalls) != 0 || len(agents.calls) != 0 {
+ t.Fatalf("stale readiness=%#v typed=%d raw=%d", readiness, len(agents.typedCalls), len(agents.calls))
+ }
+}
+
+func TestDockerContainerActionExecutorCallbackLossReconcilesReceiptWithoutRedispatch(t *testing.T) {
+ now := time.Now().UTC()
+ resource := dockerContainerActionResource("app-container:api", "docker", "running", now)
+ startedAt := now.Add(-time.Minute)
+ resource.Docker.StartedAt = &startedAt
+ h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{resource}})
+ agents := &fakeDockerActionAgentCommander{}
+ executor := newDockerContainerActionExecutor(h, agents).(dockerContainerActionExecutor)
+ record := dockerContainerActionRecord("act_container", resource.ID, "restart")
+ attempt, err := unified.NewActionDispatchAttempt(record.ID, now.Add(-5*time.Second))
+ if err != nil {
+ t.Fatal(err)
+ }
+ attempt, err = executor.BindActionDispatch(context.Background(), record, attempt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ facts := agentexec.DockerContainerLifecycleResultPayload{
+ RequestID: attempt.ID, ActionID: record.ID, Operation: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, ContainerID: resource.Docker.ContainerID,
+ ExecutionPhase: agentexec.DockerContainerPhaseComplete, MutationStarted: true, MutationCompleted: true, ReadbackRan: true,
+ Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: resource.Docker.ContainerID, State: "running", Running: true, StartedAt: startedAt, ObservedAt: now.Add(-2 * time.Second)},
+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: resource.Docker.ContainerID, State: "running", Running: true, StartedAt: now.Add(-time.Second), ObservedAt: now.Add(-time.Second)},
+ }
+ raw, _ := json.Marshal(facts)
+ identity := operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}
+ agents.queryResult = operationreceipt.QueryResult{Version: operationreceipt.ProtocolVersion, Status: operationreceipt.QueryFoundTerminal, Record: &operationreceipt.Record{Identity: identity, State: operationreceipt.StateTerminal, AcceptedAt: now.Add(-4 * time.Second), StartedAt: now.Add(-3 * time.Second), TerminalAt: now, ResultKind: agentexec.DockerContainerLifecycleReceiptKind, ResultVersion: agentexec.DockerContainerLifecycleReceiptVersion, Result: raw}}
+ result, _, found, err := executor.ReconcileActionDispatch(context.Background(), record, attempt)
+ if err != nil || !found || result == nil || result.ActionResultV2.Execution.Status != unified.ActionExecutionSucceeded || len(agents.typedCalls) != 0 || len(agents.queries) != 1 {
+ t.Fatalf("reconcile result=%#v found=%v err=%v typed=%d queries=%d", result, found, err, len(agents.typedCalls), len(agents.queries))
+ }
+}
+
func TestHandlePlanActionRejectsDisconnectedDockerContainerAgent(t *testing.T) {
now := time.Now().UTC()
h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})
@@ -408,7 +481,7 @@ func dockerContainerActionResource(id, runtime, state string, now time.Time) uni
},
Docker: &unified.DockerData{
AgentID: "agent-1",
- ContainerID: "container-123",
+ ContainerID: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
ContainerState: state,
Runtime: runtime,
},
diff --git a/internal/api/docker_container_action_result.go b/internal/api/docker_container_action_result.go
new file mode 100644
index 0000000000..677fb48b02
--- /dev/null
+++ b/internal/api/docker_container_action_result.go
@@ -0,0 +1,112 @@
+package api
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func dockerContainerExecutionResult(resourceID, agentID string, req agentexec.DockerContainerLifecyclePayload, facts agentexec.DockerContainerLifecycleResultPayload, independent *dockerContainerPostconditionObservation, receivedAt time.Time) (*unified.ExecutionResult, error) {
+ summary := dockerContainerFactSummary(facts)
+ execution := unified.ActionExecutionTruth{Status: unified.ActionExecutionNotRun, ReasonCode: "preflight_refused", Summary: summary}
+ if facts.MutationCompleted {
+ execution = unified.ActionExecutionTruth{Status: unified.ActionExecutionSucceeded, Summary: summary}
+ } else if facts.MutationStarted {
+ execution = unified.ActionExecutionTruth{Status: unified.ActionExecutionInconclusive, ReasonCode: "possible_partial_effect", Summary: summary}
+ }
+
+ verification := unified.ActionVerificationTruth{Status: unified.ActionVerificationInconclusive, EvidenceClass: unified.ActionEvidenceNone, ReasonCode: "agent_readback_unavailable", Summary: "The typed operation did not return a usable container readback."}
+ if facts.ReadbackRan {
+ if !freshDockerLifecycleObservation(facts.Before.ObservedAt, facts.After.ObservedAt, receivedAt) {
+ verification.ReasonCode = "stale_agent_readback"
+ verification.Summary = "The agent readback was stale, skewed, or had invalid mutation chronology."
+ } else {
+ evidence, err := unified.NormalizeActionEvidence(unified.ActionEvidence{
+ Version: unified.ActionEvidenceVersion, ID: req.Operation + "-agent-readback", ObserverID: agentID,
+ ObserverKind: "unified_agent", ObserverTrustDomain: "agent:" + agentID, ExecutorTrustDomain: "agent:" + agentID,
+ Method: "typed_container_read_after_write", SubjectID: resourceID, ObservedAt: facts.After.ObservedAt.UTC(), ReceivedAt: receivedAt.UTC(), Summary: summary,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("normalize docker lifecycle evidence: %w", err)
+ }
+ status := unified.ActionVerificationContradicted
+ reason := "postcondition_contradicted"
+ if dockerLifecycleFactsMatch(req.Operation, facts.Before, facts.After) {
+ status = unified.ActionVerificationConfirmed
+ reason = ""
+ }
+ verification = unified.ActionVerificationTruth{Status: status, EvidenceClass: unified.ActionEvidenceAgentAttested, ReasonCode: reason, Summary: summary, Evidence: []unified.ActionEvidence{evidence}}
+ }
+ }
+ if independent != nil && freshDockerLifecycleObservation(facts.Before.ObservedAt, independent.Snapshot.ObservedAt, independent.ReceivedAt) && strings.TrimSpace(independent.TrustDomain) != "" && strings.TrimSpace(independent.TrustDomain) != "agent:"+agentID && strings.EqualFold(independent.Snapshot.ContainerID, facts.ContainerID) {
+ observationDigest, err := operationreceipt.DigestCanonicalJSON(struct {
+ ActionID string `json:"action_id"`
+ SubjectID string `json:"subject_id"`
+ Before agentexec.DockerContainerLifecycleSnapshot `json:"before"`
+ After agentexec.DockerContainerLifecycleSnapshot `json:"after"`
+ }{req.ActionID, resourceID, facts.Before, independent.Snapshot})
+ if err != nil {
+ return nil, err
+ }
+ independentSummary := fmt.Sprintf("Direct daemon observation: before=%s; after=%s; running=%t", facts.Before.State, independent.Snapshot.State, independent.Snapshot.Running)
+ evidence, err := unified.NormalizeActionEvidence(unified.ActionEvidence{
+ Version: unified.ActionEvidenceVersion, ID: req.ActionID + "-direct-daemon-observation", ObserverID: independent.ObserverID,
+ ObserverKind: "docker_daemon_observer", ObserverTrustDomain: independent.TrustDomain, ExecutorTrustDomain: "agent:" + agentID,
+ Method: independent.Method, SubjectID: resourceID, ObservedAt: independent.Snapshot.ObservedAt, ReceivedAt: independent.ReceivedAt,
+ Summary: independentSummary, Refs: []unified.ActionEvidenceRef{{ID: req.ActionID, Kind: "docker_before_after", Digest: observationDigest}},
+ })
+ if err != nil {
+ return nil, fmt.Errorf("normalize independent docker observation: %w", err)
+ }
+ status := unified.ActionVerificationContradicted
+ reason := "postcondition_contradicted"
+ if dockerLifecycleFactsMatch(req.Operation, facts.Before, independent.Snapshot) {
+ status = unified.ActionVerificationConfirmed
+ reason = ""
+ }
+ verification = unified.ActionVerificationTruth{Status: status, EvidenceClass: unified.ActionEvidenceIndependent, ReasonCode: reason, Summary: independentSummary, Evidence: []unified.ActionEvidence{evidence}}
+ }
+
+ canonical := unified.ActionResultV2{
+ Version: unified.ActionResultV2Version, Execution: execution, Verification: verification,
+ Compensation: unified.ActionCompensationTruth{Support: unified.ActionCompensationUnavailable, Status: unified.ActionCompensationNotAvailable, Summary: "Container restart is non-rollbackable. Lab fixture cleanup is compensation for the disposable test environment, not product rollback."},
+ }
+ legacy := &unified.ExecutionResult{Output: summary}
+ projected, _, err := unified.ApplyActionResultV2(legacy, canonical)
+ if err != nil {
+ return nil, fmt.Errorf("apply canonical docker lifecycle action truth: %w", err)
+ }
+ projected.Verification = unified.LegacyActionVerificationFromV2(*projected.ActionResultV2)
+ return projected, nil
+}
+
+func dockerContainerFactSummary(facts agentexec.DockerContainerLifecycleResultPayload) string {
+ return fmt.Sprintf("Container lifecycle: phase=%s; mutation started=%t; mutation completed=%t; readback ran=%t; before=%s; after=%s", strings.TrimSpace(facts.ExecutionPhase), facts.MutationStarted, facts.MutationCompleted, facts.ReadbackRan, strings.TrimSpace(facts.Before.State), strings.TrimSpace(facts.After.State))
+}
+
+func freshDockerLifecycleObservation(before, after, receivedAt time.Time) bool {
+ if before.IsZero() || after.IsZero() || receivedAt.IsZero() || after.Before(before) {
+ return false
+ }
+ return !after.Before(receivedAt.UTC().Add(-15*time.Minute)) && !after.After(receivedAt.UTC().Add(5*time.Minute))
+}
+
+func dockerLifecycleFactsMatch(operation string, before, after agentexec.DockerContainerLifecycleSnapshot) bool {
+ if !strings.EqualFold(before.ContainerID, after.ContainerID) || after.ContainerID == "" {
+ return false
+ }
+ switch operation {
+ case agentexec.DockerContainerOperationStart:
+ return after.Running && after.State == "running"
+ case agentexec.DockerContainerOperationStop:
+ return !after.Running && after.State == "exited"
+ case agentexec.DockerContainerOperationRestart:
+ return after.Running && after.State == "running" && !after.StartedAt.IsZero() && after.StartedAt.After(before.StartedAt)
+ default:
+ return false
+ }
+}
diff --git a/internal/api/docker_container_action_result_test.go b/internal/api/docker_container_action_result_test.go
new file mode 100644
index 0000000000..950d3c14e1
--- /dev/null
+++ b/internal/api/docker_container_action_result_test.go
@@ -0,0 +1,88 @@
+package api
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func TestDockerContainerExecutionResultDerivesTruthOnlyFromFacts(t *testing.T) {
+ now := time.Now().UTC()
+ req := agentexec.DockerContainerLifecyclePayload{Operation: agentexec.DockerContainerOperationRestart}
+ tests := []struct {
+ name string
+ facts agentexec.DockerContainerLifecycleResultPayload
+ execution unified.ActionExecutionStatus
+ verification unified.ActionVerificationStatus
+ class unified.ActionEvidenceClass
+ }{
+ {name: "preflight no effect", facts: dockerResultFacts(now, false, false, false, true), execution: unified.ActionExecutionNotRun, verification: unified.ActionVerificationInconclusive, class: unified.ActionEvidenceNone},
+ {name: "completed confirmed", facts: dockerResultFacts(now, true, true, true, true), execution: unified.ActionExecutionSucceeded, verification: unified.ActionVerificationConfirmed, class: unified.ActionEvidenceAgentAttested},
+ {name: "completed contradicted", facts: dockerResultFacts(now, true, true, true, false), execution: unified.ActionExecutionSucceeded, verification: unified.ActionVerificationContradicted, class: unified.ActionEvidenceAgentAttested},
+ {name: "partial unknown", facts: dockerResultFacts(now, true, false, false, false), execution: unified.ActionExecutionInconclusive, verification: unified.ActionVerificationInconclusive, class: unified.ActionEvidenceNone},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ result, err := dockerContainerExecutionResult("app-container:fixture", "agent-1", req, tc.facts, nil, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.ActionResultV2.Execution.Status != tc.execution || result.ActionResultV2.Verification.Status != tc.verification || result.ActionResultV2.Verification.EvidenceClass != tc.class {
+ t.Fatalf("truth = %#v", result.ActionResultV2)
+ }
+ if result.ActionResultV2.Compensation.Support != unified.ActionCompensationUnavailable {
+ t.Fatalf("restart acquired rollback: %#v", result.ActionResultV2.Compensation)
+ }
+ })
+ }
+}
+
+func TestDockerContainerExecutionResultStaleReadbackIsInconclusive(t *testing.T) {
+ now := time.Now().UTC()
+ facts := dockerResultFacts(now.Add(-time.Hour), true, true, true, true)
+ result, err := dockerContainerExecutionResult("app-container:fixture", "agent-1", agentexec.DockerContainerLifecyclePayload{Operation: agentexec.DockerContainerOperationRestart}, facts, nil, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.ActionResultV2.Verification.Status != unified.ActionVerificationInconclusive || result.ActionResultV2.Verification.ReasonCode != "stale_agent_readback" {
+ t.Fatalf("verification = %#v", result.ActionResultV2.Verification)
+ }
+}
+
+func TestDockerContainerExecutionResultClassifiesDistinctDaemonObserverAsIndependent(t *testing.T) {
+ now := time.Now().UTC()
+ facts := dockerResultFacts(now, true, true, true, true)
+ facts.ContainerID = dockerLifecycleTestID
+ req := agentexec.DockerContainerLifecyclePayload{ActionID: "action-1", Operation: agentexec.DockerContainerOperationRestart}
+ observation := &dockerContainerPostconditionObservation{
+ ObserverID: "colima-direct-cli", TrustDomain: "daemon:colima-direct", Method: "docker_api_inspect",
+ Snapshot: facts.After, ReceivedAt: now,
+ }
+ result, err := dockerContainerExecutionResult("app-container:fixture", "agent-1", req, facts, observation, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := result.ActionResultV2.Verification
+ if truth.Status != unified.ActionVerificationConfirmed || truth.EvidenceClass != unified.ActionEvidenceIndependent || len(truth.Evidence) != 1 || truth.Evidence[0].Digest == "" || len(truth.Evidence[0].Refs) != 1 {
+ t.Fatalf("independent verification = %#v", truth)
+ }
+}
+
+func dockerResultFacts(now time.Time, started, completed, readback, matches bool) agentexec.DockerContainerLifecycleResultPayload {
+ beforeStart := now.Add(-time.Minute)
+ afterStart := now
+ state, running := "running", true
+ if !matches {
+ afterStart = beforeStart
+ state, running = "exited", false
+ }
+ return agentexec.DockerContainerLifecycleResultPayload{
+ ExecutionPhase: agentexec.DockerContainerPhaseComplete, MutationStarted: started, MutationCompleted: completed, ReadbackRan: readback,
+ Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: dockerLifecycleTestID, State: "running", Running: true, StartedAt: beforeStart, ObservedAt: now.Add(-time.Second)},
+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: dockerLifecycleTestID, State: state, Running: running, StartedAt: afterStart, ObservedAt: now},
+ }
+}
+
+const dockerLifecycleTestID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
diff --git a/internal/api/docker_restart_colima_real_lab_test.go b/internal/api/docker_restart_colima_real_lab_test.go
new file mode 100644
index 0000000000..e55be18138
--- /dev/null
+++ b/internal/api/docker_restart_colima_real_lab_test.go
@@ -0,0 +1,280 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/hostagent"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "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"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
+ "github.com/rs/zerolog"
+)
+
+func TestDockerRestartColimaRealLabCanonicalJourney(t *testing.T) {
+ runID := strings.TrimSpace(os.Getenv("PULSE_INTELLIGENCE_LAB_RUN_ID"))
+ containerID := strings.ToLower(strings.TrimSpace(os.Getenv("PULSE_INTELLIGENCE_LAB_CONTAINER_ID")))
+ artifactDir := strings.TrimSpace(os.Getenv("PULSE_INTELLIGENCE_LAB_ARTIFACT_DIR"))
+ scratchDir := strings.TrimSpace(os.Getenv("PULSE_INTELLIGENCE_LAB_SCRATCH_DIR"))
+ if runID == "" || containerID == "" || artifactDir == "" || scratchDir == "" {
+ t.Skip("released Colima lab environment is not configured")
+ }
+ if os.Getenv("DOCKER_CONTEXT") != "colima" {
+ t.Fatal("real lab requires DOCKER_CONTEXT=colima")
+ }
+ before, err := observeColimaContainer(context.Background(), containerID)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ agentServer := agentexec.NewServer(func(token, agent, host string) bool {
+ return token == "task06-local-lab" && agent == "task06-colima-agent"
+ })
+ wsServer := httptest.NewServer(http.HandlerFunc(agentServer.HandleWebSocket))
+ defer wsServer.Close()
+ logger := zerolog.Nop()
+ client := hostagent.NewCommandClient(hostagent.Config{PulseURL: wsServer.URL, APIToken: "task06-local-lab", StateDir: filepath.Join(scratchDir, "agent-state"), Logger: &logger}, "task06-colima-agent", "task06-colima", "darwin", "task06-current-build")
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- client.Run(ctx) }()
+ defer func() { cancel(); _ = client.Close(); <-done }()
+ deadline := time.Now().Add(5 * time.Second)
+ for !agentServer.IsAgentConnected("task06-colima-agent") && time.Now().Before(deadline) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !agentServer.IsAgentConnected("task06-colima-agent") {
+ t.Fatal("real Unified Agent command client did not connect")
+ }
+
+ resource := dockerContainerActionResource("app-container:"+runID, "docker", before.State, before.ObservedAt)
+ resource.Name = "pulse-task06-" + runID
+ resource.Docker.AgentID = "task06-colima-agent"
+ resource.Docker.ContainerID = containerID
+ resource.Docker.StartedAt = &before.StartedAt
+ resource.Docker.RestartCount = before.RestartCount
+ resources := newActionTestResourceHandlers(t, &config.Config{DataPath: filepath.Join(scratchDir, "pulse-state")})
+ resources.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: before.ObservedAt}, resources: []unified.Resource{resource}})
+ executor := dockerContainerActionExecutor{resources: resources, agents: agentServer, observer: colimaDirectObserver{}}
+ resources.SetActionExecutor(newRoutedActionExecutor(resources, executor))
+
+ aiHandler, patrol, _, _ := setupAIHandlerWithPatrol(t)
+ notifications := make(chan relay.PushNotificationPayload, 1)
+ patrol.SetPushNotifyCallback(func(payload relay.PushNotificationPayload) { notifications <- payload })
+ finding := &ai.Finding{ID: "docker-restart-loop:" + runID, Key: "docker-container-restart-loop", ResourceID: resource.ID, ResourceName: resource.Name, ResourceType: "docker", Title: "Container restart loop", Description: "Fresh Colima daemon evidence reported repeated restarts.", Evidence: fmt.Sprintf("restartCount=%d; state=%s; observedAt=%s", before.RestartCount, before.State, before.ObservedAt.Format(time.RFC3339Nano)), Severity: ai.FindingSeverityWarning, Category: ai.FindingCategoryReliability, DetectedAt: before.ObservedAt}
+ if !patrol.GetFindings().Add(finding) {
+ t.Fatal("fresh Docker finding was not admitted")
+ }
+ investigations := newTestInvestigationStore()
+ investigation := investigations.Create(finding.ID, "task06-colima-bounded-investigation")
+ aiHandler.investigationStores = map[string]aicontracts.InvestigationStore{"default": investigations}
+ aiHandler.SetResourceStoreProvider(resources.getStore)
+ resources.SetActionTransitionPublisher(aiHandler.ReconcilePatrolActionTransition)
+
+ proposal := aicontracts.ActionProposal{ProposalID: "proposal-" + runID, FindingID: finding.ID, InvestigationID: investigation.ID, ResourceID: resource.ID, CapabilityName: "restart", Params: map[string]any{}, Reason: "Restart the exact fresh disposable Colima fixture after explicit approval.", EvidenceIDs: []string{"finding-evidence:" + finding.ID}}
+ disposition, err := NewPatrolActionBroker("default", resources).Submit(context.Background(), proposal)
+ if err != nil || disposition.State != string(unified.ActionStatePending) || !disposition.Plan.RequiresApproval {
+ t.Fatalf("proposal disposition=%#v err=%v", disposition, err)
+ }
+ decision := httptest.NewRecorder()
+ decisionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+disposition.ActionID+"/decision", bytes.NewBufferString(`{"outcome":"approved","reason":"authorized disposable Colima lab"}`))
+ decisionReq.SetPathValue("id", disposition.ActionID)
+ decisionReq = decisionReq.WithContext(auth.WithUser(decisionReq.Context(), "[email protected]"))
+ resources.HandleDecideAction(decision, actionHandlerTestRequest(decisionReq, ""))
+ if decision.Code != http.StatusOK {
+ t.Fatalf("decision status=%d body=%s", decision.Code, decision.Body.String())
+ }
+ execution := httptest.NewRecorder()
+ executionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+disposition.ActionID+"/execute", bytes.NewBufferString(`{"reason":"execute one approved typed Docker restart"}`))
+ executionReq.SetPathValue("id", disposition.ActionID)
+ executionReq = executionReq.WithContext(auth.WithUser(executionReq.Context(), "[email protected]"))
+ resources.HandleExecuteAction(execution, actionHandlerTestRequest(executionReq, ""))
+ if execution.Code != http.StatusOK {
+ t.Fatalf("execution status=%d body=%s", execution.Code, execution.Body.String())
+ }
+ store, err := resources.getStore("default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ audit, found, err := store.GetActionAudit(disposition.ActionID)
+ attempt, attemptFound, attemptErr := store.GetActionDispatchAttempt(disposition.ActionID)
+ receipt, receiptFound, receiptErr := store.GetActionDispatchReceipt(attempt.ID)
+ if err != nil || !found || attemptErr != nil || !attemptFound || receiptErr != nil || !receiptFound || audit.State != unified.ActionStateCompleted || audit.Result == nil || audit.Result.ActionResultV2 == nil {
+ t.Fatalf("terminal audit/attempt audit=%#v found=%v err=%v attempt=%#v attemptFound=%v attemptErr=%v receipt=%#v receiptFound=%v receiptErr=%v", audit, found, err, attempt, attemptFound, attemptErr, receipt, receiptFound, receiptErr)
+ }
+ truth := audit.Result.ActionResultV2
+ if truth.Execution.Status != unified.ActionExecutionSucceeded || truth.Verification.Status != unified.ActionVerificationConfirmed || truth.Verification.EvidenceClass != unified.ActionEvidenceIndependent || len(truth.Verification.Evidence) != 1 {
+ t.Fatalf("terminal truth=%#v", truth)
+ }
+ if attempt.ID == "" || attempt.RequestDigest == "" || attempt.State != unified.ActionDispatchReceiptRecorded {
+ t.Fatalf("durable attempt=%#v", attempt)
+ }
+ reconciled := patrol.GetFindings().Get(finding.ID)
+ if reconciled == nil || reconciled.ResolvedAt == nil || reconciled.InvestigationOutcome != string(aicontracts.OutcomeFixVerified) {
+ t.Fatalf("reconciled finding=%#v", reconciled)
+ }
+ var notification relay.PushNotificationPayload
+ select {
+ case notification = <-notifications:
+ default:
+ t.Fatal("terminal desktop/mobile notification projection was not published")
+ }
+ after, err := observeColimaContainer(context.Background(), containerID)
+ if err != nil || !after.StartedAt.After(before.StartedAt) {
+ t.Fatalf("direct postcondition before=%s after=%s err=%v", before.StartedAt, after.StartedAt, err)
+ }
+ artifact := dockerRestartLabArtifact{
+ RunID: runID,
+ Proposal: dockerRestartLabProposal{ProposalID: proposal.ProposalID, FindingID: proposal.FindingID, InvestigationID: proposal.InvestigationID, ResourceID: proposal.ResourceID, CapabilityName: proposal.CapabilityName, Params: proposal.Params, EvidenceIDs: proposal.EvidenceIDs},
+ Investigation: dockerRestartLabInvestigation{ID: investigation.ID, FindingID: finding.ID},
+ Action: dockerRestartLabAction{
+ ID: audit.ID, CreatedAt: audit.CreatedAt, UpdatedAt: audit.UpdatedAt, State: audit.State, DecisionRevision: audit.DecisionRevision,
+ Request: dockerRestartLabActionRequest{RequestID: audit.Request.RequestID, ResourceID: audit.Request.ResourceID, CapabilityName: audit.Request.CapabilityName, Params: audit.Request.Params, Reason: audit.Request.Reason, RequestedBy: audit.Request.RequestedBy},
+ Plan: audit.Plan, Origin: audit.Origin,
+ Result: dockerRestartLabActionResult{Success: audit.Result.Success, ActionResultV2: *truth}, VerificationOutcome: audit.VerificationOutcome,
+ },
+ Attempt: dockerRestartLabAttempt{ID: attempt.ID, ActionID: attempt.ActionID, State: attempt.State, CreatedAt: attempt.CreatedAt, UpdatedAt: attempt.UpdatedAt, DispatchCount: attempt.DispatchCount, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID},
+ Receipt: receipt,
+ Finding: dockerRestartLabFinding{ID: reconciled.ID, Outcome: reconciled.InvestigationOutcome, ResolvedAt: reconciled.ResolvedAt},
+ Notification: dockerRestartLabNotification{Kind: notification.Type, Outcome: string(truth.Verification.Status), ActionType: notification.ActionType, ActionID: notification.ActionID, Category: notification.Category, Severity: notification.Severity},
+ Before: before, After: after, Evidence: truth.Verification.Evidence[0],
+ }
+ encoded, _ := json.MarshalIndent(artifact, "", " ")
+ if err := os.WriteFile(filepath.Join(artifactDir, "canonical-journey.json"), encoded, 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+type dockerRestartLabArtifact struct {
+ RunID string `json:"run_id"`
+ Proposal dockerRestartLabProposal `json:"proposal"`
+ Investigation dockerRestartLabInvestigation `json:"investigation"`
+ Action dockerRestartLabAction `json:"action"`
+ Attempt dockerRestartLabAttempt `json:"attempt"`
+ Receipt unified.ActionDispatchReceipt `json:"receipt"`
+ Finding dockerRestartLabFinding `json:"finding"`
+ Notification dockerRestartLabNotification `json:"notification"`
+ Before agentexec.DockerContainerLifecycleSnapshot `json:"before"`
+ After agentexec.DockerContainerLifecycleSnapshot `json:"after"`
+ Evidence unified.ActionEvidence `json:"evidence"`
+}
+
+type dockerRestartLabProposal struct {
+ ProposalID string `json:"proposal_id"`
+ FindingID string `json:"finding_id"`
+ InvestigationID string `json:"investigation_id"`
+ ResourceID string `json:"resource_id"`
+ CapabilityName string `json:"capability_name"`
+ Params map[string]any `json:"params"`
+ EvidenceIDs []string `json:"evidence_ids"`
+}
+
+type dockerRestartLabInvestigation struct {
+ ID string `json:"id"`
+ FindingID string `json:"finding_id"`
+}
+
+type dockerRestartLabActionRequest struct {
+ RequestID string `json:"requestId"`
+ ResourceID string `json:"resourceId"`
+ CapabilityName string `json:"capabilityName"`
+ Params map[string]any `json:"params"`
+ Reason string `json:"reason"`
+ RequestedBy string `json:"requestedBy"`
+}
+
+type dockerRestartLabActionResult struct {
+ Success bool `json:"success"`
+ ActionResultV2 unified.ActionResultV2 `json:"actionResultV2"`
+}
+
+type dockerRestartLabAction struct {
+ ID string `json:"id"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+ State unified.ActionState `json:"state"`
+ DecisionRevision uint64 `json:"decisionRevision"`
+ Request dockerRestartLabActionRequest `json:"request"`
+ Plan unified.ActionPlan `json:"plan"`
+ Origin *unified.ActionOrigin `json:"origin,omitempty"`
+ Result dockerRestartLabActionResult `json:"result"`
+ VerificationOutcome unified.VerificationOutcome `json:"verificationOutcome"`
+}
+
+type dockerRestartLabAttempt struct {
+ ID string `json:"id"`
+ ActionID string `json:"actionId"`
+ State unified.ActionDispatchState `json:"state"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+ DispatchCount int `json:"dispatchCount"`
+ OperationKind string `json:"operationKind"`
+ OperationVersion int `json:"operationVersion"`
+ RequestDigest string `json:"requestDigest"`
+ AgentID string `json:"agentId"`
+}
+
+type dockerRestartLabFinding struct {
+ ID string `json:"id"`
+ Outcome string `json:"outcome"`
+ ResolvedAt *time.Time `json:"resolved_at"`
+}
+
+type dockerRestartLabNotification struct {
+ Kind string `json:"kind"`
+ Outcome string `json:"outcome"`
+ ActionType string `json:"action_type"`
+ ActionID string `json:"action_id"`
+ Category string `json:"category"`
+ Severity string `json:"severity"`
+}
+
+type colimaDirectObserver struct{}
+
+func (colimaDirectObserver) ObserveDockerContainer(ctx context.Context, actionID, containerID string) (dockerContainerPostconditionObservation, error) {
+ snapshot, err := observeColimaContainer(ctx, containerID)
+ return dockerContainerPostconditionObservation{ObserverID: "task06-colima-direct", TrustDomain: "daemon:colima-direct", Method: "docker_context_colima_inspect", Snapshot: snapshot, ReceivedAt: time.Now().UTC()}, err
+}
+
+func observeColimaContainer(ctx context.Context, containerID string) (agentexec.DockerContainerLifecycleSnapshot, error) {
+ raw, err := exec.CommandContext(ctx, "docker", "--context", "colima", "inspect", "--format", `{{json .State}}`, containerID).CombinedOutput()
+ if err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("direct Colima inspect: %w", err)
+ }
+ var state struct {
+ Status string `json:"Status"`
+ Running bool `json:"Running"`
+ StartedAt string `json:"StartedAt"`
+ }
+ if err := json.Unmarshal(bytes.TrimSpace(raw), &state); err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, err
+ }
+ startedAt, err := time.Parse(time.RFC3339Nano, state.StartedAt)
+ if err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, err
+ }
+ restartRaw, err := exec.CommandContext(ctx, "docker", "--context", "colima", "inspect", "--format", `{{.RestartCount}}`, containerID).CombinedOutput()
+ if err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, err
+ }
+ restartCount, err := strconv.Atoi(strings.TrimSpace(string(restartRaw)))
+ if err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, err
+ }
+ return agentexec.DockerContainerLifecycleSnapshot{ContainerID: containerID, State: strings.ToLower(state.Status), Running: state.Running, StartedAt: startedAt.UTC(), RestartCount: restartCount, ObservedAt: time.Now().UTC()}, nil
+}
diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.go
index 3f47ff1c6d..d9359d93a4 100644
--- a/internal/hostagent/commands.go
+++ b/internal/hostagent/commands.go
@@ -107,6 +107,7 @@ type CommandClient struct {
commandPolicy *agentexec.CommandPolicy
packageUpdates *packageUpdateManager
storageCleanup *storageCleanupManager
+ dockerLifecycle dockerLifecycleManager
operationReceipts *operationreceipt.Store
operationReceiptErr error
operationReceiptCloseOnce sync.Once
@@ -145,6 +146,7 @@ func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *
commandPolicy: agentexec.DefaultPolicy(),
packageUpdates: cfg.packageUpdates,
storageCleanup: cfg.storageCleanup,
+ dockerLifecycle: newLocalDockerLifecycleManager(),
operationReceipts: receipts,
operationReceiptErr: receiptErr,
logger: logger,
@@ -167,23 +169,25 @@ func (c *CommandClient) stopChan() <-chan struct{} {
type messageType string
const (
- msgTypeAgentRegister messageType = "agent_register"
- msgTypeAgentPing messageType = "agent_ping"
- msgTypeCommandResult messageType = "command_result"
- msgTypeRegistered messageType = "registered"
- msgTypePong messageType = "pong"
- msgTypeExecuteCmd messageType = "execute_command"
- msgTypeReadFile messageType = "read_file"
- msgTypeHostStorageCleanup messageType = "host_storage_cleanup"
- msgTypeHostStorageCleanupResult messageType = "host_storage_cleanup_result"
- msgTypeHostUpdate messageType = "host_update"
- msgTypeHostUpdateResult messageType = "host_update_result"
- msgTypeOperationQuery messageType = "agent_operation_query"
- msgTypeOperationQueryResult messageType = "agent_operation_query_result"
- msgTypeDeployPreflight messageType = "deploy_preflight"
- msgTypeDeployInstall messageType = "deploy_install"
- msgTypeDeployCancel messageType = "deploy_cancel"
- msgTypeDeployProgress messageType = "deploy_progress"
+ msgTypeAgentRegister messageType = "agent_register"
+ msgTypeAgentPing messageType = "agent_ping"
+ msgTypeCommandResult messageType = "command_result"
+ msgTypeRegistered messageType = "registered"
+ msgTypePong messageType = "pong"
+ msgTypeExecuteCmd messageType = "execute_command"
+ msgTypeReadFile messageType = "read_file"
+ msgTypeHostStorageCleanup messageType = "host_storage_cleanup"
+ msgTypeHostStorageCleanupResult messageType = "host_storage_cleanup_result"
+ msgTypeHostUpdate messageType = "host_update"
+ msgTypeHostUpdateResult messageType = "host_update_result"
+ msgTypeDockerContainerLifecycle messageType = "docker_container_lifecycle"
+ msgTypeDockerContainerLifecycleResult messageType = "docker_container_lifecycle_result"
+ msgTypeOperationQuery messageType = "agent_operation_query"
+ msgTypeOperationQueryResult messageType = "agent_operation_query_result"
+ msgTypeDeployPreflight messageType = "deploy_preflight"
+ msgTypeDeployInstall messageType = "deploy_install"
+ msgTypeDeployCancel messageType = "deploy_cancel"
+ msgTypeDeployProgress messageType = "deploy_progress"
)
type wsMessage struct {
@@ -563,6 +567,14 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn
}
go c.handleHostStorageCleanup(ctx, conn, payload)
+ case msgTypeDockerContainerLifecycle:
+ payload, err := agentexec.DecodeDockerContainerLifecyclePayload(msg.Payload)
+ if err != nil {
+ c.logger.Error().Err(err).Msg("Failed to parse docker container lifecycle payload")
+ continue
+ }
+ go c.handleDockerContainerLifecycle(ctx, conn, payload)
+
case msgTypeOperationQuery:
query, err := operationreceipt.DecodeQuery(msg.Payload)
if err != nil {
@@ -711,6 +723,65 @@ func (c *CommandClient) handleHostStorageCleanup(ctx context.Context, conn *webs
c.sendHostStorageCleanupResult(conn, result)
}
+func (c *CommandClient) handleDockerContainerLifecycle(ctx context.Context, conn *websocket.Conn, payload agentexec.DockerContainerLifecyclePayload) {
+ identity := agentexec.DockerContainerLifecycleOperationIdentity(c.agentID, payload)
+ record, admitted, err := c.admitOperation(identity)
+ if err != nil {
+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Docker lifecycle durable admission refused")
+ return
+ }
+ if !admitted {
+ if record.State == operationreceipt.StateTerminal {
+ c.replayDockerContainerLifecycle(conn, record)
+ }
+ return
+ }
+ if _, err := c.operationReceipts.MarkStarted(identity); err != nil {
+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Docker lifecycle durable start refused")
+ return
+ }
+ timeout := time.Duration(payload.Timeout) * time.Second
+ if timeout <= 0 {
+ timeout = 2 * time.Minute
+ }
+ operationCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ result := agentexec.DockerContainerLifecycleResultPayload{
+ RequestID: payload.RequestID, ActionID: payload.ActionID, Operation: payload.Operation,
+ OperationVersion: payload.OperationVersion, RequestDigest: payload.RequestDigest, ContainerID: payload.ContainerID,
+ ExecutionPhase: agentexec.DockerContainerPhasePreflight,
+ }
+ if c.dockerLifecycle == nil {
+ result.Error = "typed container lifecycle service is unavailable"
+ } else {
+ result = c.dockerLifecycle.Apply(operationCtx, payload)
+ }
+ result.Error = sanitizeDockerLifecycleError(result.Error)
+ encoded, err := json.Marshal(result)
+ if err != nil {
+ return
+ }
+ if _, err := c.operationReceipts.Complete(identity, operationreceipt.TerminalEnvelope{Kind: agentexec.DockerContainerLifecycleReceiptKind, Version: agentexec.DockerContainerLifecycleReceiptVersion, Payload: encoded}); err != nil {
+ c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to persist docker lifecycle terminal receipt")
+ return
+ }
+ c.sendDockerContainerLifecycleResult(conn, result)
+}
+
+func (c *CommandClient) sendDockerContainerLifecycleResult(conn *websocket.Conn, result agentexec.DockerContainerLifecycleResultPayload) {
+ encoded, err := json.Marshal(result)
+ if err != nil {
+ return
+ }
+ msg := wsMessage{Type: msgTypeDockerContainerLifecycleResult, ID: result.RequestID, Timestamp: time.Now(), Payload: encoded}
+ c.connMu.Lock()
+ err = conn.WriteJSON(msg)
+ c.connMu.Unlock()
+ if err != nil {
+ c.logger.Error().Err(err).Str("request_id", result.RequestID).Msg("Failed to send docker lifecycle result")
+ }
+}
+
func (c *CommandClient) admitOperation(identity operationreceipt.Identity) (operationreceipt.Record, bool, error) {
if c.operationReceiptErr != nil {
return operationreceipt.Record{}, false, c.operationReceiptErr
@@ -764,6 +835,20 @@ func (c *CommandClient) replayHostStorageCleanup(conn *websocket.Conn, record op
}
}
+func (c *CommandClient) replayDockerContainerLifecycle(conn *websocket.Conn, record operationreceipt.Record) {
+ var result agentexec.DockerContainerLifecycleResultPayload
+ if err := json.Unmarshal(record.Result, &result); err == nil {
+ c.sendDockerContainerLifecycleResult(conn, result)
+ }
+}
+
+func sanitizeDockerLifecycleError(value string) string {
+ if strings.TrimSpace(value) == "" {
+ return ""
+ }
+ return "typed container lifecycle did not complete as requested"
+}
+
func sanitizeHostUpdateReceipt(result agentexec.HostUpdateResultPayload) agentexec.HostUpdateResultPayload {
result.Before.Packages, result.After.Packages = nil, nil
result.Before.Error, result.After.Error = "", ""
@@ -811,6 +896,16 @@ func hostOperationReceiptConfig() operationreceipt.Config {
}
return agentexec.ValidateHostStorageCleanupResultForRequest(req, result)
}},
+ agentexec.DockerContainerLifecycleReceiptKind: {agentexec.DockerContainerLifecycleReceiptVersion: func(identity operationreceipt.Identity, payload json.RawMessage) error {
+ result, err := agentexec.DecodeDockerContainerLifecycleResultPayload(payload)
+ if err != nil {
+ return err
+ }
+ if result.RequestID != identity.AttemptID || result.ActionID != identity.ActionID || result.Operation != identity.OperationKind || result.OperationVersion != identity.OperationVersion || result.RequestDigest != identity.RequestDigest {
+ return operationreceipt.ErrBindingConflict
+ }
+ return nil
+ }},
}}
}
diff --git a/internal/hostagent/docker_lifecycle.go b/internal/hostagent/docker_lifecycle.go
new file mode 100644
index 0000000000..0193f60bc3
--- /dev/null
+++ b/internal/hostagent/docker_lifecycle.go
@@ -0,0 +1,171 @@
+package hostagent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+)
+
+var dockerContextNamePattern = regexp.MustCompile(`^[a-zA-Z0-9._-]{1,128}$`)
+
+type dockerLifecycleManager interface {
+ Apply(context.Context, agentexec.DockerContainerLifecyclePayload) agentexec.DockerContainerLifecycleResultPayload
+}
+
+type dockerLifecycleCommandRunner func(context.Context, string, ...string) ([]byte, error)
+
+type localDockerLifecycleManager struct {
+ run dockerLifecycleCommandRunner
+ now func() time.Time
+}
+
+func newLocalDockerLifecycleManager() *localDockerLifecycleManager {
+ return &localDockerLifecycleManager{
+ run: func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return exec.CommandContext(ctx, name, args...).CombinedOutput()
+ },
+ now: time.Now,
+ }
+}
+
+func (m *localDockerLifecycleManager) Apply(ctx context.Context, req agentexec.DockerContainerLifecyclePayload) (result agentexec.DockerContainerLifecycleResultPayload) {
+ started := m.currentTime()
+ result = agentexec.DockerContainerLifecycleResultPayload{
+ RequestID: req.RequestID, ActionID: req.ActionID, Operation: req.Operation,
+ OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, ContainerID: req.ContainerID,
+ ExecutionPhase: agentexec.DockerContainerPhasePreflight,
+ }
+ defer func() { result.Duration = time.Since(started).Milliseconds() }()
+ if err := agentexec.ValidateDockerContainerLifecyclePayload(&req); err != nil {
+ result.Error = "typed container lifecycle preflight refused"
+ return result
+ }
+ before, err := m.inspect(ctx, req.Runtime, req.ContainerID)
+ result.Before = before
+ if err != nil {
+ result.Error = "container preflight inspect unavailable"
+ return result
+ }
+ if !dockerLifecycleBeforeMatches(req, before) {
+ result.Error = "container preflight state no longer matches the request"
+ return result
+ }
+
+ result.ExecutionPhase = agentexec.DockerContainerPhaseMutate
+ result.MutationStarted = true
+ verb := strings.TrimSuffix(req.Operation, "_container")
+ if _, err := m.command(ctx, req.Runtime, verb, req.ContainerID); err != nil {
+ result.Error = "container lifecycle mutation did not complete"
+ return result
+ }
+ result.MutationCompleted = true
+ result.ExecutionPhase = agentexec.DockerContainerPhaseVerify
+ after, err := m.inspect(ctx, req.Runtime, req.ContainerID)
+ result.After = after
+ if err != nil {
+ result.Error = "container postcondition inspect unavailable"
+ return result
+ }
+ result.ReadbackRan = true
+ if dockerLifecyclePostcondition(req, before, after) {
+ result.ExecutionPhase = agentexec.DockerContainerPhaseComplete
+ return result
+ }
+ result.Error = "container postcondition contradicted the requested state"
+ return result
+}
+
+func (m *localDockerLifecycleManager) command(ctx context.Context, runtime string, args ...string) ([]byte, error) {
+ if m == nil || m.run == nil {
+ return nil, fmt.Errorf("container runtime command runner unavailable")
+ }
+ if runtime != "docker" && runtime != "podman" {
+ return nil, fmt.Errorf("unsupported container runtime")
+ }
+ if runtime == "docker" {
+ if dockerContext := strings.TrimSpace(os.Getenv("DOCKER_CONTEXT")); dockerContext != "" {
+ if !dockerContextNamePattern.MatchString(dockerContext) {
+ return nil, fmt.Errorf("invalid Docker context name")
+ }
+ args = append([]string{"--context", dockerContext}, args...)
+ }
+ }
+ return m.run(ctx, runtime, args...)
+}
+
+func (m *localDockerLifecycleManager) inspect(ctx context.Context, runtime, containerID string) (agentexec.DockerContainerLifecycleSnapshot, error) {
+ const format = `{{json .State}}`
+ raw, err := m.command(ctx, runtime, "inspect", "--format", format, containerID)
+ if err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, err
+ }
+ var state struct {
+ Status string `json:"Status"`
+ Running bool `json:"Running"`
+ StartedAt string `json:"StartedAt"`
+ RestartCount int `json:"RestartCount"`
+ }
+ if err := json.Unmarshal([]byte(strings.TrimSpace(string(raw))), &state); err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("decode container state: %w", err)
+ }
+ startedAt := time.Time{}
+ if value := strings.TrimSpace(state.StartedAt); value != "" && !strings.HasPrefix(value, "0001-") {
+ startedAt, err = time.Parse(time.RFC3339Nano, value)
+ if err != nil {
+ return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("decode container start time: %w", err)
+ }
+ }
+ // Docker exposes RestartCount at the inspect root. Query it separately to
+ // keep the state envelope bounded and avoid persisting labels or config.
+ restartRaw, restartErr := m.command(ctx, runtime, "inspect", "--format", `{{.RestartCount}}`, containerID)
+ if restartErr == nil {
+ if count, parseErr := strconv.Atoi(strings.TrimSpace(string(restartRaw))); parseErr == nil && count >= 0 {
+ state.RestartCount = count
+ }
+ }
+ return agentexec.DockerContainerLifecycleSnapshot{
+ ContainerID: strings.ToLower(containerID), State: strings.ToLower(strings.TrimSpace(state.Status)), Running: state.Running,
+ StartedAt: startedAt.UTC(), RestartCount: state.RestartCount, ObservedAt: m.currentTime(),
+ }, nil
+}
+
+func (m *localDockerLifecycleManager) currentTime() time.Time {
+ if m != nil && m.now != nil {
+ return m.now().UTC()
+ }
+ return time.Now().UTC()
+}
+
+func dockerLifecycleBeforeMatches(req agentexec.DockerContainerLifecyclePayload, before agentexec.DockerContainerLifecycleSnapshot) bool {
+ if !strings.EqualFold(req.ContainerID, before.ContainerID) || !strings.EqualFold(req.ExpectedState, before.State) {
+ return false
+ }
+ if !req.ExpectedStartedAt.IsZero() && !req.ExpectedStartedAt.Equal(before.StartedAt) {
+ return false
+ }
+ return true
+}
+
+func dockerLifecyclePostcondition(req agentexec.DockerContainerLifecyclePayload, before, after agentexec.DockerContainerLifecycleSnapshot) bool {
+ if !strings.EqualFold(req.ContainerID, after.ContainerID) {
+ return false
+ }
+ switch req.Operation {
+ case agentexec.DockerContainerOperationStart:
+ return after.Running && after.State == "running"
+ case agentexec.DockerContainerOperationStop:
+ return !after.Running && after.State == "exited"
+ case agentexec.DockerContainerOperationRestart:
+ return after.Running && after.State == "running" && !after.StartedAt.IsZero() && after.StartedAt.After(before.StartedAt)
+ default:
+ return false
+ }
+}
diff --git a/internal/hostagent/docker_lifecycle_test.go b/internal/hostagent/docker_lifecycle_test.go
new file mode 100644
index 0000000000..cb37cc3a4d
--- /dev/null
+++ b/internal/hostagent/docker_lifecycle_test.go
@@ -0,0 +1,90 @@
+package hostagent
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+)
+
+const dockerLifecycleTestContainerID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+
+func TestDockerLifecycleManagerRestartPerformsOneMutationAndBoundedReadback(t *testing.T) {
+ t.Setenv("DOCKER_CONTEXT", "")
+ before := time.Now().UTC().Add(-time.Minute).Truncate(time.Nanosecond)
+ after := before.Add(time.Minute)
+ var calls [][]string
+ manager := &localDockerLifecycleManager{now: func() time.Time { return after }, run: func(_ context.Context, name string, args ...string) ([]byte, error) {
+ calls = append(calls, append([]string{name}, args...))
+ switch len(calls) {
+ case 1:
+ return []byte(fmt.Sprintf(`{"Status":"running","Running":true,"StartedAt":%q}`, before.Format(time.RFC3339Nano))), nil
+ case 2:
+ return []byte("0"), nil
+ case 3:
+ return []byte(dockerLifecycleTestContainerID), nil
+ case 4:
+ return []byte(fmt.Sprintf(`{"Status":"running","Running":true,"StartedAt":%q}`, after.Format(time.RFC3339Nano))), nil
+ case 5:
+ return []byte("0"), nil
+ default:
+ return nil, fmt.Errorf("unexpected command")
+ }
+ }}
+ req := dockerLifecycleTestRequest(t, before)
+ result := manager.Apply(context.Background(), req)
+ if !result.MutationStarted || !result.MutationCompleted || !result.ReadbackRan {
+ t.Fatalf("result facts = %#v", result)
+ }
+ mutations := 0
+ for _, call := range calls {
+ if len(call) > 1 && call[1] == "restart" {
+ mutations++
+ }
+ }
+ if mutations != 1 {
+ t.Fatalf("restart mutations = %d, calls=%#v", mutations, calls)
+ }
+}
+
+func TestDockerLifecycleManagerStaleBeforeStateIsTripleZero(t *testing.T) {
+ t.Setenv("DOCKER_CONTEXT", "")
+ before := time.Now().UTC().Add(-time.Minute)
+ mutations := 0
+ manager := &localDockerLifecycleManager{now: time.Now, run: func(_ context.Context, _ string, args ...string) ([]byte, error) {
+ if len(args) > 0 && args[0] == "restart" {
+ mutations++
+ }
+ if len(args) > 2 && strings.Contains(args[2], ".State") {
+ return []byte(fmt.Sprintf(`{"Status":"exited","Running":false,"StartedAt":%q}`, before.Format(time.RFC3339Nano))), nil
+ }
+ return []byte("0"), nil
+ }}
+ result := manager.Apply(context.Background(), dockerLifecycleTestRequest(t, before))
+ if result.MutationStarted || result.MutationCompleted || result.ReadbackRan || mutations != 0 {
+ t.Fatalf("stale preflight was not triple-zero: result=%#v mutations=%d", result, mutations)
+ }
+}
+
+func TestDockerLifecycleManagerFailedInspectIsTripleZero(t *testing.T) {
+ t.Setenv("DOCKER_CONTEXT", "")
+ manager := &localDockerLifecycleManager{now: time.Now, run: func(context.Context, string, ...string) ([]byte, error) {
+ return nil, fmt.Errorf("inspect unavailable")
+ }}
+ result := manager.Apply(context.Background(), dockerLifecycleTestRequest(t, time.Now().UTC().Add(-time.Minute)))
+ if result.MutationStarted || result.MutationCompleted || result.ReadbackRan {
+ t.Fatalf("failed inspect was not triple-zero: %#v", result)
+ }
+}
+
+func dockerLifecycleTestRequest(t *testing.T, startedAt time.Time) agentexec.DockerContainerLifecyclePayload {
+ t.Helper()
+ req := agentexec.DockerContainerLifecyclePayload{RequestID: "action.dispatch.1", ActionID: "action", Operation: agentexec.DockerContainerOperationRestart, Runtime: "docker", ContainerID: dockerLifecycleTestContainerID, ExpectedState: "running", ExpectedStartedAt: startedAt, Timeout: 10}
+ if err := agentexec.BindDockerContainerLifecyclePayload(&req); err != nil {
+ t.Fatal(err)
+ }
+ return req
+}
diff --git a/internal/hostagent/operation_receipt_websocket_integration_test.go b/internal/hostagent/operation_receipt_websocket_integration_test.go
index 4ddd49cd26..a6645f70c5 100644
--- a/internal/hostagent/operation_receipt_websocket_integration_test.go
+++ b/internal/hostagent/operation_receipt_websocket_integration_test.go
@@ -174,3 +174,58 @@ func TestRealServerAndUnifiedAgentWebSocketExecutesAPTThroughFakeTypedManagersAn
t.Fatalf("fake mutation catalog calls: refresh=%d upgrade=%d clean=%d", refreshCalls, upgradeCalls, cleanCalls)
}
}
+
+type countingDockerLifecycleManager struct {
+ mu sync.Mutex
+ calls int
+}
+
+func (m *countingDockerLifecycleManager) Apply(_ context.Context, req agentexec.DockerContainerLifecyclePayload) agentexec.DockerContainerLifecycleResultPayload {
+ m.mu.Lock()
+ m.calls++
+ m.mu.Unlock()
+ now := time.Now().UTC()
+ return agentexec.DockerContainerLifecycleResultPayload{
+ RequestID: req.RequestID, ActionID: req.ActionID, Operation: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, ContainerID: req.ContainerID,
+ ExecutionPhase: agentexec.DockerContainerPhaseComplete, MutationStarted: true, MutationCompleted: true, ReadbackRan: true,
+ Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, StartedAt: req.ExpectedStartedAt, ObservedAt: now.Add(-time.Second)},
+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, StartedAt: now, ObservedAt: now},
+ }
+}
+
+func TestRealServerAndUnifiedAgentWebSocketDockerDuplicateReplayMutatesOnce(t *testing.T) {
+ server := agentexec.NewServer(func(token, agent, host string) bool { return token == "token" })
+ httpServer := httptest.NewServer(http.HandlerFunc(server.HandleWebSocket))
+ defer httpServer.Close()
+ logger := zerolog.Nop()
+ client := NewCommandClient(Config{PulseURL: httpServer.URL, APIToken: "token", StateDir: t.TempDir(), Logger: &logger}, "agent-docker", "host", "linux", "6")
+ manager := &countingDockerLifecycleManager{}
+ client.dockerLifecycle = manager
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- client.Run(ctx) }()
+ defer func() { cancel(); _ = client.Close(); <-done }()
+ deadline := time.Now().Add(3 * time.Second)
+ for !server.IsAgentConnected("agent-docker") && time.Now().Before(deadline) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !server.IsAgentConnected("agent-docker") {
+ t.Fatal("real command client did not connect")
+ }
+ startedAt := time.Now().UTC().Add(-time.Minute)
+ req := agentexec.DockerContainerLifecyclePayload{RequestID: "docker.dispatch.1", ActionID: "docker", Operation: agentexec.DockerContainerOperationRestart, Runtime: "docker", ContainerID: dockerLifecycleTestContainerID, ExpectedState: "running", ExpectedStartedAt: startedAt, Timeout: 5}
+ if err := agentexec.BindDockerContainerLifecyclePayload(&req); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 2; i++ {
+ result, err := server.ExecuteDockerContainerLifecycle(context.Background(), "agent-docker", req)
+ if err != nil || result == nil || !result.MutationCompleted || !result.ReadbackRan {
+ t.Fatalf("replay %d result=%+v err=%v", i, result, err)
+ }
+ }
+ manager.mu.Lock()
+ defer manager.mu.Unlock()
+ if manager.calls != 1 {
+ t.Fatalf("typed docker mutation calls = %d, want one", manager.calls)
+ }
+}
diff --git a/scripts/intelligence_lab/README.md b/scripts/intelligence_lab/README.md
new file mode 100644
index 0000000000..71d411f13c
--- /dev/null
+++ b/scripts/intelligence_lab/README.md
@@ -0,0 +1,21 @@
+# Docker restart intelligence lab
+
+This ignored-artifact harness exercises one uniquely labelled disposable Docker
+container, volume, and network in the existing Colima VM. It refuses any
+implicit or non-Colima Docker context, uses the existing `alpine:3.20` fixture,
+and removes only resources with the exact run label.
+
+Run only after explicit local-lab authorization:
+
+```sh
+python3 scripts/intelligence_lab/docker_restart_colima.py --run-id task06-20260712-090000
+```
+
+Evidence is written beneath `tmp/intelligence-lab/<run-id>/`, which is ignored.
+Only the explicit redacted JSON, screenshot/trace, report, and checksum
+basenames are retained there. Transient Pulse and Unified Agent databases live
+under `tmp/intelligence-lab-scratch/<run-id>/` and are deleted before the
+artifact allowlist and checksum manifest are accepted.
+The second cleanup must be a no-op and the preexisting resource inventory must
+be unchanged. Container restart has no product rollback; fixture deletion is
+lab compensation only.
diff --git a/scripts/intelligence_lab/artifact_redaction.py b/scripts/intelligence_lab/artifact_redaction.py
new file mode 100644
index 0000000000..e4eb14597d
--- /dev/null
+++ b/scripts/intelligence_lab/artifact_redaction.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+"""Bounded redaction for ignored local intelligence-lab artifacts."""
+
+from __future__ import annotations
+
+import re
+import hashlib
+from pathlib import Path
+import stat
+
+MAX_ARTIFACT_TEXT = 64 * 1024
+
+ALLOWED_ARTIFACT_BASENAMES = frozenset({
+ "SHA256SUMS",
+ "actions-history-current-build.png",
+ "browser-trace.zip",
+ "canonical-journey.json",
+ "environment.json",
+ "run-report.json",
+})
+
+_PATTERNS = (
+ re.compile(r"(?i)(authorization\s*:\s*bearer\s+)[^\s\"']+"),
+ re.compile(r"(?i)((?:api[_-]?token|password|secret)\s*[=:]\s*)[^\s\"']+"),
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S),
+)
+
+
+def redact_text(value: str) -> str:
+ value = value[:MAX_ARTIFACT_TEXT]
+ for pattern in _PATTERNS:
+ value = pattern.sub(r"\1[REDACTED]" if pattern.groups else "[REDACTED PRIVATE KEY]", value)
+ return value
+
+
+def contains_forbidden_secret_shape(value: str) -> bool:
+ lowered = value.lower()
+ return any(marker in lowered for marker in ("authorization: bearer ", "-----begin private key-----"))
+
+
+def assert_allowed_artifact_tree(root: Path) -> list[Path]:
+ root = root.resolve()
+ files: list[Path] = []
+ for path in sorted(root.rglob("*")):
+ relative = path.relative_to(root)
+ if path.is_symlink():
+ raise ValueError(f"artifact symlink is forbidden: {relative}")
+ mode = path.stat().st_mode
+ if stat.S_ISSOCK(mode):
+ raise ValueError(f"artifact socket is forbidden: {relative}")
+ if path.is_dir():
+ raise ValueError(f"artifact subdirectory is forbidden: {relative}")
+ lowered = path.name.lower()
+ forbidden_name = (
+ lowered.endswith((".db", ".sqlite", ".sqlite3", ".wal", ".shm", ".log", ".env", ".sock"))
+ or ".db-" in lowered
+ or any(marker in lowered for marker in ("token", "cookie", "authorization", "auth-header", "secret", "credential"))
+ )
+ if forbidden_name:
+ raise ValueError(f"forbidden artifact basename: {relative}")
+ if path.name not in ALLOWED_ARTIFACT_BASENAMES:
+ raise ValueError(f"unknown artifact outside allowlist: {relative}")
+ files.append(path)
+ return files
+
+
+def write_checksums(root: Path) -> None:
+ files = [path for path in assert_allowed_artifact_tree(root) if path.name != "SHA256SUMS"]
+ lines = [f"{hashlib.sha256(path.read_bytes()).hexdigest()} {path.name}" for path in files]
+ manifest = root.resolve() / "SHA256SUMS"
+ manifest.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ manifest.chmod(0o600)
+ verify_checksums(root)
+
+
+def verify_checksums(root: Path) -> None:
+ files = assert_allowed_artifact_tree(root)
+ manifest = root.resolve() / "SHA256SUMS"
+ if manifest not in files:
+ raise ValueError("SHA256SUMS is required")
+ expected: dict[str, str] = {}
+ for line in manifest.read_text(encoding="utf-8").splitlines():
+ digest, separator, name = line.partition(" ")
+ if not separator or not re.fullmatch(r"[a-f0-9]{64}", digest) or name not in ALLOWED_ARTIFACT_BASENAMES or name == "SHA256SUMS":
+ raise ValueError("invalid checksum manifest entry")
+ expected[name] = digest
+ actual = {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in files if path.name != "SHA256SUMS"}
+ if expected != actual:
+ raise ValueError("checksum manifest does not match allowed artifact tree")
diff --git a/scripts/intelligence_lab/docker_restart_colima.py b/scripts/intelligence_lab/docker_restart_colima.py
new file mode 100644
index 0000000000..e54a7ce41d
--- /dev/null
+++ b/scripts/intelligence_lab/docker_restart_colima.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python3
+"""Run the released, label-scoped Task06 Docker restart journey in Colima."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import time
+import shutil
+
+from artifact_redaction import assert_allowed_artifact_tree, contains_forbidden_secret_shape, redact_text, write_checksums
+
+RUN_ID = re.compile(r"^[a-z0-9][a-z0-9-]{5,47}$")
+LABEL_KEY = "com.pulse.intelligence-lab.run"
+
+
+class LabError(RuntimeError):
+ pass
+
+
+def command(args: list[str], *, env: dict[str, str] | None = None, check: bool = True) -> subprocess.CompletedProcess[str]:
+ result = subprocess.run(args, text=True, capture_output=True, env=env, timeout=600)
+ if check and result.returncode:
+ raise LabError(f"command failed ({result.returncode}): {' '.join(args[:4])}\n{redact_text(result.stderr)}")
+ return result
+
+
+def docker(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
+ return command(["docker", "--context", "colima", *args], check=check)
+
+
+def inventory() -> dict[str, list[str]]:
+ return {
+ "containers": sorted(filter(None, docker("ps", "-aq", "--no-trunc").stdout.splitlines())),
+ "volumes": sorted(filter(None, docker("volume", "ls", "-q").stdout.splitlines())),
+ "networks": sorted(filter(None, docker("network", "ls", "-q", "--no-trunc").stdout.splitlines())),
+ }
+
+
+def labelled_ids(kind: str, run_id: str) -> list[str]:
+ label = f"{LABEL_KEY}={run_id}"
+ if kind == "container":
+ output = docker("ps", "-aq", "--filter", f"label={label}").stdout
+ elif kind == "volume":
+ output = docker("volume", "ls", "-q", "--filter", f"label={label}").stdout
+ elif kind == "network":
+ output = docker("network", "ls", "-q", "--filter", f"label={label}").stdout
+ else:
+ raise ValueError(kind)
+ return sorted(filter(None, output.splitlines()))
+
+
+def cleanup(run_id: str) -> dict[str, list[str]]:
+ removed = {"containers": [], "volumes": [], "networks": []}
+ for container_id in labelled_ids("container", run_id):
+ docker("rm", "-f", container_id)
+ removed["containers"].append(container_id)
+ for volume in labelled_ids("volume", run_id):
+ docker("volume", "rm", volume)
+ removed["volumes"].append(volume)
+ for network in labelled_ids("network", run_id):
+ docker("network", "rm", network)
+ removed["networks"].append(network)
+ return removed
+
+
+def write_json(path: Path, value: object) -> None:
+ payload = json.dumps(value, indent=2, sort_keys=True) + "\n"
+ if contains_forbidden_secret_shape(payload):
+ raise LabError(f"artifact failed secret-shape scan: {path.name}")
+ path.write_text(redact_text(payload), encoding="utf-8")
+ path.chmod(0o600)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--run-id", required=True)
+ parser.add_argument("--repo", default=str(Path(__file__).resolve().parents[2]))
+ args = parser.parse_args()
+ if not RUN_ID.fullmatch(args.run_id):
+ raise LabError("run id must be 6-48 lowercase letters, digits, or hyphens")
+ repo = Path(args.repo).resolve()
+ artifact_dir = repo / "tmp" / "intelligence-lab" / args.run_id
+ scratch_dir = repo / "tmp" / "intelligence-lab-scratch" / args.run_id
+ artifact_dir.mkdir(parents=True, exist_ok=False)
+ scratch_dir.mkdir(parents=True, exist_ok=False)
+ label = f"{LABEL_KEY}={args.run_id}"
+ name = f"pulse-task06-{args.run_id}"
+ pre = inventory()
+ report: dict[str, object] = {"run_id": args.run_id, "label": label, "preexisting_inventory": pre, "cleanup": {}}
+ failed: BaseException | None = None
+ try:
+ if docker("context", "show").stdout.strip() != "colima":
+ raise LabError("explicit Docker context is not colima")
+ versions = {
+ "git_sha": command(["git", "-C", str(repo), "rev-parse", "HEAD"]).stdout.strip(),
+ "docker_client": docker("version", "--format", "{{.Client.Version}}").stdout.strip(),
+ "docker_server": docker("version", "--format", "{{.Server.Version}}").stdout.strip(),
+ "docker_context": docker("context", "show").stdout.strip(),
+ "colima": command(["colima", "version"]).stdout.strip(),
+ }
+ write_json(artifact_dir / "environment.json", versions)
+ docker("network", "create", "--label", label, name)
+ docker("volume", "create", "--label", label, name)
+ fixture_script = 'n=$(cat /state/count 2>/dev/null || echo 0); n=$((n+1)); echo "$n" >/state/count; if [ "$n" -le 4 ]; then exit 1; fi; sleep 3600'
+ container_id = docker(
+ "run", "-d", "--name", name, "--label", label, "--network", name,
+ "--mount", f"source={name},target=/state", "--restart", "on-failure:5",
+ "alpine:3.20", "/bin/sh", "-c", fixture_script,
+ ).stdout.strip()
+ deadline = time.time() + 30
+ restart_count = 0
+ state = ""
+ while time.time() < deadline:
+ observed = docker("inspect", "--format", "{{.State.Status}} {{.RestartCount}}", container_id).stdout.split()
+ if len(observed) == 2:
+ state, restart_count = observed[0], int(observed[1])
+ if state == "running" and restart_count >= 4:
+ break
+ time.sleep(0.25)
+ if state != "running" or restart_count < 4:
+ raise LabError(f"fixture did not reach bounded fresh restart-loop state: state={state} restarts={restart_count}")
+ report["fixture"] = {"container_id": container_id, "state": state, "restart_count": restart_count}
+ env = os.environ.copy()
+ env.update({
+ "DOCKER_CONTEXT": "colima",
+ "PULSE_INTELLIGENCE_LAB_RUN_ID": args.run_id,
+ "PULSE_INTELLIGENCE_LAB_CONTAINER_ID": container_id,
+ "PULSE_INTELLIGENCE_LAB_ARTIFACT_DIR": str(artifact_dir),
+ "PULSE_INTELLIGENCE_LAB_SCRATCH_DIR": str(scratch_dir),
+ })
+ proofs = [
+ ["go", "test", "./internal/agentexec", "./internal/hostagent", "./internal/api", "-run", "DockerContainer|DockerLifecycle|DockerRestartColimaRealLab", "-count=1"],
+ ["go", "test", "./internal/actionlifecycle", "./internal/agentexec", "./internal/hostagent", "./internal/api", "-run", "ConcurrentDuplicateExecuteAtClaimBoundary|RestartRecoveryReconcilesReceiptPendingWithoutResend|RestartRecoveryNotFoundRemainsReceiptPendingWithoutResend|PolicyBarrierRevocations|EmergencyStopBlocksHumanAndPolicyAdmission|NeverAutoRemediate|WrongAgentLateDuplicateAndInterruptedAreInert|DockerDuplicateReplay|StaleBeforeStateIsTripleZero|FailedInspectIsTripleZero|StaleReadbackIsInconclusive", "-count=1"],
+ [sys.executable, "scripts/intelligence_lab/test_artifact_redaction.py"],
+ ]
+ proof_results = []
+ for proof in proofs:
+ result = command(proof, env=env)
+ proof_results.append({"command": proof, "exit_code": result.returncode, "stdout": redact_text(result.stdout), "stderr": redact_text(result.stderr)})
+ report["proofs"] = proof_results
+ except BaseException as exc:
+ failed = exc
+ report["failure"] = redact_text(str(exc))
+ finally:
+ first = cleanup(args.run_id)
+ second = cleanup(args.run_id)
+ post = inventory()
+ report["cleanup"] = {"first": first, "second": second, "post_inventory": post, "preexisting_unchanged": post == pre}
+ shutil.rmtree(scratch_dir, ignore_errors=True)
+ if scratch_dir.exists():
+ failed = failed or LabError("run-scoped scratch state was not deleted")
+ write_json(artifact_dir / "run-report.json", report)
+ assert_allowed_artifact_tree(artifact_dir)
+ write_checksums(artifact_dir)
+ if second != {"containers": [], "volumes": [], "networks": []}:
+ failed = failed or LabError("second label-scoped cleanup was not a no-op")
+ if post != pre:
+ failed = failed or LabError("preexisting Colima inventory changed")
+ if failed:
+ raise failed
+ print(artifact_dir)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/intelligence_lab/test_artifact_redaction.py b/scripts/intelligence_lab/test_artifact_redaction.py
new file mode 100644
index 0000000000..5f8740d8a3
--- /dev/null
+++ b/scripts/intelligence_lab/test_artifact_redaction.py
@@ -0,0 +1,53 @@
+import unittest
+from pathlib import Path
+import socket
+import tempfile
+
+from artifact_redaction import MAX_ARTIFACT_TEXT, assert_allowed_artifact_tree, contains_forbidden_secret_shape, redact_text, verify_checksums, write_checksums
+
+
+class ArtifactRedactionTest(unittest.TestCase):
+ def test_redacts_bearer_and_named_secret(self) -> None:
+ redacted = redact_text("Authorization: Bearer sensitive\napi_token=private")
+ self.assertNotIn("sensitive", redacted)
+ self.assertNotIn("private", redacted)
+
+ def test_bounds_output(self) -> None:
+ self.assertEqual(len(redact_text("x" * (MAX_ARTIFACT_TEXT + 20))), MAX_ARTIFACT_TEXT)
+
+ def test_rejects_unredacted_secret_shape(self) -> None:
+ self.assertTrue(contains_forbidden_secret_shape("Authorization: Bearer value"))
+
+ def test_strict_allowlist_rejects_runtime_state_and_unknown_files(self) -> None:
+ for name in ("state.db", "state.db-wal", "state.sqlite", "state.sqlite3", "state.wal", "state.shm", "runtime.log", ".env", "token.txt", "cookie.json", "unknown.txt"):
+ with self.subTest(name=name), tempfile.TemporaryDirectory() as directory:
+ (Path(directory) / name).write_text("x", encoding="utf-8")
+ with self.assertRaises(ValueError):
+ assert_allowed_artifact_tree(Path(directory))
+
+ def test_strict_allowlist_rejects_socket_and_subdirectory(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ sock = socket.socket(socket.AF_UNIX)
+ try:
+ sock.bind(str(root / "runtime.sock"))
+ with self.assertRaises(ValueError):
+ assert_allowed_artifact_tree(root)
+ finally:
+ sock.close()
+ with tempfile.TemporaryDirectory() as directory:
+ (Path(directory) / "nested").mkdir()
+ with self.assertRaises(ValueError):
+ assert_allowed_artifact_tree(Path(directory))
+
+ def test_allowed_manifest_round_trip(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / "environment.json").write_text("{}\n", encoding="utf-8")
+ (root / "run-report.json").write_text("{}\n", encoding="utf-8")
+ write_checksums(root)
+ verify_checksums(root)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index 4cb8c2241a..b1aeac9fcc 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -553,6 +553,7 @@ class CanonicalCompletionGuardTest(unittest.TestCase):
"internal/hostagent/commands_deploy_test.go",
"internal/hostagent/commands_host_update_test.go",
"internal/hostagent/commands_storage_cleanup_test.go",
+ "internal/hostagent/docker_lifecycle_test.go",
"internal/hostagent/package_updates_test.go",
"internal/hostagent/send_report_test.go",
"internal/hostagent/storage_cleanup_test.go",
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index b568ab0129..bd7f0d0b0b 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -4417,6 +4417,7 @@ class SubsystemLookupTest(unittest.TestCase):
"internal/hostagent/commands_deploy_test.go",
"internal/hostagent/commands_host_update_test.go",
"internal/hostagent/commands_storage_cleanup_test.go",
+ "internal/hostagent/docker_lifecycle_test.go",
"internal/hostagent/package_updates_test.go",
"internal/hostagent/send_report_test.go",
"internal/hostagent/storage_cleanup_test.go",
diff --git a/tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts b/tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts
new file mode 100644
index 0000000000..052dfce033
--- /dev/null
+++ b/tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts
@@ -0,0 +1,92 @@
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, test } from "@playwright/test";
+import { ensureAuthenticated } from "./helpers";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+type LabArtifact = {
+ run_id: string;
+ proposal: { proposal_id: string; finding_id: string; investigation_id: string; resource_id: string; capability_name: string; params: Record<string, unknown>; evidence_ids: string[] };
+ investigation: { id: string; finding_id: string };
+ action: {
+ id: string; createdAt: string; updatedAt: string; state: string; decisionRevision: number;
+ request: { requestId: string; resourceId: string; capabilityName: string; params?: Record<string, unknown> | null; reason: string; requestedBy: string };
+ plan: { actionId: string; requestId: string; rollbackAvailable: boolean; [key: string]: unknown };
+ origin: { surface: string; findingId: string; investigationId: string; proposalId: string };
+ result: { success: boolean; actionResultV2: { version: number; execution: { status: string; summary?: string }; verification: { status: string; evidenceClass: string; summary?: string; evidence: Array<{ id: string; observerId: string; observerKind: string; observerTrustDomain: string; executorTrustDomain: string; method: string; subjectId: string; observedAt: string; receivedAt: string; digest: string }> }; compensation: { support: string; status: string; summary?: string } } };
+ verificationOutcome: { status: string };
+ };
+ attempt: { id: string; actionId: string; state: string; createdAt: string; updatedAt: string; dispatchCount: number; operationKind: string; operationVersion: number; requestDigest: string; agentId: string };
+ receipt: { attemptId: string; actionId: string; transportRequestId: string; receivedAt: string };
+ finding: { id: string; outcome: string; resolved_at: string };
+ notification: { kind: string; outcome: string; action_type: string; action_id: string; category: string; severity: string };
+ before: { container_id: string; state: string; running: boolean; started_at: string; observed_at: string };
+ after: { container_id: string; state: string; running: boolean; started_at: string; observed_at: string };
+ evidence: { id: string; observerTrustDomain: string; executorTrustDomain: string; digest: string };
+};
+
+const loadArtifact = (): { artifact: LabArtifact; artifactDir: string } => {
+ const configured = String(process.env.PULSE_INTELLIGENCE_LAB_ARTIFACT || "").trim();
+ if (!configured) throw new Error("PULSE_INTELLIGENCE_LAB_ARTIFACT is required");
+ const artifactPath = path.resolve(configured);
+ const repoRoot = path.resolve(__dirname, "..", "..", "..");
+ const allowedRoot = path.join(repoRoot, "tmp", "intelligence-lab") + path.sep;
+ if (!artifactPath.startsWith(allowedRoot) || path.basename(artifactPath) !== "canonical-journey.json") throw new Error("artifact path must select an ignored canonical-journey.json");
+ const artifact = JSON.parse(fs.readFileSync(artifactPath, "utf8")) as LabArtifact;
+ return { artifact, artifactDir: path.dirname(artifactPath) };
+};
+
+const assertExactArtifactBindings = (artifact: LabArtifact): void => {
+ const { proposal, investigation, action, attempt, receipt, finding, evidence } = artifact;
+ if (Object.keys(proposal.params).length !== 0 || Object.keys(action.request.params ?? {}).length !== 0) throw new Error("real proposal and action must carry zero parameter authority");
+ if (proposal.proposal_id !== action.origin.proposalId || proposal.finding_id !== finding.id || proposal.finding_id !== investigation.finding_id || proposal.investigation_id !== investigation.id || proposal.investigation_id !== action.origin.investigationId || proposal.finding_id !== action.origin.findingId) throw new Error("proposal/finding/investigation correlation mismatch");
+ if (proposal.resource_id !== action.request.resourceId || proposal.capability_name !== action.request.capabilityName) throw new Error("proposal/action target mismatch");
+ if (action.id !== action.plan.actionId || action.id !== attempt.actionId || action.id !== receipt.actionId || attempt.id !== receipt.attemptId || attempt.id !== receipt.transportRequestId) throw new Error("action/attempt/receipt identity mismatch");
+ if (!attempt.requestDigest.startsWith("sha256:") || attempt.dispatchCount !== 1 || attempt.state !== "receipt_recorded") throw new Error("durable attempt binding is incomplete or duplicated");
+ const canonicalEvidence = action.result.actionResultV2.verification.evidence;
+ if (canonicalEvidence.length !== 1 || canonicalEvidence[0].id !== evidence.id || canonicalEvidence[0].digest !== evidence.digest || canonicalEvidence[0].observerTrustDomain === canonicalEvidence[0].executorTrustDomain) throw new Error("independent evidence identity mismatch");
+ if (finding.outcome !== "fix_verified" || !finding.resolved_at) throw new Error("finding did not retain a resolved verified outcome");
+ if (artifact.notification.kind !== "fix_completed" || artifact.notification.outcome !== "confirmed") throw new Error("notification outcome does not match canonical verification");
+ if (artifact.before.container_id !== artifact.after.container_id || new Date(artifact.after.started_at) <= new Date(artifact.before.started_at)) throw new Error("daemon before/after restart facts are not monotonic");
+};
+
+test("real Colima restart artifact renders one independently verified durable action", async ({ page }) => {
+ const { artifact, artifactDir } = loadArtifact();
+ assertExactArtifactBindings(artifact);
+ await page.setViewportSize({ width: 1440, height: 1600 });
+ await ensureAuthenticated(page);
+ await page.route("**/api/actions?*", async (route) => {
+ const view = new URL(route.request().url()).searchParams.get("view");
+ const actions = view === "settled" ? [artifact.action] : [];
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ view, actions, count: actions.length }) });
+ });
+ await page.route(`**/api/actions/${encodeURIComponent(artifact.action.id)}`, (route) => route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ audit: artifact.action, events: [], attempt: artifact.attempt, receipt: artifact.receipt }),
+ }));
+
+ await page.goto("/actions", { waitUntil: "domcontentloaded" });
+ await page.getByRole("tab", { name: "History" }).click();
+ const actionButton = page.getByRole("button", { name: new RegExp(`Restart.*${artifact.action.request.resourceId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`) });
+ await expect(actionButton).toHaveCount(1);
+ await actionButton.click();
+ const dialog = page.getByRole("dialog", { name: "Restart" });
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByTestId("action-execution-truth")).toContainText("Succeeded");
+ await expect(dialog.getByTestId("action-verification-truth")).toContainText("Confirmed by independent observer");
+ await expect(dialog.getByTestId("action-verification-truth")).toContainText("Source: Independent observer");
+ await expect(dialog.getByTestId("action-verification-truth")).toContainText("Direct daemon observation");
+ await expect(dialog.getByTestId("action-delivery-truth")).toHaveCount(1);
+ await expect(dialog.getByText("One agent receipt is recorded for this action.")).toBeVisible();
+ await expect(dialog.getByTestId("action-compensation-truth")).toContainText("Not Available");
+ await expect(dialog.getByTestId("action-compensation-truth")).toContainText("Support: Unavailable");
+ await expect(dialog.getByTestId("action-compensation-truth")).toContainText("Container restart is non-rollbackable");
+ await expect(dialog.getByText("Operator-selected parameters", { exact: true })).toHaveCount(0);
+ await expect(dialog.getByText("Legacy check passed (source unclassified)")).toHaveCount(0);
+ await expect(dialog.getByTestId("action-verification-truth")).toHaveCount(1);
+ await dialog.getByTestId("action-execution-truth").scrollIntoViewIfNeeded();
+ await page.screenshot({ path: path.join(artifactDir, "actions-history-current-build.png"), fullPage: true });
+});