Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Restore one-click Docker container updates through the typed action plane
rcourtman3c778e2b2674
diff --git a/cmd/pulse-agent/main.go b/cmd/pulse-agent/main.goindex b59c1ceb92..8eeea9ad1e 100644--- a/cmd/pulse-agent/main.go+++ b/cmd/pulse-agent/main.go@@ -16,6 +16,7 @@ import ("reflect""strconv""strings"+ "sync""sync/atomic""syscall""time"@@ -23,6 +24,7 @@ import ("github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/promauto""github.com/prometheus/client_golang/prometheus/promhttp"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/agentupdate""github.com/rcourtman/pulse-go-rewrite/internal/dockeragent""github.com/rcourtman/pulse-go-rewrite/internal/hostagent"@@ -354,6 +356,10 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {return nil})+ // The host module starts before the Docker module (which may only come up+ // after daemon retries), so the typed container-update bridge late-binds.+ dockerUpdaterBridge := &lateBoundDockerUpdater{}+// 8. Start Host Agent (if enabled)if cfg.EnableHost {hostCfg := hostagent.Config{@@ -382,6 +388,8 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {AppliedConfig: cfg.AppliedConfig,UpdateStatus: updater.Snapshot,ModuleStatus: runtimeStatus.moduleStatuses,++ DockerContainerUpdater: dockerUpdaterBridge,}agent, err := newHostAgent(hostCfg)@@ -427,6 +435,9 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {}dockerAgent, err = newDockerAgent(dockerCfg)+ if err == nil {+ dockerUpdaterBridge.set(dockerAgent)+ }if err != nil {runtimeStatus.setState("docker", moduleStateRetrying, err)// Docker isn't available yet - start retry loop in background@@ -440,6 +451,7 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {agent := initDockerWithRetry(ctx, dockerCfg, &logger)if agent != nil {dockerAgent = agent+ dockerUpdaterBridge.set(agent)runtimeStatus.setState("docker", moduleStateRunning, nil)logger.Info().Msg("Docker / Podman module started (after retry)")return agent.Run(ctx)@@ -1269,6 +1281,35 @@ func initModuleWithRetry[T any](ctx context.Context, logger *zerolog.Logger, com// initDockerWithRetry attempts to initialize the Docker / Podman collection module with exponential backoff.// It returns the module when Docker / Podman becomes available, or nil if the context is cancelled.+// lateBoundDockerUpdater satisfies hostagent.DockerContainerUpdater while the+// Docker module comes up (or never does). The host command client holds this+// bridge for the process lifetime; set installs the module's implementation.+type lateBoundDockerUpdater struct {+ mu sync.RWMutex+ updater hostagent.DockerContainerUpdater+}++func (b *lateBoundDockerUpdater) set(candidate any) {+ updater, ok := candidate.(hostagent.DockerContainerUpdater)+ if !ok {+ fmt.Fprintf(os.Stderr, "docker update bridge: %T does not implement the typed container updater\n", candidate)+ return+ }+ b.mu.Lock()+ b.updater = updater+ b.mu.Unlock()+}++func (b *lateBoundDockerUpdater) TypedContainerUpdate(ctx context.Context, runtime, containerID, expectedImageDigest string, progress func(string)) (agentexec.DockerContainerUpdateOutcome, error) {+ b.mu.RLock()+ updater := b.updater+ b.mu.RUnlock()+ if updater == nil {+ return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("docker module is not running on this agent")+ }+ return updater.TypedContainerUpdate(ctx, runtime, containerID, expectedImageDigest, progress)+}+func initDockerWithRetry(ctx context.Context, cfg dockeragent.Config, logger *zerolog.Logger) RunnableCloser {return initModuleWithRetry(ctx, logger, "docker_agent", "Docker", "Docker not available, will retry", func() (RunnableCloser, error) {return newDockerAgent(cfg)diff --git a/cmd/pulse-agent/main_test.go b/cmd/pulse-agent/main_test.goindex 3f62c1b6fa..46730ef449 100644--- a/cmd/pulse-agent/main_test.go+++ b/cmd/pulse-agent/main_test.go@@ -17,6 +17,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/agentupdate""github.com/rcourtman/pulse-go-rewrite/internal/dockeragent""github.com/rcourtman/pulse-go-rewrite/internal/hostagent"@@ -2172,3 +2173,40 @@ func TestAgentIDFilePersistence(t *testing.T) {}})}++type stubTypedContainerUpdater struct {+ calls int+}++func (s *stubTypedContainerUpdater) TypedContainerUpdate(context.Context, string, string, string, func(string)) (agentexec.DockerContainerUpdateOutcome, error) {+ s.calls+++ return agentexec.DockerContainerUpdateOutcome{Success: true}, nil+}++func TestLateBoundDockerUpdaterBridgesModuleWhenItComesUp(t *testing.T) {+ bridge := &lateBoundDockerUpdater{}++ if _, err := bridge.TypedContainerUpdate(context.Background(), "docker", strings.Repeat("a", 12), "sha256:"+strings.Repeat("1", 64), nil); err == nil {+ t.Fatal("bridge without a docker module accepted an update")+ }++ bridge.set(struct{}{}) // non-implementing candidates must not install+ if _, err := bridge.TypedContainerUpdate(context.Background(), "docker", strings.Repeat("a", 12), "sha256:"+strings.Repeat("1", 64), nil); err == nil {+ t.Fatal("bridge accepted an update after a non-implementing candidate was offered")+ }++ stub := &stubTypedContainerUpdater{}+ bridge.set(stub)+ if _, err := bridge.TypedContainerUpdate(context.Background(), "docker", strings.Repeat("a", 12), "sha256:"+strings.Repeat("1", 64), nil); err != nil {+ t.Fatalf("bridge with an installed module refused: %v", err)+ }+ if stub.calls != 1 {+ t.Fatalf("expected one delegated call, got %d", stub.calls)+ }+}++func TestDockerAgentImplementsTypedContainerUpdater(t *testing.T) {+ // The bridge installs by structural assertion; if the Docker module's+ // method signature drifts, updates silently refuse at runtime. Pin it.+ var _ hostagent.DockerContainerUpdater = (*dockeragent.Agent)(nil)+}diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 5047cf6e25..00efee35fe 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -455,16 +455,36 @@ the API-owned action audit records `executing` before dispatch and theterminal execution result afterward. Dry-run-only plans remain planning evidenceonly; lifecycle surfaces must not present them as executable, dispatch themthrough agent-local command paths, or bypass the API fail-closed execution gate.-Docker / Podman container start, stop, and restart affordances follow that same-boundary: lifecycle UI may consume unified-resource capabilities for enabled or-disabled presentation, but execution must stay inside the API-owned action-executor wired from `internal/api/router.go` and must not shell out, SSH, or call-Docker / Podman from lifecycle-local code. That API-owned executor may resolve-the command WebSocket by Docker source ID or canonical Docker host name and may-mark its vetted container lifecycle dispatch as a trusted agent command after-the API action has entered execution; lifecycle surfaces still consume only the-resource payload, action readiness, and action-audit result rather than issuing-or approving command-agent grants themselves.+Docker / Podman container start, stop, restart, and image-update affordances+follow that same boundary: lifecycle UI may consume unified-resource+capabilities for enabled or disabled presentation, but execution must stay+inside the API-owned action executor wired from `internal/api/router.go` and+must not shell out, SSH, or call Docker / Podman from lifecycle-local code.+That API-owned executor may resolve the command WebSocket by Docker source ID+or canonical Docker host name and may mark its vetted container lifecycle+dispatch as a trusted agent command after the API action has entered+execution; lifecycle surfaces still consume only the resource payload, action+readiness, and action-audit result rather than issuing or approving+command-agent grants themselves.++Docker / Podman container image updates are a fourth typed operation on that+same closed channel, not an extension of the raw command path and not a+revival of the retired queued `update_container` transport.+`docker_container_update` has its own strict codec in+`internal/agentexec/docker_update_codec.go`: the payload carries only the+immutable container id, the runtime, and the exact image reference the plan+was bound to (part of the request digest; no command text, flags, or+user-controlled names), and the result reports phase, replacement-container+identity, image digests, backup identity, and rollback attempt and outcome as+facts, never canonical action truth. The unified agent admits the operation+through the same durable operation-receipt store and bridges execution to the+Docker module's own pull/backup/recreate/verify/rollback implementation via+`internal/hostagent/docker_update.go`; a missing Docker module, a runtime+mismatch, or image drift since planning refuses before any mutation. The+module attests the first mutating step (the backup rename), so failures before+it report an unmutated tree, and restore attempts with their outcome ride the+result so the server-side executor reports declared compensation truth instead+of guessing.Host OS package updates follow a stricter adjacent boundary. The Unified Agentmay report a bounded, read-only APT upgrade simulation through`pkg/agents/host/report.go`, but installation authority is available only viadiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex dcad68c585..e650c305fb 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -5828,8 +5828,14 @@ bind mechanically discovered API, job, and transport candidates to one registrydisposition. Transport lifecycle entries must name non-transport lifecycleauthority and committed authority before delivery. Task 07 owns durabledelivery/reconnect and Task 10 owns terminal truth/compensation; incomplete-Docker, Kubernetes/native-provider, delivery, and rollback paths remain-`retired_denied`, not parallel executors.+Kubernetes/native-provider, delivery, and rollback paths remain+`retired_denied`, not parallel executors. Docker container image updates left+the incomplete set: `resource.docker.container-update` and+`transport.agent.docker-container-update` are lifecycle-dispositioned over the+typed `docker_container_update` operation with durable receipts and declared+backup/rollback compensation, while the model-originated+`assistant.docker.update` route and the legacy queued update transports stay+`retired_denied`.Enterprise command-remediation records are readable historical imports only.Production code contains no command or rollback execution algorithm; exporteddiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 7bc7bccc6c..602093df98 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -7496,8 +7496,18 @@ exact: it covers `/api/actions/`, `/api/agents/docker/`, `/api/updates/`,`/api/ai/remediation/`, and `/api/ai/run-command`; general settings and metadataCRUD are not claimed as customer-infrastructure mutation enumeration.-Raw command/file write/arbitrary pod exec, direct Docker update/control, and-enterprise command remediation are retired compatibility surfaces. Enterprise+Raw command/file write/arbitrary pod exec, the legacy queued Docker+update/control transports, and enterprise command remediation are retired+compatibility surfaces. Container image updates re-entered the plane as+`resource.docker.container-update` and+`transport.agent.docker-container-update`: lifecycle-dispositioned, planned+against an `update` capability that containers advertise only while an image+update is detected, and executed solely through `dockerContainerActionExecutor`+over the typed `docker_container_update` agentexec operation with durable+receipts and declared backup/rollback compensation truth. The legacy+`POST /api/agents/docker/containers/update` and `/update-all` HTTP surfaces+remain `retired_denied` and answer 410 with copy that points at the action+plane. Enterprise`remediation.json` remains readable history, but approve, execute, and rollbackreturn `command_remediation_retired`/`ErrLegacyRemediationRetired` before anyinjected executor. Task 07 owns durable delivery/reconnect, Task 10 owns truthdiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex fe6945353c..a8b99c2a3d 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -484,6 +484,13 @@ Raw command, file-write, arbitrary pod-exec, and legacy remediation authorityare retired before handler or transport execution. Extension aliases cannotshadow retired names, and transport delivery must name committed lifecycleauthority rather than accepting model-supplied command or rollback text.+Container image updates re-entered the plane as a closed typed operation:+the `docker_container_update` payload carries only an immutable container id,+runtime, and the plan-observed image digest (never a pull reference or+command text), the unified agent binds it through the same durable+operation-receipt admission as the other typed operations, and the process+bridge in `cmd/pulse-agent/main.go` late-binds the Docker module so a missing+module refuses before any mutation.Unified Agent Pulse transports share one fail-closed TLS policy across host,Docker/Podman, Kubernetes, remote configuration, commands, and self-update.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 04bd1482a9..7d716dcbbd 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -1771,8 +1771,13 @@ must not treat starterInfrastructure rollback is a declared lifecycle property, not executable modelor legacy remediation text. Task 10 owns compensation/truth representation;-until that contract is complete, affected Docker, Kubernetes, and native-provider mutations remain fail-closed denied.+until that contract is complete, affected Kubernetes and native provider+mutations remain fail-closed denied. Docker container image updates left that+denied set: the update executor in `internal/api/` reports declared+compensation (`backup_rename_restore`) with the agent-attested backup+identity, rollback attempt, and rollback outcome carried in the typed result,+so a failed update surfaces whether the original container was restored+instead of guessing.Storage and recovery consumers inherit create-once action identity, monotonicterminal state, and exactly-one executor admission from the shared lifecycle.diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 8226f8b99b..bd6a8f4091 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -648,7 +648,12 @@ cannot create a browser mutation.governed resource contract: `resourceFromDockerContainer` may advertise`start`, `stop`, and `restart` only for fresh, supported, agent-backedDocker/Podman reports whose daemon posture does not block mutating- commands. The API action executor must consume those capabilities through+ commands. An `update` capability rides the same gate with two extra+ preconditions: the report must carry a detected image update+ (`updateStatus.updateAvailable`) and a current image digest, because the+ plan binds the typed update dispatch to that digest and a container whose+ digest cannot be stated cannot be safely updated. The API action executor+ must consume those capabilities through`/api/actions/*` and the agent command server; platform rows or drawersmust not wire direct shell, SSH, provider, or runtime calls around thiscapability contract.diff --git a/internal/agentexec/apt_codec.go b/internal/agentexec/apt_codec.goindex e16479c905..144d421caa 100644--- a/internal/agentexec/apt_codec.go+++ b/internal/agentexec/apt_codec.go@@ -163,6 +163,21 @@ func ValidateOperationQueryResultForIdentity(result operationreceipt.QueryResultreturn fmt.Errorf("docker container lifecycle readback has invalid terminal chronology")}return nil+ case DockerContainerOperationUpdate:+ if result.Record.ResultKind != DockerContainerUpdateReceiptKind || result.Record.ResultVersion != DockerContainerUpdateReceiptVersion {+ return fmt.Errorf("docker container update query result envelope mismatch")+ }+ payload, err := DecodeDockerContainerUpdateResultPayload(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 update readback has invalid terminal chronology")+ }+ return nildefault:return fmt.Errorf("unsupported operation query kind %q", identity.OperationKind)}diff --git a/internal/agentexec/docker_lifecycle_contract_test.go b/internal/agentexec/docker_lifecycle_contract_test.goindex ba3efd8d2f..91eb79fa0d 100644--- a/internal/agentexec/docker_lifecycle_contract_test.go+++ b/internal/agentexec/docker_lifecycle_contract_test.go@@ -6,6 +6,7 @@ import ("reflect""strings""testing"+ "time""github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt")@@ -72,3 +73,134 @@ func jsonContains(payload []byte, value string) bool {}return false}++func validDockerUpdatePayload(t *testing.T) DockerContainerUpdatePayload {+ t.Helper()+ payload := DockerContainerUpdatePayload{+ RequestID: "attempt-1",+ ActionID: "action-1",+ Runtime: "docker",+ ContainerID: strings.Repeat("a", 12),+ ExpectedImageDigest: "sha256:" + strings.Repeat("9", 64),+ Timeout: 600,+ }+ if err := BindDockerContainerUpdatePayload(&payload); err != nil {+ t.Fatal(err)+ }+ return payload+}++func validDockerUpdateResult(t *testing.T, req DockerContainerUpdatePayload) DockerContainerUpdateResultPayload {+ t.Helper()+ observed := time.Date(2026, 7, 14, 12, 0, 0, 0, time.UTC)+ return DockerContainerUpdateResultPayload{+ RequestID: req.RequestID, ActionID: req.ActionID, Operation: req.Operation,+ OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, ContainerID: req.ContainerID,+ ExecutionPhase: DockerContainerPhaseComplete, MutationStarted: true, MutationCompleted: true, ReadbackRan: true,+ NewContainerID: strings.Repeat("b", 12), ContainerName: "app",+ OldImageDigest: "sha256:" + strings.Repeat("1", 64), NewImageDigest: "sha256:" + strings.Repeat("2", 64),+ BackupCreated: true, BackupContainer: "app_pulse_backup_20260714_120000",+ After: DockerContainerLifecycleSnapshot{ContainerID: strings.Repeat("b", 12), State: "running", Running: true, ObservedAt: observed},+ }+}++func TestDockerContainerUpdatePayloadBindAndValidate(t *testing.T) {+ payload := validDockerUpdatePayload(t)+ if payload.Operation != DockerContainerOperationUpdate || payload.OperationVersion != DockerContainerUpdateOperationVersion {+ t.Fatalf("bind did not stamp operation identity: %+v", payload)+ }+ if err := ValidateDockerContainerUpdatePayload(&payload); err != nil {+ t.Fatal(err)+ }++ tampered := payload+ tampered.ExpectedImageDigest = "sha256:" + strings.Repeat("8", 64)+ if err := ValidateDockerContainerUpdatePayload(&tampered); err == nil {+ t.Fatal("digest mismatch after expected-image tamper was accepted")+ }++ badDigest := payload+ badDigest.ExpectedImageDigest = "busybox:latest"+ if err := BindDockerContainerUpdatePayload(&badDigest); err != nil {+ t.Fatal(err)+ }+ if err := ValidateDockerContainerUpdatePayload(&badDigest); err == nil {+ t.Fatal("non-digest expected image was accepted")+ }+}++func TestDockerContainerUpdateResultContract(t *testing.T) {+ req := validDockerUpdatePayload(t)+ result := validDockerUpdateResult(t, req)+ if err := ValidateDockerContainerUpdateResultForRequest(req, result); err != nil {+ t.Fatal(err)+ }++ completeWithoutReplacement := result+ completeWithoutReplacement.NewContainerID = ""+ if err := ValidateDockerContainerUpdateResultPayload(&completeWithoutReplacement); err == nil {+ t.Fatal("complete phase without replacement container was accepted")+ }++ rollbackWithoutAttempt := result+ rollbackWithoutAttempt.ExecutionPhase = DockerContainerPhaseMutate+ rollbackWithoutAttempt.MutationCompleted = false+ rollbackWithoutAttempt.Error = "create failed"+ rollbackWithoutAttempt.RolledBack = true+ rollbackWithoutAttempt.RollbackAttempted = false+ if err := ValidateDockerContainerUpdateResultPayload(&rollbackWithoutAttempt); err == nil {+ t.Fatal("rollback success without attempt was accepted")+ }++ wrongContainer := result+ wrongContainer.ContainerID = strings.Repeat("c", 12)+ if err := ValidateDockerContainerUpdateResultForRequest(req, wrongContainer); err == nil {+ t.Fatal("result for a different container was accepted")+ }+}++func TestDockerContainerUpdateWireCarriesFactsNotActionTruth(t *testing.T) {+ typeOf := reflect.TypeOf(DockerContainerUpdateResultPayload{})+ for _, forbidden := range []string{"Success", "Verification", "Evidence", "EvidenceClass", "Compensation", "Independent"} {+ if _, ok := typeOf.FieldByName(forbidden); ok {+ t.Fatalf("Docker update wire result declares canonical action truth field %q", forbidden)+ }+ }+ payload, err := json.Marshal(DockerContainerUpdateResultPayload{})+ if err != nil {+ t.Fatal(err)+ }+ for _, forbidden := range []string{`"success"`, `"verification"`, `"evidence"`, `"evidence_class"`, `"compensation"`, `"independent"`} {+ if jsonContains(payload, forbidden) {+ t.Fatalf("Docker update wire result exposes canonical action truth key %s: %s", forbidden, payload)+ }+ }+}++func TestDockerContainerUpdateOperationQueryEnvelope(t *testing.T) {+ req := validDockerUpdatePayload(t)+ result := validDockerUpdateResult(t, req)+ encoded, err := json.Marshal(result)+ if err != nil {+ t.Fatal(err)+ }+ identity := DockerContainerUpdateOperationIdentity("agent-1", req)+ terminalAt := result.After.ObservedAt.Add(time.Second)+ query := operationreceipt.QueryResult{+ Version: operationreceipt.ProtocolVersion,+ Status: operationreceipt.QueryFoundTerminal,+ Record: &operationreceipt.Record{+ Identity: identity, State: operationreceipt.StateTerminal,+ AcceptedAt: result.After.ObservedAt.Add(-time.Minute), StartedAt: result.After.ObservedAt.Add(-30 * time.Second), TerminalAt: terminalAt,+ ResultKind: DockerContainerUpdateReceiptKind, ResultVersion: DockerContainerUpdateReceiptVersion, Result: encoded,+ },+ }+ if err := ValidateOperationQueryResultForIdentity(query, identity, terminalAt.Add(time.Minute)); err != nil {+ t.Fatal(err)+ }++ query.Record.ResultKind = DockerContainerLifecycleReceiptKind+ if err := ValidateOperationQueryResultForIdentity(query, identity, terminalAt.Add(time.Minute)); err == nil {+ t.Fatal("lifecycle envelope was accepted for an update identity")+ }+}diff --git a/internal/agentexec/docker_update_codec.go b/internal/agentexec/docker_update_codec.gonew file mode 100644index 0000000000..fd9c685dcd--- /dev/null+++ b/internal/agentexec/docker_update_codec.go@@ -0,0 +1,196 @@+package agentexec++import (+ "fmt"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"+)++const (+ DockerContainerUpdateOperationVersion = 1+ DockerContainerUpdateReceiptKind = "pulse.docker_container_update_result"+ DockerContainerUpdateReceiptVersion = 1++ maxDockerContainerNameLength = 256+ maxDockerImageDigestLength = 256+ // Image pulls dominate update time; the module's own overall budget is 15+ // minutes, so the transport bound leaves headroom without being unbounded.+ maxDockerContainerUpdateTimeoutSeconds = 1800+ defaultDockerContainerUpdateTimeoutSeconds = 900+)++func DecodeDockerContainerUpdatePayload(data []byte) (DockerContainerUpdatePayload, error) {+ var payload DockerContainerUpdatePayload+ if err := decodeStrictDockerLifecycle(data, &payload); err != nil {+ return DockerContainerUpdatePayload{}, err+ }+ if err := ValidateDockerContainerUpdatePayload(&payload); err != nil {+ return DockerContainerUpdatePayload{}, err+ }+ return payload, nil+}++func DecodeDockerContainerUpdateResultPayload(data []byte) (DockerContainerUpdateResultPayload, error) {+ var payload DockerContainerUpdateResultPayload+ if err := decodeStrictDockerLifecycle(data, &payload); err != nil {+ return DockerContainerUpdateResultPayload{}, err+ }+ if err := ValidateDockerContainerUpdateResultPayload(&payload); err != nil {+ return DockerContainerUpdateResultPayload{}, err+ }+ return payload, nil+}++func BindDockerContainerUpdatePayload(payload *DockerContainerUpdatePayload) error {+ if payload == nil {+ return fmt.Errorf("docker container update payload is required")+ }+ payload.Operation = DockerContainerOperationUpdate+ payload.OperationVersion = DockerContainerUpdateOperationVersion+ digest, err := dockerContainerUpdateRequestDigest(*payload)+ if err != nil {+ return err+ }+ payload.RequestDigest = digest+ return nil+}++func dockerContainerUpdateRequestDigest(payload DockerContainerUpdatePayload) (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"`+ ExpectedImageDigest string `json:"expected_image_digest"`+ }{+ 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.ExpectedImageDigest)),+ })+}++func ValidateDockerContainerUpdatePayload(payload *DockerContainerUpdatePayload) error {+ if payload == nil {+ return fmt.Errorf("docker container update 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.ExpectedImageDigest = strings.ToLower(strings.TrimSpace(payload.ExpectedImageDigest))+ if payload.RequestID == "" || len(payload.RequestID) > maxRequestIDLength || payload.ActionID == "" || len(payload.ActionID) > maxRequestIDLength {+ return fmt.Errorf("invalid docker update request or action id")+ }+ if payload.Operation != DockerContainerOperationUpdate {+ return fmt.Errorf("unsupported docker container update operation %q", payload.Operation)+ }+ if payload.OperationVersion != DockerContainerUpdateOperationVersion {+ return fmt.Errorf("unsupported docker container update 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 !hostUpdateInventoryHashPattern.MatchString(payload.ExpectedImageDigest) {+ return fmt.Errorf("invalid docker update expected image digest")+ }+ expectedDigest, err := dockerContainerUpdateRequestDigest(*payload)+ if err != nil {+ return err+ }+ if payload.RequestDigest != expectedDigest {+ return fmt.Errorf("docker container update request digest mismatch")+ }+ if payload.Timeout < 0 || payload.Timeout > maxDockerContainerUpdateTimeoutSeconds {+ return fmt.Errorf("docker container update timeout must be between 0 and %d seconds", maxDockerContainerUpdateTimeoutSeconds)+ }+ if payload.Timeout == 0 {+ payload.Timeout = defaultDockerContainerUpdateTimeoutSeconds+ }+ return nil+}++func ValidateDockerContainerUpdateResultPayload(result *DockerContainerUpdateResultPayload) error {+ if result == nil {+ return fmt.Errorf("docker container update 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.NewContainerID = strings.ToLower(strings.TrimSpace(result.NewContainerID))+ result.ContainerName = strings.TrimSpace(result.ContainerName)+ result.OldImageDigest = strings.TrimSpace(result.OldImageDigest)+ result.NewImageDigest = strings.TrimSpace(result.NewImageDigest)+ result.BackupContainer = strings.TrimSpace(result.BackupContainer)+ 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 update result identity")+ }+ if result.Operation != DockerContainerOperationUpdate {+ return fmt.Errorf("unsupported docker update result operation %q", result.Operation)+ }+ if result.OperationVersion != DockerContainerUpdateOperationVersion || !dockerContainerIDPattern.MatchString(result.ContainerID) || !hostUpdateInventoryHashPattern.MatchString(result.RequestDigest) {+ return fmt.Errorf("invalid docker update result binding")+ }+ if result.ExecutionPhase != DockerContainerPhasePreflight && result.ExecutionPhase != DockerContainerPhaseMutate && result.ExecutionPhase != DockerContainerPhaseVerify && result.ExecutionPhase != DockerContainerPhaseComplete {+ return fmt.Errorf("unsupported docker update execution phase %q", result.ExecutionPhase)+ }+ if result.NewContainerID != "" && !dockerContainerIDPattern.MatchString(result.NewContainerID) {+ return fmt.Errorf("docker update result has invalid replacement container id")+ }+ if len(result.Error) > 1024 || len(result.ContainerName) > maxDockerContainerNameLength || len(result.BackupContainer) > maxDockerContainerNameLength {+ return fmt.Errorf("docker update result exceeds bounded contract")+ }+ if len(result.OldImageDigest) > maxDockerImageDigestLength || len(result.NewImageDigest) > maxDockerImageDigestLength {+ return fmt.Errorf("docker update result digest exceeds bounded contract")+ }+ if result.MutationCompleted && !result.MutationStarted {+ return fmt.Errorf("completed docker update mutation requires mutation start")+ }+ if result.RolledBack && !result.RollbackAttempted {+ return fmt.Errorf("docker update rollback success requires a rollback attempt")+ }+ if result.RollbackAttempted && !result.MutationStarted {+ return fmt.Errorf("docker update rollback requires mutation start")+ }+ if result.ReadbackRan && result.After.ObservedAt.IsZero() {+ return fmt.Errorf("docker update readback requires an observation")+ }+ if result.ExecutionPhase == DockerContainerPhaseComplete {+ if result.Error != "" || !result.MutationCompleted || result.NewContainerID == "" {+ return fmt.Errorf("complete docker update requires a replacement container and no error")+ }+ }+ return nil+}++func DockerContainerUpdateOperationIdentity(agentID string, payload DockerContainerUpdatePayload) 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 ValidateDockerContainerUpdateResultForRequest(req DockerContainerUpdatePayload, result DockerContainerUpdateResultPayload) error {+ if err := ValidateDockerContainerUpdatePayload(&req); err != nil {+ return err+ }+ if err := ValidateDockerContainerUpdateResultPayload(&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 {+ return fmt.Errorf("docker update result identity mismatch")+ }+ if result.ContainerID != req.ContainerID {+ return fmt.Errorf("docker update result container mismatch")+ }+ if result.After.ContainerID != "" && result.NewContainerID != "" && !strings.EqualFold(result.After.ContainerID, result.NewContainerID) {+ return fmt.Errorf("docker update after-state container mismatch")+ }+ return nil+}diff --git a/internal/agentexec/server.go b/internal/agentexec/server.goindex 3e78a70b52..a236ce4af4 100644--- a/internal/agentexec/server.go+++ b/internal/agentexec/server.go@@ -67,6 +67,7 @@ type Server struct {pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup responsependingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update responsependingDockerContainerLifecycles map[string]chan DockerContainerLifecycleResultPayload+ pendingDockerContainerUpdates map[string]chan DockerContainerUpdateResultPayloadpendingHostOperations map[string]pendingHostOperation // scoped request key -> exact typed APT operation/query identitypendingOperationQueries map[string]pendingOperationQuerydeploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber@@ -147,6 +148,7 @@ func NewServer(validateToken func(token string, agentID string, hostname string)pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),pendingDockerContainerLifecycles: make(map[string]chan DockerContainerLifecycleResultPayload),+ pendingDockerContainerUpdates: make(map[string]chan DockerContainerUpdateResultPayload),pendingHostOperations: make(map[string]pendingHostOperation),pendingOperationQueries: make(map[string]pendingOperationQuery),deploySubs: make(map[string]chan DeployProgressPayload),@@ -229,6 +231,15 @@ func (s *Server) matchesPendingDockerOperation(agentID string, result DockerContreturn ok && expected.identity == actual && expected.subjectID == strings.ToLower(strings.TrimSpace(result.ContainerID))}+func (s *Server) matchesPendingDockerUpdateOperation(agentID string, result DockerContainerUpdateResultPayload) 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)@@ -985,6 +996,27 @@ func (s *Server) readLoop(ac *agentConn) {}}+ case MsgTypeDockerContainerUpdateResult:+ result, decodeErr := DecodeDockerContainerUpdateResultPayload(msg.Payload)+ if decodeErr != nil {+ log.Warn().Err(decodeErr).Str("agent_id", ac.agent.AgentID).Msg("Dropping invalid docker container update result")+ continue+ }+ if !s.matchesPendingDockerUpdateOperation(ac.agent.AgentID, result) {+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Dropping uncorrelated docker update result")+ continue+ }+ s.mu.RLock()+ ch, ok := s.pendingDockerContainerUpdates[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 update result channel full, dropping")+ }+ }+case MsgTypeOperationQueryResult:result, decodeErr := operationreceipt.DecodeQueryResult(msg.Payload)if decodeErr != nil {@@ -1508,6 +1540,25 @@ func (s *Server) ExecuteDockerContainerLifecycle(ctx context.Context, agentID stif err := ValidateDockerContainerLifecyclePayload(&req); err != nil {return nil, err}+ identity := DockerContainerLifecycleOperationIdentity(agentID, req)+ return dispatchTypedDockerContainerOperation(ctx, s, agentID, req.RequestID, req.Timeout, identity, req.ContainerID,+ MsgTypeDockerContainerLifecycle, req, s.pendingDockerContainerLifecycles, "docker container lifecycle",+ func(result DockerContainerLifecycleResultPayload) error {+ return ValidateDockerContainerLifecycleResultForRequest(req, result)+ })+}++// dispatchTypedDockerContainerOperation owns the shared skeleton for closed+// typed container dispatches: durable-receipt capability check, pending+// operation claim, single-flight request registration, send, and the bounded+// wait for the validated result.+func dispatchTypedDockerContainerOperation[Res any](+ ctx context.Context, s *Server, agentID, requestID string, timeoutSeconds int,+ identity operationreceipt.Identity, containerID string,+ msgType MessageType, payload any,+ pending map[string]chan Res, label string,+ validate func(Res) error,+) (*Res, error) {s.mu.RLock()ac, ok := s.agents[agentID]s.mu.RUnlock()@@ -1518,56 +1569,83 @@ func (s *Server) ExecuteDockerContainerLifecycle(ctx context.Context, agentID streturn 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)+ respCh := make(chan Res, 1)+ reqKey := pendingRequestKey(agentID, requestID)+ hostOperationKey, err := s.claimPendingDockerOperation(identity, containerID)if err != nil {return nil, err}defer s.releasePendingHostOperation(hostOperationKey)s.mu.Lock()- if _, exists := s.pendingDockerContainerLifecycles[reqKey]; exists {+ if _, exists := pending[reqKey]; exists {s.mu.Unlock()- return nil, fmt.Errorf("docker container lifecycle request %q is already pending", req.RequestID)+ return nil, fmt.Errorf("%s request %q is already pending", label, requestID)}- s.pendingDockerContainerLifecycles[reqKey] = respCh+ pending[reqKey] = respChs.mu.Unlock()defer func() {s.mu.Lock()- delete(s.pendingDockerContainerLifecycles, reqKey)+ delete(pending, reqKey)s.mu.Unlock()}()- msg, err := NewMessage(MsgTypeDockerContainerLifecycle, req.RequestID, req)+ msg, err := NewMessage(msgType, requestID, payload)if err != nil {- return nil, fmt.Errorf("failed to encode docker container lifecycle request: %w", err)+ return nil, fmt.Errorf("failed to encode %s request: %w", label, 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)+ return nil, fmt.Errorf("failed to send %s request: %w", label, err)}- timer := time.NewTimer(time.Duration(req.Timeout) * time.Second)+ timer := time.NewTimer(time.Duration(timeoutSeconds) * 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)+ if err := validate(result); err != nil {+ return nil, fmt.Errorf("%s result validation failed: %w", label, err)}return &result, nilcase <-timer.C:- return nil, fmt.Errorf("docker container lifecycle timed out after %s", time.Duration(req.Timeout)*time.Second)+ return nil, fmt.Errorf("%s timed out after %s", label, time.Duration(timeoutSeconds)*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)+ return nil, fmt.Errorf("agent %s disconnected before %s receipt", agentID, label)case <-s.shutdown:return nil, errServerShuttingDown}}+// ExecuteDockerContainerUpdate dispatches one closed typed container image+// update. The Unified Agent owns pull, backup, recreate, verification, and+// rollback inside this single dispatch and reports the compensation outcome.+func (s *Server) ExecuteDockerContainerUpdate(ctx context.Context, agentID string, req DockerContainerUpdatePayload) (*DockerContainerUpdateResultPayload, 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 := BindDockerContainerUpdatePayload(&req); err != nil {+ return nil, err+ }+ if err := ValidateDockerContainerUpdatePayload(&req); err != nil {+ return nil, err+ }+ identity := DockerContainerUpdateOperationIdentity(agentID, req)+ return dispatchTypedDockerContainerOperation(ctx, s, agentID, req.RequestID, req.Timeout, identity, req.ContainerID,+ MsgTypeDockerContainerUpdate, req, s.pendingDockerContainerUpdates, "docker container update",+ func(result DockerContainerUpdateResultPayload) error {+ return ValidateDockerContainerUpdateResultForRequest(req, result)+ })+}+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.goindex b3736a2060..ebb00108a9 100644--- a/internal/agentexec/types.go+++ b/internal/agentexec/types.go@@ -18,6 +18,7 @@ const (MsgTypeHostStorageCleanupResult MessageType = "host_storage_cleanup_result"MsgTypeHostUpdateResult MessageType = "host_update_result"MsgTypeDockerContainerLifecycleResult MessageType = "docker_container_lifecycle_result"+ MsgTypeDockerContainerUpdateResult MessageType = "docker_container_update_result"MsgTypeOperationQueryResult MessageType = "agent_operation_query_result"// Server -> Agent messages@@ -28,6 +29,7 @@ const (MsgTypeReadFile MessageType = "read_file"MsgTypeHostUpdate MessageType = "host_update"MsgTypeDockerContainerLifecycle MessageType = "docker_container_lifecycle"+ MsgTypeDockerContainerUpdate MessageType = "docker_container_update"MsgTypeOperationQuery MessageType = "agent_operation_query"MsgTypeDeployPreflight MessageType = "deploy_preflight"MsgTypeDeployInstall MessageType = "deploy_install"@@ -162,6 +164,7 @@ const (DockerContainerOperationStart = "start_container"DockerContainerOperationStop = "stop_container"DockerContainerOperationRestart = "restart_container"+ DockerContainerOperationUpdate = "update_container")// DockerContainerLifecyclePayload is a closed container lifecycle operation.@@ -213,6 +216,69 @@ const (DockerContainerPhaseComplete = "complete")+// DockerContainerUpdatePayload is the closed, typed container image update+// operation. It carries an immutable container ID and the exact image digest+// the plan observed; the agent refuses when the container no longer runs that+// digest, then pulls the container's own configured image reference and+// recreates it from its inspected configuration. It never carries command+// text, flags, a pull reference, or a user-controlled container name.+type DockerContainerUpdatePayload 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"`+ ExpectedImageDigest string `json:"expected_image_digest"`+ Timeout int `json:"timeout,omitempty"`+}++// DockerContainerUpdateResultPayload reports an update outcome. ContainerID+// is the container the request targeted; a successful update recreates it, so+// NewContainerID carries the replacement identity and the compensation fields+// say whether a backup existed and whether rollback was applied on failure.+type DockerContainerUpdateResultPayload 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"`+ NewContainerID string `json:"new_container_id,omitempty"`+ ContainerName string `json:"container_name,omitempty"`+ OldImageDigest string `json:"old_image_digest,omitempty"`+ NewImageDigest string `json:"new_image_digest,omitempty"`+ BackupCreated bool `json:"backup_created"`+ BackupContainer string `json:"backup_container,omitempty"`+ RollbackAttempted bool `json:"rollback_attempted"`+ RolledBack bool `json:"rolled_back"`+ After DockerContainerLifecycleSnapshot `json:"after"`+ Error string `json:"error,omitempty"`+ Duration int64 `json:"duration_ms"`+}++// DockerContainerUpdateOutcome is the neutral bridge between the Docker+// module's update implementation and the typed command channel, so the host+// command client does not import the Docker module directly.+type DockerContainerUpdateOutcome struct {+ Success bool+ ContainerName string+ OldContainerID string+ NewContainerID string+ OldImageDigest string+ NewImageDigest string+ BackupCreated bool+ BackupContainer string+ RollbackAttempted bool+ RolledBack bool+ Error string+}+// 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 wholediff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 49e1f952a0..8f88f630f1 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -20998,3 +20998,40 @@ func TestContract_BackgroundReportingFailsClosedWithoutCommercialEntitlement(t *t.Fatal("background reporting accepted a missing tenant license service")}}++func TestContract_RetiredDockerUpdateEndpointsAnswer410WithActionableCopy(t *testing.T) {+ handlers := &DockerAgentHandlers{}++ update := httptest.NewRecorder()+ handlers.HandleContainerUpdate(update, httptest.NewRequest(http.MethodPost, "/api/agents/docker/containers/update", strings.NewReader(`{"agentId":"a","containerId":"c"}`)))+ if update.Code != http.StatusGone {+ t.Fatalf("legacy container update status = %d, want 410", update.Code)+ }+ if body := update.Body.String(); !strings.Contains(body, "/api/actions") || strings.Contains(body, "typed lifecycle delivery") {+ t.Fatalf("legacy container update copy must point at the action plane without internal jargon: %s", body)+ }++ updateAll := httptest.NewRecorder()+ handlers.HandleUpdateAll(updateAll, httptest.NewRequest(http.MethodPost, "/api/agents/docker/runtimes/agent-1/update-all", nil))+ if updateAll.Code != http.StatusGone {+ t.Fatalf("legacy update-all status = %d, want 410", updateAll.Code)+ }+ if body := updateAll.Body.String(); !strings.Contains(body, "/api/actions") {+ t.Fatalf("legacy update-all copy must point at the action plane: %s", body)+ }+}++func TestContract_DockerContainerUpdateRidesTheLifecycleExecutor(t *testing.T) {+ executor := dockerContainerActionExecutor{}+ names := executor.ActionHandlerNames()+ want := []string{dockerContainerLifecycleHandler, dockerContainerUpdateHandler}+ if !reflect.DeepEqual(names, want) {+ t.Fatalf("docker executor handler names = %v, want %v", names, want)+ }+ if handler := dockerContainerOperationHandler("update"); handler != dockerContainerUpdateHandler {+ t.Fatalf("update operation resolves handler %q, want %q", handler, dockerContainerUpdateHandler)+ }+ if handler := dockerContainerOperationHandler("restart"); handler != dockerContainerLifecycleHandler {+ t.Fatalf("restart operation resolves handler %q, want %q", handler, dockerContainerLifecycleHandler)+ }+}diff --git a/internal/api/docker_agents.go b/internal/api/docker_agents.goindex f007264fd4..655f1c1f52 100644--- a/internal/api/docker_agents.go+++ b/internal/api/docker_agents.go@@ -532,7 +532,7 @@ func (h *DockerAgentHandlers) HandleContainerUpdate(w http.ResponseWriter, r *htreturn}- writeErrorResponse(w, http.StatusGone, "docker_update_retired", "Docker container updates are unavailable until typed lifecycle delivery and compensation are implemented.", nil)+ writeErrorResponse(w, http.StatusGone, "docker_update_retired", "This endpoint was retired: container updates now run as audited actions through /api/actions. Refresh the Pulse UI to use the new update flow.", nil)}// HandleUpdateAll triggers an update for all containers with updates available on a Docker / Podman host.@@ -549,7 +549,7 @@ func (h *DockerAgentHandlers) HandleUpdateAll(w http.ResponseWriter, r *http.Reqreturn}- writeErrorResponse(w, http.StatusGone, "docker_update_all_retired", "Bulk Docker updates are unavailable until typed lifecycle delivery and compensation are implemented.", nil)+ writeErrorResponse(w, http.StatusGone, "docker_update_all_retired", "This endpoint was retired: container updates now run as audited actions through /api/actions, one action per container. Refresh the Pulse UI to use the new update flow.", nil)}// HandleCheckUpdates triggers an immediate update check for all containers on a Docker / Podman host.diff --git a/internal/api/docker_container_action_executor.go b/internal/api/docker_container_action_executor.goindex 0eb922684b..8d2a5c7ec8 100644--- a/internal/api/docker_container_action_executor.go+++ b/internal/api/docker_container_action_executor.go@@ -13,7 +13,10 @@ import (unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")-const dockerContainerLifecycleHandler = "docker.container.lifecycle"+const (+ dockerContainerLifecycleHandler = "docker.container.lifecycle"+ dockerContainerUpdateHandler = "docker.container.update"+)type dockerContainerActionExecutor struct {resources *ResourceHandlers@@ -37,7 +40,44 @@ type dockerContainerLifecycleAgentCommander interface {ExecuteDockerContainerLifecycle(context.Context, string, agentexec.DockerContainerLifecyclePayload) (*agentexec.DockerContainerLifecycleResultPayload, error)}+type dockerContainerUpdateAgentCommander interface {+ ExecuteDockerContainerUpdate(context.Context, string, agentexec.DockerContainerUpdatePayload) (*agentexec.DockerContainerUpdateResultPayload, error)+}++func isDockerContainerUpdateOperation(operation string) bool {+ return strings.TrimSpace(operation) == "update"+}++// dockerContainerOperationHandler returns the internal handler a capability+// must advertise for the requested operation, so an update request can never+// ride a lifecycle capability or vice versa.+func dockerContainerOperationHandler(operation string) string {+ if isDockerContainerUpdateOperation(operation) {+ return dockerContainerUpdateHandler+ }+ return dockerContainerLifecycleHandler+}+func (e dockerContainerActionExecutor) BindActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {+ if isDockerContainerUpdateOperation(record.Request.CapabilityName) {+ 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, err := dockerContainerUpdateRequest(attempt.ID, record.ID, runtime, resource)+ if err != nil {+ return unified.ActionDispatchAttempt{}, err+ }+ return unified.BindActionDispatchAttempt(attempt, unified.ActionDispatchBinding{OperationKind: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, AgentID: agentID})+ }operation, err := dockerAgentLifecycleOperation(record.Request.CapabilityName)if err != nil {return unified.ActionDispatchAttempt{}, err@@ -69,7 +109,7 @@ func newDockerContainerActionExecutor(resources *ResourceHandlers, agents action}func (e dockerContainerActionExecutor) ActionHandlerNames() []string {- return []string{dockerContainerLifecycleHandler}+ return []string{dockerContainerLifecycleHandler, dockerContainerUpdateHandler}}func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {@@ -82,6 +122,9 @@ func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, recordreturn nil, err}operation := strings.TrimSpace(record.Request.CapabilityName)+ if isDockerContainerUpdateOperation(operation) {+ return e.executeDockerContainerUpdate(ctx, record, attempt)+ }if !isDockerContainerLifecycleOperation(operation) {return nil, fmt.Errorf("unsupported docker container lifecycle capability %q", operation)}@@ -137,6 +180,72 @@ func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, recordreturn dockerContainerExecutionResult(record.Request.ResourceID, agentID, req, *result, independent, receivedAt)}+func (e dockerContainerActionExecutor) executeDockerContainerUpdate(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (*unified.ExecutionResult, error) {+ operation := strings.TrimSpace(record.Request.CapabilityName)+ resource, err := e.currentDockerContainerResource(ctx, record.Request.ResourceID, operation)+ if err != nil {+ return nil, err+ }+ runtime, err := dockerContainerRuntime(resource)+ if err != nil {+ return nil, err+ }+ if dockerContainerRef(resource) == "" {+ return nil, fmt.Errorf("docker container resource %q has no executable container id", record.Request.ResourceID)+ }+ agentID, err := e.connectedDockerCommandAgentID(resource)+ if err != nil {+ return nil, err+ }+ typedAgents, ok := e.agents.(dockerContainerUpdateAgentCommander)+ if !ok {+ return nil, fmt.Errorf("typed docker container update agent is unavailable")+ }+ req, err := dockerContainerUpdateRequest(attempt.ID, record.ID, runtime, resource)+ if err != nil {+ return nil, err+ }+ if agentexec.DockerContainerUpdateOperationIdentity(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 update dispatch binding drift")+ }+ result, err := typedAgents.ExecuteDockerContainerUpdate(ctx, agentID, req)+ if err != nil {+ return nil, err+ }+ if result == nil {+ return nil, fmt.Errorf("docker container update agent returned no result")+ }+ receivedAt := time.Now().UTC()+ if err := agentexec.ValidateDockerContainerUpdateResultForRequest(req, *result); err != nil {+ return nil, fmt.Errorf("invalid docker container update agent result: %w", err)+ }+ var independent *dockerContainerPostconditionObservation+ if e.observer != nil && result.NewContainerID != "" {+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, result.NewContainerID); observeErr == nil {+ independent = &observation+ }+ }+ return dockerContainerUpdateExecutionResult(record.Request.ResourceID, agentID, *result, independent, receivedAt)+}++func dockerContainerUpdateRequest(attemptID, actionID, runtime string, resource unified.Resource) (agentexec.DockerContainerUpdatePayload, error) {+ expectedDigest := ""+ if resource.Docker != nil && resource.Docker.UpdateStatus != nil {+ expectedDigest = strings.ToLower(strings.TrimSpace(resource.Docker.UpdateStatus.CurrentDigest))+ }+ if expectedDigest == "" {+ return agentexec.DockerContainerUpdatePayload{}, fmt.Errorf("resource %q has no current image digest to bind the update against", resource.ID)+ }+ req := agentexec.DockerContainerUpdatePayload{+ RequestID: attemptID, ActionID: actionID, Runtime: runtime,+ ContainerID: dockerContainerRef(resource), ExpectedImageDigest: expectedDigest,+ }+ if err := agentexec.BindDockerContainerUpdatePayload(&req); err != nil {+ return agentexec.DockerContainerUpdatePayload{}, err+ }+ return req, nil+}+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 {@@ -154,6 +263,24 @@ func (e dockerContainerActionExecutor) ReconcileActionDispatch(ctx context.Conteif err := agentexec.ValidateOperationQueryResultForIdentity(query, identity, receivedAt); err != nil {return nil, unified.ActionDispatchReceipt{}, false, err}+ if attempt.OperationKind == agentexec.DockerContainerOperationUpdate {+ result, err := agentexec.DecodeDockerContainerUpdateResultPayload(query.Record.Result)+ if err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ var independent *dockerContainerPostconditionObservation+ if e.observer != nil && result.NewContainerID != "" {+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, result.NewContainerID); observeErr == nil {+ independent = &observation+ }+ }+ execution, err := dockerContainerUpdateExecutionResult(record.Request.ResourceID, attempt.AgentID, 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+ }result, err := agentexec.DecodeDockerContainerLifecycleResultPayload(query.Record.Result)if err != nil {return nil, unified.ActionDispatchReceipt{}, false, err@@ -176,14 +303,18 @@ func (e dockerContainerActionExecutor) ReconcileActionDispatch(ctx context.Contefunc (e dockerContainerActionExecutor) CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {operation := strings.TrimSpace(req.CapabilityName)capability, ok := findDockerLifecycleCapability(resource.Capabilities, operation)- if !ok || capability.InternalHandler != dockerContainerLifecycleHandler {+ if !ok || capability.InternalHandler != dockerContainerOperationHandler(operation) {return unified.ResourceActionReadiness{}}readiness := unified.ResourceActionReadiness{Name: operation, Available: true}if e.agents == nil {return unavailableDockerActionReadiness(operation, "command_agent_unavailable", "Docker / Podman command execution is not available.")}- if _, ok := e.agents.(dockerContainerLifecycleAgentCommander); !ok {+ if isDockerContainerUpdateOperation(operation) {+ if _, ok := e.agents.(dockerContainerUpdateAgentCommander); !ok {+ return unavailableDockerActionReadiness(operation, "typed_operation_unavailable", "Typed Docker / Podman update execution is not available.")+ }+ } else 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 {@@ -231,7 +362,7 @@ func (e dockerContainerActionExecutor) executableDockerContainerResource(_ conte}if capability, ok := findDockerLifecycleCapability(resource.Capabilities, operation); !ok {return unified.Resource{}, fmt.Errorf("resource %q does not currently advertise %s capability", resource.ID, operation)- } else if capability.InternalHandler != dockerContainerLifecycleHandler {+ } else if capability.InternalHandler != dockerContainerOperationHandler(operation) {return unified.Resource{}, fmt.Errorf("resource %q advertises %s through unsupported handler %q", resource.ID, operation, capability.InternalHandler)}return resource, nildiff --git a/internal/api/docker_container_action_executor_test.go b/internal/api/docker_container_action_executor_test.goindex b33aa4ba63..3bac3fcdcf 100644--- a/internal/api/docker_container_action_executor_test.go+++ b/internal/api/docker_container_action_executor_test.go@@ -20,14 +20,15 @@ import ()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+ results []*agentexec.CommandResultPayload+ calls []agentexec.ExecuteCommandPayload+ callAgents []string+ typedCalls []agentexec.DockerContainerLifecyclePayload+ typedUpdateCalls []agentexec.DockerContainerUpdatePayload+ 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 {@@ -62,6 +63,22 @@ func (f *fakeDockerActionAgentCommander) ExecuteDockerContainerLifecycle(_ conte}, nil}+func (f *fakeDockerActionAgentCommander) ExecuteDockerContainerUpdate(_ context.Context, agentID string, req agentexec.DockerContainerUpdatePayload) (*agentexec.DockerContainerUpdateResultPayload, error) {+ f.callAgents = append(f.callAgents, agentID)+ f.typedUpdateCalls = append(f.typedUpdateCalls, req)+ now := time.Now().UTC()+ newID := "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"+ return &agentexec.DockerContainerUpdateResultPayload{+ 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,+ NewContainerID: newID, ContainerName: "api",+ OldImageDigest: "sha256:1111111111111111111111111111111111111111111111111111111111111111",+ NewImageDigest: "sha256:2222222222222222222222222222222222222222222222222222222222222222",+ BackupCreated: true, BackupContainer: "api_pulse_backup_20260714_000000",+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: newID, State: "running", Running: true, StartedAt: now, ObservedAt: now},+ }, nil+}+func (f *fakeDockerActionAgentCommander) ExecuteCommand(_ context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {f.callAgents = append(f.callAgents, agentID)f.calls = append(f.calls, cmd)@@ -526,3 +543,79 @@ func dockerContainerActionRecord(actionID, resourceID, operation string) unified},}}++func dockerContainerUpdateActionResource(id, runtime string, now time.Time) unified.Resource {+ resource := dockerContainerActionResource(id, runtime, "running", now)+ resource.Docker.Image = "ghcr.io/example/api:latest"+ resource.Docker.UpdateStatus = &unified.DockerUpdateStatusMeta{+ UpdateAvailable: true,+ CurrentDigest: "sha256:" + strings.Repeat("9", 64),+ LatestDigest: "sha256:" + strings.Repeat("a", 64),+ }+ resource.Capabilities = append(resource.Capabilities, unified.ResourceCapability{+ Name: "update",+ Type: unified.CapabilityTypeCommon,+ Description: "Update this container",+ MinimumApprovalLevel: unified.ApprovalAdmin,+ Platform: runtime,+ InternalHandler: dockerContainerUpdateHandler,+ })+ return resource+}++func TestDockerContainerActionExecutorDispatchesTypedUpdate(t *testing.T) {+ now := time.Now().UTC()+ h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})+ h.SetStateProvider(resourceUnifiedSeedProvider{+ snapshot: models.StateSnapshot{LastUpdate: now},+ resources: []unified.Resource{+ dockerContainerUpdateActionResource("app-container:api", "docker", now),+ },+ })+ agents := &fakeDockerActionAgentCommander{}+ executor := newDockerContainerActionExecutor(h, agents).(dockerContainerActionExecutor)+ record := dockerContainerActionRecord("act_update", "app-container:api", "update")++ 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.typedUpdateCalls) != 1 || len(agents.typedCalls) != 0 || len(agents.calls) != 0 {+ t.Fatalf("update/lifecycle/raw agent calls = %d/%d/%d, want exactly one typed update dispatch", len(agents.typedUpdateCalls), len(agents.typedCalls), len(agents.calls))+ }+ call := agents.typedUpdateCalls[0]+ if call.Operation != agentexec.DockerContainerOperationUpdate || call.ExpectedImageDigest != "sha256:"+strings.Repeat("9", 64) || call.Runtime != "docker" {+ t.Fatalf("typed update payload = %+v", call)+ }+ if result.ActionResultV2 == nil || result.ActionResultV2.Compensation.Support != unified.ActionCompensationDeclared || result.ActionResultV2.Compensation.Status != unified.ActionCompensationNotNeeded {+ t.Fatalf("compensation truth = %+v, want declared/not_needed", result.ActionResultV2)+ }+}++func TestDockerContainerActionExecutorRefusesUpdateThroughLifecycleHandler(t *testing.T) {+ now := time.Now().UTC()+ resource := dockerContainerActionResource("app-container:api", "docker", "running", now)+ resource.Docker.Image = "ghcr.io/example/api:latest"+ resource.Capabilities = append(resource.Capabilities, unified.ResourceCapability{+ Name: "update",+ Type: unified.CapabilityTypeCommon,+ MinimumApprovalLevel: unified.ApprovalAdmin,+ Platform: "docker",+ InternalHandler: dockerContainerLifecycleHandler,+ })+ 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_update_wrong", "app-container:api", "update")++ if readiness := executor.CheckActionAvailable(context.Background(), record.Request, resource); readiness.Available || readiness.Name != "" {+ t.Fatalf("readiness = %+v, want fail-closed for wrong handler", readiness)+ }+}diff --git a/internal/api/docker_container_action_result.go b/internal/api/docker_container_action_result.goindex 677fb48b02..9112abef93 100644--- a/internal/api/docker_container_action_result.go+++ b/internal/api/docker_container_action_result.go@@ -84,6 +84,149 @@ func dockerContainerExecutionResult(resourceID, agentID string, req agentexec.Doreturn projected, nil}+func dockerContainerUpdateExecutionResult(resourceID, agentID string, facts agentexec.DockerContainerUpdateResultPayload, independent *dockerContainerPostconditionObservation, receivedAt time.Time) (*unified.ExecutionResult, error) {+ summary := dockerContainerUpdateFactSummary(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 replacement-container readback."}+ if facts.ReadbackRan {+ if !freshDockerUpdateObservation(facts.After.ObservedAt, receivedAt) {+ verification.ReasonCode = "stale_agent_readback"+ verification.Summary = "The agent readback was stale or skewed."+ } else {+ evidence, err := unified.NormalizeActionEvidence(unified.ActionEvidence{+ Version: unified.ActionEvidenceVersion, ID: facts.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 update evidence: %w", err)+ }+ status := unified.ActionVerificationContradicted+ reason := "postcondition_contradicted"+ if dockerUpdateFactsMatch(facts, 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 && facts.NewContainerID != "" && freshDockerUpdateObservation(independent.Snapshot.ObservedAt, independent.ReceivedAt) && strings.TrimSpace(independent.TrustDomain) != "" && strings.TrimSpace(independent.TrustDomain) != "agent:"+agentID {+ observationDigest, err := operationreceipt.DigestCanonicalJSON(struct {+ ActionID string `json:"action_id"`+ SubjectID string `json:"subject_id"`+ NewContainerID string `json:"new_container_id"`+ After agentexec.DockerContainerLifecycleSnapshot `json:"after"`+ }{facts.ActionID, resourceID, facts.NewContainerID, independent.Snapshot})+ if err != nil {+ return nil, err+ }+ independentSummary := fmt.Sprintf("Direct daemon observation of replacement container: state=%s; running=%t", independent.Snapshot.State, independent.Snapshot.Running)+ evidence, err := unified.NormalizeActionEvidence(unified.ActionEvidence{+ Version: unified.ActionEvidenceVersion, ID: facts.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: facts.ActionID, Kind: "docker_update_replacement", Digest: observationDigest}},+ })+ if err != nil {+ return nil, fmt.Errorf("normalize independent docker update observation: %w", err)+ }+ status := unified.ActionVerificationContradicted+ reason := "postcondition_contradicted"+ if dockerUpdateFactsMatch(facts, 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: dockerUpdateCompensationTruth(facts),+ }+ legacy := &unified.ExecutionResult{Output: summary}+ projected, _, err := unified.ApplyActionResultV2(legacy, canonical)+ if err != nil {+ return nil, fmt.Errorf("apply canonical docker update action truth: %w", err)+ }+ projected.Verification = unified.LegacyActionVerificationFromV2(*projected.ActionResultV2)+ return projected, nil+}++// dockerUpdateCompensationTruth reports real compensation state: the agent+// creates a backup rename before recreating and restores it when the+// replacement fails, so unlike restarts this operation declares support.+func dockerUpdateCompensationTruth(facts agentexec.DockerContainerUpdateResultPayload) unified.ActionCompensationTruth {+ truth := unified.ActionCompensationTruth{+ Support: unified.ActionCompensationDeclared,+ Strategy: "backup_rename_restore",+ Trigger: "replacement_create_start_or_stability_failure",+ }+ switch {+ case facts.MutationCompleted:+ truth.Status = unified.ActionCompensationNotNeeded+ truth.Summary = "Update succeeded; the renamed backup container is removed automatically after a stability window."+ case !facts.MutationStarted:+ truth.Status = unified.ActionCompensationNotNeeded+ truth.Summary = "The update failed before mutating the container, so there was nothing to roll back."+ case facts.RolledBack:+ truth.Status = unified.ActionCompensationSucceeded+ truth.Summary = "The update failed and the original container was restored from its backup."+ case facts.RollbackAttempted:+ truth.Status = unified.ActionCompensationFailed+ truth.Summary = "The update failed and the automatic restore did not complete; the original container may still carry its backup name (" + strings.TrimSpace(facts.BackupContainer) + ")."+ default:+ truth.Status = unified.ActionCompensationNotAttempted+ truth.Summary = "The update failed after mutation started and no automatic restore ran."+ }+ return truth+}++func dockerContainerUpdateFactSummary(facts agentexec.DockerContainerUpdateResultPayload) string {+ summary := fmt.Sprintf(+ "Container update: phase=%s; mutation started=%t; mutation completed=%t; readback ran=%t; container=%s; replacement=%s; old image=%s; new image=%s; backup=%s; rollback attempted=%t; rolled back=%t",+ strings.TrimSpace(facts.ExecutionPhase), facts.MutationStarted, facts.MutationCompleted, facts.ReadbackRan,+ strings.TrimSpace(facts.ContainerName), strings.TrimSpace(facts.NewContainerID),+ shortDockerDigest(facts.OldImageDigest), shortDockerDigest(facts.NewImageDigest),+ strings.TrimSpace(facts.BackupContainer), facts.RollbackAttempted, facts.RolledBack,+ )+ if errText := strings.TrimSpace(facts.Error); errText != "" {+ summary += "; error=" + errText+ }+ return summary+}++func shortDockerDigest(digest string) string {+ digest = strings.TrimSpace(digest)+ const previewLen = 19 // "sha256:" + 12 hex characters+ if len(digest) <= previewLen {+ return digest+ }+ return digest[:previewLen]+}++func freshDockerUpdateObservation(observedAt, receivedAt time.Time) bool {+ if observedAt.IsZero() || receivedAt.IsZero() {+ return false+ }+ return !observedAt.Before(receivedAt.UTC().Add(-30*time.Minute)) && !observedAt.After(receivedAt.UTC().Add(5*time.Minute))+}++// dockerUpdateFactsMatch confirms the observed container is the replacement+// the agent claims to have created. A stopped original is recreated without+// being started, so run-state is not part of the postcondition; identity is.+func dockerUpdateFactsMatch(facts agentexec.DockerContainerUpdateResultPayload, observed agentexec.DockerContainerLifecycleSnapshot) bool {+ if facts.NewContainerID == "" || observed.ContainerID == "" {+ return false+ }+ return strings.EqualFold(facts.NewContainerID, observed.ContainerID)+}+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))}diff --git a/internal/dockeragent/container_update.go b/internal/dockeragent/container_update.goindex f1eadc0ec1..b3d8e16720 100644--- a/internal/dockeragent/container_update.go+++ b/internal/dockeragent/container_update.go@@ -25,7 +25,12 @@ type ContainerUpdateResult struct {NewImageDigest string `json:"newImageDigest,omitempty"`BackupCreated bool `json:"backupCreated"`BackupContainer string `json:"backupContainer,omitempty"`- Error string `json:"error,omitempty"`+ // RollbackAttempted / RolledBack record compensation truth: whether a+ // failure path tried to restore the original container, and whether the+ // restore itself succeeded.+ RollbackAttempted bool `json:"rollbackAttempted,omitempty"`+ RolledBack bool `json:"rolledBack,omitempty"`+ Error string `json:"error,omitempty"`}type updateContainerCommandPayload struct {@@ -319,7 +324,8 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID strresult.Error = fmt.Sprintf("Failed to create new container: %v", annotateDockerConnectionError(err))a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Failed to create new container")// Rollback: rename backup back to original name- a.rollbackRenameAndRestart(ctx, backupName, result.ContainerName, containerID, wasRunning)+ result.RollbackAttempted = true+ result.RolledBack = a.rollbackRenameAndRestart(ctx, backupName, result.ContainerName, containerID, wasRunning)return result}@@ -358,7 +364,8 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID strresult.Error = fmt.Sprintf("Failed to start new container: %v", annotateDockerConnectionError(err))a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Failed to start new container")// Rollback: remove new container, rename backup back- a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)+ result.RollbackAttempted = true+ result.RolledBack = a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)return result}@@ -376,7 +383,8 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID strif err != nil {result.Error = fmt.Sprintf("Failed to inspect new container: %v", annotateDockerConnectionError(err))a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Failed to inspect new container")- a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)+ result.RollbackAttempted = true+ result.RolledBack = a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)return result}@@ -392,7 +400,8 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID strresult.Error = fmt.Sprintf("New container crashed immediately (exit code %d): %s", exitCode, stateErr)a.logger.Error().Str("container", result.ContainerName).Int("exitCode", exitCode).Msg("New container crashed, rolling back")// Rollback- a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)+ result.RollbackAttempted = true+ result.RolledBack = a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)return result}@@ -401,7 +410,8 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID strresult.Error = "New container reported unhealthy status"a.logger.Error().Str("container", result.ContainerName).Msg("New container unhealthy, rolling back")// Rollback- a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)+ result.RollbackAttempted = true+ result.RolledBack = a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)return result}}@@ -431,8 +441,10 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID strreturn result}-func (a *Agent) rollbackRenameAndRestart(ctx context.Context, backupName, originalName, originalID string, restart bool) {+func (a *Agent) rollbackRenameAndRestart(ctx context.Context, backupName, originalName, originalID string, restart bool) bool {+ restored := trueif err := a.docker.ContainerRename(ctx, backupName, originalName); err != nil {+ restored = falsea.logger.Warn().Err(err).Str("backup", backupName).@@ -441,22 +453,26 @@ func (a *Agent) rollbackRenameAndRestart(ctx context.Context, backupName, origin}if restart {if err := a.docker.ContainerStart(ctx, originalID, dockerContainerStartOptions{}); err != nil {+ restored = falsea.logger.Warn().Err(err).Str("container", originalName).Msg("Rollback step failed: restart original container")}}+ return restored}-func (a *Agent) rollbackRemoveRenameAndRestart(ctx context.Context, newContainerID, backupName, originalName, originalID string, restart bool) {+func (a *Agent) rollbackRemoveRenameAndRestart(ctx context.Context, newContainerID, backupName, originalName, originalID string, restart bool) bool {+ restored := trueif err := a.docker.ContainerRemove(ctx, newContainerID, dockerContainerRemoveOptions{Force: true}); err != nil {+ restored = falsea.logger.Warn().Err(err).Str("containerId", newContainerID).Msg("Rollback step failed: remove replacement container")}- a.rollbackRenameAndRestart(ctx, backupName, originalName, originalID, restart)+ return a.rollbackRenameAndRestart(ctx, backupName, originalName, originalID, restart) && restored}func shortDigest(digest string) string {diff --git a/internal/dockeragent/container_update_typed.go b/internal/dockeragent/container_update_typed.gonew file mode 100644index 0000000000..90124df81b--- /dev/null+++ b/internal/dockeragent/container_update_typed.go@@ -0,0 +1,50 @@+package dockeragent++import (+ "context"+ "fmt"+ "strings"++ containertypes "github.com/moby/moby/api/types/container"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+)++// TypedContainerUpdate runs a container image update for the typed command+// channel. It refuses when the runtime or the container's current image+// digest no longer matches what the plan was bound to, then delegates to the+// same pull/backup/recreate/rollback implementation the module has always+// used and reports the neutral outcome the unified agent bridge forwards.+func (a *Agent) TypedContainerUpdate(ctx context.Context, runtime, containerID, expectedImageDigest string, progress func(string)) (agentexec.DockerContainerUpdateOutcome, error) {+ if a == nil || a.docker == nil {+ return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("docker module is not connected to a container runtime")+ }+ requestedRuntime := strings.ToLower(strings.TrimSpace(runtime))+ if requestedRuntime != "" && requestedRuntime != strings.ToLower(string(a.runtime)) {+ return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("container runtime mismatch: module runs %s", a.runtime)+ }++ inspect, err := dockerCallWithRetry(ctx, dockerUpdateCallTimeout, func(callCtx context.Context) (containertypes.InspectResponse, error) {+ return a.docker.ContainerInspect(callCtx, containerID)+ })+ if err != nil {+ return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("container preflight inspect unavailable: %v", annotateDockerConnectionError(err))+ }+ if expectedImageDigest != "" && !strings.EqualFold(strings.TrimSpace(inspect.Image), expectedImageDigest) {+ return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("container image digest no longer matches the planned update")+ }++ result := a.updateContainerWithProgress(ctx, containerID, progress)+ return agentexec.DockerContainerUpdateOutcome{+ Success: result.Success,+ ContainerName: result.ContainerName,+ OldContainerID: result.OldContainerID,+ NewContainerID: result.NewContainerID,+ OldImageDigest: result.OldImageDigest,+ NewImageDigest: result.NewImageDigest,+ BackupCreated: result.BackupCreated,+ BackupContainer: result.BackupContainer,+ RollbackAttempted: result.RollbackAttempted,+ RolledBack: result.RolledBack,+ Error: result.Error,+ }, nil+}diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex 9b3c9d546f..9b13238299 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -80,6 +80,11 @@ type Config struct {Collector SystemCollector // Optional: override default system information collector (for testing)+ // DockerContainerUpdater bridges typed container update operations to the+ // Docker / Podman module when the unified agent runs both. Nil when the+ // Docker module is disabled or not yet connected.+ DockerContainerUpdater DockerContainerUpdater+newCommandClientFn func(Config, string, string, string, string) *CommandClientrunCommandClientFn func(*CommandClient, context.Context) errorupdatedFromVersionFn func() stringdiff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.goindex fbba5287b5..6048b1ced2 100644--- a/internal/hostagent/commands.go+++ b/internal/hostagent/commands.go@@ -108,6 +108,7 @@ type CommandClient struct {packageUpdates *packageUpdateManagerstorageCleanup *storageCleanupManagerdockerLifecycle dockerLifecycleManager+ dockerUpdater DockerContainerUpdateroperationReceipts *operationreceipt.StoreoperationReceiptErr erroroperationReceiptCloseOnce sync.Once@@ -147,6 +148,7 @@ func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *packageUpdates: cfg.packageUpdates,storageCleanup: cfg.storageCleanup,dockerLifecycle: newLocalDockerLifecycleManager(),+ dockerUpdater: cfg.DockerContainerUpdater,operationReceipts: receipts,operationReceiptErr: receiptErr,logger: logger,@@ -182,6 +184,8 @@ const (msgTypeHostUpdateResult messageType = "host_update_result"msgTypeDockerContainerLifecycle messageType = "docker_container_lifecycle"msgTypeDockerContainerLifecycleResult messageType = "docker_container_lifecycle_result"+ msgTypeDockerContainerUpdate messageType = "docker_container_update"+ msgTypeDockerContainerUpdateResult messageType = "docker_container_update_result"msgTypeOperationQuery messageType = "agent_operation_query"msgTypeOperationQueryResult messageType = "agent_operation_query_result"msgTypeDeployPreflight messageType = "deploy_preflight"@@ -567,6 +571,14 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn}go c.handleHostStorageCleanup(ctx, conn, payload)+ case msgTypeDockerContainerUpdate:+ payload, err := agentexec.DecodeDockerContainerUpdatePayload(msg.Payload)+ if err != nil {+ c.logger.Warn().Err(err).Msg("Dropping invalid docker container update request")+ continue+ }+ go c.handleDockerContainerUpdate(ctx, conn, payload)+case msgTypeDockerContainerLifecycle:payload, err := agentexec.DecodeDockerContainerLifecyclePayload(msg.Payload)if err != nil {@@ -898,6 +910,16 @@ func hostOperationReceiptConfig() operationreceipt.Config {}return nil}},+ agentexec.DockerContainerUpdateReceiptKind: {agentexec.DockerContainerUpdateReceiptVersion: func(identity operationreceipt.Identity, payload json.RawMessage) error {+ result, err := agentexec.DecodeDockerContainerUpdateResultPayload(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_test.go b/internal/hostagent/docker_lifecycle_test.goindex cb37cc3a4d..c59f5e6ebb 100644--- a/internal/hostagent/docker_lifecycle_test.go+++ b/internal/hostagent/docker_lifecycle_test.go@@ -2,6 +2,7 @@ package hostagentimport ("context"+ "encoding/json""fmt""strings""testing"@@ -88,3 +89,119 @@ func dockerLifecycleTestRequest(t *testing.T, startedAt time.Time) agentexec.Doc}return req}++type stubDockerUpdater struct {+ outcome agentexec.DockerContainerUpdateOutcome+ err error+}++func (s stubDockerUpdater) TypedContainerUpdate(_ context.Context, _, _, _ string, _ func(string)) (agentexec.DockerContainerUpdateOutcome, error) {+ return s.outcome, s.err+}++func boundUpdatePayload(t *testing.T) agentexec.DockerContainerUpdatePayload {+ t.Helper()+ payload := agentexec.DockerContainerUpdatePayload{+ RequestID: "attempt-1",+ ActionID: "action-1",+ Runtime: "docker",+ ContainerID: strings.Repeat("a", 12),+ ExpectedImageDigest: "sha256:" + strings.Repeat("9", 64),+ Timeout: 60,+ }+ if err := agentexec.BindDockerContainerUpdatePayload(&payload); err != nil {+ t.Fatal(err)+ }+ if err := agentexec.ValidateDockerContainerUpdatePayload(&payload); err != nil {+ t.Fatal(err)+ }+ return payload+}++func newUpdateTestClient(updater DockerContainerUpdater) *CommandClient {+ return &CommandClient{+ agentID: "agent-1",+ dockerUpdater: updater,+ dockerLifecycle: &localDockerLifecycleManager{+ run: func(context.Context, string, ...string) ([]byte, error) {+ return []byte(`{"Status":"running","Running":true,"StartedAt":"2026-07-14T12:00:00Z","RestartCount":0}`), nil+ },+ now: func() time.Time { return time.Date(2026, 7, 14, 12, 0, 5, 0, time.UTC) },+ },+ }+}++func TestRunDockerContainerUpdateSuccessMapsCompleteResult(t *testing.T) {+ payload := boundUpdatePayload(t)+ newID := strings.Repeat("b", 12)+ client := newUpdateTestClient(stubDockerUpdater{outcome: agentexec.DockerContainerUpdateOutcome{+ Success: true, ContainerName: "app", OldContainerID: payload.ContainerID, NewContainerID: newID,+ OldImageDigest: "sha256:" + strings.Repeat("1", 64), NewImageDigest: "sha256:" + strings.Repeat("2", 64),+ BackupCreated: true, BackupContainer: "app_pulse_backup_20260714_120000",+ }})++ result := client.runDockerContainerUpdate(context.Background(), payload)+ if err := agentexec.ValidateDockerContainerUpdateResultForRequest(payload, result); err != nil {+ t.Fatalf("success result failed the wire contract: %v (%+v)", err, result)+ }+ if result.ExecutionPhase != agentexec.DockerContainerPhaseComplete || result.NewContainerID != newID || !result.ReadbackRan {+ t.Fatalf("unexpected success mapping: %+v", result)+ }+}++func TestRunDockerContainerUpdateFailureCarriesCompensationTruth(t *testing.T) {+ payload := boundUpdatePayload(t)+ client := newUpdateTestClient(stubDockerUpdater{outcome: agentexec.DockerContainerUpdateOutcome{+ Success: false, ContainerName: "app", Error: "Failed to create new container: boom",+ BackupCreated: true, BackupContainer: "app_pulse_backup_20260714_120000",+ RollbackAttempted: true, RolledBack: true,+ }})++ result := client.runDockerContainerUpdate(context.Background(), payload)+ if err := agentexec.ValidateDockerContainerUpdateResultForRequest(payload, result); err != nil {+ t.Fatalf("failure result failed the wire contract: %v (%+v)", err, result)+ }+ if result.ExecutionPhase == agentexec.DockerContainerPhaseComplete || !result.MutationStarted || !result.RolledBack || result.Error == "" {+ t.Fatalf("unexpected failure mapping: %+v", result)+ }+}++func TestRunDockerContainerUpdateWithoutModuleRefuses(t *testing.T) {+ payload := boundUpdatePayload(t)+ client := newUpdateTestClient(nil)++ result := client.runDockerContainerUpdate(context.Background(), payload)+ if err := agentexec.ValidateDockerContainerUpdateResultForRequest(payload, result); err != nil {+ t.Fatalf("refusal result failed the wire contract: %v (%+v)", err, result)+ }+ if result.MutationStarted || result.Error == "" || result.ExecutionPhase != agentexec.DockerContainerPhasePreflight {+ t.Fatalf("unexpected refusal mapping: %+v", result)+ }+}++func TestHostOperationReceiptConfigAcceptsDockerUpdateReceipts(t *testing.T) {+ cfg := hostOperationReceiptConfig()+ validators, ok := cfg.Validators[agentexec.DockerContainerUpdateReceiptKind]+ if !ok {+ t.Fatal("docker update receipt kind is not registered with the receipt store")+ }+ validator, ok := validators[agentexec.DockerContainerUpdateReceiptVersion]+ if !ok {+ t.Fatal("docker update receipt version is not registered with the receipt store")+ }++ payload := boundUpdatePayload(t)+ newID := strings.Repeat("b", 12)+ client := newUpdateTestClient(stubDockerUpdater{outcome: agentexec.DockerContainerUpdateOutcome{+ Success: true, ContainerName: "app", OldContainerID: payload.ContainerID, NewContainerID: newID,+ BackupCreated: true, BackupContainer: "app_pulse_backup_20260714_120000",+ }})+ result := client.runDockerContainerUpdate(context.Background(), payload)+ encoded, err := json.Marshal(result)+ if err != nil {+ t.Fatal(err)+ }+ if err := validator(agentexec.DockerContainerUpdateOperationIdentity("agent-1", payload), encoded); err != nil {+ t.Fatalf("terminal receipt for a successful update was rejected: %v", err)+ }+}diff --git a/internal/hostagent/docker_update.go b/internal/hostagent/docker_update.gonew file mode 100644index 0000000000..1e4b25eb15--- /dev/null+++ b/internal/hostagent/docker_update.go@@ -0,0 +1,154 @@+package hostagent++import (+ "context"+ "encoding/json"+ "strings"+ "time"++ "github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"+)++// DockerContainerUpdater bridges the typed container update operation to the+// Docker / Podman module's update implementation when the unified agent runs+// both modules. Implementations own pull, backup, recreate, verification, and+// rollback; the error return is reserved for infrastructural refusals (module+// missing, runtime mismatch, preflight drift) as opposed to update failures,+// which arrive inside the outcome.+type DockerContainerUpdater interface {+ TypedContainerUpdate(ctx context.Context, runtime, containerID, expectedImageDigest string, progress func(string)) (agentexec.DockerContainerUpdateOutcome, error)+}++func (c *CommandClient) handleDockerContainerUpdate(ctx context.Context, conn *websocket.Conn, payload agentexec.DockerContainerUpdatePayload) {+ identity := agentexec.DockerContainerUpdateOperationIdentity(c.agentID, payload)+ record, admitted, err := c.admitOperation(identity)+ if err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Docker update durable admission refused")+ return+ }+ if !admitted {+ if record.State == operationreceipt.StateTerminal {+ c.replayDockerContainerUpdate(conn, record)+ }+ return+ }+ if _, err := c.operationReceipts.MarkStarted(identity); err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Docker update durable start refused")+ return+ }+ timeout := time.Duration(payload.Timeout) * time.Second+ if timeout <= 0 {+ timeout = 15 * time.Minute+ }+ operationCtx, cancel := context.WithTimeout(ctx, timeout)+ defer cancel()++ result := c.runDockerContainerUpdate(operationCtx, payload)+ encoded, err := json.Marshal(result)+ if err != nil {+ return+ }+ if _, err := c.operationReceipts.Complete(identity, operationreceipt.TerminalEnvelope{Kind: agentexec.DockerContainerUpdateReceiptKind, Version: agentexec.DockerContainerUpdateReceiptVersion, Payload: encoded}); err != nil {+ c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to persist docker update terminal receipt")+ return+ }+ c.sendDockerContainerUpdateResult(conn, result)+}++func (c *CommandClient) runDockerContainerUpdate(ctx context.Context, payload agentexec.DockerContainerUpdatePayload) agentexec.DockerContainerUpdateResultPayload {+ started := time.Now()+ result := agentexec.DockerContainerUpdateResultPayload{+ RequestID: payload.RequestID, ActionID: payload.ActionID, Operation: payload.Operation,+ OperationVersion: payload.OperationVersion, RequestDigest: payload.RequestDigest, ContainerID: payload.ContainerID,+ ExecutionPhase: agentexec.DockerContainerPhasePreflight,+ }+ defer func() { result.Duration = time.Since(started).Milliseconds() }()++ if err := agentexec.ValidateDockerContainerUpdatePayload(&payload); err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Docker update preflight refused: invalid payload")+ result.Error = "typed container update preflight refused"+ return result+ }+ if c.dockerUpdater == nil {+ c.logger.Warn().Str("request_id", payload.RequestID).Msg("Docker update refused: no docker module bridge wired")+ result.Error = "docker module is not available on this agent"+ return result+ }+ progress := func(step string) {+ c.logger.Info().Str("request_id", payload.RequestID).Str("container_id", payload.ContainerID).Msg(strings.TrimSpace(step))+ }+ outcome, err := c.dockerUpdater.TypedContainerUpdate(ctx, payload.Runtime, payload.ContainerID, payload.ExpectedImageDigest, progress)+ if err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Str("container_id", payload.ContainerID).Msg("Docker update refused before mutation")+ result.Error = boundDockerUpdateError(err.Error())+ return result+ }++ result.ContainerName = outcome.ContainerName+ result.OldImageDigest = outcome.OldImageDigest+ result.NewImageDigest = outcome.NewImageDigest+ result.BackupCreated = outcome.BackupCreated+ result.BackupContainer = outcome.BackupContainer+ result.RollbackAttempted = outcome.RollbackAttempted+ result.RolledBack = outcome.RolledBack+ // The backup rename is the first mutating step the outcome can attest to;+ // failures before it (inspect, pull, stop) leave the tree unmutated.+ result.MutationStarted = outcome.BackupCreated || outcome.RollbackAttempted || outcome.Success+ if result.MutationStarted {+ result.ExecutionPhase = agentexec.DockerContainerPhaseMutate+ }+ result.NewContainerID = strings.ToLower(strings.TrimSpace(outcome.NewContainerID))+ if !outcome.Success || result.NewContainerID == "" {+ result.Error = boundDockerUpdateError(outcome.Error)+ if result.Error == "" {+ result.Error = "container update did not complete"+ }+ return result+ }++ result.MutationCompleted = true+ result.ExecutionPhase = agentexec.DockerContainerPhaseVerify++ // The module verified the replacement (start + stability window) before+ // declaring success; read the replacement state back through the same+ // inspector the lifecycle path uses so the server gets an observation.+ if inspector, ok := c.dockerLifecycle.(*localDockerLifecycleManager); ok && inspector != nil && result.NewContainerID != "" {+ if after, inspectErr := inspector.inspect(ctx, payload.Runtime, result.NewContainerID); inspectErr == nil {+ result.After = after+ result.ReadbackRan = true+ }+ }+ result.ExecutionPhase = agentexec.DockerContainerPhaseComplete+ return result+}++func boundDockerUpdateError(message string) string {+ message = strings.TrimSpace(message)+ if len(message) > 1024 {+ message = message[:1024]+ }+ return message+}++func (c *CommandClient) sendDockerContainerUpdateResult(conn *websocket.Conn, result agentexec.DockerContainerUpdateResultPayload) {+ encoded, err := json.Marshal(result)+ if err != nil {+ return+ }+ msg := wsMessage{Type: msgTypeDockerContainerUpdateResult, 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 update result")+ }+}++func (c *CommandClient) replayDockerContainerUpdate(conn *websocket.Conn, record operationreceipt.Record) {+ var result agentexec.DockerContainerUpdateResultPayload+ if err := json.Unmarshal(record.Result, &result); err == nil {+ c.sendDockerContainerUpdateResult(conn, result)+ }+}diff --git a/internal/mutationregistry/manifest.json b/internal/mutationregistry/manifest.jsonindex d68fefa46c..5855d72aee 100644--- a/internal/mutationregistry/manifest.json+++ b/internal/mutationregistry/manifest.json@@ -34,11 +34,13 @@{"id":"patrol.typed-action","origin":"job","resource_class":"customer_infrastructure","resource_kind":"unified-resource","capability":"advertised_resource_action","entrypoint":"patrol_propose_action -> OrchestratorActionBroker","disposition":"lifecycle","lifecycle_executor":"internal/actionlifecycle.Service","approval_floor":"policy_or_admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},{"id":"resource.docker.container-lifecycle","origin":"api","resource_class":"customer_infrastructure","resource_kind":"app-container","capability":"start_stop_restart","entrypoint":"docker.container.lifecycle","disposition":"lifecycle","lifecycle_executor":"dockerContainerActionExecutor","approval_floor":"admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},+ {"id":"resource.docker.container-update","origin":"api","resource_class":"customer_infrastructure","resource_kind":"app-container","capability":"update_container","entrypoint":"docker.container.update","disposition":"lifecycle","lifecycle_executor":"dockerContainerActionExecutor","approval_floor":"admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},{"id":"resource.host.package-cache-cleanup","origin":"api","resource_class":"customer_infrastructure","resource_kind":"agent","capability":"clean_package_cache","entrypoint":"host.storage_cleanup","disposition":"lifecycle","lifecycle_executor":"hostStorageCleanupActionExecutor","approval_floor":"policy_or_admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"unsupported"},{"id":"resource.host.package-update","origin":"api","resource_class":"customer_infrastructure","resource_kind":"agent","capability":"install_os_updates","entrypoint":"host.package_updates","disposition":"lifecycle","lifecycle_executor":"hostUpdateActionExecutor","approval_floor":"policy_or_admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},{"id":"resource.proxmox.guest-lifecycle","origin":"api","resource_class":"customer_infrastructure","resource_kind":"vm_or_system-container","capability":"start_shutdown_reboot_stop","entrypoint":"proxmox.vm.lifecycle/proxmox.ct.lifecycle","disposition":"lifecycle","lifecycle_executor":"proxmoxGuestActionExecutor","approval_floor":"admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},{"id":"transport.agent.docker-container-lifecycle","origin":"transport","resource_class":"customer_infrastructure","resource_kind":"app-container","capability":"start_stop_restart","entrypoint":"agentexec docker_container_lifecycle","disposition":"lifecycle","lifecycle_executor":"dockerContainerActionExecutor","approval_floor":"admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},+ {"id":"transport.agent.docker-container-update","origin":"transport","resource_class":"customer_infrastructure","resource_kind":"app-container","capability":"update_container","entrypoint":"agentexec docker_container_update","disposition":"lifecycle","lifecycle_executor":"dockerContainerActionExecutor","approval_floor":"admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},{"id":"transport.agent.host-package-cache-cleanup","origin":"transport","resource_class":"customer_infrastructure","resource_kind":"agent","capability":"clean_package_cache","entrypoint":"agentexec host_storage_cleanup","disposition":"lifecycle","lifecycle_executor":"hostStorageCleanupActionExecutor","approval_floor":"policy_or_admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"unsupported"},{"id":"transport.agent.host-package-update","origin":"transport","resource_class":"customer_infrastructure","resource_kind":"agent","capability":"install_os_updates","entrypoint":"agentexec host_update","disposition":"lifecycle","lifecycle_executor":"hostUpdateActionExecutor","approval_floor":"policy_or_admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},{"id":"transport.agent.raw-command","origin":"transport","resource_class":"customer_infrastructure","resource_kind":"agent-target","capability":"executor_owned_command","entrypoint":"agentexec execute_command","disposition":"lifecycle","lifecycle_executor":"dockerContainerActionExecutor/proxmoxGuestActionExecutor","approval_floor":"admin","delivery":"committed_lifecycle_before_transport","verification":"required","rollback":"task_10_truth_and_compensation","residual_owners":["task_10_truth_and_compensation"]},diff --git a/internal/mutationregistry/registry_generated.go b/internal/mutationregistry/registry_generated.goindex 0d747de070..c2dc6b9d1a 100644--- a/internal/mutationregistry/registry_generated.go+++ b/internal/mutationregistry/registry_generated.go@@ -33,6 +33,7 @@ var generatedEntries = []Entry{{ID: "legacy.model.run-command", Origin: Origin("legacy"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "agent-target", Capability: "raw_command", Entrypoint: "run_command provider alias", Disposition: Disposition("retired_denied"), LifecycleExecutor: "", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("denied_before_transport"), Verification: VerificationClass("denied"), Rollback: RollbackClass("denied"), ResidualOwners: []string{"retired_compatibility_response_only"}},{ID: "patrol.typed-action", Origin: Origin("job"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "unified-resource", Capability: "advertised_resource_action", Entrypoint: "patrol_propose_action -> OrchestratorActionBroker", Disposition: Disposition("lifecycle"), LifecycleExecutor: "internal/actionlifecycle.Service", Approval: ApprovalFloor("policy_or_admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},{ID: "resource.docker.container-lifecycle", Origin: Origin("api"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "app-container", Capability: "start_stop_restart", Entrypoint: "docker.container.lifecycle", Disposition: Disposition("lifecycle"), LifecycleExecutor: "dockerContainerActionExecutor", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},+ {ID: "resource.docker.container-update", Origin: Origin("api"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "app-container", Capability: "update_container", Entrypoint: "docker.container.update", Disposition: Disposition("lifecycle"), LifecycleExecutor: "dockerContainerActionExecutor", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},{ID: "resource.host.package-cache-cleanup", Origin: Origin("api"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "agent", Capability: "clean_package_cache", Entrypoint: "host.storage_cleanup", Disposition: Disposition("lifecycle"), LifecycleExecutor: "hostStorageCleanupActionExecutor", Approval: ApprovalFloor("policy_or_admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("unsupported"), ResidualOwners: []string(nil)},{ID: "resource.host.package-update", Origin: Origin("api"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "agent", Capability: "install_os_updates", Entrypoint: "host.package_updates", Disposition: Disposition("lifecycle"), LifecycleExecutor: "hostUpdateActionExecutor", Approval: ApprovalFloor("policy_or_admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},{ID: "resource.proxmox.guest-lifecycle", Origin: Origin("api"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "vm_or_system-container", Capability: "start_shutdown_reboot_stop", Entrypoint: "proxmox.vm.lifecycle/proxmox.ct.lifecycle", Disposition: Disposition("lifecycle"), LifecycleExecutor: "proxmoxGuestActionExecutor", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},@@ -40,6 +41,7 @@ var generatedEntries = []Entry{{ID: "transport.agent.deploy-install", Origin: Origin("transport"), ResourceClass: ResourceClass("pulse_administration"), ResourceKind: "agent-enrollment", Capability: "deploy_agent", Entrypoint: "agentexec deploy_install", Disposition: Disposition("administrative_exception"), LifecycleExecutor: "", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("administrative_transaction"), Verification: VerificationClass("administrative"), Rollback: RollbackClass("unsupported"), ResidualOwners: []string{"task_12_final_governance"}},{ID: "transport.agent.deploy-preflight", Origin: Origin("transport"), ResourceClass: ResourceClass("pulse_administration"), ResourceKind: "agent-enrollment", Capability: "deploy_agent", Entrypoint: "agentexec deploy_preflight", Disposition: Disposition("administrative_exception"), LifecycleExecutor: "", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("administrative_transaction"), Verification: VerificationClass("administrative"), Rollback: RollbackClass("unsupported"), ResidualOwners: []string{"task_12_final_governance"}},{ID: "transport.agent.docker-container-lifecycle", Origin: Origin("transport"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "app-container", Capability: "start_stop_restart", Entrypoint: "agentexec docker_container_lifecycle", Disposition: Disposition("lifecycle"), LifecycleExecutor: "dockerContainerActionExecutor", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},+ {ID: "transport.agent.docker-container-update", Origin: Origin("transport"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "app-container", Capability: "update_container", Entrypoint: "agentexec docker_container_update", Disposition: Disposition("lifecycle"), LifecycleExecutor: "dockerContainerActionExecutor", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},{ID: "transport.agent.host-package-cache-cleanup", Origin: Origin("transport"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "agent", Capability: "clean_package_cache", Entrypoint: "agentexec host_storage_cleanup", Disposition: Disposition("lifecycle"), LifecycleExecutor: "hostStorageCleanupActionExecutor", Approval: ApprovalFloor("policy_or_admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("unsupported"), ResidualOwners: []string(nil)},{ID: "transport.agent.host-package-update", Origin: Origin("transport"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "agent", Capability: "install_os_updates", Entrypoint: "agentexec host_update", Disposition: Disposition("lifecycle"), LifecycleExecutor: "hostUpdateActionExecutor", Approval: ApprovalFloor("policy_or_admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},{ID: "transport.agent.raw-command", Origin: Origin("transport"), ResourceClass: ResourceClass("customer_infrastructure"), ResourceKind: "agent-target", Capability: "executor_owned_command", Entrypoint: "agentexec execute_command", Disposition: Disposition("lifecycle"), LifecycleExecutor: "dockerContainerActionExecutor/proxmoxGuestActionExecutor", Approval: ApprovalFloor("admin"), Delivery: DeliveryClass("committed_lifecycle_before_transport"), Verification: VerificationClass("required"), Rollback: RollbackClass("task_10_truth_and_compensation"), ResidualOwners: []string{"task_10_truth_and_compensation"}},diff --git a/internal/mutationregistry/runtime_surface_audit_test.go b/internal/mutationregistry/runtime_surface_audit_test.goindex 8a16fb36fa..ecb7eba316 100644--- a/internal/mutationregistry/runtime_surface_audit_test.go+++ b/internal/mutationregistry/runtime_surface_audit_test.go@@ -161,6 +161,7 @@ func TestTransportCommandCatalogsResolveToRegistry(t *testing.T) {"MsgTypeCommandResult": {Role: TransportRoleOperationResult},"MsgTypeHostStorageCleanupResult": {Role: TransportRoleOperationResult}, "MsgTypeHostUpdateResult": {Role: TransportRoleOperationResult},"MsgTypeDockerContainerLifecycleResult": {Role: TransportRoleOperationResult},+ "MsgTypeDockerContainerUpdateResult": {Role: TransportRoleOperationResult},"MsgTypeOperationQueryResult": {Role: TransportRoleOperationReceipt},"MsgTypeRegistered": {Role: TransportRoleProtocol}, "MsgTypePong": {Role: TransportRoleProtocol},"MsgTypeExecuteCmd": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.raw-command", DurableAuthorityID: "assistant.resource-action"},@@ -168,6 +169,7 @@ func TestTransportCommandCatalogsResolveToRegistry(t *testing.T) {"MsgTypeReadFile": {Role: TransportRoleProtocol},"MsgTypeHostUpdate": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.host-package-update", DurableAuthorityID: "resource.host.package-update"},"MsgTypeDockerContainerLifecycle": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.docker-container-lifecycle", DurableAuthorityID: "resource.docker.container-lifecycle"},+ "MsgTypeDockerContainerUpdate": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.docker-container-update", DurableAuthorityID: "resource.docker.container-update"},"MsgTypeOperationQuery": {Role: TransportRoleOperationQuery},"MsgTypeDeployPreflight": {Role: TransportRoleAdministrativeRequest, MutationID: "transport.agent.deploy-preflight"},"MsgTypeDeployInstall": {Role: TransportRoleAdministrativeRequest, MutationID: "transport.agent.deploy-install"},diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.goindex d31ec669b9..b6c4d527d9 100644--- a/internal/unifiedresources/adapters.go+++ b/internal/unifiedresources/adapters.go@@ -2281,14 +2281,35 @@ func dockerContainerLifecycleCapabilities(ct models.DockerContainer, host modelsreturn nil}+ var capabilities []ResourceCapabilityswitch strings.ToLower(strings.TrimSpace(ct.State)) {case "running":- return dockerContainerLifecycleCapabilitySet(runtime, "stop", "restart")+ capabilities = dockerContainerLifecycleCapabilitySet(runtime, "stop", "restart")case "created", "exited", "dead", "stopped":- return dockerContainerLifecycleCapabilitySet(runtime, "start")+ capabilities = dockerContainerLifecycleCapabilitySet(runtime, "start")default:return nil}+ if ct.UpdateStatus != nil && ct.UpdateStatus.UpdateAvailable && strings.TrimSpace(ct.UpdateStatus.CurrentDigest) != "" {+ capabilities = append(capabilities, dockerContainerUpdateCapability(runtime))+ }+ return capabilities+}++func dockerContainerUpdateCapability(runtime string) ResourceCapability {+ displayRuntime := "Docker"+ if runtime == "podman" {+ displayRuntime = "Podman"+ }+ return ResourceCapability{+ Name: "update",+ Type: CapabilityTypeCommon,+ Description: fmt.Sprintf("Update this %s container to its latest image through its reporting Pulse agent, with automatic backup and rollback.", displayRuntime),+ MinimumApprovalLevel: ApprovalAdmin,+ AutoAuthorization: AutoAuthorizeNever,+ Platform: runtime,+ InternalHandler: "docker.container.update",+ }}func normalizeDockerLifecycleRuntime(runtime string, podman bool) string {diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.goindex bf75a293e1..cb46d6320e 100644--- a/internal/unifiedresources/adapters_test.go+++ b/internal/unifiedresources/adapters_test.go@@ -1660,3 +1660,65 @@ func TestResourceFromHostCarriesReclaimableMemoryCache(t *testing.T) {t.Fatalf("agent memory used+cache+free %d exceeds total %d", sum, resource.Agent.Memory.Total)}}++func TestResourceFromDockerContainerAdvertisesUpdateCapabilityOnlyWithDigest(t *testing.T) {+ now := time.Now().UTC()+ host := models.DockerHost{+ ID: "docker-host-1",+ AgentID: "agent-1",+ Hostname: "dock1",+ Runtime: "docker",+ LastSeen: now,+ }++ withDigest, _ := resourceFromDockerContainer(models.DockerContainer{+ ID: "abc123",+ Name: "web",+ State: "running",+ Image: "example/web:latest",+ UpdateStatus: &models.DockerContainerUpdateStatus{+ UpdateAvailable: true,+ CurrentDigest: "sha256:" + strings.Repeat("1", 64),+ LatestDigest: "sha256:" + strings.Repeat("2", 64),+ },+ }, host)+ if got := capabilityNames(withDigest.Capabilities); !reflect.DeepEqual(got, []string{"stop", "restart", "update"}) {+ t.Fatalf("capabilities with detected update = %#v, want stop/restart/update", got)+ }+ for _, capability := range withDigest.Capabilities {+ if capability.Name != "update" {+ continue+ }+ if capability.InternalHandler != "docker.container.update" || capability.MinimumApprovalLevel != ApprovalAdmin || capability.AutoAuthorization != AutoAuthorizeNever {+ t.Fatalf("update capability contract = %+v", capability)+ }+ }++ // The typed dispatch binds to the plan-observed digest; a report that+ // cannot state the current digest must not offer the action.+ withoutDigest, _ := resourceFromDockerContainer(models.DockerContainer{+ ID: "abc124",+ Name: "web2",+ State: "running",+ Image: "example/web:latest",+ UpdateStatus: &models.DockerContainerUpdateStatus{+ UpdateAvailable: true,+ },+ }, host)+ if got := capabilityNames(withoutDigest.Capabilities); !reflect.DeepEqual(got, []string{"stop", "restart"}) {+ t.Fatalf("capabilities without current digest = %#v, want stop/restart only", got)+ }++ current, _ := resourceFromDockerContainer(models.DockerContainer{+ ID: "abc125",+ Name: "web3",+ State: "running",+ Image: "example/web:latest",+ UpdateStatus: &models.DockerContainerUpdateStatus{+ CurrentDigest: "sha256:" + strings.Repeat("1", 64),+ },+ }, host)+ if got := capabilityNames(current.Capabilities); !reflect.DeepEqual(got, []string{"stop", "restart"}) {+ t.Fatalf("capabilities without available update = %#v, want stop/restart only", got)+ }+}