Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Add safe APT workflow foundations

rcourtmane77ab9518d90
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 767a16a44e..6c412472f7 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -6304,6 +6304,12 @@
"kind": "file",
"evidence_tier": "test-proof"
},
+ {
+ "repo": "pulse",
+ "path": "internal/agentexec/apt_codec_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/agentexec/server_websocket_test.go",
@@ -6325,6 +6331,12 @@
"path": "internal/ai/approval/store_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/ai/findings_apt_workflows_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/ai/tools/action_audit.go",
@@ -6366,6 +6378,12 @@
"path": "internal/api/contract_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/host_apt_action_result_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/api/host_storage_cleanup_action_executor.go",
@@ -6415,6 +6433,12 @@
"kind": "file",
"evidence_tier": "test-proof"
},
+ {
+ "repo": "pulse",
+ "path": "internal/hostagent/package_manager_lease_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/hostagent/package_updates.go",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index a2d3fd4f85..bd02303080 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4356,3 +4356,19 @@ Task 08 actor/RBAC/approval boundary, Task 07 dispatch contract, and Task 10
two-axis result contract. API tokens are ineligible for the human Autopilot
acknowledgement even where an owner-bound token remains compatible with an
authenticated action capability.
+
+### Task 09 typed APT transport and shared package-manager authority (partial)
+
+Host update and package-cache cleanup use one strict server/agent codec;
+unknown fields, trailing JSON, malformed identity, and open command, path,
+package, removal, or reboot authority are rejected. Pending delivery binds the
+authenticated agent, dispatch request, action, and operation. All APT
+inspection, refresh, update, and cleanup paths share one composition-root-
+injected lease; nil authority fails closed. Metadata refresh is the first
+possible external effect.
+
+This slice contains no APT-specific journal or replay store. Accepted Task 07
+has server dispatch attempts and query-only reconciliation but no reusable
+agent-side durable typed-operation receipt primitive. Disconnect, restart,
+late-receipt, and no-blind-replay proof stay open until that generic crash-safe
+contract exists and Task 09 consumes it.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 20d004aff1..af5718cc6b 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -5817,3 +5817,19 @@ class, and honest inconclusive outcomes. They do not promise independent
verification, and execution success remains separate from outcome truth.
Task 11 still owns the explicit acknowledgement UX and browser/device proof;
Task 12 still owns final certification.
+
+### Task 09 APT finding producer (partial)
+
+`internal/ai/findings_apt_workflows.go` deterministically produces agent-managed
+APT update and pressure-gated package-cache findings. Admission requires fresh
+dual-timestamp telemetry and the exact current canonical capability/handler.
+Stale, skewed, replayed, errored, or capability-less state is unknown and must
+not resolve an active finding; only fresh authoritative clear evidence or
+explicit resource removal reconciles it. Durable disconnect/restart
+reconciliation remains open on the Task 07 generic agent-operation receipt
+continuation.
+
+This partial producer/transport slice does not close L20 or RA35, claims 16 or
+17, either APT workflow scorecard, durable disconnect/restart/late-receipt/no-
+blind-replay evidence, browser workflow evidence, or Debian/Ubuntu real-lab
+evidence. Those remain explicit continuation or certification inputs.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index c1d7a705fa..05a47af53d 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7450,3 +7450,15 @@ boolean, the current expected versioned contract, and the selected record's
version/status metadata without rewriting historical evidence. Stable failure codes distinguish
missing, stale, wrong-organization, wrong-actor, expired, revoked, malformed,
conflicting, and unavailable-store evidence.
+
+Task 09 APT executors consume Task 10 `ActionResultV2` without local truth
+enums. APT metadata refresh is an external package-manager effect, so refresh
+failure or cancellation is `inconclusive/possible_partial_effect`, never
+`not_run`. Readback from the mutating agent is `agent_attested`, preserves
+agent-observed and server-received timestamps, and declares compensation
+unavailable. Durable post-disconnect reconciliation remains a Task 07
+continuation dependency.
+
+This is a partial non-lab producer migration only. It does not change L20 or
+RA35 completion, claims 16/17, workflow scorecards, browser certification, or
+real Debian/Ubuntu execution status.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 29ce2430e7..2ae9f5a4cc 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -1629,3 +1629,8 @@ belongs to a future PVE `/cluster/backup` source. PBS task-history reads must
therefore use a bounded filtered lookback over `/nodes/localhost/tasks` and
surface truncation or permission gaps explicitly instead of treating one recent
unfiltered sample as configured backup-job proof.
+
+Task 09 preserves two APT telemetry clocks at host-agent ingest: `CheckedAt`
+is agent-observed time and `ObservedAt` is server-received time. Monitoring
+must not overwrite the former with the latter; replay and skew safety consumes
+both timestamps downstream.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 6838f97c88..1a588043ba 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -2049,6 +2049,13 @@ while storage detail drawers and filter controls must route summary series IDs,
source tones, and disk metrics through the shared storage helpers instead of
reconstructing them from local table state.
+Task 09 package-cache cleanup remains a bounded typed action over the fixed APT
+cache provider and requires fresh canonical reclaimable-byte and containing-
+filesystem pressure evidence. It accepts no path, package selector,
+installed-package removal, reboot, or rollback authority. Compensation is
+unavailable; durable restart/replay continuity remains an explicit Task 07
+dependency.
+
### Patrol Autopilot config recovery
The tenant AI config is the durable owner for immutable Patrol Autopilot
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 973691080b..afe8e0a9b3 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1710,6 +1710,13 @@ through the canonical resource model, but unified-resource consumers must not
reintroduce removed workload aliases or feature-local resource-type shims just
to satisfy one table, drawer, or badge surface.
+Task 09 owns shared APT telemetry freshness in
+`internal/unifiedresources/host_apt_telemetry.go`. Capability construction,
+finding admission, and execution readiness consume the same dual-timestamp and
+SHA-256 validation rules. A retransmitted old agent observation stays stale
+when freshly received, future/skewed clocks fail closed, and capability removal
+cannot be bypassed by duplicated telemetry predicates.
+
### Patrol Autopilot authority evidence
`internal/unifiedresources/patrol_autopilot.go` owns the versioned immutable
diff --git a/internal/agentexec/apt_codec.go b/internal/agentexec/apt_codec.go
new file mode 100644
index 0000000000..5dfa323082
--- /dev/null
+++ b/internal/agentexec/apt_codec.go
@@ -0,0 +1,197 @@
+package agentexec
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "strings"
+ "time"
+)
+
+func decodeStrictAPTPayload(data []byte, target any) error {
+ if len(bytes.TrimSpace(data)) == 0 {
+ return fmt.Errorf("APT payload is empty")
+ }
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(target); err != nil {
+ return err
+ }
+ if err := decoder.Decode(&struct{}{}); err != io.EOF {
+ if err == nil {
+ return fmt.Errorf("APT payload contains trailing JSON")
+ }
+ return fmt.Errorf("APT payload contains trailing data: %w", err)
+ }
+ return nil
+}
+
+func DecodeHostUpdatePayload(data []byte) (HostUpdatePayload, error) {
+ var payload HostUpdatePayload
+ if err := decodeStrictAPTPayload(data, &payload); err != nil {
+ return HostUpdatePayload{}, err
+ }
+ if err := ValidateHostUpdatePayload(&payload); err != nil {
+ return HostUpdatePayload{}, err
+ }
+ return payload, nil
+}
+
+func DecodeHostUpdateResultPayload(data []byte) (HostUpdateResultPayload, error) {
+ var payload HostUpdateResultPayload
+ if err := decodeStrictAPTPayload(data, &payload); err != nil {
+ return HostUpdateResultPayload{}, err
+ }
+ if err := ValidateHostUpdateResultPayload(&payload); err != nil {
+ return HostUpdateResultPayload{}, err
+ }
+ return payload, nil
+}
+
+func DecodeHostStorageCleanupPayload(data []byte) (HostStorageCleanupPayload, error) {
+ var payload HostStorageCleanupPayload
+ if err := decodeStrictAPTPayload(data, &payload); err != nil {
+ return HostStorageCleanupPayload{}, err
+ }
+ if err := ValidateHostStorageCleanupPayload(&payload); err != nil {
+ return HostStorageCleanupPayload{}, err
+ }
+ return payload, nil
+}
+
+func DecodeHostStorageCleanupResultPayload(data []byte) (HostStorageCleanupResultPayload, error) {
+ var payload HostStorageCleanupResultPayload
+ if err := decodeStrictAPTPayload(data, &payload); err != nil {
+ return HostStorageCleanupResultPayload{}, err
+ }
+ if err := ValidateHostStorageCleanupResultPayload(&payload); err != nil {
+ return HostStorageCleanupResultPayload{}, err
+ }
+ return payload, nil
+}
+
+func ValidateHostUpdatePayload(payload *HostUpdatePayload) error {
+ return validateHostUpdatePayload(payload)
+}
+
+func ValidateHostStorageCleanupPayload(payload *HostStorageCleanupPayload) error {
+ return validateHostStorageCleanupPayload(payload)
+}
+
+func ValidateHostUpdateResultPayload(result *HostUpdateResultPayload) error {
+ if err := validateHostUpdateResultPayload(result); err != nil {
+ return err
+ }
+ result.ActionID = strings.TrimSpace(result.ActionID)
+ result.ExecutionPhase = strings.TrimSpace(result.ExecutionPhase)
+ if result.ActionID == "" || len(result.ActionID) > maxRequestIDLength {
+ return fmt.Errorf("invalid action id")
+ }
+ switch result.ExecutionPhase {
+ case HostUpdatePhasePreflight, HostUpdatePhaseRefresh, HostUpdatePhaseInstall, HostUpdatePhaseVerify, HostUpdatePhaseComplete:
+ default:
+ return fmt.Errorf("unsupported host update execution phase %q", result.ExecutionPhase)
+ }
+ if result.Success && result.ExecutionPhase != HostUpdatePhaseComplete {
+ return fmt.Errorf("successful host update must be complete")
+ }
+ if (result.Verification == HostUpdateVerificationVerified || result.Verification == HostUpdateVerificationFailed) && !validAPTResultObservationChronology(result.Before.CheckedAt, result.After.CheckedAt) {
+ return fmt.Errorf("evidence-bearing host update observation timestamps are invalid")
+ }
+ if result.MutationStarted && result.ExecutionPhase != HostUpdatePhaseRefresh && result.ExecutionPhase != HostUpdatePhaseInstall && result.ExecutionPhase != HostUpdatePhaseVerify && result.ExecutionPhase != HostUpdatePhaseComplete {
+ return fmt.Errorf("host update mutation state conflicts with execution phase")
+ }
+ return nil
+}
+
+func ValidateHostStorageCleanupResultPayload(result *HostStorageCleanupResultPayload) error {
+ if err := validateHostStorageCleanupResultPayload(result); err != nil {
+ return err
+ }
+ result.ActionID = strings.TrimSpace(result.ActionID)
+ result.ExecutionPhase = strings.TrimSpace(result.ExecutionPhase)
+ if result.ActionID == "" || len(result.ActionID) > maxRequestIDLength {
+ return fmt.Errorf("invalid action id")
+ }
+ switch result.ExecutionPhase {
+ case HostStorageCleanupPhasePreflight, HostStorageCleanupPhaseClean, HostStorageCleanupPhaseVerify, HostStorageCleanupPhaseComplete:
+ default:
+ return fmt.Errorf("unsupported host storage cleanup execution phase %q", result.ExecutionPhase)
+ }
+ if result.Success && result.ExecutionPhase != HostStorageCleanupPhaseComplete {
+ return fmt.Errorf("successful host storage cleanup must be complete")
+ }
+ if (result.Verification == HostStorageCleanupVerificationVerified || result.Verification == HostStorageCleanupVerificationFailed) && !validAPTResultObservationChronology(result.Before.CheckedAt, result.After.CheckedAt) {
+ return fmt.Errorf("evidence-bearing host storage cleanup observation timestamps are invalid")
+ }
+ if result.MutationStarted && result.ExecutionPhase != HostStorageCleanupPhaseClean && result.ExecutionPhase != HostStorageCleanupPhaseVerify && result.ExecutionPhase != HostStorageCleanupPhaseComplete {
+ return fmt.Errorf("host storage cleanup mutation state conflicts with execution phase")
+ }
+ return nil
+}
+
+func validAPTResultObservationChronology(before, after time.Time) bool {
+ return !before.IsZero() && !after.IsZero() && !after.Before(before)
+}
+
+func ValidateHostUpdateResultForRequest(req HostUpdatePayload, result HostUpdateResultPayload) error {
+ if err := ValidateHostUpdateResultPayload(&result); err != nil {
+ return err
+ }
+ if result.RequestID != req.RequestID || result.ActionID != req.ActionID {
+ return fmt.Errorf("host update result identity does not match request")
+ }
+ if result.Verification == HostUpdateVerificationVerified || result.Verification == HostUpdateVerificationFailed {
+ if result.Before.InventoryHash != req.ExpectedInventoryHash {
+ return fmt.Errorf("evidence-bearing host update before-state does not match request")
+ }
+ }
+ return nil
+}
+
+func ValidateHostUpdateResultForRequestAt(req HostUpdatePayload, result HostUpdateResultPayload, receivedAt time.Time) error {
+ if err := ValidateHostUpdateResultForRequest(req, result); err != nil {
+ return err
+ }
+ if (result.Verification == HostUpdateVerificationVerified || result.Verification == HostUpdateVerificationFailed) && !validAPTResultObservationAt(result.Before.CheckedAt, result.After.CheckedAt, receivedAt) {
+ return fmt.Errorf("host update result observation is stale or skewed")
+ }
+ return nil
+}
+
+func ValidateHostStorageCleanupResultForRequest(req HostStorageCleanupPayload, result HostStorageCleanupResultPayload) error {
+ if err := ValidateHostStorageCleanupResultPayload(&result); err != nil {
+ return err
+ }
+ if result.RequestID != req.RequestID || result.ActionID != req.ActionID {
+ return fmt.Errorf("host storage cleanup result identity does not match request")
+ }
+ if result.Verification == HostStorageCleanupVerificationVerified || result.Verification == HostStorageCleanupVerificationFailed {
+ if result.Before.Fingerprint != req.ExpectedFingerprint {
+ return fmt.Errorf("evidence-bearing host storage cleanup before-state does not match request")
+ }
+ }
+ return nil
+}
+
+func ValidateHostStorageCleanupResultForRequestAt(req HostStorageCleanupPayload, result HostStorageCleanupResultPayload, receivedAt time.Time) error {
+ if err := ValidateHostStorageCleanupResultForRequest(req, result); err != nil {
+ return err
+ }
+ if (result.Verification == HostStorageCleanupVerificationVerified || result.Verification == HostStorageCleanupVerificationFailed) && !validAPTResultObservationAt(result.Before.CheckedAt, result.After.CheckedAt, receivedAt) {
+ return fmt.Errorf("host storage cleanup result observation is stale or skewed")
+ }
+ return nil
+}
+
+const hostAPTResultFreshness = 15 * time.Minute
+
+func validAPTResultObservationAt(before, after, receivedAt time.Time) bool {
+ if receivedAt.IsZero() || !validAPTResultObservationChronology(before, after) {
+ return false
+ }
+ receivedAt = receivedAt.UTC()
+ after = after.UTC()
+ return !after.Before(receivedAt.Add(-hostAPTResultFreshness)) && !after.After(receivedAt.Add(5*time.Minute))
+}
diff --git a/internal/agentexec/apt_codec_test.go b/internal/agentexec/apt_codec_test.go
new file mode 100644
index 0000000000..60008c4747
--- /dev/null
+++ b/internal/agentexec/apt_codec_test.go
@@ -0,0 +1,160 @@
+package agentexec
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestStrictAPTCodecsRejectUnknownTrailingAndOpenAuthorityFields(t *testing.T) {
+ hash := "sha256:" + strings.Repeat("a", 64)
+ base := fmt.Sprintf(`{"request_id":"r1","action_id":"a1","operation":"install_os_updates","expected_inventory_hash":"%s","timeout":30}`, hash)
+ for _, tc := range []struct {
+ name string
+ body string
+ }{
+ {name: "unknown command", body: strings.TrimSuffix(base, "}") + `,"command":"apt-get upgrade"}`},
+ {name: "package selector", body: strings.TrimSuffix(base, "}") + `,"packages":["x"]}`},
+ {name: "path selector", body: strings.TrimSuffix(base, "}") + `,"path":"/tmp"}`},
+ {name: "removal authority", body: strings.TrimSuffix(base, "}") + `,"allow_remove":true}`},
+ {name: "reboot authority", body: strings.TrimSuffix(base, "}") + `,"reboot":true}`},
+ {name: "trailing json", body: base + `{}`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, err := DecodeHostUpdatePayload([]byte(tc.body)); err == nil {
+ t.Fatal("strict host update codec accepted open authority")
+ }
+ })
+ }
+}
+
+func TestMalformedOrCrossTypeAPTResultCannotPoisonPendingUpdate(t *testing.T) {
+ hash := "sha256:" + strings.Repeat("a", 64)
+ empty := "sha256:" + strings.Repeat("b", 64)
+ s := NewServer(allowAllTestTokens)
+ ts := newWSServer(t, s)
+ defer ts.Close()
+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "apt-agent", Hostname: "host", Version: "6", Platform: "linux", Token: "any"}))
+ _ = wsReadRegisteredPayload(t, conn)
+
+ done := make(chan error, 1)
+ go func() {
+ _, err := s.ExecuteHostUpdate(context.Background(), "apt-agent", HostUpdatePayload{RequestID: "attempt-1", ActionID: "action-1", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: hash, Timeout: 2})
+ done <- err
+ }()
+ msg, err := wsReadRawMessageWithTimeout(conn, time.Second)
+ if err != nil || msg.Type != MsgTypeHostUpdate {
+ t.Fatalf("dispatch msg=%+v err=%v", msg, err)
+ }
+
+ malformed := json.RawMessage(`{"request_id":"attempt-1","action_id":"action-1","execution_phase":"complete","verification":"verified","unknown":true}`)
+ if err := conn.WriteJSON(wsMessageForTest(MsgTypeHostUpdateResult, "attempt-1", malformed)); err != nil {
+ t.Fatal(err)
+ }
+ crossType := HostStorageCleanupResultPayload{RequestID: "attempt-1", ActionID: "action-1", ExecutionPhase: HostStorageCleanupPhaseClean, MutationStarted: true, Verification: HostStorageCleanupVerificationInconclusive, Error: "unknown"}
+ if err := conn.WriteJSON(mustNewMessage(t, MsgTypeHostStorageCleanupResult, "attempt-1", crossType)); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case err := <-done:
+ t.Fatalf("malformed/cross-type result terminated pending update: %v", err)
+ case <-time.After(100 * time.Millisecond):
+ }
+
+ now := time.Now().UTC()
+ valid := HostUpdateResultPayload{RequestID: "attempt-1", ActionID: "action-1", ExecutionPhase: HostUpdatePhaseComplete, Success: true, Verification: HostUpdateVerificationVerified,
+ Before: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: hash, PendingCount: 1, CheckedAt: now},
+ After: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: empty, PendingCount: 0, CheckedAt: now}}
+ if err := conn.WriteJSON(mustNewMessage(t, MsgTypeHostUpdateResult, "attempt-1", valid)); err != nil {
+ t.Fatal(err)
+ }
+ if err := <-done; err != nil {
+ t.Fatalf("valid correlated result failed: %v", err)
+ }
+}
+
+func TestCrossTypeSameRequestCollisionRefusesSecondMutation(t *testing.T) {
+ hash := "sha256:" + strings.Repeat("a", 64)
+ s := NewServer(allowAllTestTokens)
+ ts := newWSServer(t, s)
+ defer ts.Close()
+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "apt-agent", Hostname: "host", Version: "6", Platform: "linux", Token: "any"}))
+ _ = wsReadRegisteredPayload(t, conn)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ updateDone := make(chan error, 1)
+ go func() {
+ _, err := s.ExecuteHostUpdate(ctx, "apt-agent", HostUpdatePayload{RequestID: "same-attempt", ActionID: "action-1", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: hash, Timeout: 30})
+ updateDone <- err
+ }()
+ if msg, err := wsReadRawMessageWithTimeout(conn, time.Second); err != nil || msg.Type != MsgTypeHostUpdate {
+ t.Fatalf("first dispatch msg=%+v err=%v", msg, err)
+ }
+ _, cleanupErr := s.ExecuteHostStorageCleanup(context.Background(), "apt-agent", HostStorageCleanupPayload{RequestID: "same-attempt", ActionID: "action-1", Operation: HostStorageCleanupOperationPackageCache, ExpectedFingerprint: hash, Timeout: 1})
+ if cleanupErr == nil || !strings.Contains(cleanupErr.Error(), "already pending") {
+ t.Fatalf("cross-type collision error=%v", cleanupErr)
+ }
+ if _, err := wsReadRawMessageWithTimeout(conn, 100*time.Millisecond); err == nil {
+ t.Fatal("cross-type collision dispatched a second mutation")
+ }
+ cancel()
+ if err := <-updateDone; err == nil {
+ t.Fatal("canceled first mutation unexpectedly succeeded")
+ }
+}
+
+func TestHostUpdateContradictionRejectsWrongRequestBoundBeforeHash(t *testing.T) {
+ now := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ want := "sha256:" + strings.Repeat("a", 64)
+ wrong := "sha256:" + strings.Repeat("b", 64)
+ req := HostUpdatePayload{RequestID: "attempt-1", ActionID: "action-1", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: want}
+ result := HostUpdateResultPayload{RequestID: req.RequestID, ActionID: req.ActionID, ExecutionPhase: HostUpdatePhaseVerify, MutationStarted: true, Verification: HostUpdateVerificationFailed,
+ Before: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: wrong, PendingCount: 1, CheckedAt: now.Add(-time.Minute)},
+ After: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: wrong, PendingCount: 1, CheckedAt: now}}
+ if err := ValidateHostUpdateResultForRequestAt(req, result, now); err == nil || !strings.Contains(err.Error(), "before-state") {
+ t.Fatalf("wrong before hash error=%v", err)
+ }
+}
+
+func TestHostStorageCleanupContradictionRejectsWrongRequestBoundBeforeFingerprint(t *testing.T) {
+ now := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ want := "sha256:" + strings.Repeat("a", 64)
+ wrong := "sha256:" + strings.Repeat("b", 64)
+ req := HostStorageCleanupPayload{RequestID: "attempt-1", ActionID: "action-1", Operation: HostStorageCleanupOperationPackageCache, ExpectedFingerprint: want}
+ result := HostStorageCleanupResultPayload{RequestID: req.RequestID, ActionID: req.ActionID, ExecutionPhase: HostStorageCleanupPhaseVerify, MutationStarted: true, Verification: HostStorageCleanupVerificationFailed,
+ Before: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: wrong, ReclaimableBytes: 100, CheckedAt: now.Add(-time.Minute)},
+ After: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: wrong, ReclaimableBytes: 100, CheckedAt: now}}
+ if err := ValidateHostStorageCleanupResultForRequestAt(req, result, now); err == nil || !strings.Contains(err.Error(), "before-state") {
+ t.Fatalf("wrong before fingerprint error=%v", err)
+ }
+}
+
+func TestAPTResultReceiptTimeValidationUsesControlledClock(t *testing.T) {
+ receivedAt := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ hash := "sha256:" + strings.Repeat("a", 64)
+ req := HostUpdatePayload{RequestID: "attempt-1", ActionID: "action-1", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: hash}
+ result := HostUpdateResultPayload{RequestID: req.RequestID, ActionID: req.ActionID, ExecutionPhase: HostUpdatePhaseVerify, MutationStarted: true, Verification: HostUpdateVerificationFailed,
+ Before: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: hash, PendingCount: 1, CheckedAt: receivedAt.Add(-time.Hour - time.Minute)},
+ After: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: hash, PendingCount: 1, CheckedAt: receivedAt.Add(-time.Hour)}}
+ if err := ValidateHostUpdateResultForRequestAt(req, result, receivedAt); err == nil || !strings.Contains(err.Error(), "stale") {
+ t.Fatalf("stale result error=%v", err)
+ }
+}
+
+func wsMessageForTest(messageType MessageType, id string, payload json.RawMessage) Message {
+ return Message{Type: messageType, ID: id, Timestamp: time.Now().UTC(), Payload: payload}
+}
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index 455c1cc08a..fa5f106266 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -64,6 +64,7 @@ type Server struct {
pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup response
pendingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update response
+ pendingHostOperations map[string]pendingHostOperation // scoped request key -> exact typed APT operation/query identity
deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber
validateToken func(token string, agentID string, hostname string) bool
commandPolicy *CommandPolicy
@@ -74,6 +75,7 @@ type Server struct {
pingInterval time.Duration
commandAuthorizationVerifier func(CommandAuthorizationRequest) error
newCommandApprovalGrant func([]byte, string, ExecuteCommandPayload, time.Time, time.Duration) (*CommandApprovalGrant, error)
+ now func() time.Time
}
// CommandAuthorizationRequest is the complete server-side approval scope
@@ -97,6 +99,11 @@ type agentConn struct {
doneOnce sync.Once
}
+type pendingHostOperation struct {
+ actionID string
+ operation string
+}
+
func (ac *agentConn) signalDone() {
ac.doneOnce.Do(func() {
defer func() {
@@ -128,6 +135,7 @@ func NewServer(validateToken func(token string, agentID string, hostname string)
pendingReqs: make(map[string]chan CommandResultPayload),
pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),
pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),
+ pendingHostOperations: make(map[string]pendingHostOperation),
deploySubs: make(map[string]chan DeployProgressPayload),
validateToken: validateToken,
commandPolicy: DefaultPolicy(),
@@ -136,6 +144,7 @@ func NewServer(validateToken func(token string, agentID string, hostname string)
shutdown: make(chan struct{}),
pingInterval: defaultPingInterval,
newCommandApprovalGrant: NewCommandApprovalGrant,
+ now: time.Now,
}
}
@@ -161,6 +170,34 @@ func pendingRequestKey(agentID, requestID string) string {
return agentID + "\x00" + requestID
}
+func (s *Server) claimPendingHostOperation(agentID, requestID, actionID, operation string) (string, error) {
+ key := pendingRequestKey(agentID, requestID)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if _, exists := s.pendingHostOperations[key]; exists {
+ return "", fmt.Errorf("typed host operation request %q is already pending", requestID)
+ }
+ s.pendingHostOperations[key] = pendingHostOperation{
+ actionID: strings.TrimSpace(actionID),
+ operation: strings.TrimSpace(operation),
+ }
+ return key, nil
+}
+
+func (s *Server) matchesPendingHostOperation(agentID, requestID, actionID, operation string) bool {
+ key := pendingRequestKey(agentID, requestID)
+ s.mu.RLock()
+ expected, ok := s.pendingHostOperations[key]
+ s.mu.RUnlock()
+ return ok && expected.actionID == strings.TrimSpace(actionID) && expected.operation == strings.TrimSpace(operation)
+}
+
+func (s *Server) releasePendingHostOperation(key string) {
+ s.mu.Lock()
+ delete(s.pendingHostOperations, key)
+ s.mu.Unlock()
+}
+
func deploySubKey(agentID, jobID string) string {
return agentID + "\x00" + jobID
}
@@ -828,24 +865,15 @@ func (s *Server) readLoop(ac *agentConn) {
}
case MsgTypeHostUpdateResult:
- var result HostUpdateResultPayload
- if err := msg.DecodePayload(&result); err != nil {
- log.Error().Err(err).Str("agent_id", ac.agent.AgentID).Msg("Failed to parse host update result")
+ result, decodeErr := DecodeHostUpdateResultPayload(msg.Payload)
+ if decodeErr != nil {
+ log.Warn().Err(decodeErr).Str("agent_id", ac.agent.AgentID).Msg("Dropping invalid host update result")
continue
}
- requestID := strings.TrimSpace(result.RequestID)
- if requestID == "" || len(requestID) > maxRequestIDLength {
- log.Warn().Str("agent_id", ac.agent.AgentID).Msg("Dropping host update result with invalid request id")
+ if !s.matchesPendingHostOperation(ac.agent.AgentID, result.RequestID, result.ActionID, HostUpdateOperationInstall) {
+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Dropping uncorrelated host update result")
continue
}
- if err := validateHostUpdateResultPayload(&result); err != nil {
- log.Warn().Err(err).Str("agent_id", ac.agent.AgentID).Str("request_id", requestID).Msg("Replacing invalid host update result with a safe failure")
- result = HostUpdateResultPayload{
- RequestID: requestID,
- Verification: HostUpdateVerificationInconclusive,
- Error: "agent returned invalid host update evidence",
- }
- }
s.mu.RLock()
ch, ok := s.pendingHostUpdates[pendingRequestKey(ac.agent.AgentID, result.RequestID)]
s.mu.RUnlock()
@@ -858,24 +886,15 @@ func (s *Server) readLoop(ac *agentConn) {
}
case MsgTypeHostStorageCleanupResult:
- var result HostStorageCleanupResultPayload
- if err := msg.DecodePayload(&result); err != nil {
- log.Error().Err(err).Str("agent_id", ac.agent.AgentID).Msg("Failed to parse host storage cleanup result")
+ result, decodeErr := DecodeHostStorageCleanupResultPayload(msg.Payload)
+ if decodeErr != nil {
+ log.Warn().Err(decodeErr).Str("agent_id", ac.agent.AgentID).Msg("Dropping invalid host storage cleanup result")
continue
}
- requestID := strings.TrimSpace(result.RequestID)
- if requestID == "" || len(requestID) > maxRequestIDLength {
- log.Warn().Str("agent_id", ac.agent.AgentID).Msg("Dropping host storage cleanup result with invalid request id")
+ if !s.matchesPendingHostOperation(ac.agent.AgentID, result.RequestID, result.ActionID, HostStorageCleanupOperationPackageCache) {
+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Dropping uncorrelated host storage cleanup result")
continue
}
- if err := validateHostStorageCleanupResultPayload(&result); err != nil {
- log.Warn().Err(err).Str("agent_id", ac.agent.AgentID).Str("request_id", requestID).Msg("Replacing invalid host storage cleanup result with a safe failure")
- result = HostStorageCleanupResultPayload{
- RequestID: requestID,
- Verification: HostStorageCleanupVerificationInconclusive,
- Error: "agent returned invalid host storage cleanup evidence",
- }
- }
s.mu.RLock()
ch, ok := s.pendingHostStorageCleanups[pendingRequestKey(ac.agent.AgentID, result.RequestID)]
s.mu.RUnlock()
@@ -1217,7 +1236,7 @@ func (s *Server) ExecuteHostUpdate(ctx context.Context, agentID string, req Host
if strings.TrimSpace(req.RequestID) == "" {
req.RequestID = uuid.New().String()
}
- if err := validateHostUpdatePayload(&req); err != nil {
+ if err := ValidateHostUpdatePayload(&req); err != nil {
return nil, err
}
@@ -1230,6 +1249,11 @@ func (s *Server) ExecuteHostUpdate(ctx context.Context, agentID string, req Host
respCh := make(chan HostUpdateResultPayload, 1)
reqKey := pendingRequestKey(agentID, req.RequestID)
+ hostOperationKey, err := s.claimPendingHostOperation(agentID, req.RequestID, req.ActionID, req.Operation)
+ if err != nil {
+ return nil, err
+ }
+ defer s.releasePendingHostOperation(hostOperationKey)
s.mu.Lock()
if _, exists := s.pendingHostUpdates[reqKey]; exists {
s.mu.Unlock()
@@ -1258,11 +1282,16 @@ func (s *Server) ExecuteHostUpdate(ctx context.Context, agentID string, req Host
defer timer.Stop()
select {
case result := <-respCh:
+ if err := ValidateHostUpdateResultForRequestAt(req, result, s.currentTime()); err != nil {
+ return nil, fmt.Errorf("host update result validation failed: %w", err)
+ }
return &result, nil
case <-timer.C:
return nil, fmt.Errorf("host update timed out after %s", time.Duration(req.Timeout)*time.Second)
case <-ctx.Done():
return nil, ctx.Err()
+ case <-ac.done:
+ return nil, fmt.Errorf("agent %s disconnected before host update receipt", agentID)
case <-s.shutdown:
return nil, errServerShuttingDown
}
@@ -1282,7 +1311,7 @@ func (s *Server) ExecuteHostStorageCleanup(ctx context.Context, agentID string,
if strings.TrimSpace(req.RequestID) == "" {
req.RequestID = uuid.New().String()
}
- if err := validateHostStorageCleanupPayload(&req); err != nil {
+ if err := ValidateHostStorageCleanupPayload(&req); err != nil {
return nil, err
}
@@ -1295,6 +1324,11 @@ func (s *Server) ExecuteHostStorageCleanup(ctx context.Context, agentID string,
respCh := make(chan HostStorageCleanupResultPayload, 1)
reqKey := pendingRequestKey(agentID, req.RequestID)
+ hostOperationKey, err := s.claimPendingHostOperation(agentID, req.RequestID, req.ActionID, req.Operation)
+ if err != nil {
+ return nil, err
+ }
+ defer s.releasePendingHostOperation(hostOperationKey)
s.mu.Lock()
if _, exists := s.pendingHostStorageCleanups[reqKey]; exists {
s.mu.Unlock()
@@ -1323,16 +1357,28 @@ func (s *Server) ExecuteHostStorageCleanup(ctx context.Context, agentID string,
defer timer.Stop()
select {
case result := <-respCh:
+ if err := ValidateHostStorageCleanupResultForRequestAt(req, result, s.currentTime()); err != nil {
+ return nil, fmt.Errorf("host storage cleanup result validation failed: %w", err)
+ }
return &result, nil
case <-timer.C:
return nil, fmt.Errorf("host storage cleanup timed out after %s", time.Duration(req.Timeout)*time.Second)
case <-ctx.Done():
return nil, ctx.Err()
+ case <-ac.done:
+ return nil, fmt.Errorf("agent %s disconnected before host storage cleanup receipt", agentID)
case <-s.shutdown:
return nil, errServerShuttingDown
}
}
+func (s *Server) currentTime() time.Time {
+ if s != nil && s.now != nil {
+ return s.now().UTC()
+ }
+ return time.Now().UTC()
+}
+
// ReadFile reads a file from an agent
func (s *Server) ReadFile(ctx context.Context, agentID string, req ReadFilePayload) (*CommandResultPayload, error) {
agentID = strings.TrimSpace(agentID)
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index 3ebf9cff47..7c13ba7d61 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -562,11 +562,13 @@ func TestExecuteHostUpdateRoundTripUsesTypedCommandFreeEnvelope(t *testing.T) {
return
}
response := HostUpdateResultPayload{
- RequestID: payload.RequestID,
- Success: true,
- Before: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", PendingCount: 2},
- After: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: emptyInventoryHash, PendingCount: 0, RebootRequired: true},
- Verification: HostUpdateVerificationVerified,
+ RequestID: payload.RequestID,
+ ActionID: payload.ActionID,
+ Success: true,
+ ExecutionPhase: HostUpdatePhaseComplete,
+ Before: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: inventoryHash, PendingCount: 2, CheckedAt: time.Now().UTC()},
+ After: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: emptyInventoryHash, PendingCount: 0, RebootRequired: true, CheckedAt: time.Now().UTC()},
+ Verification: HostUpdateVerificationVerified,
}
if err := conn.WriteJSON(mustNewMessage(t, MsgTypeHostUpdateResult, payload.RequestID, response)); err != nil {
agentErr <- err
@@ -662,9 +664,11 @@ func TestExecuteHostStorageCleanupRoundTripUsesPathAndCommandFreeEnvelope(t *tes
}
response := HostStorageCleanupResultPayload{
RequestID: payload.RequestID,
+ ActionID: payload.ActionID,
+ ExecutionPhase: HostStorageCleanupPhaseComplete,
Success: true,
- Before: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: fingerprint, ReclaimableBytes: 500},
- After: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: afterFingerprint, ReclaimableBytes: 20},
+ Before: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: fingerprint, ReclaimableBytes: 500, CheckedAt: time.Now().UTC()},
+ After: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: afterFingerprint, ReclaimableBytes: 20, CheckedAt: time.Now().UTC()},
ReclaimedBytes: 480,
Verification: HostStorageCleanupVerificationVerified,
}
diff --git a/internal/agentexec/types.go b/internal/agentexec/types.go
index e343eab651..5bd707ee36 100644
--- a/internal/agentexec/types.go
+++ b/internal/agentexec/types.go
@@ -192,15 +192,26 @@ const (
// independently. Success means the package-manager mutation completed;
// Verification states whether the postcondition was actually observed.
type HostUpdateResultPayload struct {
- RequestID string `json:"request_id"`
- Success bool `json:"success"`
- Before HostPackageUpdateSnapshot `json:"before"`
- After HostPackageUpdateSnapshot `json:"after"`
- Verification string `json:"verification"`
- Error string `json:"error,omitempty"`
- Duration int64 `json:"duration_ms"`
+ RequestID string `json:"request_id"`
+ ActionID string `json:"action_id"`
+ Success bool `json:"success"`
+ ExecutionPhase string `json:"execution_phase"`
+ MutationStarted bool `json:"mutation_started"`
+ Before HostPackageUpdateSnapshot `json:"before"`
+ After HostPackageUpdateSnapshot `json:"after"`
+ Verification string `json:"verification"`
+ Error string `json:"error,omitempty"`
+ Duration int64 `json:"duration_ms"`
}
+const (
+ HostUpdatePhasePreflight = "preflight"
+ HostUpdatePhaseRefresh = "refresh"
+ HostUpdatePhaseInstall = "install"
+ HostUpdatePhaseVerify = "verify"
+ HostUpdatePhaseComplete = "complete"
+)
+
const HostStorageCleanupOperationPackageCache = "clean_package_cache"
const HostStorageCleanupMaxReportedBytes int64 = 1 << 60
@@ -234,16 +245,26 @@ const (
// HostStorageCleanupResultPayload separates mutation success from the
// read-after-write observation of reclaimed cache bytes.
type HostStorageCleanupResultPayload struct {
- RequestID string `json:"request_id"`
- Success bool `json:"success"`
- Before HostStorageCleanupSnapshot `json:"before"`
- After HostStorageCleanupSnapshot `json:"after"`
- ReclaimedBytes int64 `json:"reclaimed_bytes"`
- Verification string `json:"verification"`
- Error string `json:"error,omitempty"`
- Duration int64 `json:"duration_ms"`
+ RequestID string `json:"request_id"`
+ ActionID string `json:"action_id"`
+ Success bool `json:"success"`
+ ExecutionPhase string `json:"execution_phase"`
+ MutationStarted bool `json:"mutation_started"`
+ Before HostStorageCleanupSnapshot `json:"before"`
+ After HostStorageCleanupSnapshot `json:"after"`
+ ReclaimedBytes int64 `json:"reclaimed_bytes"`
+ Verification string `json:"verification"`
+ Error string `json:"error,omitempty"`
+ Duration int64 `json:"duration_ms"`
}
+const (
+ HostStorageCleanupPhasePreflight = "preflight"
+ HostStorageCleanupPhaseClean = "clean"
+ HostStorageCleanupPhaseVerify = "verify"
+ HostStorageCleanupPhaseComplete = "complete"
+)
+
// ConnectedAgent represents an agent connected via WebSocket
type ConnectedAgent struct {
AgentID string
diff --git a/internal/ai/findings_apt_workflows.go b/internal/ai/findings_apt_workflows.go
new file mode 100644
index 0000000000..6b4030123a
--- /dev/null
+++ b/internal/ai/findings_apt_workflows.go
@@ -0,0 +1,183 @@
+package ai
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
+)
+
+const (
+ aptWorkflowFindingSource = "apt-workflow"
+ aptHostUpdateFindingKey = "apt-host-updates"
+ aptPackageCacheFindingKey = "apt-package-cache-pressure"
+ aptHostUpdateFindingIDPrefix = "apt:host-update:"
+ aptPackageCacheFindingIDPrefix = "apt:cache-cleanup:"
+ aptWorkflowResolveCleared = "apt_workflow:condition_cleared"
+ aptWorkflowResolveRemoved = "apt_workflow:resource_removed"
+)
+
+type aptWorkflowWatcher struct{}
+
+func newAPTWorkflowWatcher() *aptWorkflowWatcher { return &aptWorkflowWatcher{} }
+
+func (w *aptWorkflowWatcher) Observe(state patrolRuntimeState, active []*Finding, now time.Time) (emit []*Finding, resolve []resolveSentinel) {
+ if w == nil {
+ return nil, nil
+ }
+ if state.readState == nil {
+ state = state.withDerivedProviders()
+ }
+ if state.readState == nil {
+ return nil, nil
+ }
+ now = now.UTC()
+ present := make(map[string]struct{})
+ resolved := make(map[string]struct{})
+ for _, host := range state.readState.Hosts() {
+ if host == nil || strings.TrimSpace(host.ID()) == "" {
+ continue
+ }
+ resourceID := strings.TrimSpace(host.ID())
+ present[resourceID] = struct{}{}
+ if finding, known, cleared := aptHostUpdateFinding(host, now); finding != nil {
+ emit = append(emit, finding)
+ } else if known && cleared {
+ id := aptHostUpdateFindingIDPrefix + resourceID
+ resolve = append(resolve, resolveSentinel{DedupKey: id, Reason: aptWorkflowResolveCleared})
+ resolved[id] = struct{}{}
+ }
+ if finding, known, cleared := aptPackageCacheFinding(host, now); finding != nil {
+ emit = append(emit, finding)
+ } else if known && cleared {
+ id := aptPackageCacheFindingIDPrefix + resourceID
+ resolve = append(resolve, resolveSentinel{DedupKey: id, Reason: aptWorkflowResolveCleared})
+ resolved[id] = struct{}{}
+ }
+ }
+ for _, finding := range active {
+ if finding == nil || finding.Source != aptWorkflowFindingSource {
+ continue
+ }
+ if _, ok := present[strings.TrimSpace(finding.ResourceID)]; ok {
+ continue
+ }
+ if _, done := resolved[finding.ID]; done {
+ continue
+ }
+ resolve = append(resolve, resolveSentinel{DedupKey: finding.ID, Reason: aptWorkflowResolveRemoved})
+ }
+ return emit, resolve
+}
+
+func aptHostUpdateFinding(host *unifiedresources.HostView, now time.Time) (*Finding, bool, bool) {
+ status := host.PackageUpdates()
+ if status == nil || strings.TrimSpace(status.Error) != "" || !status.Supported || strings.TrimSpace(status.Manager) != "apt" || !unifiedresources.ValidHostAPTDigest(status.InventoryHash) || !unifiedresources.HostPackageUpdateTelemetryFresh(status, now) {
+ return nil, false, false
+ }
+ if !aptHostHasCapability(host, "install_os_updates", "host.package_updates") {
+ return nil, false, false
+ }
+ if status.PendingCount <= 0 {
+ return nil, true, true
+ }
+ name := aptWorkflowHostName(host)
+ id := aptHostUpdateFindingIDPrefix + host.ID()
+ return &Finding{
+ ID: id, Key: aptHostUpdateFindingKey, Severity: FindingSeverityWarning, Category: FindingCategoryReliability,
+ ResourceID: host.ID(), ResourceName: name, ResourceType: string(unifiedresources.ResourceTypeAgent),
+ Title: fmt.Sprintf("%d operating system update(s) are ready on %s", status.PendingCount, name),
+ Description: "Pulse found standard APT upgrades using fresh Unified Agent telemetry. The governed action refreshes metadata, refuses package removal, and never reboots the host.",
+ Impact: "Leaving operating system updates pending can delay security and reliability fixes.",
+ Recommendation: "Review the proposed host update and its current policy before approving it.",
+ Evidence: fmt.Sprintf("pending_updates=%d inventory=%s checked_at=%s received_at=%s reboot_required=%t", status.PendingCount, status.InventoryHash, status.CheckedAt.UTC().Format(time.RFC3339), status.ObservedAt.UTC().Format(time.RFC3339), status.RebootRequired),
+ Source: aptWorkflowFindingSource, DetectedAt: now, LastSeenAt: now,
+ }, true, false
+}
+
+func aptPackageCacheFinding(host *unifiedresources.HostView, now time.Time) (*Finding, bool, bool) {
+ status := host.StorageCleanup()
+ if status == nil || strings.TrimSpace(status.Error) != "" || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" || !unifiedresources.ValidHostAPTDigest(status.Fingerprint) || !unifiedresources.HostStorageCleanupTelemetryFresh(status, now) {
+ return nil, false, false
+ }
+ if !aptHostHasCapability(host, "clean_package_cache", "host.storage_cleanup") {
+ return nil, false, false
+ }
+ disk, pressured := unifiedresources.HostStorageCleanupPressureDisk(host.Disks())
+ if status.ReclaimableBytes < unifiedresources.HostStorageCleanupMinReclaimableBytes || !pressured {
+ return nil, true, true
+ }
+ name := aptWorkflowHostName(host)
+ id := aptPackageCacheFindingIDPrefix + host.ID()
+ return &Finding{
+ ID: id, Key: aptPackageCacheFindingKey, Severity: FindingSeverityWarning, Category: FindingCategoryCapacity,
+ ResourceID: host.ID(), ResourceName: name, ResourceType: string(unifiedresources.ResourceTypeAgent),
+ Title: fmt.Sprintf("Package downloads can free %s on %s", formatAPTBytes(status.ReclaimableBytes), name),
+ Description: "The filesystem containing the fixed APT package cache is under pressure. Pulse can remove only cached package archives through the governed cleanup action.",
+ Impact: "The pressured filesystem has less room for normal host operation.",
+ Recommendation: "Review the proposed package-cache cleanup and the reported reclaimed-space evidence.",
+ Evidence: fmt.Sprintf("reclaimable_bytes=%d filesystem_usage=%.1f fingerprint=%s checked_at=%s received_at=%s", status.ReclaimableBytes, disk.Usage, status.Fingerprint, status.CheckedAt.UTC().Format(time.RFC3339), status.ObservedAt.UTC().Format(time.RFC3339)),
+ Source: aptWorkflowFindingSource, DetectedAt: now, LastSeenAt: now,
+ }, true, false
+}
+
+func aptHostHasCapability(host *unifiedresources.HostView, name, handler string) bool {
+ if host == nil || host.Status() == unifiedresources.StatusOffline {
+ return false
+ }
+ for _, capability := range host.Capabilities() {
+ if strings.TrimSpace(capability.Name) == name && strings.TrimSpace(capability.InternalHandler) == handler {
+ return true
+ }
+ }
+ return false
+}
+
+func aptWorkflowHostName(host *unifiedresources.HostView) string {
+ if name := strings.TrimSpace(host.Name()); name != "" {
+ return name
+ }
+ if name := strings.TrimSpace(host.Hostname()); name != "" {
+ return name
+ }
+ return host.ID()
+}
+
+func formatAPTBytes(value int64) string {
+ const mib = int64(1024 * 1024)
+ if value < 1024*mib {
+ return fmt.Sprintf("%d MiB", value/mib)
+ }
+ return fmt.Sprintf("%.1f GiB", float64(value)/float64(1024*mib))
+}
+
+func verifyAPTWorkflowFinding(state patrolRuntimeState, findingKey, resourceID string, now time.Time) (bool, bool, error) {
+ if state.readState == nil {
+ state = state.withDerivedProviders()
+ }
+ if state.readState == nil {
+ return false, true, fmt.Errorf("%w: unified resource state unavailable", aicontracts.ErrVerificationUnknown)
+ }
+ for _, host := range state.readState.Hosts() {
+ if host == nil || host.ID() != resourceID {
+ continue
+ }
+ switch findingKey {
+ case aptHostUpdateFindingKey:
+ finding, known, cleared := aptHostUpdateFinding(host, now)
+ if !known {
+ return false, true, fmt.Errorf("%w: host update telemetry is not fresh and trustworthy", aicontracts.ErrVerificationUnknown)
+ }
+ return finding == nil && cleared, true, nil
+ case aptPackageCacheFindingKey:
+ finding, known, cleared := aptPackageCacheFinding(host, now)
+ if !known {
+ return false, true, fmt.Errorf("%w: package-cache telemetry is not fresh and trustworthy", aicontracts.ErrVerificationUnknown)
+ }
+ return finding == nil && cleared, true, nil
+ }
+ }
+ return false, true, fmt.Errorf("%w: governed host resource is no longer present", aicontracts.ErrVerificationUnknown)
+}
diff --git a/internal/ai/findings_apt_workflows_test.go b/internal/ai/findings_apt_workflows_test.go
new file mode 100644
index 0000000000..c2329a20dc
--- /dev/null
+++ b/internal/ai/findings_apt_workflows_test.go
@@ -0,0 +1,125 @@
+package ai
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ ur "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func aptWorkflowTestHost(now time.Time) *ur.HostView {
+ digestA := "sha256:" + strings.Repeat("a", 64)
+ digestB := "sha256:" + strings.Repeat("b", 64)
+ resource := &ur.Resource{
+ ID: "agent:host-1", Type: ur.ResourceTypeAgent, Name: "host-1", Status: ur.StatusOnline,
+ Capabilities: []ur.ResourceCapability{
+ {Name: "install_os_updates", InternalHandler: "host.package_updates"},
+ {Name: "clean_package_cache", InternalHandler: "host.storage_cleanup"},
+ },
+ Agent: &ur.AgentData{
+ AgentID: "host-1", CommandsEnabled: true,
+ PackageUpdates: &ur.AgentPackageUpdateMeta{Supported: true, Manager: "apt", InventoryHash: digestA, PendingCount: 3, CheckedAt: now.Add(-time.Minute), ObservedAt: now},
+ StorageCleanup: &ur.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: digestB, ReclaimableBytes: 128 * 1024 * 1024, CheckedAt: now.Add(-time.Minute), ObservedAt: now},
+ Disks: []ur.DiskInfo{{Mountpoint: "/", Usage: 95}},
+ },
+ }
+ view := ur.NewHostView(resource)
+ return &view
+}
+
+func TestAPTWorkflowWatcherEmitsDeterministicCapabilityBoundFindings(t *testing.T) {
+ now := time.Date(2026, 7, 12, 8, 0, 0, 0, time.UTC)
+ host := aptWorkflowTestHost(now)
+ emit, resolve := newAPTWorkflowWatcher().Observe(patrolRuntimeState{readState: &mockReadState{hosts: []*ur.HostView{host}}}, nil, now)
+ if len(emit) != 2 || len(resolve) != 0 {
+ t.Fatalf("emit=%d resolve=%d", len(emit), len(resolve))
+ }
+ if emit[0].ID != "apt:host-update:agent:host-1" || emit[1].ID != "apt:cache-cleanup:agent:host-1" {
+ t.Fatalf("unexpected stable ids: %q %q", emit[0].ID, emit[1].ID)
+ }
+ for _, finding := range emit {
+ lower := strings.ToLower(finding.Evidence + " " + finding.Description)
+ for _, forbidden := range []string{"apt-get", "/var/cache", "--no-remove", "dpkg"} {
+ if strings.Contains(lower, forbidden) {
+ t.Fatalf("finding exposed command/path %q: %s", forbidden, lower)
+ }
+ }
+ }
+}
+
+func TestAPTWorkflowWatcherReplayAndFutureTimesRemainUnresolved(t *testing.T) {
+ now := time.Date(2026, 7, 12, 8, 0, 0, 0, time.UTC)
+ active := []*Finding{{ID: "apt:host-update:agent:host-1", ResourceID: "agent:host-1", Source: aptWorkflowFindingSource}}
+ tests := []struct {
+ name string
+ checked time.Time
+ seen time.Time
+ }{
+ {name: "old agent observation retransmitted with fresh server receipt", checked: now.Add(-ur.HostPackageUpdateFreshness - time.Minute), seen: now},
+ {name: "future agent observation", checked: now.Add(ur.HostAPTTelemetryMaxClockSkew + time.Second), seen: now},
+ {name: "future server receipt", checked: now, seen: now.Add(ur.HostAPTTelemetryMaxClockSkew + time.Second)},
+ {name: "server receipt predates agent observation beyond skew", checked: now, seen: now.Add(-ur.HostAPTTelemetryMaxClockSkew - time.Second)},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ host := aptWorkflowTestHost(now)
+ host.PackageUpdates().CheckedAt = tc.checked // copy accessor proves callers cannot mutate authority
+ resource := hostResourceForAPTTest(host, now)
+ resource.Capabilities = resource.Capabilities[:1]
+ resource.Agent.StorageCleanup = nil
+ resource.Agent.PackageUpdates.CheckedAt, resource.Agent.PackageUpdates.ObservedAt = tc.checked, tc.seen
+ view := ur.NewHostView(resource)
+ emit, resolve := newAPTWorkflowWatcher().Observe(patrolRuntimeState{readState: &mockReadState{hosts: []*ur.HostView{&view}}}, active, now)
+ if len(emit) != 0 || len(resolve) != 0 {
+ t.Fatalf("stale/skewed telemetry emitted=%d resolved=%d", len(emit), len(resolve))
+ }
+ })
+ }
+}
+
+func TestAPTWorkflowWatcherCapabilityLossDoesNotResolveActiveFinding(t *testing.T) {
+ now := time.Date(2026, 7, 12, 8, 0, 0, 0, time.UTC)
+ resource := hostResourceForAPTTest(aptWorkflowTestHost(now), now)
+ resource.Agent.PackageUpdates.PendingCount = 0
+ resource.Capabilities = []ur.ResourceCapability{{Name: "replacement", InternalHandler: "host.package_updates"}}
+ view := ur.NewHostView(resource)
+ active := []*Finding{{ID: "apt:host-update:agent:host-1", ResourceID: "agent:host-1", Source: aptWorkflowFindingSource}}
+ emit, resolve := newAPTWorkflowWatcher().Observe(patrolRuntimeState{readState: &mockReadState{hosts: []*ur.HostView{&view}}}, active, now)
+ if len(emit) != 0 || len(resolve) != 0 {
+ t.Fatalf("capability loss emitted=%d resolved=%d", len(emit), len(resolve))
+ }
+ cleared, handled, err := verifyAPTWorkflowFinding(patrolRuntimeState{readState: &mockReadState{hosts: []*ur.HostView{&view}}}, aptHostUpdateFindingKey, resource.ID, now)
+ if cleared || !handled || err == nil {
+ t.Fatalf("verification cleared=%t handled=%t err=%v", cleared, handled, err)
+ }
+}
+
+func TestAPTWorkflowWatcherFreshClearReconcilesAndRemovalIsExplicit(t *testing.T) {
+ now := time.Date(2026, 7, 12, 8, 0, 0, 0, time.UTC)
+ resource := hostResourceForAPTTest(aptWorkflowTestHost(now), now)
+ resource.Agent.PackageUpdates.PendingCount = 0
+ view := ur.NewHostView(resource)
+ active := []*Finding{{ID: "apt:host-update:agent:host-1", ResourceID: "agent:host-1", Source: aptWorkflowFindingSource}}
+ _, resolve := newAPTWorkflowWatcher().Observe(patrolRuntimeState{readState: &mockReadState{hosts: []*ur.HostView{&view}}}, active, now)
+ if len(resolve) != 1 || resolve[0].Reason != aptWorkflowResolveCleared {
+ t.Fatalf("fresh clear resolve=%+v", resolve)
+ }
+ _, removed := newAPTWorkflowWatcher().Observe(patrolRuntimeState{readState: &mockReadState{}}, active, now)
+ if len(removed) != 1 || removed[0].Reason != aptWorkflowResolveRemoved {
+ t.Fatalf("removed resolve=%+v", removed)
+ }
+}
+
+func hostResourceForAPTTest(_ *ur.HostView, now time.Time) *ur.Resource {
+ digestA := "sha256:" + strings.Repeat("a", 64)
+ digestB := "sha256:" + strings.Repeat("b", 64)
+ return &ur.Resource{
+ ID: "agent:host-1", Type: ur.ResourceTypeAgent, Name: "host-1", Status: ur.StatusOnline,
+ Capabilities: []ur.ResourceCapability{{Name: "install_os_updates", InternalHandler: "host.package_updates"}, {Name: "clean_package_cache", InternalHandler: "host.storage_cleanup"}},
+ Agent: &ur.AgentData{AgentID: "host-1", CommandsEnabled: true,
+ PackageUpdates: &ur.AgentPackageUpdateMeta{Supported: true, Manager: "apt", InventoryHash: digestA, PendingCount: 3, CheckedAt: now.Add(-time.Minute), ObservedAt: now},
+ StorageCleanup: &ur.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: digestB, ReclaimableBytes: 128 * 1024 * 1024, CheckedAt: now.Add(-time.Minute), ObservedAt: now},
+ Disks: []ur.DiskInfo{{Mountpoint: "/", Usage: 95}}},
+ }
+}
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index fcd17f623c..9c589dfc3a 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -473,6 +473,7 @@ type PatrolService struct {
// lifetime; in-memory only, no goroutine.
stormThrottler *findingStormThrottler
updateSafetyWatcher *UpdateSafetyWatcher
+ aptWorkflowWatcher *aptWorkflowWatcher
// PDM alert bridge -- polls the PDM resource list on each patrol cycle
// and emits reliability findings for offline nodes and failed guests.
// Nil source makes Observe a no-op when PDM env configuration is absent.
@@ -701,6 +702,7 @@ func NewPatrolService(aiService *Service, stateProvider StateProvider) *PatrolSe
p.stormThrottler = newFindingStormThrottler()
p.findings.SetStormThrottler(p.stormThrottler)
p.updateSafetyWatcher = newUpdateSafetyWatcher()
+ p.aptWorkflowWatcher = newAPTWorkflowWatcher()
p.pdmAlertBridge = newPDMAlertBridge(newPDMAlertSourceFromEnv())
return p
}
diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.go
index e78a0e3082..1010d8cccf 100644
--- a/internal/ai/patrol_findings.go
+++ b/internal/ai/patrol_findings.go
@@ -1296,6 +1296,9 @@ func (p *PatrolService) verifyFixDeterministically(
// State-only verifiers (no tools required).
fullState := p.currentPatrolRuntimeState()
+ if resolved, handled, err := verifyAPTWorkflowFinding(fullState, key, resourceID, time.Now()); handled {
+ return resolved, err
+ }
switch key {
case "backup-stale":
ok, err := verifyBackupFreshState(fullState, resourceID)
diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.go
index 9e924a1243..b7cd8c48e8 100644
--- a/internal/ai/patrol_run.go
+++ b/internal/ai/patrol_run.go
@@ -431,6 +431,23 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
}
}
+ if cfg.AnalyzeHosts && p.aptWorkflowWatcher != nil {
+ aptEmit, aptResolve := p.aptWorkflowWatcher.Observe(state, p.findings.GetActive(FindingSeverityInfo), time.Now())
+ for _, f := range aptEmit {
+ trackFinding(f)
+ }
+ for _, sentinel := range aptResolve {
+ if p.findings.ResolveWithReason(sentinel.DedupKey, sentinel.Reason) {
+ p.mu.RLock()
+ resolveUnified := p.unifiedFindingResolver
+ p.mu.RUnlock()
+ if resolveUnified != nil {
+ resolveUnified(sentinel.DedupKey)
+ }
+ }
+ }
+ }
+
// Run PDM alert bridge on every patrol cycle if a source is configured.
// Nil source guard mirrors the MVP no-op behavior; the real HTTP client
// is wired in a follow-on. Direct FindingsStore.Add bypasses push.
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index fd6a3b153f..d3d6baf0e9 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -20037,13 +20037,22 @@ func TestContract_HostUpdatesUseTypedFingerprintBoundAgentOperation(t *testing.T
runtimeSrc := string(agentRuntimeSource)
for _, snippet := range []string{
"ExecuteHostUpdate(ctx context.Context, agentID string, req agentexec.HostUpdatePayload)",
+ "attempt, ok := actionlifecycle.DispatchAttemptFromContext(ctx)",
+ "if !ok || attempt.ActionID != record.ID",
+ "RequestID: attempt.ID",
+ "ActionID: record.ID",
"ExpectedInventoryHash: resource.Agent.PackageUpdates.InventoryHash",
"agentexec.HostUpdateOperationInstall",
+ "beforeBound := result.Before.InventoryHash == resource.Agent.PackageUpdates.InventoryHash",
+ "hostAPTExecutionResult(record.Request.ResourceID, agentID, agentexec.HostUpdateOperationInstall, output, result.Success, result.MutationStarted, result.Verification, beforeBound, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())",
} {
if !strings.Contains(executorSrc, snippet) {
t.Fatalf("host update executor missing typed operation invariant %q", snippet)
}
}
+ if strings.Contains(executorSrc, "func projectHostUpdateVerification") {
+ t.Fatal("host update executor must not reintroduce a local verification projection")
+ }
for _, snippet := range []string{
"ExpectedInventoryHash string `json:\"expected_inventory_hash\"`",
"const HostUpdateOperationInstall = \"install_os_updates\"",
@@ -20082,14 +20091,23 @@ func TestContract_HostStorageCleanupIsTypedFingerprintBoundAndPathFree(t *testin
runtimeSrc := string(agentRuntimeSource)
for _, snippet := range []string{
"ExecuteHostStorageCleanup(ctx context.Context, agentID string, req agentexec.HostStorageCleanupPayload)",
+ "attempt, ok := actionlifecycle.DispatchAttemptFromContext(ctx)",
+ "if !ok || attempt.ActionID != record.ID",
+ "RequestID: attempt.ID",
+ "ActionID: record.ID",
"resource.Agent.StorageCleanup.Fingerprint",
"agentexec.HostStorageCleanupOperationPackageCache",
"unified.HostStorageCleanupPressureDisk(resource.Agent.Disks)",
+ "beforeBound := result.Before.Fingerprint == resource.Agent.StorageCleanup.Fingerprint",
+ "hostAPTExecutionResult(record.Request.ResourceID, resource.Agent.AgentID, agentexec.HostStorageCleanupOperationPackageCache, output, result.Success, result.MutationStarted, result.Verification, beforeBound, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())",
} {
if !strings.Contains(executorSrc, snippet) {
t.Fatalf("host storage cleanup executor missing invariant %q", snippet)
}
}
+ if strings.Contains(executorSrc, "func projectHostStorageCleanupVerification") {
+ t.Fatal("host storage cleanup executor must not reintroduce a local verification projection")
+ }
for _, snippet := range []string{
"ExpectedFingerprint string `json:\"expected_fingerprint\"`",
"const HostStorageCleanupOperationPackageCache = \"clean_package_cache\"",
diff --git a/internal/api/host_apt_action_result.go b/internal/api/host_apt_action_result.go
new file mode 100644
index 0000000000..daaf408d86
--- /dev/null
+++ b/internal/api/host_apt_action_result.go
@@ -0,0 +1,69 @@
+package api
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func hostAPTExecutionResult(resourceID, agentID, operation, output string, success, mutationStarted bool, verification string, beforeStateBound bool, beforeObservedAt, afterObservedAt, receivedAt time.Time) (*unified.ExecutionResult, error) {
+ execution := unified.ActionExecutionTruth{Status: unified.ActionExecutionSucceeded, Summary: output}
+ if !success {
+ if mutationStarted {
+ execution = unified.ActionExecutionTruth{Status: unified.ActionExecutionInconclusive, ReasonCode: "possible_partial_effect", Summary: "The agent could not establish the final mutation outcome."}
+ } else {
+ execution = unified.ActionExecutionTruth{Status: unified.ActionExecutionNotRun, ReasonCode: "preflight_refused", Summary: "The typed host operation did not begin mutation."}
+ }
+ }
+
+ verificationTruth := unified.ActionVerificationTruth{Status: unified.ActionVerificationInconclusive, EvidenceClass: unified.ActionEvidenceNone, ReasonCode: "agent_readback_inconclusive", Summary: "The agent readback was inconclusive and did not establish the requested postcondition."}
+ if verification == agentexec.HostUpdateVerificationVerified || verification == agentexec.HostStorageCleanupVerificationVerified || verification == agentexec.HostUpdateVerificationFailed || verification == agentexec.HostStorageCleanupVerificationFailed {
+ if !beforeStateBound {
+ verificationTruth.ReasonCode = "before_state_mismatch"
+ verificationTruth.Summary = "The agent readback did not match the request-bound before state."
+ } else if !freshHostAPTResultObservation(beforeObservedAt, afterObservedAt, receivedAt) {
+ verificationTruth.ReasonCode = "stale_agent_readback"
+ verificationTruth.Summary = "The agent readback was stale, skewed, or had invalid mutation chronology."
+ } else {
+ evidence, err := unified.NormalizeActionEvidence(unified.ActionEvidence{
+ Version: unified.ActionEvidenceVersion, ID: operation + "-agent-readback", ObserverID: agentID,
+ ObserverKind: "unified_agent", ObserverTrustDomain: "agent:" + agentID, ExecutorTrustDomain: "agent:" + agentID,
+ Method: "typed_read_after_write", SubjectID: resourceID, ObservedAt: afterObservedAt.UTC(), ReceivedAt: receivedAt.UTC(),
+ Summary: "Bounded typed readback received from the mutating agent.",
+ })
+ if err == nil {
+ status := unified.ActionVerificationConfirmed
+ if verification == agentexec.HostUpdateVerificationFailed || verification == agentexec.HostStorageCleanupVerificationFailed {
+ status = unified.ActionVerificationContradicted
+ }
+ verificationTruth = unified.ActionVerificationTruth{Status: status, EvidenceClass: unified.ActionEvidenceAgentAttested, Evidence: []unified.ActionEvidence{evidence}, Summary: evidence.Summary}
+ }
+ }
+ }
+
+ canonical := unified.ActionResultV2{
+ Version: unified.ActionResultV2Version,
+ Execution: execution,
+ Verification: verificationTruth,
+ Compensation: unified.ActionCompensationTruth{Support: unified.ActionCompensationUnavailable, Status: unified.ActionCompensationNotAvailable},
+ }
+ legacy := &unified.ExecutionResult{Output: strings.TrimSpace(output)}
+ projected, _, err := unified.ApplyActionResultV2(legacy, canonical)
+ if err != nil {
+ return nil, fmt.Errorf("apply canonical host APT action truth: %w", err)
+ }
+ projected.Verification = unified.LegacyActionVerificationFromV2(*projected.ActionResultV2)
+ return projected, nil
+}
+
+func freshHostAPTResultObservation(before, after, receivedAt time.Time) bool {
+ if before.IsZero() || after.IsZero() || receivedAt.IsZero() || after.Before(before) {
+ return false
+ }
+ receivedAt = receivedAt.UTC()
+ after = after.UTC()
+ return !after.Before(receivedAt.Add(-15*time.Minute)) && !after.After(receivedAt.Add(unified.HostAPTTelemetryMaxClockSkew))
+}
diff --git a/internal/api/host_apt_action_result_test.go b/internal/api/host_apt_action_result_test.go
new file mode 100644
index 0000000000..245f9aa70b
--- /dev/null
+++ b/internal/api/host_apt_action_result_test.go
@@ -0,0 +1,77 @@
+package api
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func TestHostAPTActionResultRefreshFailureIsPossiblePartialEffect(t *testing.T) {
+ now := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ result, err := hostAPTExecutionResult("agent:host-1", "host-1", agentexec.HostUpdateOperationInstall, "refresh failed", false, true, agentexec.HostUpdateVerificationInconclusive, true, time.Time{}, time.Time{}, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.ActionResultV2.Execution.Status != unified.ActionExecutionInconclusive || result.ActionResultV2.Execution.ReasonCode != "possible_partial_effect" || result.ActionResultV2.Execution.Status == unified.ActionExecutionNotRun {
+ t.Fatalf("canonical execution truth = %#v", result.ActionResultV2.Execution)
+ }
+ if result.ActionResultV2.Compensation.Support != unified.ActionCompensationUnavailable || result.ActionResultV2.Compensation.Status != unified.ActionCompensationNotAvailable {
+ t.Fatalf("compensation truth = %#v", result.ActionResultV2.Compensation)
+ }
+}
+
+func TestHostAPTActionResultPreservesAgentObservedAndServerReceivedTimes(t *testing.T) {
+ checkedAt := time.Date(2026, 7, 12, 8, 59, 0, 0, time.UTC)
+ observedAt := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ result, err := hostAPTExecutionResult("agent:host-1", "host-1", agentexec.HostUpdateOperationInstall, "updates complete", true, true, agentexec.HostUpdateVerificationVerified, true, checkedAt.Add(-time.Second), checkedAt, observedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := result.ActionResultV2.Verification
+ if truth.Status != unified.ActionVerificationConfirmed || truth.EvidenceClass != unified.ActionEvidenceAgentAttested || len(truth.Evidence) != 1 {
+ t.Fatalf("verification truth = %#v", truth)
+ }
+ if !truth.Evidence[0].ObservedAt.Equal(checkedAt) || !truth.Evidence[0].ReceivedAt.Equal(observedAt) {
+ t.Fatalf("evidence timestamps = %#v", truth.Evidence[0])
+ }
+ if truth.Evidence[0].ObserverTrustDomain != truth.Evidence[0].ExecutorTrustDomain {
+ t.Fatalf("same-agent evidence was falsely independent: %#v", truth.Evidence[0])
+ }
+}
+
+func TestHostAPTActionResultFutureVerifiedClaimFailsClosed(t *testing.T) {
+ now := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ result, err := hostAPTExecutionResult("agent:host-1", "host-1", agentexec.HostUpdateOperationInstall, "updates complete", true, true, agentexec.HostUpdateVerificationVerified, true, now, now.Add(unified.HostAPTTelemetryMaxClockSkew+time.Second), now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.ActionResultV2.Verification.Status != unified.ActionVerificationInconclusive || result.ActionResultV2.Verification.EvidenceClass != unified.ActionEvidenceNone {
+ t.Fatalf("future evidence did not fail closed: %#v", result.ActionResultV2.Verification)
+ }
+}
+
+func TestHostAPTActionResultStaleReadbackFailsClosed(t *testing.T) {
+ now := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ result, err := hostAPTExecutionResult("agent:host-1", "host-1", agentexec.HostUpdateOperationInstall, "updates complete", true, true, agentexec.HostUpdateVerificationVerified, true, now.Add(-time.Hour-time.Minute), now.Add(-time.Hour), now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := result.ActionResultV2.Verification
+ if truth.Status != unified.ActionVerificationInconclusive || truth.EvidenceClass != unified.ActionEvidenceNone || truth.ReasonCode != "stale_agent_readback" {
+ t.Fatalf("stale readback truth=%#v", truth)
+ }
+}
+
+func TestHostAPTActionResultBeforeStateMismatchCannotBecomeContradictionEvidence(t *testing.T) {
+ now := time.Date(2026, 7, 12, 9, 0, 0, 0, time.UTC)
+ result, err := hostAPTExecutionResult("agent:host-1", "host-1", agentexec.HostStorageCleanupOperationPackageCache, "cleanup contradicted", true, true, agentexec.HostStorageCleanupVerificationFailed, false, now.Add(-time.Minute), now, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ truth := result.ActionResultV2.Verification
+ if truth.Status != unified.ActionVerificationInconclusive || truth.EvidenceClass != unified.ActionEvidenceNone || truth.ReasonCode != "before_state_mismatch" {
+ t.Fatalf("mismatched before-state truth=%#v", truth)
+ }
+}
diff --git a/internal/api/host_storage_cleanup_action_executor.go b/internal/api/host_storage_cleanup_action_executor.go
index 08fc1793d2..82020f432e 100644
--- a/internal/api/host_storage_cleanup_action_executor.go
+++ b/internal/api/host_storage_cleanup_action_executor.go
@@ -91,15 +91,8 @@ func (e hostStorageCleanupActionExecutor) ExecuteAction(ctx context.Context, rec
}
output := fmt.Sprintf("APT package cache: %d bytes before, %d bytes after, %d bytes reclaimed", result.Before.ReclaimableBytes, result.After.ReclaimableBytes, result.ReclaimedBytes)
- execution := &unified.ExecutionResult{
- Success: result.Success,
- Output: output,
- Verification: projectHostStorageCleanupVerification(result),
- }
- if !result.Success {
- execution.ErrorMessage = "host package-cache cleanup failed on the agent"
- }
- return execution, nil
+ beforeBound := result.Before.Fingerprint == resource.Agent.StorageCleanup.Fingerprint
+ return hostAPTExecutionResult(record.Request.ResourceID, resource.Agent.AgentID, agentexec.HostStorageCleanupOperationPackageCache, output, result.Success, result.MutationStarted, result.Verification, beforeBound, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())
}
func (e hostStorageCleanupActionExecutor) currentResource(ctx context.Context, resourceID string) (unified.Resource, error) {
@@ -141,7 +134,7 @@ func (e hostStorageCleanupActionExecutor) validateResource(resource unified.Reso
if !hostStorageCleanupFingerprintPattern.MatchString(strings.TrimSpace(status.Fingerprint)) {
return fmt.Errorf("host storage cleanup fingerprint is invalid")
}
- if status.CheckedAt.IsZero() || e.currentTime().Sub(status.CheckedAt.UTC()) > unified.HostStorageCleanupFreshness {
+ if !unified.HostStorageCleanupTelemetryFresh(status, e.currentTime()) {
return fmt.Errorf("host storage cleanup inventory is stale")
}
if status.ReclaimableBytes < unified.HostStorageCleanupMinReclaimableBytes {
@@ -164,24 +157,6 @@ func (e hostStorageCleanupActionExecutor) currentTime() time.Time {
return time.Now().UTC()
}
-func projectHostStorageCleanupVerification(result *agentexec.HostStorageCleanupResultPayload) *unified.ActionVerificationResult {
- if result == nil {
- return &unified.ActionVerificationResult{Ran: false, Note: "agent returned no verification evidence"}
- }
- note := fmt.Sprintf("package cache bytes %d -> %d; reclaimed=%d", result.Before.ReclaimableBytes, result.After.ReclaimableBytes, result.ReclaimedBytes)
- switch strings.TrimSpace(result.Verification) {
- case agentexec.HostStorageCleanupVerificationVerified:
- if !result.Success || !result.After.Supported || result.After.Provider != "apt-package-cache" || result.After.Error != "" || !hostStorageCleanupFingerprintPattern.MatchString(result.After.Fingerprint) || result.ReclaimedBytes <= 0 || result.After.ReclaimableBytes >= result.Before.ReclaimableBytes {
- return &unified.ActionVerificationResult{Ran: false, Note: "agent returned invalid verification evidence"}
- }
- return &unified.ActionVerificationResult{Ran: true, Success: true, Command: "typed:host_storage_cleanup/clean_package_cache", Output: note, Note: note, RanAt: time.Now().UTC()}
- case agentexec.HostStorageCleanupVerificationFailed:
- return &unified.ActionVerificationResult{Ran: true, Success: false, Command: "typed:host_storage_cleanup/clean_package_cache", Output: note, Note: "post-cleanup cache inspection did not confirm reclaimed space", RanAt: time.Now().UTC()}
- default:
- return &unified.ActionVerificationResult{Ran: false, Note: "post-cleanup package-cache inspection was inconclusive"}
- }
-}
-
func hostStorageCleanupUnavailableReasonCode(err error) string {
if err == nil {
return "unavailable"
diff --git a/internal/api/host_storage_cleanup_action_executor_test.go b/internal/api/host_storage_cleanup_action_executor_test.go
index 921320ed31..f392f48633 100644
--- a/internal/api/host_storage_cleanup_action_executor_test.go
+++ b/internal/api/host_storage_cleanup_action_executor_test.go
@@ -157,10 +157,11 @@ func TestHostStorageCleanupAvailabilityFailsClosed(t *testing.T) {
}
func verifiedHostStorageCleanupAgent() *fakeHostStorageCleanupAgent {
+ now := time.Now().UTC()
return &fakeHostStorageCleanupAgent{connected: true, result: &agentexec.HostStorageCleanupResultPayload{
RequestID: "filled-by-executor", Success: true,
- Before: agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupFingerprint, ReclaimableBytes: 512 * 1024 * 1024},
- After: agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupAfterFingerprint, ReclaimableBytes: 8 * 1024 * 1024},
+ Before: agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupFingerprint, ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now.Add(-time.Second)},
+ After: agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupAfterFingerprint, ReclaimableBytes: 8 * 1024 * 1024, CheckedAt: now},
ReclaimedBytes: 504 * 1024 * 1024,
Verification: agentexec.HostStorageCleanupVerificationVerified,
}}
@@ -174,7 +175,7 @@ func hostStorageCleanupActionResource(now time.Time) unified.Resource {
Agent: &unified.AgentData{
AgentID: "agent-1", Platform: "linux", CommandsEnabled: true,
Disks: []unified.DiskInfo{{Mountpoint: "/", Usage: 95}},
- StorageCleanup: &unified.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupFingerprint, ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now},
+ StorageCleanup: &unified.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupFingerprint, ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now, ObservedAt: now},
},
Capabilities: []unified.ResourceCapability{{
Name: hostStorageCleanupCapability, Type: unified.CapabilityTypeCommon,
diff --git a/internal/api/host_update_action_executor.go b/internal/api/host_update_action_executor.go
index 2e7ed18b50..af7ffa945a 100644
--- a/internal/api/host_update_action_executor.go
+++ b/internal/api/host_update_action_executor.go
@@ -92,15 +92,8 @@ func (e hostUpdateActionExecutor) ExecuteAction(ctx context.Context, record unif
}
output := fmt.Sprintf("APT package updates: %d pending before, %d pending after; reboot required: %t", result.Before.PendingCount, result.After.PendingCount, result.After.RebootRequired)
- execution := &unified.ExecutionResult{
- Success: result.Success,
- Output: output,
- Verification: projectHostUpdateVerification(result),
- }
- if !result.Success {
- execution.ErrorMessage = "host package update failed on the agent"
- }
- return execution, nil
+ beforeBound := result.Before.InventoryHash == resource.Agent.PackageUpdates.InventoryHash
+ return hostAPTExecutionResult(record.Request.ResourceID, agentID, agentexec.HostUpdateOperationInstall, output, result.Success, result.MutationStarted, result.Verification, beforeBound, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())
}
func (e hostUpdateActionExecutor) currentResource(ctx context.Context, resourceID string) (unified.Resource, error) {
@@ -142,7 +135,7 @@ func (e hostUpdateActionExecutor) validateResource(resource unified.Resource) er
if !hostPackageUpdateInventoryHashPattern.MatchString(strings.TrimSpace(status.InventoryHash)) {
return fmt.Errorf("host package update inventory fingerprint is invalid")
}
- if status.CheckedAt.IsZero() || e.currentTime().Sub(status.CheckedAt.UTC()) > unified.HostPackageUpdateFreshness {
+ if !unified.HostPackageUpdateTelemetryFresh(status, e.currentTime()) {
return fmt.Errorf("host package update inventory is stale")
}
if status.PendingCount <= 0 {
@@ -162,24 +155,6 @@ func (e hostUpdateActionExecutor) currentTime() time.Time {
return time.Now().UTC()
}
-func projectHostUpdateVerification(result *agentexec.HostUpdateResultPayload) *unified.ActionVerificationResult {
- if result == nil {
- return &unified.ActionVerificationResult{Ran: false, Note: "agent returned no verification evidence"}
- }
- note := fmt.Sprintf("pending packages %d -> %d; reboot required=%t", result.Before.PendingCount, result.After.PendingCount, result.After.RebootRequired)
- switch strings.TrimSpace(result.Verification) {
- case agentexec.HostUpdateVerificationVerified:
- if !result.Success || !result.After.Supported || result.After.Manager != "apt" || result.After.PendingCount != 0 || !hostPackageUpdateInventoryHashPattern.MatchString(result.After.InventoryHash) {
- return &unified.ActionVerificationResult{Ran: false, Note: "agent returned invalid verification evidence"}
- }
- return &unified.ActionVerificationResult{Ran: true, Success: true, Command: "typed:host_update/install_os_updates", Output: note, Note: note, RanAt: time.Now().UTC()}
- case agentexec.HostUpdateVerificationFailed:
- return &unified.ActionVerificationResult{Ran: true, Success: false, Command: "typed:host_update/install_os_updates", Output: note, Note: "post-update package inventory did not confirm the intended state", RanAt: time.Now().UTC()}
- default:
- return &unified.ActionVerificationResult{Ran: false, Note: "post-update package inventory was inconclusive"}
- }
-}
-
func hostUpdateUnavailableReasonCode(err error) string {
if err == nil {
return "unavailable"
diff --git a/internal/api/host_update_action_executor_test.go b/internal/api/host_update_action_executor_test.go
index 71bb0ef85e..6e634402bc 100644
--- a/internal/api/host_update_action_executor_test.go
+++ b/internal/api/host_update_action_executor_test.go
@@ -42,8 +42,8 @@ func TestHostUpdateActionExecutorDispatchesTypedOperationAndProjectsVerification
agents := &fakeHostUpdateAgent{connected: true, result: &agentexec.HostUpdateResultPayload{
RequestID: "action-host-update",
Success: true,
- Before: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageInventoryHash, PendingCount: 3},
- After: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageEmptyInventoryHash, PendingCount: 0, RebootRequired: true},
+ Before: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageInventoryHash, PendingCount: 3, CheckedAt: now.Add(-time.Second)},
+ After: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageEmptyInventoryHash, PendingCount: 0, RebootRequired: true, CheckedAt: now},
Verification: agentexec.HostUpdateVerificationVerified,
}}
executor := newHostUpdateActionExecutor(h, agents)
@@ -83,7 +83,7 @@ func TestHostUpdateActionExecutorReportsInconclusiveVerificationHonestly(t *test
if err != nil {
t.Fatalf("ExecuteAction: %v", err)
}
- if result == nil || !result.Success || result.Verification == nil || result.Verification.Ran || !strings.Contains(result.Verification.Note, "inconclusive") {
+ if result == nil || !result.Success || result.Verification == nil || result.Verification.Ran || result.ActionResultV2 == nil || result.ActionResultV2.Verification.Status != unified.ActionVerificationInconclusive || result.ActionResultV2.Verification.ReasonCode != "agent_readback_inconclusive" {
t.Fatalf("result = %#v", result)
}
}
@@ -94,8 +94,8 @@ func TestPatrolFullModeRunsHostUpdateThroughCanonicalLifecycle(t *testing.T) {
h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{hostUpdateActionResource(now)}})
agents := &fakeHostUpdateAgent{connected: true, result: &agentexec.HostUpdateResultPayload{
RequestID: "filled-by-executor", Success: true,
- Before: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageInventoryHash, PendingCount: 3},
- After: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageEmptyInventoryHash, PendingCount: 0},
+ Before: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageInventoryHash, PendingCount: 3, CheckedAt: now.Add(-time.Second)},
+ After: agentexec.HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: testHostPackageEmptyInventoryHash, PendingCount: 0, CheckedAt: now},
Verification: agentexec.HostUpdateVerificationVerified,
}}
h.SetActionExecutor(newRoutedActionExecutor(h, newHostUpdateActionExecutor(h, agents)))
@@ -173,7 +173,7 @@ func hostUpdateActionResource(now time.Time) unified.Resource {
SourceStatus: map[unified.DataSource]unified.SourceStatus{unified.SourceAgent: {Status: "online", LastSeen: now}},
Agent: &unified.AgentData{
AgentID: "agent-1", Platform: "linux", CommandsEnabled: true,
- PackageUpdates: &unified.AgentPackageUpdateMeta{Supported: true, Manager: "apt", InventoryHash: testHostPackageInventoryHash, PendingCount: 3, CheckedAt: now},
+ PackageUpdates: &unified.AgentPackageUpdateMeta{Supported: true, Manager: "apt", InventoryHash: testHostPackageInventoryHash, PendingCount: 3, CheckedAt: now, ObservedAt: now},
},
Capabilities: []unified.ResourceCapability{{
Name: hostPackageUpdateCapability, Type: unified.CapabilityTypeCommon,
diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.go
index a6d1e5507d..edcbb85a8f 100644
--- a/internal/hostagent/agent.go
+++ b/internal/hostagent/agent.go
@@ -317,14 +317,9 @@ func New(cfg Config) (*Agent, error) {
}
packageUpdates := cfg.packageUpdates
- if packageUpdates == nil {
- packageUpdates = newPackageUpdateManager(platform)
- }
- cfg.packageUpdates = packageUpdates
storageCleanup := cfg.storageCleanup
- if storageCleanup == nil {
- storageCleanup = newStorageCleanupManager(platform)
- }
+ packageUpdates, storageCleanup = configurePackageManagers(platform, packageUpdates, storageCleanup)
+ cfg.packageUpdates = packageUpdates
cfg.storageCleanup = storageCleanup
agent := &Agent{
@@ -847,7 +842,9 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {
packageUpdateCtx, cancelPackageUpdates := context.WithTimeout(ctx, 20*time.Second)
packageUpdates := a.currentPackageUpdateStatus(packageUpdateCtx)
cancelPackageUpdates()
- storageCleanup := a.currentStorageCleanupStatus()
+ storageCleanupCtx, cancelStorageCleanup := context.WithTimeout(ctx, 20*time.Second)
+ storageCleanup := a.currentStorageCleanupStatus(storageCleanupCtx)
+ cancelStorageCleanup()
// Carry updated_from on the first freshly built v6 report only. If that
// report is buffered, the buffered copy still retains the field for retry.
@@ -932,11 +929,11 @@ func (a *Agent) currentPackageUpdateStatus(ctx context.Context) *agentshost.Pack
}
}
-func (a *Agent) currentStorageCleanupStatus() *agentshost.StorageCleanupStatus {
+func (a *Agent) currentStorageCleanupStatus(ctx context.Context) *agentshost.StorageCleanupStatus {
if a == nil || a.storageCleanup == nil {
return nil
}
- snapshot := a.storageCleanup.Snapshot(false)
+ snapshot := a.storageCleanup.Snapshot(ctx, false)
return &agentshost.StorageCleanupStatus{
Supported: snapshot.Supported,
Provider: snapshot.Provider,
diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.go
index f8a185ba58..c43bdaea2e 100644
--- a/internal/hostagent/commands.go
+++ b/internal/hostagent/commands.go
@@ -529,16 +529,16 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn
go c.handleExecuteCommand(ctx, conn, payload)
case msgTypeHostUpdate:
- var payload agentexec.HostUpdatePayload
- if err := json.Unmarshal(msg.Payload, &payload); err != nil {
+ payload, err := agentexec.DecodeHostUpdatePayload(msg.Payload)
+ if err != nil {
c.logger.Error().Err(err).Msg("Failed to parse host_update payload")
continue
}
go c.handleHostUpdate(ctx, conn, payload)
case msgTypeHostStorageCleanup:
- var payload agentexec.HostStorageCleanupPayload
- if err := json.Unmarshal(msg.Payload, &payload); err != nil {
+ payload, err := agentexec.DecodeHostStorageCleanupPayload(msg.Payload)
+ if err != nil {
c.logger.Error().Err(err).Msg("Failed to parse host_storage_cleanup payload")
continue
}
@@ -583,23 +583,26 @@ func (c *CommandClient) handleHostUpdate(ctx context.Context, conn *websocket.Co
defer cancel()
result := agentexec.HostUpdateResultPayload{
- RequestID: strings.TrimSpace(payload.RequestID),
- Verification: agentexec.HostUpdateVerificationInconclusive,
+ RequestID: strings.TrimSpace(payload.RequestID), ActionID: strings.TrimSpace(payload.ActionID),
+ ExecutionPhase: agentexec.HostUpdatePhasePreflight, Verification: agentexec.HostUpdateVerificationInconclusive,
}
if c.packageUpdates == nil {
result.Error = "host package update service is unavailable"
} else {
result = c.packageUpdates.Apply(updateCtx, payload)
}
+ c.sendHostUpdateResult(conn, result)
+}
+func (c *CommandClient) sendHostUpdateResult(conn *websocket.Conn, result agentexec.HostUpdateResultPayload) {
encoded, err := json.Marshal(result)
if err != nil {
- c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to marshal host update result")
+ c.logger.Error().Err(err).Str("request_id", result.RequestID).Msg("Failed to marshal host update result")
return
}
msg := wsMessage{
Type: msgTypeHostUpdateResult,
- ID: payload.RequestID,
+ ID: result.RequestID,
Timestamp: time.Now(),
Payload: encoded,
}
@@ -607,7 +610,7 @@ func (c *CommandClient) handleHostUpdate(ctx context.Context, conn *websocket.Co
err = conn.WriteJSON(msg)
c.connMu.Unlock()
if err != nil {
- c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to send host update result")
+ c.logger.Error().Err(err).Str("request_id", result.RequestID).Msg("Failed to send host update result")
}
}
@@ -620,23 +623,26 @@ func (c *CommandClient) handleHostStorageCleanup(ctx context.Context, conn *webs
defer cancel()
result := agentexec.HostStorageCleanupResultPayload{
- RequestID: strings.TrimSpace(payload.RequestID),
- Verification: agentexec.HostStorageCleanupVerificationInconclusive,
+ RequestID: strings.TrimSpace(payload.RequestID), ActionID: strings.TrimSpace(payload.ActionID),
+ ExecutionPhase: agentexec.HostStorageCleanupPhasePreflight, Verification: agentexec.HostStorageCleanupVerificationInconclusive,
}
if c.storageCleanup == nil {
result.Error = "host storage cleanup service is unavailable"
} else {
result = c.storageCleanup.Apply(cleanupCtx, payload)
}
+ c.sendHostStorageCleanupResult(conn, result)
+}
+func (c *CommandClient) sendHostStorageCleanupResult(conn *websocket.Conn, result agentexec.HostStorageCleanupResultPayload) {
encoded, err := json.Marshal(result)
if err != nil {
- c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to marshal host storage cleanup result")
+ c.logger.Error().Err(err).Str("request_id", result.RequestID).Msg("Failed to marshal host storage cleanup result")
return
}
msg := wsMessage{
Type: msgTypeHostStorageCleanupResult,
- ID: payload.RequestID,
+ ID: result.RequestID,
Timestamp: time.Now(),
Payload: encoded,
}
@@ -644,7 +650,7 @@ func (c *CommandClient) handleHostStorageCleanup(ctx context.Context, conn *webs
err = conn.WriteJSON(msg)
c.connMu.Unlock()
if err != nil {
- c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to send host storage cleanup result")
+ c.logger.Error().Err(err).Str("request_id", result.RequestID).Msg("Failed to send host storage cleanup result")
}
}
diff --git a/internal/hostagent/commands_host_update_test.go b/internal/hostagent/commands_host_update_test.go
index 8136d38a19..6e6b5a937d 100644
--- a/internal/hostagent/commands_host_update_test.go
+++ b/internal/hostagent/commands_host_update_test.go
@@ -16,7 +16,7 @@ import (
)
func TestCommandClientHandlesTypedHostUpdateWithoutExecuteCommand(t *testing.T) {
- manager := newPackageUpdateManager("linux")
+ manager := newPackageUpdateManager("linux", newPackageManagerLease())
manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
manager.stat = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }
simulations := 0
diff --git a/internal/hostagent/commands_storage_cleanup_test.go b/internal/hostagent/commands_storage_cleanup_test.go
index 0cf6aaba3d..d1dcb576d4 100644
--- a/internal/hostagent/commands_storage_cleanup_test.go
+++ b/internal/hostagent/commands_storage_cleanup_test.go
@@ -18,7 +18,7 @@ func TestCommandClientHandlesTypedHostStorageCleanup(t *testing.T) {
before := agentexec.HostStorageCleanupSnapshot{Fingerprint: "sha256:" + strings.Repeat("a", 64), ReclaimableBytes: 512}
after := agentexec.HostStorageCleanupSnapshot{Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 12}
snapshots := []agentexec.HostStorageCleanupSnapshot{before, after}
- manager := newStorageCleanupManager("linux")
+ manager := newStorageCleanupManager("linux", newPackageManagerLease())
manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
manager.scan = func() (agentexec.HostStorageCleanupSnapshot, error) {
snapshot := snapshots[0]
diff --git a/internal/hostagent/package_manager_lease.go b/internal/hostagent/package_manager_lease.go
new file mode 100644
index 0000000000..dcd9f4e5f1
--- /dev/null
+++ b/internal/hostagent/package_manager_lease.go
@@ -0,0 +1,56 @@
+package hostagent
+
+import (
+ "context"
+ "fmt"
+ "sync"
+)
+
+// packageManagerLease is the single host-local authority for every APT-backed
+// inspection and mutation. Keeping this above the individual managers prevents
+// telemetry refresh from racing an update or cache cleanup.
+type packageManagerLease struct {
+ once sync.Once
+ ch chan struct{}
+}
+
+func newPackageManagerLease() *packageManagerLease {
+ lease := &packageManagerLease{}
+ lease.init()
+ return lease
+}
+
+func configurePackageManagers(platform string, updates *packageUpdateManager, cleanup *storageCleanupManager) (*packageUpdateManager, *storageCleanupManager) {
+ lease := newPackageManagerLease()
+ if updates == nil {
+ updates = newPackageUpdateManager(platform, lease)
+ } else {
+ updates.lease = lease
+ }
+ if cleanup == nil {
+ cleanup = newStorageCleanupManager(platform, lease)
+ } else {
+ cleanup.lease = lease
+ }
+ return updates, cleanup
+}
+
+func (l *packageManagerLease) init() {
+ l.once.Do(func() {
+ l.ch = make(chan struct{}, 1)
+ l.ch <- struct{}{}
+ })
+}
+
+func (l *packageManagerLease) acquire(ctx context.Context) (func(), error) {
+ if l == nil {
+ return nil, fmt.Errorf("shared package manager lease is required")
+ }
+ l.init()
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-l.ch:
+ return func() { l.ch <- struct{}{} }, nil
+ }
+}
diff --git a/internal/hostagent/package_manager_lease_test.go b/internal/hostagent/package_manager_lease_test.go
new file mode 100644
index 0000000000..189b560d14
--- /dev/null
+++ b/internal/hostagent/package_manager_lease_test.go
@@ -0,0 +1,75 @@
+package hostagent
+
+import (
+ "context"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+)
+
+func TestPackageManagerLeaseNilFailsClosed(t *testing.T) {
+ if release, err := (*packageManagerLease)(nil).acquire(context.Background()); err == nil || release != nil {
+ t.Fatalf("nil lease acquire returned a release function=%t err=%v", release != nil, err)
+ }
+ manager := newPackageUpdateManager("linux", nil)
+ called := false
+ manager.run = func(context.Context, []string, string, ...string) packageUpdateCommandResult {
+ called = true
+ return packageUpdateCommandResult{}
+ }
+ snapshot := manager.Snapshot(context.Background(), true)
+ if called || snapshot.Error == "" {
+ t.Fatalf("nil lease did not fail closed: called=%t snapshot=%#v", called, snapshot)
+ }
+}
+
+func TestConfigurePackageManagersInjectsOneSharedLeaseAndSerializesRefresh(t *testing.T) {
+ updates, cleanup := configurePackageManagers("linux", nil, nil)
+ if updates.lease == nil || cleanup.lease == nil || updates.lease != cleanup.lease {
+ t.Fatalf("managers do not share one lease: update=%p cleanup=%p", updates.lease, cleanup.lease)
+ }
+ updates.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
+ cleanup.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
+ entered := make(chan struct{})
+ releaseUpdate := make(chan struct{})
+ updates.run = func(context.Context, []string, string, ...string) packageUpdateCommandResult {
+ close(entered)
+ <-releaseUpdate
+ return packageUpdateCommandResult{}
+ }
+ var cleanupEntered atomic.Bool
+ cleanup.scan = func() (agentexec.HostStorageCleanupSnapshot, error) {
+ cleanupEntered.Store(true)
+ return agentexec.HostStorageCleanupSnapshot{}, nil
+ }
+ doneUpdate := make(chan struct{})
+ go func() { updates.Snapshot(context.Background(), true); close(doneUpdate) }()
+ <-entered
+ doneCleanup := make(chan struct{})
+ go func() { cleanup.Snapshot(context.Background(), true); close(doneCleanup) }()
+ time.Sleep(25 * time.Millisecond)
+ if cleanupEntered.Load() {
+ t.Fatal("cleanup refresh entered while update refresh held the shared lease")
+ }
+ close(releaseUpdate)
+ <-doneUpdate
+ select {
+ case <-doneCleanup:
+ case <-time.After(time.Second):
+ t.Fatal("cleanup refresh did not proceed after shared lease release")
+ }
+ if !cleanupEntered.Load() {
+ t.Fatal("cleanup refresh never entered")
+ }
+}
+
+func TestConfigurePackageManagersRebindsInjectedManagersToOneAuthority(t *testing.T) {
+ updates := newPackageUpdateManager("linux", nil)
+ cleanup := newStorageCleanupManager("linux", nil)
+ gotUpdates, gotCleanup := configurePackageManagers("linux", updates, cleanup)
+ if gotUpdates != updates || gotCleanup != cleanup || gotUpdates.lease == nil || gotUpdates.lease != gotCleanup.lease {
+ t.Fatal("runtime composition did not inject one shared package manager authority")
+ }
+}
diff --git a/internal/hostagent/package_updates.go b/internal/hostagent/package_updates.go
index 2bc9353380..c158612c85 100644
--- a/internal/hostagent/package_updates.go
+++ b/internal/hostagent/package_updates.go
@@ -37,12 +37,13 @@ type packageUpdateManager struct {
run func(context.Context, []string, string, ...string) packageUpdateCommandResult
lookPath func(string) (string, error)
stat func(string) (os.FileInfo, error)
+ lease *packageManagerLease
mu sync.Mutex
cached *agentexec.HostPackageUpdateSnapshot
}
-func newPackageUpdateManager(platform string) *packageUpdateManager {
+func newPackageUpdateManager(platform string, lease *packageManagerLease) *packageUpdateManager {
return &packageUpdateManager{
platform: strings.ToLower(strings.TrimSpace(platform)),
now: time.Now,
@@ -50,6 +51,7 @@ func newPackageUpdateManager(platform string) *packageUpdateManager {
run: runPackageUpdateCommand,
lookPath: packageUpdateLookPath,
stat: packageUpdateStat,
+ lease: lease,
}
}
@@ -57,6 +59,11 @@ func (m *packageUpdateManager) Snapshot(ctx context.Context, force bool) agentex
if m == nil {
return agentexec.HostPackageUpdateSnapshot{}
}
+ release, err := m.lease.acquire(ctx)
+ if err != nil {
+ return agentexec.HostPackageUpdateSnapshot{CheckedAt: m.currentTime(), Error: "package update inspection canceled"}
+ }
+ defer release()
m.mu.Lock()
defer m.mu.Unlock()
return m.snapshotLocked(ctx, force)
@@ -98,7 +105,10 @@ func (m *packageUpdateManager) snapshotLocked(ctx context.Context, force bool) a
func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpdatePayload) (result agentexec.HostUpdateResultPayload) {
startedAt := time.Now()
- result = agentexec.HostUpdateResultPayload{RequestID: strings.TrimSpace(req.RequestID)}
+ result = agentexec.HostUpdateResultPayload{
+ RequestID: strings.TrimSpace(req.RequestID), ActionID: strings.TrimSpace(req.ActionID),
+ ExecutionPhase: agentexec.HostUpdatePhasePreflight,
+ }
defer func() { result.Duration = time.Since(startedAt).Milliseconds() }()
if strings.TrimSpace(req.Operation) != agentexec.HostUpdateOperationInstall {
@@ -106,6 +116,13 @@ func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpda
result.Error = "unsupported typed host update operation"
return result
}
+ release, err := m.lease.acquire(ctx)
+ if err != nil {
+ result.Verification = agentexec.HostUpdateVerificationInconclusive
+ result.Error = "package manager lease unavailable"
+ return result
+ }
+ defer release()
m.mu.Lock()
defer m.mu.Unlock()
@@ -119,6 +136,8 @@ func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpda
return result
}
+ result.ExecutionPhase = agentexec.HostUpdatePhaseRefresh
+ result.MutationStarted = true
refresh := m.run(ctx, nil, "apt-get", "update")
if refresh.err != nil || refresh.exitCode != 0 {
result.Before = probe
@@ -144,6 +163,7 @@ func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpda
}
if before.PendingCount == 0 {
result.Success = true
+ result.ExecutionPhase = agentexec.HostUpdatePhaseComplete
result.After = before
result.Verification = agentexec.HostUpdateVerificationVerified
return result
@@ -154,6 +174,7 @@ func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpda
"APT_LISTCHANGES_FRONTEND=none",
"NEEDRESTART_MODE=a",
}
+ result.ExecutionPhase = agentexec.HostUpdatePhaseInstall
install := m.run(ctx, env, "apt-get", "-y", "--no-remove", "-o", "Dpkg::Options::=--force-confold", "upgrade")
if install.err != nil || install.exitCode != 0 {
after := m.snapshotLocked(ctx, true)
@@ -164,6 +185,7 @@ func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpda
}
result.Success = true
+ result.ExecutionPhase = agentexec.HostUpdatePhaseVerify
after := m.snapshotLocked(ctx, true)
result.After = after
if after.Error != "" {
@@ -177,6 +199,7 @@ func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpda
return result
}
result.Verification = agentexec.HostUpdateVerificationVerified
+ result.ExecutionPhase = agentexec.HostUpdatePhaseComplete
return result
}
diff --git a/internal/hostagent/package_updates_test.go b/internal/hostagent/package_updates_test.go
index 5c839aa407..4ed142c821 100644
--- a/internal/hostagent/package_updates_test.go
+++ b/internal/hostagent/package_updates_test.go
@@ -33,7 +33,7 @@ Conf openssl (3.0.12-1 Debian-Security:12/stable-security [amd64])`
func TestPackageUpdateManagerApplyUsesClosedAPTCommandCatalogAndVerifies(t *testing.T) {
beforeOutput := "Inst openssl [1.0] (1.1 repo [amd64])\nInst curl [8.0] (8.1 repo [amd64])\n"
- m := newPackageUpdateManager("linux")
+ m := newPackageUpdateManager("linux", newPackageManagerLease())
m.lookPath = func(name string) (string, error) {
if name != "apt-get" {
t.Fatalf("lookPath(%q), want apt-get", name)
@@ -106,7 +106,7 @@ func TestPackageUpdateManagerApplyUsesClosedAPTCommandCatalogAndVerifies(t *test
}
func TestPackageUpdateManagerFailsClosedWhenRefreshFails(t *testing.T) {
- m := newPackageUpdateManager("linux")
+ m := newPackageUpdateManager("linux", newPackageManagerLease())
m.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
m.stat = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }
calls := 0
@@ -122,13 +122,32 @@ func TestPackageUpdateManagerFailsClosedWhenRefreshFails(t *testing.T) {
if result.Success || result.Verification != agentexec.HostUpdateVerificationInconclusive || result.Error != "package index refresh failed" {
t.Fatalf("result = %#v", result)
}
+ if !result.MutationStarted || result.ExecutionPhase != agentexec.HostUpdatePhaseRefresh {
+ t.Fatalf("refresh failure must report possible external effect: %#v", result)
+ }
if calls != 2 {
t.Fatalf("calls = %d, want probe and refresh only", calls)
}
}
+func TestPackageUpdateManagerCanceledRefreshReportsPossibleExternalEffect(t *testing.T) {
+ m := newPackageUpdateManager("linux", newPackageManagerLease())
+ m.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
+ m.stat = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }
+ m.run = func(ctx context.Context, _ []string, _ string, args ...string) packageUpdateCommandResult {
+ if strings.Join(args, " ") == "update" {
+ return packageUpdateCommandResult{exitCode: -1, err: context.Canceled}
+ }
+ return packageUpdateCommandResult{stdout: "Inst openssl [1.0] (1.1 repo [amd64])\n"}
+ }
+ result := m.Apply(context.Background(), agentexec.HostUpdatePayload{RequestID: "r1", ActionID: "a1", Operation: agentexec.HostUpdateOperationInstall, ExpectedInventoryHash: aptUpgradeInventoryHash("Inst openssl [1.0] (1.1 repo [amd64])\n")})
+ if !result.MutationStarted || result.ExecutionPhase != agentexec.HostUpdatePhaseRefresh || result.Success {
+ t.Fatalf("canceled refresh truth = %#v", result)
+ }
+}
+
func TestPackageUpdateManagerRefusesRefreshTimeInventoryDriftBeforeInstall(t *testing.T) {
- m := newPackageUpdateManager("linux")
+ m := newPackageUpdateManager("linux", newPackageManagerLease())
m.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
m.stat = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }
stale := "Inst openssl [1.0] (1.1 repo [amd64])\n"
@@ -163,7 +182,7 @@ func TestPackageUpdateManagerRefusesRefreshTimeInventoryDriftBeforeInstall(t *te
func TestPackageUpdateSnapshotCachesAndUnsupportedPlatformsFailClosed(t *testing.T) {
now := time.Date(2026, 7, 11, 1, 0, 0, 0, time.UTC)
- m := newPackageUpdateManager("windows")
+ m := newPackageUpdateManager("windows", newPackageManagerLease())
m.now = func() time.Time { return now }
m.run = func(context.Context, []string, string, ...string) packageUpdateCommandResult {
t.Fatal("unsupported platform must not execute package manager")
diff --git a/internal/hostagent/storage_cleanup.go b/internal/hostagent/storage_cleanup.go
index 52faf2d5fa..c1e8e44a44 100644
--- a/internal/hostagent/storage_cleanup.go
+++ b/internal/hostagent/storage_cleanup.go
@@ -28,12 +28,13 @@ type storageCleanupManager struct {
run func(context.Context, []string, string, ...string) packageUpdateCommandResult
lookPath func(string) (string, error)
scan func() (agentexec.HostStorageCleanupSnapshot, error)
+ lease *packageManagerLease
mu sync.Mutex
cached *agentexec.HostStorageCleanupSnapshot
}
-func newStorageCleanupManager(platform string) *storageCleanupManager {
+func newStorageCleanupManager(platform string, lease *packageManagerLease) *storageCleanupManager {
return &storageCleanupManager{
platform: strings.ToLower(strings.TrimSpace(platform)),
now: time.Now,
@@ -41,13 +42,19 @@ func newStorageCleanupManager(platform string) *storageCleanupManager {
run: runPackageUpdateCommand,
lookPath: packageUpdateLookPath,
scan: scanAPTPackageCache,
+ lease: lease,
}
}
-func (m *storageCleanupManager) Snapshot(force bool) agentexec.HostStorageCleanupSnapshot {
+func (m *storageCleanupManager) Snapshot(ctx context.Context, force bool) agentexec.HostStorageCleanupSnapshot {
if m == nil {
return agentexec.HostStorageCleanupSnapshot{}
}
+ release, err := m.lease.acquire(ctx)
+ if err != nil {
+ return agentexec.HostStorageCleanupSnapshot{CheckedAt: m.currentTime(), Error: "package cache inspection canceled"}
+ }
+ defer release()
m.mu.Lock()
defer m.mu.Unlock()
return m.snapshotLocked(force)
@@ -86,8 +93,9 @@ func (m *storageCleanupManager) snapshotLocked(force bool) agentexec.HostStorage
func (m *storageCleanupManager) Apply(ctx context.Context, req agentexec.HostStorageCleanupPayload) (result agentexec.HostStorageCleanupResultPayload) {
startedAt := time.Now()
result = agentexec.HostStorageCleanupResultPayload{
- RequestID: strings.TrimSpace(req.RequestID),
- Verification: agentexec.HostStorageCleanupVerificationInconclusive,
+ RequestID: strings.TrimSpace(req.RequestID), ActionID: strings.TrimSpace(req.ActionID),
+ ExecutionPhase: agentexec.HostStorageCleanupPhasePreflight,
+ Verification: agentexec.HostStorageCleanupVerificationInconclusive,
}
defer func() { result.Duration = time.Since(startedAt).Milliseconds() }()
@@ -95,6 +103,12 @@ func (m *storageCleanupManager) Apply(ctx context.Context, req agentexec.HostSto
result.Error = "unsupported typed host storage cleanup operation"
return result
}
+ release, err := m.lease.acquire(ctx)
+ if err != nil {
+ result.Error = "package manager lease unavailable"
+ return result
+ }
+ defer release()
m.mu.Lock()
defer m.mu.Unlock()
@@ -122,6 +136,8 @@ func (m *storageCleanupManager) Apply(ctx context.Context, req agentexec.HostSto
return result
}
+ result.ExecutionPhase = agentexec.HostStorageCleanupPhaseClean
+ result.MutationStarted = true
clean := m.run(ctx, []string{"DEBIAN_FRONTEND=noninteractive"}, "apt-get", "clean")
if clean.err != nil || clean.exitCode != 0 {
result.After = m.snapshotLocked(true)
@@ -131,6 +147,7 @@ func (m *storageCleanupManager) Apply(ctx context.Context, req agentexec.HostSto
}
result.Success = true
+ result.ExecutionPhase = agentexec.HostStorageCleanupPhaseVerify
after := m.snapshotLocked(true)
result.After = after
if after.Error != "" {
@@ -146,6 +163,7 @@ func (m *storageCleanupManager) Apply(ctx context.Context, req agentexec.HostSto
return result
}
result.Verification = agentexec.HostStorageCleanupVerificationVerified
+ result.ExecutionPhase = agentexec.HostStorageCleanupPhaseComplete
return result
}
diff --git a/internal/hostagent/storage_cleanup_test.go b/internal/hostagent/storage_cleanup_test.go
index 72433ccee8..d20121c506 100644
--- a/internal/hostagent/storage_cleanup_test.go
+++ b/internal/hostagent/storage_cleanup_test.go
@@ -52,7 +52,7 @@ func TestStorageCleanupManagerApplyUsesClosedAPTCatalogAndVerifiesBytes(t *testi
after := agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 40, CheckedAt: time.Now().UTC()}
snapshots := []agentexec.HostStorageCleanupSnapshot{before, after}
var calls [][]string
- manager := newStorageCleanupManager("linux")
+ manager := newStorageCleanupManager("linux", newPackageManagerLease())
manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
manager.scan = func() (agentexec.HostStorageCleanupSnapshot, error) {
snapshot := snapshots[0]
@@ -81,7 +81,7 @@ func TestStorageCleanupManagerApplyUsesClosedAPTCatalogAndVerifiesBytes(t *testi
}
func TestStorageCleanupManagerRefusesFingerprintDriftBeforeMutation(t *testing.T) {
- manager := newStorageCleanupManager("linux")
+ manager := newStorageCleanupManager("linux", newPackageManagerLease())
manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
manager.scan = func() (agentexec.HostStorageCleanupSnapshot, error) {
return agentexec.HostStorageCleanupSnapshot{Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 400}, nil
diff --git a/internal/models/models.go b/internal/models/models.go
index 9b1f740c78..942f9b4701 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -308,6 +308,7 @@ type HostPackageUpdateStatus struct {
PendingCount int `json:"pendingCount"`
Packages []HostPackageUpdate `json:"packages,omitempty"`
CheckedAt time.Time `json:"checkedAt,omitempty"`
+ ObservedAt time.Time `json:"observedAt,omitempty"`
RebootRequired bool `json:"rebootRequired,omitempty"`
Error string `json:"error,omitempty"`
}
@@ -324,6 +325,7 @@ type HostStorageCleanupStatus struct {
Fingerprint string `json:"fingerprint,omitempty"`
ReclaimableBytes int64 `json:"reclaimableBytes"`
CheckedAt time.Time `json:"checkedAt,omitempty"`
+ ObservedAt time.Time `json:"observedAt,omitempty"`
Error string `json:"error,omitempty"`
}
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index c0604bd460..c0b248b4f9 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -2231,7 +2231,8 @@ func convertHostPackageUpdateStatus(status *agentshost.PackageUpdateStatus, obse
InventoryHash: strings.TrimSpace(status.InventoryHash),
PendingCount: max(0, status.PendingCount),
Packages: packages,
- CheckedAt: observedAt.UTC(),
+ CheckedAt: status.CheckedAt.UTC(),
+ ObservedAt: observedAt.UTC(),
RebootRequired: status.RebootRequired,
Error: strings.TrimSpace(status.Error),
}
@@ -2246,7 +2247,8 @@ func convertHostStorageCleanupStatus(status *agentshost.StorageCleanupStatus, ob
Provider: strings.TrimSpace(status.Provider),
Fingerprint: strings.TrimSpace(status.Fingerprint),
ReclaimableBytes: status.ReclaimableBytes,
- CheckedAt: observedAt.UTC(),
+ CheckedAt: status.CheckedAt.UTC(),
+ ObservedAt: observedAt.UTC(),
Error: strings.TrimSpace(status.Error),
}
}
diff --git a/internal/monitoring/monitor_package_updates_test.go b/internal/monitoring/monitor_package_updates_test.go
index 1d39c6b91e..f063ac1865 100644
--- a/internal/monitoring/monitor_package_updates_test.go
+++ b/internal/monitoring/monitor_package_updates_test.go
@@ -15,7 +15,7 @@ func TestConvertHostPackageUpdateStatusPreservesTypedInventoryWithoutAliasing(t
Packages: []agentshost.PackageUpdate{{Name: " openssl ", InstalledVersion: " 1.0 ", AvailableVersion: " 1.1 "}},
}
got := convertHostPackageUpdateStatus(input, now)
- if got == nil || !got.Supported || got.Manager != "apt" || got.InventoryHash != "sha256:"+strings.Repeat("a", 64) || got.PendingCount != 2 || !got.RebootRequired || !got.CheckedAt.Equal(now) {
+ if got == nil || !got.Supported || got.Manager != "apt" || got.InventoryHash != "sha256:"+strings.Repeat("a", 64) || got.PendingCount != 2 || !got.RebootRequired || !got.CheckedAt.Equal(input.CheckedAt) || !got.ObservedAt.Equal(now) {
t.Fatalf("status = %#v", got)
}
if len(got.Packages) != 1 || got.Packages[0].Name != "openssl" || got.Packages[0].InstalledVersion != "1.0" || got.Packages[0].AvailableVersion != "1.1" {
@@ -27,13 +27,13 @@ func TestConvertHostPackageUpdateStatusPreservesTypedInventoryWithoutAliasing(t
}
}
-func TestConvertHostStorageCleanupStatusUsesServerReceiptFreshness(t *testing.T) {
+func TestConvertHostStorageCleanupStatusPreservesAgentCheckedAndServerObservedTimes(t *testing.T) {
now := time.Now().UTC()
input := &agentshost.StorageCleanupStatus{
Supported: true, Provider: " apt-package-cache ", Fingerprint: " sha256:" + strings.Repeat("b", 64) + " ", ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now.Add(48 * time.Hour), Error: " ",
}
got := convertHostStorageCleanupStatus(input, now)
- if got == nil || !got.Supported || got.Provider != "apt-package-cache" || got.Fingerprint != "sha256:"+strings.Repeat("b", 64) || got.ReclaimableBytes != 512*1024*1024 || !got.CheckedAt.Equal(now) || got.Error != "" {
+ if got == nil || !got.Supported || got.Provider != "apt-package-cache" || got.Fingerprint != "sha256:"+strings.Repeat("b", 64) || got.ReclaimableBytes != 512*1024*1024 || !got.CheckedAt.Equal(input.CheckedAt) || !got.ObservedAt.Equal(now) || got.Error != "" {
t.Fatalf("status = %#v", got)
}
}
diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.go
index 4f0ec64306..9ee4f5cfe6 100644
--- a/internal/unifiedresources/adapters.go
+++ b/internal/unifiedresources/adapters.go
@@ -181,6 +181,7 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {
PendingCount: host.PackageUpdates.PendingCount,
Packages: packages,
CheckedAt: host.PackageUpdates.CheckedAt,
+ ObservedAt: host.PackageUpdates.ObservedAt,
RebootRequired: host.PackageUpdates.RebootRequired,
Error: host.PackageUpdates.Error,
}
@@ -192,6 +193,7 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {
Fingerprint: host.StorageCleanup.Fingerprint,
ReclaimableBytes: host.StorageCleanup.ReclaimableBytes,
CheckedAt: host.StorageCleanup.CheckedAt,
+ ObservedAt: host.StorageCleanup.ObservedAt,
Error: host.StorageCleanup.Error,
}
}
@@ -517,7 +519,9 @@ func hostActionCapabilities(host models.Host) []ResourceCapability {
func hostPackageUpdateCapabilities(host models.Host) []ResourceCapability {
status := host.PackageUpdates
- if !host.CommandsEnabled || status == nil || !status.Supported || strings.TrimSpace(status.Manager) != "apt" || strings.TrimSpace(status.InventoryHash) == "" || status.PendingCount <= 0 || strings.TrimSpace(status.Error) != "" || status.CheckedAt.IsZero() || time.Since(status.CheckedAt.UTC()) > HostPackageUpdateFreshness {
+ now := time.Now().UTC()
+ meta := agentPackageUpdateMetaFromModel(status)
+ if !host.CommandsEnabled || status == nil || !status.Supported || strings.TrimSpace(status.Manager) != "apt" || strings.TrimSpace(status.InventoryHash) == "" || status.PendingCount <= 0 || strings.TrimSpace(status.Error) != "" || !HostPackageUpdateTelemetryFresh(meta, now) {
return nil
}
return []ResourceCapability{{
@@ -533,7 +537,9 @@ func hostPackageUpdateCapabilities(host models.Host) []ResourceCapability {
func hostStorageCleanupCapability(host models.Host) (ResourceCapability, bool) {
status := host.StorageCleanup
- if !host.CommandsEnabled || status == nil || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" || strings.TrimSpace(status.Fingerprint) == "" || status.ReclaimableBytes < HostStorageCleanupMinReclaimableBytes || strings.TrimSpace(status.Error) != "" || status.CheckedAt.IsZero() || time.Since(status.CheckedAt.UTC()) > HostStorageCleanupFreshness {
+ now := time.Now().UTC()
+ meta := agentStorageCleanupMetaFromModel(status)
+ if !host.CommandsEnabled || status == nil || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" || strings.TrimSpace(status.Fingerprint) == "" || status.ReclaimableBytes < HostStorageCleanupMinReclaimableBytes || strings.TrimSpace(status.Error) != "" || !HostStorageCleanupTelemetryFresh(meta, now) {
return ResourceCapability{}, false
}
if _, ok := HostStorageCleanupPressureDisk(convertDisks(host.Disks)); !ok {
@@ -550,6 +556,20 @@ func hostStorageCleanupCapability(host models.Host) (ResourceCapability, bool) {
}, true
}
+func agentPackageUpdateMetaFromModel(status *models.HostPackageUpdateStatus) *AgentPackageUpdateMeta {
+ if status == nil {
+ return nil
+ }
+ return &AgentPackageUpdateMeta{CheckedAt: status.CheckedAt, ObservedAt: status.ObservedAt}
+}
+
+func agentStorageCleanupMetaFromModel(status *models.HostStorageCleanupStatus) *AgentStorageCleanupMeta {
+ if status == nil {
+ return nil
+ }
+ return &AgentStorageCleanupMeta{CheckedAt: status.CheckedAt, ObservedAt: status.ObservedAt}
+}
+
func hostThermalStateToMeta(in *models.HostThermalState) *HostThermalState {
if in == nil {
return nil
diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.go
index 179ea51d77..fff97801a8 100644
--- a/internal/unifiedresources/adapters_test.go
+++ b/internal/unifiedresources/adapters_test.go
@@ -72,13 +72,13 @@ func TestResourceFromHostAdvertisesElevatedTypedPackageUpdateCapability(t *testi
host := models.Host{
ID: "agent-1", Hostname: "host-1", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true,
PackageUpdates: &models.HostPackageUpdateStatus{
- Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 2, CheckedAt: now, RebootRequired: true,
+ Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 2, CheckedAt: now.Add(-time.Minute), ObservedAt: now, RebootRequired: true,
Packages: []models.HostPackageUpdate{{Name: "openssl", InstalledVersion: "1.0", AvailableVersion: "1.1"}},
},
}
resource, _ := resourceFromHost(host)
- if resource.Agent == nil || resource.Agent.PackageUpdates == nil || resource.Agent.PackageUpdates.PendingCount != 2 || !resource.Agent.PackageUpdates.RebootRequired {
+ if resource.Agent == nil || resource.Agent.PackageUpdates == nil || resource.Agent.PackageUpdates.PendingCount != 2 || !resource.Agent.PackageUpdates.RebootRequired || !resource.Agent.PackageUpdates.CheckedAt.Equal(now.Add(-time.Minute)) || !resource.Agent.PackageUpdates.ObservedAt.Equal(now) {
t.Fatalf("package update projection = %#v", resource.Agent)
}
if len(resource.Capabilities) != 1 {
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index f39e6d3cdf..c5d89f8630 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -65,6 +65,7 @@ import (
"regexp"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
@@ -1667,6 +1668,23 @@ func TestHostMaintenancePostureRemainsAgentScoped(t *testing.T) {
t.Fatalf("expected typed storage-cleanup metadata, got %v", cleanupField.Type)
}
+ for _, tc := range []struct {
+ name string
+ typeOf reflect.Type
+ }{
+ {name: "package updates", typeOf: reflect.TypeOf(AgentPackageUpdateMeta{})},
+ {name: "storage cleanup", typeOf: reflect.TypeOf(AgentStorageCleanupMeta{})},
+ } {
+ checkedAt, ok := tc.typeOf.FieldByName("CheckedAt")
+ if !ok || checkedAt.Type != reflect.TypeOf(time.Time{}) || checkedAt.Tag.Get("json") != "checkedAt,omitempty" {
+ t.Fatalf("%s CheckedAt contract = %#v", tc.name, checkedAt)
+ }
+ observedAt, ok := tc.typeOf.FieldByName("ObservedAt")
+ if !ok || observedAt.Type != reflect.TypeOf(time.Time{}) || observedAt.Tag.Get("json") != "observedAt,omitempty" {
+ t.Fatalf("%s ObservedAt contract = %#v", tc.name, observedAt)
+ }
+ }
+
resourceType := reflect.TypeOf(Resource{})
if _, ok := resourceType.FieldByName("PackageUpdates"); ok {
t.Fatal("package-update posture must not become an unscoped top-level Resource field")
@@ -1676,6 +1694,58 @@ func TestHostMaintenancePostureRemainsAgentScoped(t *testing.T) {
}
}
+func TestHostAPTTelemetryTruthStaysUnifiedResourceOwned(t *testing.T) {
+ ownerSource, err := os.ReadFile("host_apt_telemetry.go")
+ if err != nil {
+ t.Fatalf("read canonical host APT telemetry owner: %v", err)
+ }
+ for _, required := range []string{
+ "func ValidHostAPTDigest(value string) bool",
+ "func HostPackageUpdateTelemetryFresh(status *AgentPackageUpdateMeta, now time.Time) bool",
+ "func HostStorageCleanupTelemetryFresh(status *AgentStorageCleanupMeta, now time.Time) bool",
+ } {
+ if !strings.Contains(string(ownerSource), required) {
+ t.Fatalf("unifiedresources must own host APT telemetry truth: missing %q", required)
+ }
+ }
+
+ workflowFiles := []string{
+ filepath.Join("..", "ai", "findings_apt_workflows.go"),
+ filepath.Join("..", "api", "host_update_action_executor.go"),
+ filepath.Join("..", "api", "host_storage_cleanup_action_executor.go"),
+ }
+ forbiddenDeclarations := []*regexp.Regexp{
+ regexp.MustCompile(`(?m)^type\s+AgentPackageUpdateMeta\b`),
+ regexp.MustCompile(`(?m)^type\s+AgentStorageCleanupMeta\b`),
+ regexp.MustCompile(`(?m)^func\s+\w*(?:TelemetryFresh|APTDigest)\b`),
+ }
+ for _, path := range workflowFiles {
+ source, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read host APT workflow %s: %v", path, err)
+ }
+ for _, forbidden := range forbiddenDeclarations {
+ if forbidden.Match(source) {
+ t.Fatalf("host APT workflow %s duplicates unified-resource telemetry truth with %s", path, forbidden)
+ }
+ }
+ }
+
+ findingSource, err := os.ReadFile(filepath.Join("..", "ai", "findings_apt_workflows.go"))
+ if err != nil {
+ t.Fatalf("read host APT finding producer: %v", err)
+ }
+ for _, required := range []string{
+ "unifiedresources.ValidHostAPTDigest",
+ "unifiedresources.HostPackageUpdateTelemetryFresh",
+ "unifiedresources.HostStorageCleanupTelemetryFresh",
+ } {
+ if !strings.Contains(string(findingSource), required) {
+ t.Fatalf("host APT finding producer must consume canonical telemetry truth: missing %q", required)
+ }
+ }
+}
+
// TestNoLegacyMigrationHintsInRuntimeCode prevents reintroducing runtime
// messages that point removed aliases at the wrong token guidance.
func TestNoLegacyMigrationHintsInRuntimeCode(t *testing.T) {
diff --git a/internal/unifiedresources/host_apt_telemetry.go b/internal/unifiedresources/host_apt_telemetry.go
new file mode 100644
index 0000000000..d7171193db
--- /dev/null
+++ b/internal/unifiedresources/host_apt_telemetry.go
@@ -0,0 +1,42 @@
+package unifiedresources
+
+import (
+ "encoding/hex"
+ "strings"
+ "time"
+)
+
+const HostAPTTelemetryMaxClockSkew = 5 * time.Minute
+
+func ValidHostAPTDigest(value string) bool {
+ value = strings.TrimSpace(value)
+ if len(value) != len("sha256:")+64 || !strings.HasPrefix(value, "sha256:") {
+ return false
+ }
+ _, err := hex.DecodeString(strings.TrimPrefix(value, "sha256:"))
+ return err == nil && value == strings.ToLower(value)
+}
+
+func hostAPTTelemetryFresh(checkedAt, observedAt, now time.Time, maxAge time.Duration) bool {
+ if checkedAt.IsZero() || observedAt.IsZero() || maxAge <= 0 {
+ return false
+ }
+ checkedAt = checkedAt.UTC()
+ observedAt = observedAt.UTC()
+ now = now.UTC()
+ if checkedAt.After(now.Add(HostAPTTelemetryMaxClockSkew)) || observedAt.After(now.Add(HostAPTTelemetryMaxClockSkew)) {
+ return false
+ }
+ if observedAt.Before(checkedAt.Add(-HostAPTTelemetryMaxClockSkew)) {
+ return false
+ }
+ return now.Sub(checkedAt) <= maxAge && now.Sub(observedAt) <= maxAge
+}
+
+func HostPackageUpdateTelemetryFresh(status *AgentPackageUpdateMeta, now time.Time) bool {
+ return status != nil && hostAPTTelemetryFresh(status.CheckedAt, status.ObservedAt, now, HostPackageUpdateFreshness)
+}
+
+func HostStorageCleanupTelemetryFresh(status *AgentStorageCleanupMeta, now time.Time) bool {
+ return status != nil && hostAPTTelemetryFresh(status.CheckedAt, status.ObservedAt, now, HostStorageCleanupFreshness)
+}
diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.go
index 7b41510e87..cf25a6bf81 100644
--- a/internal/unifiedresources/types.go
+++ b/internal/unifiedresources/types.go
@@ -787,6 +787,7 @@ type AgentPackageUpdateMeta struct {
PendingCount int `json:"pendingCount"`
Packages []AgentPackageUpdate `json:"packages,omitempty"`
CheckedAt time.Time `json:"checkedAt,omitempty"`
+ ObservedAt time.Time `json:"observedAt,omitempty"`
RebootRequired bool `json:"rebootRequired,omitempty"`
Error string `json:"error,omitempty"`
}
@@ -803,6 +804,7 @@ type AgentStorageCleanupMeta struct {
Fingerprint string `json:"fingerprint,omitempty"`
ReclaimableBytes int64 `json:"reclaimableBytes"`
CheckedAt time.Time `json:"checkedAt,omitempty"`
+ ObservedAt time.Time `json:"observedAt,omitempty"`
Error string `json:"error,omitempty"`
}
diff --git a/internal/unifiedresources/views.go b/internal/unifiedresources/views.go
index df894ad672..30ca2dd66a 100644
--- a/internal/unifiedresources/views.go
+++ b/internal/unifiedresources/views.go
@@ -1064,6 +1064,30 @@ func (v HostView) CommandsEnabled() bool {
return v.r.Agent.CommandsEnabled
}
+func (v HostView) PackageUpdates() *AgentPackageUpdateMeta {
+ if v.r == nil || v.r.Agent == nil || v.r.Agent.PackageUpdates == nil {
+ return nil
+ }
+ copy := *v.r.Agent.PackageUpdates
+ copy.Packages = append([]AgentPackageUpdate(nil), v.r.Agent.PackageUpdates.Packages...)
+ return &copy
+}
+
+func (v HostView) StorageCleanup() *AgentStorageCleanupMeta {
+ if v.r == nil || v.r.Agent == nil || v.r.Agent.StorageCleanup == nil {
+ return nil
+ }
+ copy := *v.r.Agent.StorageCleanup
+ return &copy
+}
+
+func (v HostView) Capabilities() []ResourceCapability {
+ if v.r == nil {
+ return nil
+ }
+ return append([]ResourceCapability(nil), v.r.Capabilities...)
+}
+
func (v HostView) ReportIP() string {
if v.r == nil || v.r.Agent == nil {
return ""