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
fix(patrol): require Docker health recovery
rcourtmana9076de15acd
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex fb01c38102..602a5cac3b 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -1679,8 +1679,18 @@ the intentionally sparse public response.or a typed inconclusive reason. It must never enter the operation receiptstore, execute a mutation, accept command text, or infer action truth. Theserver validates freshness and correlation and owns all evidence-class and- verification projection. Older agents advertise version zero and therefore+ verification projection. Agents advertising a protocol version below 2fail closed without receiving an unsupported request.+ Observation protocol version 2 also requires an explicit bounded daemon+ health state (`none`, `starting`, `healthy`, or `unhealthy`) in every+ successful snapshot. `none` means the daemon confirms that no health check+ exists; omission is unknown, never an alias for `none`. Typed start and+ restart execution waits within the existing action timeout while a running+ container remains `starting` or `unhealthy`, performs no second mutation,+ and completes only after the daemon reports `healthy` or explicit `none`.+ Timeout, persistent unhealthy state, unsupported health vocabulary, or a+ missing health fact remains contradicted or inconclusive rather than+ manufacturing a successful postcondition from running state alone.RG-06 has a separate mutation harness at`scripts/intelligence_lab/patrol_autonomy_colima.py` and`internal/api/patrol_autonomy_colima_real_lab_test.go`. It must run from adiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex aa45a7eb16..89ea28fc6d 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -3596,7 +3596,11 @@ resolve canonical/source IDs and unique aliases before collection, rejectresource's current typed catalogue without authority or proposal sideeffects; only then may `patrol_propose_action` leave one side-effect-freetyped proposal for the canonical approval, execution, and independent-- verification lifecycle.+ verification lifecycle. For Docker container-health remediation, that+ lifecycle may claim verified recovery only from version-2 daemon evidence+ whose health state is explicitly `healthy` or `none`; running state,+ `starting`, `unhealthy`, and omitted legacy health remain non-terminal+ finding evidence.1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as OpenAI-compatible `tool_choice` handling, runtime-failure classification splits (for example separating tool-choice request rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the preflight-runtime-recovery contract where a successful Patrol preflight with an observed tool call resolves the synthetic Patrol runtime failure finding while failed or no-tool-call preflights leave it active, the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier either still detects the failure signal **or returns an inconclusive result** — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate). The fail-closed-on-inconclusive policy treats verifier errors (timeouts, executor unavailability, transport faults) as "we don't know" rather than "go ahead": resolution of an event/persistent finding is effectively permanent (next detection registers as a regression and inflates counters), so the safe default is to refuse and require either a successful re-verification or operator action. The gate has a symmetric counterpart, the verified stale-resolve contract: `reconcileStaleFindings` (`internal/ai/patrol_ai.go`) may auto-resolve an event/persistent finding that was seeded but neither re-reported nor resolved ONLY when the finding's key has a deterministic verifier and that verifier affirmatively confirms the failure signal is gone — absence of a re-report remains insufficient evidence for these categories, "still present" or inconclusive verification leaves the finding active (the same fail-closed default), and verifications are capped per reconcile pass (`maxVerifiedStaleResolvesPerRun`) with deferred candidates logged and retried on the next successful full patrol. Without this counterpart the lifecycle was asymmetric: a genuinely fixed backup or recovered service stayed an active finding indefinitely unless the LLM happened to call `patrol_resolve_finding`. `hasDeterministicVerifierForKey` (`internal/ai/patrol_findings.go`) is the single source of truth for which keys have verifiers, consulted by both the gate and the reconcile pass, and must stay aligned with the dispatch switch in `verifyFixDeterministically` (it previously listed two of the seven dispatch keys, silently skipping verification that existed). Finding keys normalize onto the canonical verifier vocabulary in `normalizeFindingKey` via an alias map of unambiguous directional synonyms (`high-cpu` → `cpu-high`, `high-memory` → `memory-high`, `high-disk` → `disk-high`) so deduplication and deterministic verification meet on one key, and the `patrol_report_finding` key guidance (`internal/ai/tools/tools_patrol.go`) teaches the canonical vocabulary; semantically distinct keys (`pbs-job-failed`, `node-offline`) must not be aliased onto verifier keys whose resource model they do not match, the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data, and the patrol-session-bound contract where `ExecutePatrolStream` calls `SessionStore.TrimMessages` after persisting each run's messages to cap the patrol-main session at 200 messages (roughly two recent runs' worth) — without the bound the file grew unbounded at every scheduled run, reaching 16 MB and 3,593 messages within a month and making every `AddMessage` rewrite linearly more expensive; the canonical Patrol forensic log is the `PatrolRunRecord` history surfaced at `/api/ai/patrol/runs`, not the chat-session-shaped fileThe bounded container-health failure vocabulary, including resource-familydiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 15de29c53c..1588b61dea 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -2437,6 +2437,14 @@ a new API state machine, queue contract, or verification-accounting field.server clock, the API conservatively binds its canonical `ObservedAt` to theserver `ReceivedAt` boundary; stale or excessively future observations stayinconclusive and must never be made fresh by clamping.+ The version-2 independent Docker observation contract carries a canonical+ daemon health state as well as lifecycle state. For start and restart, the+ API may confirm the postcondition only when the container is running and+ the independent snapshot says `healthy` or explicitly `none` because no+ health check exists. `starting`, `unhealthy`, missing health, protocol-v1+ agents, and unsupported values remain contradicted or inconclusive. Legacy+ durable receipts without health stay recoverable but cannot be upgraded+ from execution truth to verified outcome truth.Proxmox QEMU VM and LXC lifecycle execution is part of that same API-ownedaction contract. Proxmox guest resources may expose only conservativelifecycle operations (`start`, `shutdown`, `reboot`, `stop`) and executiondiff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 42ef1efc12..497270aadd 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -2409,6 +2409,12 @@ stale snapshots, digest or subject mismatch, and same-agent receipt evidenceremain verification unknown. This closes the prior structural dead end wherean unhealthy-container restart could execute in production but the executorhad no observer capable of satisfying Patrol's verified-outcome contract.+Running state alone is not recovery evidence for a container-health finding.+The version-2 observer must explicitly report `healthy`, or `none` when the+daemon confirms no health check exists; `starting`, `unhealthy`, omitted+health, and legacy protocol versions cannot advance the finding to+`fix_verified`. The agent may wait for a health transition within the bounded+action timeout, but it must never repeat the mutation while waiting.Patrol now consumes the server-derived effective Autopilot mode. Requested`full` is admitted only with a current persisted human acknowledgement anddiff --git a/internal/agentexec/docker_lifecycle_codec.go b/internal/agentexec/docker_lifecycle_codec.goindex 6ec1c170ec..02e616753b 100644--- a/internal/agentexec/docker_lifecycle_codec.go+++ b/internal/agentexec/docker_lifecycle_codec.go@@ -16,6 +16,10 @@ const (DockerContainerLifecycleOperationVersion = 1DockerContainerLifecycleReceiptKind = "pulse.docker_container_lifecycle_result"DockerContainerLifecycleReceiptVersion = 1+ DockerContainerHealthNone = "none"+ DockerContainerHealthStarting = "starting"+ DockerContainerHealthHealthy = "healthy"+ DockerContainerHealthUnhealthy = "unhealthy")var dockerContainerIDPattern = regexp.MustCompile(`^[a-f0-9]{12,64}$`)@@ -168,9 +172,13 @@ func ValidateDockerContainerLifecycleResultPayload(result *DockerContainerLifecyreturn fmt.Errorf("docker lifecycle refusal reason conflicts with mutation state")}for _, snapshot := range []DockerContainerLifecycleSnapshot{result.Before, result.After} {+ snapshot.Health = strings.ToLower(strings.TrimSpace(snapshot.Health))if snapshot.ContainerID != "" && !dockerContainerIDPattern.MatchString(strings.ToLower(strings.TrimSpace(snapshot.ContainerID))) {return fmt.Errorf("docker lifecycle result has invalid container id")}+ if snapshot.Health != "" && !IsDockerContainerHealth(snapshot.Health) {+ return fmt.Errorf("docker lifecycle result has invalid container health")+ }if !snapshot.ObservedAt.IsZero() && snapshot.ObservedAt.Location() != time.UTC {return fmt.Errorf("docker lifecycle observation timestamp must be UTC")}@@ -184,6 +192,23 @@ func ValidateDockerContainerLifecycleResultPayload(result *DockerContainerLifecyreturn nil}+func IsDockerContainerHealth(health string) bool {+ switch strings.ToLower(strings.TrimSpace(health)) {+ case DockerContainerHealthNone, DockerContainerHealthStarting, DockerContainerHealthHealthy, DockerContainerHealthUnhealthy:+ return true+ default:+ return false+ }+}++// DockerContainerHealthAllowsVerifiedRunningState admits only a confirmed+// healthy check or an explicit daemon statement that no health check exists.+// Missing and transitional health are never equivalent to recovery.+func DockerContainerHealthAllowsVerifiedRunningState(health string) bool {+ health = strings.ToLower(strings.TrimSpace(health))+ return health == DockerContainerHealthNone || health == DockerContainerHealthHealthy+}+func DockerContainerLifecycleOperationIdentity(agentID string, payload DockerContainerLifecyclePayload) operationreceipt.Identity {return operationreceipt.Identity{AttemptID: payload.RequestID, ActionID: payload.ActionID, OperationKind: payload.Operation, OperationVersion: payload.OperationVersion, RequestDigest: payload.RequestDigest, AgentID: strings.TrimSpace(agentID)}}diff --git a/internal/agentexec/docker_observation_codec.go b/internal/agentexec/docker_observation_codec.goindex bd73ff79b3..7f7439bb91 100644--- a/internal/agentexec/docker_observation_codec.go+++ b/internal/agentexec/docker_observation_codec.go@@ -8,7 +8,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt")-const DockerContainerObservationProtocolVersion = 1+const DockerContainerObservationProtocolVersion = 2const dockerContainerObservationMaxClockSkew = 5 * time.Minute@@ -97,6 +97,7 @@ func ValidateDockerContainerObservationResultPayload(result *DockerContainerObseresult.ReasonCode = strings.TrimSpace(result.ReasonCode)result.Snapshot.ContainerID = strings.ToLower(strings.TrimSpace(result.Snapshot.ContainerID))result.Snapshot.State = strings.ToLower(strings.TrimSpace(result.Snapshot.State))+ result.Snapshot.Health = strings.ToLower(strings.TrimSpace(result.Snapshot.Health))result.Snapshot.ObservedAt = result.Snapshot.ObservedAt.UTC()result.Snapshot.StartedAt = result.Snapshot.StartedAt.UTC()if result.RequestID == "" || len(result.RequestID) > maxRequestIDLength || result.ActionID == "" || len(result.ActionID) > maxRequestIDLength {@@ -106,12 +107,12 @@ func ValidateDockerContainerObservationResultPayload(result *DockerContainerObsereturn fmt.Errorf("invalid docker observation result binding")}if !result.Observed {- if !IsActionRefusalReasonCode(result.ReasonCode) || result.Snapshot.ContainerID != "" || result.Snapshot.State != "" || result.Snapshot.Running || !result.Snapshot.StartedAt.IsZero() || result.Snapshot.RestartCount != 0 || !result.Snapshot.ObservedAt.IsZero() {+ if !IsActionRefusalReasonCode(result.ReasonCode) || result.Snapshot.ContainerID != "" || result.Snapshot.State != "" || result.Snapshot.Health != "" || result.Snapshot.Running || !result.Snapshot.StartedAt.IsZero() || result.Snapshot.RestartCount != 0 || !result.Snapshot.ObservedAt.IsZero() {return fmt.Errorf("inconclusive docker observation requires a bounded reason and no snapshot")}return nil}- if result.ReasonCode != "" || !dockerContainerIDPattern.MatchString(result.Snapshot.ContainerID) || result.Snapshot.State == "" || len(result.Snapshot.State) > 32 || result.Snapshot.RestartCount < 0 || result.Snapshot.ObservedAt.IsZero() {+ if result.ReasonCode != "" || !dockerContainerIDPattern.MatchString(result.Snapshot.ContainerID) || result.Snapshot.State == "" || len(result.Snapshot.State) > 32 || !IsDockerContainerHealth(result.Snapshot.Health) || result.Snapshot.RestartCount < 0 || result.Snapshot.ObservedAt.IsZero() {return fmt.Errorf("invalid docker observation snapshot")}return nildiff --git a/internal/agentexec/docker_observation_codec_test.go b/internal/agentexec/docker_observation_codec_test.goindex 0d79315f03..9a2e7f92c3 100644--- a/internal/agentexec/docker_observation_codec_test.go+++ b/internal/agentexec/docker_observation_codec_test.go@@ -26,7 +26,7 @@ func TestDockerContainerObservationContractBindsRequestAndFreshResult(t *testingresult := DockerContainerObservationResultPayload{RequestID: decoded.RequestID, ActionID: decoded.ActionID, ProtocolVersion: decoded.ProtocolVersion, RequestDigest: decoded.RequestDigest,Observed: true,- Snapshot: DockerContainerLifecycleSnapshot{ContainerID: decoded.ContainerID, State: "running", Running: true, ObservedAt: now},+ Snapshot: DockerContainerObservationSnapshot{ContainerID: decoded.ContainerID, State: "running", Running: true, Health: DockerContainerHealthHealthy, ObservedAt: now},}if err := ValidateDockerContainerObservationResultForRequest(decoded, result, now); err != nil {t.Fatalf("fresh bound result rejected: %v", err)@@ -44,8 +44,34 @@ func TestDockerContainerObservationContractBindsRequestAndFreshResult(t *testing}}+func TestDockerContainerObservationRequiresExplicitHealthTruth(t *testing.T) {+ now := time.Now().UTC()+ req := DockerContainerObservationPayload{RequestID: "observe-1", ActionID: "action-1", Runtime: "docker", ContainerID: strings.Repeat("a", 64)}+ if err := BindDockerContainerObservationPayload(&req); err != nil {+ t.Fatal(err)+ }+ base := DockerContainerObservationResultPayload{+ RequestID: req.RequestID, ActionID: req.ActionID, ProtocolVersion: req.ProtocolVersion, RequestDigest: req.RequestDigest, Observed: true,+ Snapshot: DockerContainerObservationSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, ObservedAt: now},+ }+ for _, health := range []string{"", "unknown", "degraded"} {+ result := base+ result.Snapshot.Health = health+ if err := ValidateDockerContainerObservationResultForRequest(req, result, now); err == nil {+ t.Fatalf("health %q was accepted without canonical truth", health)+ }+ }+ for _, health := range []string{DockerContainerHealthNone, DockerContainerHealthStarting, DockerContainerHealthHealthy, DockerContainerHealthUnhealthy} {+ result := base+ result.Snapshot.Health = health+ if err := ValidateDockerContainerObservationResultForRequest(req, result, now); err != nil {+ t.Fatalf("canonical health %q was rejected: %v", health, err)+ }+ }+}+func TestDockerContainerObservationWireCarriesFactsNotActionTruth(t *testing.T) {- payload, err := json.Marshal(DockerContainerObservationResultPayload{})+ payload, err := json.Marshal(DockerContainerObservationResultPayload{Snapshot: DockerContainerObservationSnapshot{Health: DockerContainerHealthHealthy}})if err != nil {t.Fatal(err)}@@ -55,4 +81,14 @@ func TestDockerContainerObservationWireCarriesFactsNotActionTruth(t *testing.T)t.Fatalf("observation wire contains forbidden action-truth or authority field %s: %s", forbidden, encoded)}}+ if !strings.Contains(encoded, `"health":"healthy"`) {+ t.Fatalf("observation wire omitted explicit health fact: %s", encoded)+ }+ lifecycle, err := json.Marshal(DockerContainerLifecycleSnapshot{Health: DockerContainerHealthHealthy})+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(lifecycle), `"health"`) {+ t.Fatalf("version-1 lifecycle receipt wire changed incompatibly: %s", lifecycle)+ }}diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.goindex c4fba9f0eb..e4754f2cb3 100644--- a/internal/agentexec/server_websocket_test.go+++ b/internal/agentexec/server_websocket_test.go@@ -783,7 +783,7 @@ func TestDockerContainerObservationRoundTripIsReadOnlyAndActionBound(t *testing.result := DockerContainerObservationResultPayload{RequestID: payload.RequestID, ActionID: payload.ActionID, ProtocolVersion: payload.ProtocolVersion, RequestDigest: payload.RequestDigest,Observed: true,- Snapshot: DockerContainerLifecycleSnapshot{ContainerID: payload.ContainerID, State: "running", Running: true, ObservedAt: time.Now().UTC()},+ Snapshot: DockerContainerObservationSnapshot{ContainerID: payload.ContainerID, State: "running", Running: true, Health: DockerContainerHealthHealthy, ObservedAt: time.Now().UTC()},}agentErr <- conn.WriteJSON(mustNewMessage(t, MsgTypeDockerContainerObserveResult, payload.RequestID, result))}()@@ -812,6 +812,7 @@ func TestDockerContainerObservationRejectsUnsupportedAgentBeforeDispatch(t *testdefer conn.Close()wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "older-agent", Hostname: "host1", Version: "6.3", Platform: "linux", Token: "any",+ DockerObservationVersion: 1,}))_ = wsReadRegisteredPayload(t, conn)started := time.Now()diff --git a/internal/agentexec/types.go b/internal/agentexec/types.goindex 014dcf9abc..286a297c64 100644--- a/internal/agentexec/types.go+++ b/internal/agentexec/types.go@@ -203,6 +203,21 @@ type DockerContainerLifecycleSnapshot struct {ContainerID string `json:"container_id"`State string `json:"state"`Running bool `json:"running"`+ Health string `json:"-"`+ StartedAt time.Time `json:"started_at,omitempty"`+ RestartCount int `json:"restart_count"`+ ObservedAt time.Time `json:"observed_at"`+}++// DockerContainerObservationSnapshot is the protocol-v2, read-only daemon+// fact envelope. Health is deliberately absent from the version-1 lifecycle+// receipt above so a new agent remains receipt-compatible with an older Pulse+// server while independent verification can require an explicit health fact.+type DockerContainerObservationSnapshot struct {+ ContainerID string `json:"container_id"`+ State string `json:"state"`+ Running bool `json:"running"`+ Health string `json:"health"`StartedAt time.Time `json:"started_at,omitempty"`RestartCount int `json:"restart_count"`ObservedAt time.Time `json:"observed_at"`@@ -222,13 +237,13 @@ type DockerContainerObservationPayload struct {}type DockerContainerObservationResultPayload struct {- RequestID string `json:"request_id"`- ActionID string `json:"action_id"`- ProtocolVersion int `json:"protocol_version"`- RequestDigest string `json:"request_digest"`- Observed bool `json:"observed"`- ReasonCode string `json:"reason_code,omitempty"`- Snapshot DockerContainerLifecycleSnapshot `json:"snapshot"`+ RequestID string `json:"request_id"`+ ActionID string `json:"action_id"`+ ProtocolVersion int `json:"protocol_version"`+ RequestDigest string `json:"request_digest"`+ Observed bool `json:"observed"`+ ReasonCode string `json:"reason_code,omitempty"`+ Snapshot DockerContainerObservationSnapshot `json:"snapshot"`}type DockerContainerLifecycleResultPayload struct {diff --git a/internal/api/docker_container_action_executor.go b/internal/api/docker_container_action_executor.goindex edd415a949..b6c360392a 100644--- a/internal/api/docker_container_action_executor.go+++ b/internal/api/docker_container_action_executor.go@@ -29,7 +29,7 @@ type dockerContainerPostconditionObservation struct {ObserverID stringTrustDomain stringMethod string- Snapshot agentexec.DockerContainerLifecycleSnapshot+ Snapshot agentexec.DockerContainerObservationSnapshotReceivedAt time.Time}diff --git a/internal/api/docker_container_action_executor_test.go b/internal/api/docker_container_action_executor_test.goindex e2040e5197..6f41024b79 100644--- a/internal/api/docker_container_action_executor_test.go+++ b/internal/api/docker_container_action_executor_test.go@@ -50,7 +50,7 @@ func (f *observingDockerActionAgentCommander) ObserveDockerContainer(_ context.Creturn &agentexec.DockerContainerObservationResultPayload{RequestID: req.RequestID, ActionID: req.ActionID, ProtocolVersion: req.ProtocolVersion, RequestDigest: req.RequestDigest,Observed: true,- Snapshot: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, StartedAt: time.Now().UTC(), ObservedAt: time.Now().UTC()},+ Snapshot: agentexec.DockerContainerObservationSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthHealthy, StartedAt: time.Now().UTC(), ObservedAt: time.Now().UTC()},}, nil}@@ -103,8 +103,8 @@ func (f *fakeDockerActionAgentCommander) ExecuteDockerContainerLifecycle(_ contereturn &agentexec.DockerContainerLifecycleResultPayload{RequestID: req.RequestID, ActionID: req.ActionID, Operation: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, ContainerID: req.ContainerID,ExecutionPhase: agentexec.DockerContainerPhaseComplete, MutationStarted: true, MutationCompleted: true, ReadbackRan: true,- Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: req.ExpectedState, Running: true, StartedAt: req.ExpectedStartedAt, ObservedAt: now.Add(-time.Second)},- After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, StartedAt: now, ObservedAt: now},+ Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: req.ExpectedState, Running: true, Health: agentexec.DockerContainerHealthNone, StartedAt: req.ExpectedStartedAt, ObservedAt: now.Add(-time.Second)},+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthNone, StartedAt: now, ObservedAt: now},}, nil}diff --git a/internal/api/docker_container_action_result.go b/internal/api/docker_container_action_result.goindex 1d12acebb6..00111231ea 100644--- a/internal/api/docker_container_action_result.go+++ b/internal/api/docker_container_action_result.go@@ -36,7 +36,10 @@ func dockerContainerExecutionResult(resourceID, agentID string, req agentexec.Do}status := unified.ActionVerificationContradictedreason := "postcondition_contradicted"- if dockerLifecycleFactsMatch(req.Operation, facts.Before, facts.After) {+ if dockerLifecycleRunningHealthUnknown(req.Operation, facts.After) {+ status = unified.ActionVerificationInconclusive+ reason = "container_health_unknown"+ } else if dockerLifecycleFactsMatch(req.Operation, facts.Before, facts.After) {status = unified.ActionVerificationConfirmedreason = ""}@@ -46,15 +49,15 @@ func dockerContainerExecutionResult(resourceID, agentID string, req agentexec.Doif independent != nil && freshDockerLifecycleObservation(facts.Before.ObservedAt, independent.Snapshot.ObservedAt, independent.ReceivedAt) && strings.TrimSpace(independent.TrustDomain) != "" && strings.TrimSpace(independent.TrustDomain) != "agent:"+agentID && strings.EqualFold(independent.Snapshot.ContainerID, facts.ContainerID) {evidenceObservedAt, evidenceReceivedAt := dockerActionEvidenceTimes(independent.Snapshot.ObservedAt, independent.ReceivedAt)observationDigest, err := operationreceipt.DigestCanonicalJSON(struct {- ActionID string `json:"action_id"`- SubjectID string `json:"subject_id"`- Before agentexec.DockerContainerLifecycleSnapshot `json:"before"`- After agentexec.DockerContainerLifecycleSnapshot `json:"after"`+ ActionID string `json:"action_id"`+ SubjectID string `json:"subject_id"`+ Before agentexec.DockerContainerLifecycleSnapshot `json:"before"`+ After agentexec.DockerContainerObservationSnapshot `json:"after"`}{req.ActionID, resourceID, facts.Before, independent.Snapshot})if err != nil {return nil, err}- independentSummary := fmt.Sprintf("Direct daemon observation: before=%s; after=%s; running=%t", facts.Before.State, independent.Snapshot.State, independent.Snapshot.Running)+ independentSummary := fmt.Sprintf("Direct daemon observation: before=%s; after=%s; running=%t; health=%s", facts.Before.State, independent.Snapshot.State, independent.Snapshot.Running, independent.Snapshot.Health)evidence, err := unified.NormalizeActionEvidence(unified.ActionEvidence{Version: unified.ActionEvidenceVersion, ID: req.ActionID + "-direct-daemon-observation", ObserverID: independent.ObserverID,ObserverKind: "docker_daemon_observer", ObserverTrustDomain: independent.TrustDomain, ExecutorTrustDomain: "agent:" + agentID,@@ -66,7 +69,7 @@ func dockerContainerExecutionResult(resourceID, agentID string, req agentexec.Do}status := unified.ActionVerificationContradictedreason := "postcondition_contradicted"- if dockerLifecycleFactsMatch(req.Operation, facts.Before, independent.Snapshot) {+ if dockerLifecycleObservationFactsMatch(req.Operation, facts.Before, independent.Snapshot) {status = unified.ActionVerificationConfirmedreason = ""}@@ -112,7 +115,7 @@ func dockerContainerUpdateExecutionResult(resourceID, agentID string, facts agen}status := unified.ActionVerificationContradictedreason := "postcondition_contradicted"- if dockerUpdateFactsMatch(facts, facts.After) {+ if dockerUpdateFactsMatch(facts, facts.After.ContainerID) {status = unified.ActionVerificationConfirmedreason = ""}@@ -122,10 +125,10 @@ func dockerContainerUpdateExecutionResult(resourceID, agentID string, facts agenif independent != nil && facts.NewContainerID != "" && freshDockerUpdateObservation(independent.Snapshot.ObservedAt, independent.ReceivedAt) && strings.TrimSpace(independent.TrustDomain) != "" && strings.TrimSpace(independent.TrustDomain) != "agent:"+agentID {evidenceObservedAt, evidenceReceivedAt := dockerActionEvidenceTimes(independent.Snapshot.ObservedAt, independent.ReceivedAt)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"`+ ActionID string `json:"action_id"`+ SubjectID string `json:"subject_id"`+ NewContainerID string `json:"new_container_id"`+ After agentexec.DockerContainerObservationSnapshot `json:"after"`}{facts.ActionID, resourceID, facts.NewContainerID, independent.Snapshot})if err != nil {return nil, err@@ -142,7 +145,7 @@ func dockerContainerUpdateExecutionResult(resourceID, agentID string, facts agen}status := unified.ActionVerificationContradictedreason := "postcondition_contradicted"- if dockerUpdateFactsMatch(facts, independent.Snapshot) {+ if dockerUpdateFactsMatch(facts, independent.Snapshot.ContainerID) {status = unified.ActionVerificationConfirmedreason = ""}@@ -253,15 +256,22 @@ func dockerActionEvidenceTimes(observedAt, receivedAt time.Time) (time.Time, tim// 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 == "" {+func dockerUpdateFactsMatch(facts agentexec.DockerContainerUpdateResultPayload, observedContainerID string) bool {+ if facts.NewContainerID == "" || observedContainerID == "" {return false}- return strings.EqualFold(facts.NewContainerID, observed.ContainerID)+ return strings.EqualFold(facts.NewContainerID, observedContainerID)}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))+ return fmt.Sprintf("Container lifecycle: phase=%s; mutation started=%t; mutation completed=%t; readback ran=%t; before=%s/%s; after=%s/%s", strings.TrimSpace(facts.ExecutionPhase), facts.MutationStarted, facts.MutationCompleted, facts.ReadbackRan, strings.TrimSpace(facts.Before.State), dockerLifecycleHealthSummary(facts.Before.Health), strings.TrimSpace(facts.After.State), dockerLifecycleHealthSummary(facts.After.Health))+}++func dockerLifecycleHealthSummary(health string) string {+ if health = strings.TrimSpace(health); health != "" {+ return health+ }+ return "unknown"}func freshDockerLifecycleObservation(before, after, receivedAt time.Time) bool {@@ -277,12 +287,23 @@ func dockerLifecycleFactsMatch(operation string, before, after agentexec.DockerC}switch operation {case agentexec.DockerContainerOperationStart:- return after.Running && after.State == "running"+ return after.Running && after.State == "running" && agentexec.DockerContainerHealthAllowsVerifiedRunningState(after.Health)case agentexec.DockerContainerOperationStop:return !after.Running && after.State == "exited"case agentexec.DockerContainerOperationRestart:- return after.Running && after.State == "running" && !after.StartedAt.IsZero() && after.StartedAt.After(before.StartedAt)+ return after.Running && after.State == "running" && !after.StartedAt.IsZero() && after.StartedAt.After(before.StartedAt) && agentexec.DockerContainerHealthAllowsVerifiedRunningState(after.Health)default:return false}}++func dockerLifecycleObservationFactsMatch(operation string, before agentexec.DockerContainerLifecycleSnapshot, after agentexec.DockerContainerObservationSnapshot) bool {+ return dockerLifecycleFactsMatch(operation, before, agentexec.DockerContainerLifecycleSnapshot{+ ContainerID: after.ContainerID, State: after.State, Running: after.Running, Health: after.Health,+ StartedAt: after.StartedAt, RestartCount: after.RestartCount, ObservedAt: after.ObservedAt,+ })+}++func dockerLifecycleRunningHealthUnknown(operation string, after agentexec.DockerContainerLifecycleSnapshot) bool {+ return (operation == agentexec.DockerContainerOperationStart || operation == agentexec.DockerContainerOperationRestart) && !agentexec.IsDockerContainerHealth(after.Health)+}diff --git a/internal/api/docker_container_action_result_test.go b/internal/api/docker_container_action_result_test.goindex 390f94bcfe..4df41f1676 100644--- a/internal/api/docker_container_action_result_test.go+++ b/internal/api/docker_container_action_result_test.go@@ -128,7 +128,7 @@ func TestDockerContainerExecutionResultClassifiesDistinctDaemonObserverAsIndepenreq := agentexec.DockerContainerLifecyclePayload{ActionID: "action-1", Operation: agentexec.DockerContainerOperationRestart}observation := &dockerContainerPostconditionObservation{ObserverID: "colima-direct-cli", TrustDomain: "daemon:colima-direct", Method: "docker_api_inspect",- Snapshot: facts.After, ReceivedAt: now,+ Snapshot: dockerObservationSnapshotFromLifecycle(facts.After), ReceivedAt: now,}result, err := dockerContainerExecutionResult("app-container:fixture", "agent-1", req, facts, observation, now)if err != nil {@@ -140,6 +140,48 @@ func TestDockerContainerExecutionResultClassifiesDistinctDaemonObserverAsIndepen}}+func TestDockerContainerExecutionResultDoesNotVerifyUnrecoveredHealth(t *testing.T) {+ now := time.Now().UTC()+ facts := dockerResultFacts(now, true, true, true, true)+ facts.ContainerID = dockerLifecycleTestID+ req := agentexec.DockerContainerLifecyclePayload{ActionID: "action-1", Operation: agentexec.DockerContainerOperationRestart}+ for _, health := range []string{"", agentexec.DockerContainerHealthStarting, agentexec.DockerContainerHealthUnhealthy} {+ observation := &dockerContainerPostconditionObservation{+ ObserverID: "docker-observer", TrustDomain: "docker-daemon:agent-1", Method: "docker_api_inspect",+ Snapshot: dockerObservationSnapshotFromLifecycle(facts.After), ReceivedAt: now,+ }+ observation.Snapshot.Health = health+ result, err := dockerContainerExecutionResult("app-container:fixture", "agent-1", req, facts, observation, now)+ if err != nil {+ t.Fatal(err)+ }+ if result.ActionResultV2.Verification.Status == unified.ActionVerificationConfirmed {+ t.Fatalf("health %q produced confirmed verification: %#v", health, result.ActionResultV2.Verification)+ }+ }+}++func dockerObservationSnapshotFromLifecycle(snapshot agentexec.DockerContainerLifecycleSnapshot) agentexec.DockerContainerObservationSnapshot {+ return agentexec.DockerContainerObservationSnapshot{+ ContainerID: snapshot.ContainerID, State: snapshot.State, Running: snapshot.Running, Health: snapshot.Health,+ StartedAt: snapshot.StartedAt, RestartCount: snapshot.RestartCount, ObservedAt: snapshot.ObservedAt,+ }+}++func TestDockerContainerExecutionResultTreatsLegacyMissingHealthAsInconclusive(t *testing.T) {+ now := time.Now().UTC()+ facts := dockerResultFacts(now, true, true, true, true)+ facts.After.Health = ""+ result, err := dockerContainerExecutionResult("app-container:fixture", "agent-1", agentexec.DockerContainerLifecyclePayload{Operation: agentexec.DockerContainerOperationRestart}, facts, nil, now)+ if err != nil {+ t.Fatal(err)+ }+ verification := result.ActionResultV2.Verification+ if verification.Status != unified.ActionVerificationInconclusive || verification.ReasonCode != "container_health_unknown" {+ t.Fatalf("legacy health verification = %#v", verification)+ }+}+func dockerResultFacts(now time.Time, started, completed, readback, matches bool) agentexec.DockerContainerLifecycleResultPayload {beforeStart := now.Add(-time.Minute)afterStart := now@@ -150,8 +192,8 @@ func dockerResultFacts(now time.Time, started, completed, readback, matches bool}return agentexec.DockerContainerLifecycleResultPayload{ExecutionPhase: agentexec.DockerContainerPhaseComplete, MutationStarted: started, MutationCompleted: completed, ReadbackRan: readback,- Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: dockerLifecycleTestID, State: "running", Running: true, StartedAt: beforeStart, ObservedAt: now.Add(-time.Second)},- After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: dockerLifecycleTestID, State: state, Running: running, StartedAt: afterStart, ObservedAt: now},+ Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: dockerLifecycleTestID, State: "running", Running: true, Health: agentexec.DockerContainerHealthHealthy, StartedAt: beforeStart, ObservedAt: now.Add(-time.Second)},+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: dockerLifecycleTestID, State: state, Running: running, Health: agentexec.DockerContainerHealthHealthy, StartedAt: afterStart, ObservedAt: now},}}diff --git a/internal/api/docker_restart_colima_real_lab_test.go b/internal/api/docker_restart_colima_real_lab_test.goindex 4da42dba75..045485dc11 100644--- a/internal/api/docker_restart_colima_real_lab_test.go+++ b/internal/api/docker_restart_colima_real_lab_test.go@@ -161,17 +161,17 @@ func TestDockerRestartColimaRealLabCanonicalJourney(t *testing.T) {}type dockerRestartLabArtifact struct {- RunID string `json:"run_id"`- Proposal dockerRestartLabProposal `json:"proposal"`- Investigation dockerRestartLabInvestigation `json:"investigation"`- Action dockerRestartLabAction `json:"action"`- Attempt dockerRestartLabAttempt `json:"attempt"`- Receipt unified.ActionDispatchReceipt `json:"receipt"`- Finding dockerRestartLabFinding `json:"finding"`- Notification dockerRestartLabNotification `json:"notification"`- Before agentexec.DockerContainerLifecycleSnapshot `json:"before"`- After agentexec.DockerContainerLifecycleSnapshot `json:"after"`- Evidence unified.ActionEvidence `json:"evidence"`+ RunID string `json:"run_id"`+ Proposal dockerRestartLabProposal `json:"proposal"`+ Investigation dockerRestartLabInvestigation `json:"investigation"`+ Action dockerRestartLabAction `json:"action"`+ Attempt dockerRestartLabAttempt `json:"attempt"`+ Receipt unified.ActionDispatchReceipt `json:"receipt"`+ Finding dockerRestartLabFinding `json:"finding"`+ Notification dockerRestartLabNotification `json:"notification"`+ Before agentexec.DockerContainerObservationSnapshot `json:"before"`+ After agentexec.DockerContainerObservationSnapshot `json:"after"`+ Evidence unified.ActionEvidence `json:"evidence"`}type dockerRestartLabProposal struct {@@ -251,30 +251,40 @@ func (colimaDirectObserver) ObserveDockerContainer(ctx context.Context, actionIDreturn dockerContainerPostconditionObservation{ObserverID: "task06-colima-direct", TrustDomain: "daemon:colima-direct", Method: "docker_context_colima_inspect", Snapshot: snapshot, ReceivedAt: time.Now().UTC()}, err}-func observeColimaContainer(ctx context.Context, containerID string) (agentexec.DockerContainerLifecycleSnapshot, error) {+func observeColimaContainer(ctx context.Context, containerID string) (agentexec.DockerContainerObservationSnapshot, error) {raw, err := exec.CommandContext(ctx, "docker", "--context", "colima", "inspect", "--format", `{{json .State}}`, containerID).CombinedOutput()if err != nil {- return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("direct Colima inspect: %w", err)+ return agentexec.DockerContainerObservationSnapshot{}, fmt.Errorf("direct Colima inspect: %w", err)}var state struct {Status string `json:"Status"`Running bool `json:"Running"`StartedAt string `json:"StartedAt"`+ Health *struct {+ Status string `json:"Status"`+ } `json:"Health"`}if err := json.Unmarshal(bytes.TrimSpace(raw), &state); err != nil {- return agentexec.DockerContainerLifecycleSnapshot{}, err+ return agentexec.DockerContainerObservationSnapshot{}, err}startedAt, err := time.Parse(time.RFC3339Nano, state.StartedAt)if err != nil {- return agentexec.DockerContainerLifecycleSnapshot{}, err+ return agentexec.DockerContainerObservationSnapshot{}, err}restartRaw, err := exec.CommandContext(ctx, "docker", "--context", "colima", "inspect", "--format", `{{.RestartCount}}`, containerID).CombinedOutput()if err != nil {- return agentexec.DockerContainerLifecycleSnapshot{}, err+ return agentexec.DockerContainerObservationSnapshot{}, err}restartCount, err := strconv.Atoi(strings.TrimSpace(string(restartRaw)))if err != nil {- return agentexec.DockerContainerLifecycleSnapshot{}, err+ return agentexec.DockerContainerObservationSnapshot{}, err}- return agentexec.DockerContainerLifecycleSnapshot{ContainerID: containerID, State: strings.ToLower(state.Status), Running: state.Running, StartedAt: startedAt.UTC(), RestartCount: restartCount, ObservedAt: time.Now().UTC()}, nil+ health := agentexec.DockerContainerHealthNone+ if state.Health != nil {+ health = strings.ToLower(strings.TrimSpace(state.Health.Status))+ if !agentexec.IsDockerContainerHealth(health) {+ return agentexec.DockerContainerObservationSnapshot{}, fmt.Errorf("unsupported Colima container health status %q", health)+ }+ }+ return agentexec.DockerContainerObservationSnapshot{ContainerID: containerID, State: strings.ToLower(state.Status), Running: state.Running, Health: health, StartedAt: startedAt.UTC(), RestartCount: restartCount, ObservedAt: time.Now().UTC()}, nil}diff --git a/internal/dockeragent/container_lifecycle_typed.go b/internal/dockeragent/container_lifecycle_typed.goindex d9d998179a..9d06c63149 100644--- a/internal/dockeragent/container_lifecycle_typed.go+++ b/internal/dockeragent/container_lifecycle_typed.go@@ -31,6 +31,13 @@ func (a *Agent) InspectDockerContainerLifecycle(ctx context.Context, runtime, coif inspect.State == nil {return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("container inspect returned no state")}+ health := agentexec.DockerContainerHealthNone+ if inspect.State.Health != nil {+ health = strings.ToLower(strings.TrimSpace(string(inspect.State.Health.Status)))+ if !agentexec.IsDockerContainerHealth(health) {+ return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("container inspect returned unsupported health status")+ }+ }startedAt := time.Time{}if value := strings.TrimSpace(inspect.State.StartedAt); value != "" && !strings.HasPrefix(value, "0001-") {startedAt, err = time.Parse(time.RFC3339Nano, value)@@ -42,6 +49,7 @@ func (a *Agent) InspectDockerContainerLifecycle(ctx context.Context, runtime, coContainerID: strings.ToLower(strings.TrimSpace(inspect.ID)),State: strings.ToLower(strings.TrimSpace(string(inspect.State.Status))),Running: inspect.State.Running,+ Health: health,StartedAt: startedAt.UTC(),RestartCount: inspect.RestartCount,ObservedAt: time.Now().UTC(),diff --git a/internal/dockeragent/container_lifecycle_typed_test.go b/internal/dockeragent/container_lifecycle_typed_test.goindex 7284320440..3b93972663 100644--- a/internal/dockeragent/container_lifecycle_typed_test.go+++ b/internal/dockeragent/container_lifecycle_typed_test.go@@ -8,6 +8,7 @@ import ("time"containertypes "github.com/moby/moby/api/types/container"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec")func TestTypedContainerLifecycleUsesConnectedDaemonAPI(t *testing.T) {@@ -23,7 +24,7 @@ func TestTypedContainerLifecycleUsesConnectedDaemonAPI(t *testing.T) {}return containertypes.InspectResponse{ID: containerID, RestartCount: 3,- State: &containertypes.State{Status: containertypes.ContainerState("running"), Running: true, StartedAt: startedAt.Format(time.RFC3339Nano)},+ State: &containertypes.State{Status: containertypes.ContainerState("running"), Running: true, StartedAt: startedAt.Format(time.RFC3339Nano), Health: &containertypes.Health{Status: "healthy"}},}, nil},containerRestartFn: func(_ context.Context, id string, _ dockerContainerRestartOptions) error {@@ -39,7 +40,7 @@ func TestTypedContainerLifecycleUsesConnectedDaemonAPI(t *testing.T) {if err != nil {t.Fatal(err)}- if snapshot.ContainerID != containerID || snapshot.State != "running" || !snapshot.Running || snapshot.RestartCount != 3 || !snapshot.StartedAt.Equal(startedAt) {+ if snapshot.ContainerID != containerID || snapshot.State != "running" || !snapshot.Running || snapshot.Health != agentexec.DockerContainerHealthHealthy || snapshot.RestartCount != 3 || !snapshot.StartedAt.Equal(startedAt) {t.Fatalf("snapshot = %#v", snapshot)}if err := agent.MutateDockerContainerLifecycle(context.Background(), "docker", "restart", containerID); err != nil {diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.goindex fae70a110c..1ebeddecda 100644--- a/internal/hostagent/commands.go+++ b/internal/hostagent/commands.go@@ -742,7 +742,7 @@ func (c *CommandClient) handleDockerContainerObservation(ctx context.Context, coobserveCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()observer, ok := c.dockerLifecycle.(interface {- Observe(context.Context, string, string) (agentexec.DockerContainerLifecycleSnapshot, error)+ Observe(context.Context, string, string) (agentexec.DockerContainerObservationSnapshot, error)})result := agentexec.DockerContainerObservationResultPayload{RequestID: payload.RequestID, ActionID: payload.ActionID, ProtocolVersion: payload.ProtocolVersion,diff --git a/internal/hostagent/commands_registration_test.go b/internal/hostagent/commands_registration_test.goindex 4a0445381e..8ff4c68c96 100644--- a/internal/hostagent/commands_registration_test.go+++ b/internal/hostagent/commands_registration_test.go@@ -9,6 +9,7 @@ import ("time""github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/securityutil""github.com/rs/zerolog")@@ -105,8 +106,8 @@ func TestCommandClient_sendRegistration_WritesExpectedPayload(t *testing.T) {if payload.Token != "token-1" {t.Fatalf("payload.Token = %q, want %q", payload.Token, "token-1")}- if payload.DockerObservationVersion != 1 {- t.Fatalf("payload.DockerObservationVersion = %d, want 1", payload.DockerObservationVersion)+ if payload.DockerObservationVersion != agentexec.DockerContainerObservationProtocolVersion {+ t.Fatalf("payload.DockerObservationVersion = %d, want %d", payload.DockerObservationVersion, agentexec.DockerContainerObservationProtocolVersion)}}diff --git a/internal/hostagent/docker_lifecycle.go b/internal/hostagent/docker_lifecycle.goindex b3439f3290..41c76e7799 100644--- a/internal/hostagent/docker_lifecycle.go+++ b/internal/hostagent/docker_lifecycle.go@@ -16,13 +16,22 @@ import (var dockerContextNamePattern = regexp.MustCompile(`^[a-zA-Z0-9._-]{1,128}$`)+const dockerLifecycleHealthPollInterval = 2 * time.Second+type dockerLifecycleManager interface {Apply(context.Context, agentexec.DockerContainerLifecyclePayload) agentexec.DockerContainerLifecycleResultPayloadPreflight(context.Context, agentexec.DockerContainerLifecyclePayload) (bool, string)}-func (m *localDockerLifecycleManager) Observe(ctx context.Context, runtime, containerID string) (agentexec.DockerContainerLifecycleSnapshot, error) {- return m.inspect(ctx, runtime, containerID)+func (m *localDockerLifecycleManager) Observe(ctx context.Context, runtime, containerID string) (agentexec.DockerContainerObservationSnapshot, error) {+ snapshot, err := m.inspect(ctx, runtime, containerID)+ if err != nil {+ return agentexec.DockerContainerObservationSnapshot{}, err+ }+ return agentexec.DockerContainerObservationSnapshot{+ ContainerID: snapshot.ContainerID, State: snapshot.State, Running: snapshot.Running, Health: snapshot.Health,+ StartedAt: snapshot.StartedAt, RestartCount: snapshot.RestartCount, ObservedAt: snapshot.ObservedAt,+ }, nil}// DockerContainerLifecycleOperator is the narrow bridge from the host command@@ -37,9 +46,10 @@ type DockerContainerLifecycleOperator interface {type dockerLifecycleCommandRunner func(context.Context, string, ...string) ([]byte, error)type localDockerLifecycleManager struct {- run dockerLifecycleCommandRunner- operator DockerContainerLifecycleOperator- now func() time.Time+ run dockerLifecycleCommandRunner+ operator DockerContainerLifecycleOperator+ now func() time.Time+ healthPollInterval time.Duration}func newLocalDockerLifecycleManager(operators ...DockerContainerLifecycleOperator) *localDockerLifecycleManager {@@ -101,6 +111,25 @@ func (m *localDockerLifecycleManager) Apply(ctx context.Context, req agentexec.Dresult.ExecutionPhase = agentexec.DockerContainerPhaseCompletereturn result}+ if dockerLifecycleHealthPending(req, before, after) {+ verifyCtx, cancel := context.WithTimeout(ctx, time.Duration(req.Timeout)*time.Second)+ defer cancel()+ for dockerLifecycleHealthPending(req, before, after) {+ if err := m.waitForDockerLifecycleHealth(verifyCtx); err != nil {+ break+ }+ after, err = m.inspect(verifyCtx, req.Runtime, req.ContainerID)+ if err != nil {+ result.Error = "container postcondition inspect unavailable"+ return result+ }+ result.After = after+ if dockerLifecyclePostcondition(req, before, after) {+ result.ExecutionPhase = agentexec.DockerContainerPhaseComplete+ return result+ }+ }+ }result.Error = "container postcondition contradicted the requested state"return result}@@ -159,6 +188,9 @@ func (m *localDockerLifecycleManager) inspect(ctx context.Context, runtime, contRunning bool `json:"Running"`StartedAt string `json:"StartedAt"`RestartCount int `json:"RestartCount"`+ Health *struct {+ Status string `json:"Status"`+ } `json:"Health"`}if err := json.Unmarshal([]byte(strings.TrimSpace(string(raw))), &state); err != nil {return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("decode container state: %w", err)@@ -178,9 +210,16 @@ func (m *localDockerLifecycleManager) inspect(ctx context.Context, runtime, contstate.RestartCount = count}}+ health := agentexec.DockerContainerHealthNone+ if state.Health != nil {+ health = strings.ToLower(strings.TrimSpace(state.Health.Status))+ if !agentexec.IsDockerContainerHealth(health) {+ return agentexec.DockerContainerLifecycleSnapshot{}, fmt.Errorf("container inspect returned unsupported health status")+ }+ }return agentexec.DockerContainerLifecycleSnapshot{ContainerID: strings.ToLower(containerID), State: strings.ToLower(strings.TrimSpace(state.Status)), Running: state.Running,- StartedAt: startedAt.UTC(), RestartCount: state.RestartCount, ObservedAt: m.currentTime(),+ Health: health, StartedAt: startedAt.UTC(), RestartCount: state.RestartCount, ObservedAt: m.currentTime(),}, nil}@@ -207,12 +246,42 @@ func dockerLifecyclePostcondition(req agentexec.DockerContainerLifecyclePayload,}switch req.Operation {case agentexec.DockerContainerOperationStart:- return after.Running && after.State == "running"+ return after.Running && after.State == "running" && agentexec.DockerContainerHealthAllowsVerifiedRunningState(after.Health)case agentexec.DockerContainerOperationStop:return !after.Running && after.State == "exited"+ case agentexec.DockerContainerOperationRestart:+ return after.Running && after.State == "running" && !after.StartedAt.IsZero() && after.StartedAt.After(before.StartedAt) && agentexec.DockerContainerHealthAllowsVerifiedRunningState(after.Health)+ default:+ return false+ }+}++func dockerLifecycleHealthPending(req agentexec.DockerContainerLifecyclePayload, before, after agentexec.DockerContainerLifecycleSnapshot) bool {+ health := strings.ToLower(strings.TrimSpace(after.Health))+ if health != agentexec.DockerContainerHealthStarting && health != agentexec.DockerContainerHealthUnhealthy {+ return false+ }+ switch req.Operation {+ case agentexec.DockerContainerOperationStart:+ return after.Running && after.State == "running"case agentexec.DockerContainerOperationRestart:return after.Running && after.State == "running" && !after.StartedAt.IsZero() && after.StartedAt.After(before.StartedAt)default:return false}}++func (m *localDockerLifecycleManager) waitForDockerLifecycleHealth(ctx context.Context) error {+ interval := dockerLifecycleHealthPollInterval+ if m != nil && m.healthPollInterval > 0 {+ interval = m.healthPollInterval+ }+ timer := time.NewTimer(interval)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ return nil+ }+}diff --git a/internal/hostagent/docker_lifecycle_test.go b/internal/hostagent/docker_lifecycle_test.goindex 399052dccd..66729b9b10 100644--- a/internal/hostagent/docker_lifecycle_test.go+++ b/internal/hostagent/docker_lifecycle_test.go@@ -42,8 +42,8 @@ func TestDockerLifecycleManagerUsesConnectedModuleWithoutExternalCLI(t *testing.before := time.Now().UTC().Add(-time.Minute).Truncate(time.Nanosecond)after := before.Add(time.Minute)operator := &stubDockerLifecycleOperator{snapshots: []agentexec.DockerContainerLifecycleSnapshot{- {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, StartedAt: before, ObservedAt: before},- {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, StartedAt: after, ObservedAt: after},+ {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthUnhealthy, StartedAt: before, ObservedAt: before},+ {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthHealthy, StartedAt: after, ObservedAt: after},}}manager := newLocalDockerLifecycleManager(operator)manager.run = func(context.Context, string, ...string) ([]byte, error) {@@ -58,10 +58,46 @@ func TestDockerLifecycleManagerUsesConnectedModuleWithoutExternalCLI(t *testing.}}+func TestDockerLifecycleManagerWaitsForHealthRecovery(t *testing.T) {+ before := time.Now().UTC().Add(-time.Minute).Truncate(time.Nanosecond)+ after := before.Add(time.Minute)+ operator := &stubDockerLifecycleOperator{snapshots: []agentexec.DockerContainerLifecycleSnapshot{+ {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthUnhealthy, StartedAt: before, ObservedAt: before},+ {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthStarting, StartedAt: after, ObservedAt: after},+ {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthHealthy, StartedAt: after, ObservedAt: after.Add(time.Millisecond)},+ }}+ manager := newLocalDockerLifecycleManager(operator)+ manager.healthPollInterval = time.Millisecond+ result := manager.Apply(context.Background(), dockerLifecycleTestRequest(t, before))+ if result.ExecutionPhase != agentexec.DockerContainerPhaseComplete || result.After.Health != agentexec.DockerContainerHealthHealthy {+ t.Fatalf("health recovery result = %#v", result)+ }+ if len(operator.mutations) != 1 {+ t.Fatalf("mutations = %v, want one restart", operator.mutations)+ }+}++func TestDockerLifecycleManagerDoesNotVerifyPersistentUnhealthyState(t *testing.T) {+ before := time.Now().UTC().Add(-time.Minute).Truncate(time.Nanosecond)+ after := before.Add(time.Minute)+ operator := &stubDockerLifecycleOperator{snapshots: []agentexec.DockerContainerLifecycleSnapshot{+ {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthUnhealthy, StartedAt: before, ObservedAt: before},+ {ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthUnhealthy, StartedAt: after, ObservedAt: after},+ }}+ manager := newLocalDockerLifecycleManager(operator)+ manager.healthPollInterval = time.Second+ ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond)+ defer cancel()+ result := manager.Apply(ctx, dockerLifecycleTestRequest(t, before))+ if result.ExecutionPhase == agentexec.DockerContainerPhaseComplete || result.After.Health != agentexec.DockerContainerHealthUnhealthy {+ t.Fatalf("persistent unhealthy result = %#v", result)+ }+}+func TestDockerLifecycleManagerObservationIsReadOnly(t *testing.T) {now := time.Now().UTC()operator := &stubDockerLifecycleOperator{snapshots: []agentexec.DockerContainerLifecycleSnapshot{{- ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, ObservedAt: now,+ ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, Health: agentexec.DockerContainerHealthNone, ObservedAt: now,}}}manager := newLocalDockerLifecycleManager(operator)manager.run = func(context.Context, string, ...string) ([]byte, error) {