Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add governed host update autonomy
rcourtman1312da3acb9c
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex f9f8747fbd..5e06de9a6a 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -3963,6 +3963,19 @@],"release_gate_ids": [],"proof_commands": [+ {+ "id": "ra35-typed-host-update-vertical",+ "run": [+ "go",+ "test",+ "./internal/api",+ "./internal/agentexec",+ "./internal/hostagent",+ "-run",+ "TestPatrolFullModeRunsHostUpdateThroughCanonicalLifecycle|TestExecuteHostUpdateRoundTripUsesTypedCommandFreeEnvelope|TestPackageUpdateManagerApplyUsesClosedAPTCommandCatalogAndVerifies|TestPackageUpdateManagerRefusesRefreshTimeInventoryDriftBeforeInstall",+ "-count=1"+ ]+ },{"id": "ra35-typed-proposal-channel","run": [@@ -3987,6 +4000,11 @@}],"evidence": [+ {+ "repo": "pulse",+ "path": "internal/agentexec/types.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/ai/chat/service_investigation.go",@@ -4012,11 +4030,21 @@"path": "internal/ai/tools/tools_propose.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/api/host_update_action_executor.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/api/patrol_action_broker.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/hostagent/package_updates.go",+ "kind": "file"+ },{"repo": "pulse","path": "pkg/aicontracts/action_broker.go",@@ -5590,7 +5618,7 @@"status": "partial","completion": {"state": "bounded-residual",- "summary": "Action governance has a first-class governed floor AND the typed action lifecycle is now the only autonomous route for Patrol: investigations run under a core-owned, non-interactive, read-only execution profile and can only emit a side-effect-free typed action proposal (patrol_propose_action), which the shared action lifecycle plans, approves, and executes with plan hashing, remediation locks, plan-drift revalidation, and read-after-write verification. The first policy-authorized vertical is live: Docker/Podman restart is capability-owned low-risk eligible, requires an explicit per-resource capability allowlist, supports an optional recurring timezone window, remains bounded by the tenant Patrol mode and full-mode unlock, rechecks policy before decision and dispatch, and records its server-owned policy approval plus terminal verification in the same audit trail. Never-auto-remediate, missing/unknown policy, unsupported capabilities, dry-run/MFA floors, closed windows, and mode downgrades all fail closed. Action continuity is audit-authoritative: idempotent proposal replay cannot rewind or double-execute a terminal action, callbacks trigger org-scoped re-reads, investigation reads recover missed transitions by trusted origin, desktop and mobile decisions use the canonical /api/actions routes, terminal verification maps honestly onto Patrol findings and push outcomes, and legacy command-shaped history remains inert. Remaining post-RC hardening: broader tenant defaults/inheritance and automation rate budgets, host-update and storage-pressure workflows as the second and third complete verticals, richer dry-run providers, multi-actor approvals, and a real-lab detect-plan-execute-verify-rollback journey proof.",+ "summary": "Action governance has a first-class governed floor AND the typed action lifecycle is now the only autonomous route for Patrol: investigations run under a core-owned, non-interactive, read-only execution profile and can only emit a side-effect-free typed action proposal (patrol_propose_action), which the shared action lifecycle plans, approves, and executes with plan hashing, remediation locks, plan-drift revalidation, and read-after-write verification. Two policy-authorized verticals are live. Docker/Podman restart is capability-owned low-risk eligible. Agent-managed APT host updates are capability-owned elevated eligible and cross a closed typed host_update protocol with no command, package-selection, removal, or reboot authority; the agent owns metadata refresh, preflight simulation, guarded installation, and post-install simulation, while the audit records verified, failed, or honestly inconclusive outcomes plus reboot-required state. Both require explicit per-resource capability allowlists and optional recurring timezone windows, remain bounded by tenant Patrol mode and full-mode unlock, recheck policy/readiness before decision and dispatch, and record server-owned policy approval plus terminal verification in the same audit trail. Never-auto-remediate, missing/unknown policy, unsupported capabilities, stale/error/empty package inventories, dry-run/MFA floors, closed windows, and mode downgrades all fail closed. Action continuity is audit-authoritative: idempotent proposal replay cannot rewind or double-execute a terminal action, callbacks trigger org-scoped re-reads, investigation reads recover missed transitions by trusted origin, desktop and mobile decisions use the canonical /api/actions routes, terminal verification maps honestly onto Patrol findings and push outcomes, and legacy command-shaped history remains inert. Remaining post-RC hardening: broader tenant defaults/inheritance and automation rate budgets, storage pressure as the third complete workflow, richer dry-run providers, multi-actor approvals, additional package-manager providers beyond APT, separately governed reboot orchestration, and a real-lab detect-plan-execute-verify-rollback journey proof.","tracking": [{"kind": "lane-followup",@@ -5709,6 +5737,28 @@"path": "frontend-modern/src/utils/actionAuditPresentation.ts","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/agentcontext/resource_context_sections.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/agentcontext/resource_context_sections_test.go",+ "kind": "file",+ "evidence_tier": "test-proof"+ },+ {+ "repo": "pulse",+ "path": "internal/agentexec/server_websocket_test.go",+ "kind": "file",+ "evidence_tier": "test-proof"+ },+ {+ "repo": "pulse",+ "path": "internal/agentexec/types.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/ai/approval/store.go",@@ -5744,6 +5794,17 @@"path": "internal/api/contract_test.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/api/host_update_action_executor.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/api/host_update_action_executor_test.go",+ "kind": "file",+ "evidence_tier": "test-proof"+ },{"repo": "pulse","path": "internal/api/patrol_action_broker.go",@@ -5759,6 +5820,17 @@"path": "internal/api/patrol_action_reconciliation.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/hostagent/package_updates.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/hostagent/package_updates_test.go",+ "kind": "file",+ "evidence_tier": "test-proof"+ },{"repo": "pulse","path": "internal/unifiedresources/actions.go",@@ -5769,6 +5841,17 @@"path": "internal/unifiedresources/actions_test.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/unifiedresources/adapters.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/unifiedresources/adapters_test.go",+ "kind": "file",+ "evidence_tier": "test-proof"+ },{"repo": "pulse","path": "internal/unifiedresources/resource_operator_state_policy_test.go",@@ -5784,6 +5867,11 @@"path": "internal/unifiedresources/store_test.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "pkg/agents/host/report.go",+ "kind": "file"+ },{"repo": "pulse-enterprise","path": "internal/investigation/orchestrator_test.go",diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 8e48784b37..f0ec72ab49 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -257,7 +257,8 @@ update, profile rollout, command reachability, or fleet-control authority.completed lifecycle registration.22. `internal/api/unified_agent.go` shared with `api-contracts`: unified agent download and installer handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.23. `internal/kubernetesagent/agent.go` shared with `monitoring`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.-24. `scripts/install.ps1` shared with `deployment-installability`: the Windows installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.+24. `pkg/agents/host/report.go` shared with `monitoring`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host package-update posture.+25. `scripts/install.ps1` shared with `deployment-installability`: the Windows installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.The Windows installer must support a non-mutating download preflight thatcan run before Administrator-only install work, must accept token-fileenrollment input, and must persist plain-HTTP/insecure runtime continuity@@ -273,7 +274,7 @@ update, profile rollout, command reachability, or fleet-control authority.version replacement, logged readiness, forced-process recovery, servicerestart or OS reboot persistence, and complete uninstall cleanup throughthe reusable lifecycle harness under `scripts/installtests/`.-25. `scripts/install.sh` shared with `deployment-installability`: the shell installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.+26. `scripts/install.sh` shared with `deployment-installability`: the shell installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.Legacy update recovery is cross-platform lifecycle continuity. Linux mayread procfs or a systemd unit, while FreeBSD and pfSense must recover thesame URL, token, feature, identity, and trust arguments from the live@@ -407,6 +408,21 @@ mark its vetted container lifecycle dispatch as a trusted agent command afterthe API action has entered execution; lifecycle surfaces still consume only theresource payload, action readiness, and action-audit result rather than issuingor approving command-agent grants themselves.+Host OS package updates follow a stricter adjacent boundary. The Unified Agent+may report a bounded, read-only APT upgrade simulation through+`pkg/agents/host/report.go`, but installation authority is available only via+the closed `host_update` WebSocket operation owned by `internal/agentexec` and+`internal/hostagent/package_updates.go`. That envelope carries an action id and+the exact `install_os_updates` operation only: it has no command, package-name,+reboot, removal, or arbitrary-argument field. The agent owns metadata refresh,+preflight simulation, noninteractive `apt-get upgrade --no-remove` execution,+and the second simulation used as read-after-write evidence. The request carries+the agent-authored expected inventory fingerprint; if metadata refresh changes+that inventory, the agent updates its observed state and refuses installation+so Pulse must re-plan against the widened or changed set. A reboot-required+marker is reported as state, never acted upon by this capability. Generic+agent command execution, Patrol prose, lifecycle UI, and external agents must+not reconstruct or bypass this typed operation.Proxmox VM and LXC lifecycle affordances follow the same adjacent boundary:lifecycle and fleet surfaces may consume backend-advertised `start`,`shutdown`, `reboot`, and `stop` capabilities and typed `actionReadiness`, butdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex c80f52ae16..4ab56e57e9 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -37,6 +37,7 @@ product API routes free of maintainer commercial analytics.5a. `internal/api/action_executor.go`5b. `internal/api/docker_container_action_executor.go`5c. `internal/api/proxmox_guest_action_executor.go`+ 5d. `internal/api/host_update_action_executor.go`6a. `internal/actionlifecycle/service.go`7. `internal/actionplanner/planner.go`8. `pkg/pulsecli/api_client.go`@@ -1931,6 +1932,19 @@ a new API state machine, queue contract, or verification-accounting field.guests, stale Proxmox inventory, incomplete VMID/node metadata, unsupportedhandlers, and disconnected node command agents must fail closed through thesame readiness and audit model.+ Agent-managed Linux host package updates are the second complete typed+ action vertical. `install_os_updates` is admin-floor and elevated-policy+ eligible, has no model-selectable parameters, and is advertised only for a+ command-enabled host whose agent reports supported APT posture. Planning+ and dispatch recheck a fresh error-free inventory, a positive pending count,+ the registered handler, and live agent connectivity. Execution uses only+ `ExecuteHostUpdate` with the closed typed envelope; it must not synthesize a+ shell command in the API. The terminal audit distinguishes package-manager+ success from verified, failed, or inconclusive post-install simulation and+ records reboot-required state without rebooting. The API injects the+ agent-authored inventory fingerprint into the typed request; refresh-time+ fingerprint drift refuses before installation and requires a new plan, so a+ stale package index cannot silently widen the approved mutation.Resource payloads may expose the same executor-owned unavailable state as`actionReadiness[]` entries with stable `name`, `available`, `reasonCode`,and `reason` fields so browser and agent clients can explain disabled@@ -3428,6 +3442,13 @@ Backend API payloads and `frontend-modern/src/types/api.ts` must preserve thatoptional map without making it a required compatibility field, and clients mustkeep it as descriptive host telemetry rather than a temperature metric,resource identity, alert metric, or storage/recovery signal.+Agent resource-context sections expose host package posture only as bounded+operational facts: package manager, pending count, inventory state, inspection+freshness, and reboot-required state. Raw package identifiers, versions, and+agent-authored error text remain outside model context, so a private package+name or repository detail cannot leak merely because Patrol investigates a+host. Those facts are observation only; capability authority continues to come+from the typed resource catalog and action lifecycle.`aicontracts.Finding` (the shape Patrol hands the investigationorchestrator) carries optional `OperatorContext` anddiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex e106a51fb8..1997debbae 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -138,6 +138,7 @@ resource health.1. `internal/kubernetesagent/agent.go` shared with `agent-lifecycle`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.2. `internal/proxmoxidentity/backup_identity.go` shared with `alerts`, `storage-recovery`: Proxmox PBS backup subject identity is a shared runtime boundary for monitoring backup freshness, backup-age alert attribution, and recovery-point guest mapping.+3. `pkg/agents/host/report.go` shared with `agent-lifecycle`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host package-update posture.## Extension Points@@ -468,6 +469,14 @@ an active process from an initialized monitoring source. The Kubernetes moduleuses the shared agent TLS constructor for custom CA and leaf-fingerprint trust;its Pulse transport must not regress to a Kubernetes-local insecure-only TLSconfiguration.+The same host report carries bounded OS package-update posture: supported+manager, pending count, package/version identifiers, inspection time,+reboot-required state, and an operator-safe inspection error. Monitoring owns+normalization and deep-copying of that observed state, and stamps inventory+freshness from server receipt time so a skewed agent clock cannot keep update+authority fresh indefinitely; it does not infer+updates from kernel strings, refresh package indexes, install packages, or+convert the presence of an update into execution authority.HTTP availability probes consume the shared explicitly unverified,parseable-peer-certificate capturediff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex c353302e83..97780286ed 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -352,6 +352,12 @@ regression protection.while per-action resource refresh, policy validation, agent command dispatch,polling verification, and audit completion must occur inside the route-localexecute handler path.+ Agent-managed host package updates follow the same bounded setup rule. Router+ construction may register the typed host-update executor once, but package+ refresh, fingerprint comparison, APT execution, and post-install verification+ must remain inside the selected action and agent command paths. Generic+ request admission must not probe agents, refresh package indexes, enumerate+ pending packages, or wait for update completion.The Patrol action-broker and proposal-catalog factories are wired the samebounded way: `internal/api/router.go` installs the per-org factory closureson the AI settings handler once at startup, and each broker or catalog isdiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 3a54292ccc..49bb08f6eb 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -964,6 +964,14 @@"storage-recovery"]},+ {+ "path": "pkg/agents/host/report.go",+ "rationale": "the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host package-update posture",+ "subsystems": [+ "agent-lifecycle",+ "monitoring"+ ]+ },{"path": "pkg/aicontracts/action_broker.go","rationale": "the public typed action-proposal broker contract is both an AI runtime proposal boundary (the only sanctioned Patrol route to an infrastructure mutation) and a canonical API dependency contract over the shared action lifecycle service",@@ -1100,6 +1108,7 @@"internal/kubernetesagent/agent.go","internal/remoteconfig/client.go","internal/securityutil/httpurl.go",+ "pkg/agents/host/report.go","pkg/securityutil/httpurl.go","scripts/install.ps1","scripts/install.sh",@@ -1205,7 +1214,9 @@"match_prefixes": ["internal/hostagent/"],- "match_files": [],+ "match_files": [+ "pkg/agents/host/report.go"+ ],"allow_same_subsystem_tests": false,"test_prefixes": [],"exact_files": [@@ -1214,6 +1225,8 @@"internal/hostagent/agent_new_test.go","internal/hostagent/command_client_test.go","internal/hostagent/commands_deploy_test.go",+ "internal/hostagent/commands_host_update_test.go",+ "internal/hostagent/package_updates_test.go","internal/hostagent/send_report_test.go"]},@@ -2073,6 +2086,7 @@"internal/actionlifecycle/","internal/actionplanner/","internal/agentcapabilities/",+ "internal/agentcontext/","internal/api/"],"owned_files": [@@ -2128,6 +2142,19 @@],"require_explicit_path_policy_coverage": true,"path_policies": [+ {+ "id": "agent-resource-context-sections",+ "label": "agent resource context section proof",+ "match_prefixes": [+ "internal/agentcontext/"+ ],+ "match_files": [],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/agentcontext/resource_context_sections_test.go"+ ]+ },{"id": "agent-capabilities-manifest-contract","label": "agent capabilities manifest contract proof",@@ -4489,6 +4516,7 @@"internal/models/models_frontend.go","internal/proxmoxidentity/backup_identity.go","pkg/agents/docker/report.go",+ "pkg/agents/host/report.go","pkg/agents/kubernetes/report.go","pkg/proxmox/ceph.go","pkg/proxmox/zfs.go"@@ -4528,12 +4556,14 @@"label": "monitoring host-agent ingest proof","match_prefixes": [],"match_files": [- "internal/monitoring/monitor_agents.go"+ "internal/monitoring/monitor_agents.go",+ "pkg/agents/host/report.go"],"allow_same_subsystem_tests": false,"test_prefixes": [],"exact_files": ["internal/monitoring/monitor_host_agents_test.go",+ "internal/monitoring/monitor_package_updates_test.go","internal/unifiedresources/code_standards_test.go"]},@@ -4692,8 +4722,10 @@"test_prefixes": [],"exact_files": ["internal/dockeragent/swarm_coverage_test.go",+ "internal/models/deepcopy_test.go","internal/models/state_host_test.go","internal/monitoring/monitor_host_agents_test.go",+ "internal/monitoring/monitor_package_updates_test.go","internal/unifiedresources/adapter_coverage_test.go","internal/unifiedresources/registry_test.go"]diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex c3d2c10de3..be7af87d7a 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -333,6 +333,12 @@ the `white_label` branding entitlement.action lifecycle, but it exposes only typed-proposal capture and gives theorchestrator no autonomy control, command execution, or command-shapedapproval path.+ The typed host-update executor wired here is likewise not generic command+ authority. It may dispatch only the closed `install_os_updates` operation,+ bound to the server-observed package inventory fingerprint and canonical+ action approval. Package names, versions, raw APT output, and agent error+ text must not enter model context or action results; reboot remains a+ reported fact rather than an authorized operation.Router glue may also pass monitor-owned source freshness thresholds intounified-resource adapters, but those thresholds are operational cadencemetadata only. They must not disclose credentials, command output, rawdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 137240da4a..280721eb54 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -385,6 +385,12 @@ an action is unavailable, but must not reinterpret it as recovery degradationor attempt a recovery-local container command path. Typed resource`actionReadiness` reasons are operator explanation only in this subsystem, notbackup freshness, restore support, or recovery action authority.+Agent-managed host package updates follow the same boundary. The API-owned+`internal/api/host_update_action_executor.go` may dispatch only the closed,+fingerprint-bound `install_os_updates` operation after canonical lifecycle+approval. Storage/recovery consumers may observe its redacted audit outcome and+reboot-required fact as context, but must not treat package installation as+storage maintenance, recovery evidence, or a storage-owned mutation path.Storage and recovery surfaces may consume Discovery context from the sharedAPI boundary when it helps explain protected workloads or storage-adjacentservices, including mock-mode config/data/log path examples. That context isdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex c56e754d1e..18fff5c3b6 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -643,6 +643,17 @@ container inventory table.Unified-resource consumers must not infer Proxmox lifecycle affordances fromtable row status alone or issue direct `qm` / `pct`, SSH, provider API, orguest-agent calls outside the governed action contract.+ Agent-managed Linux hosts may advertise `install_os_updates` only when the+ report carries supported APT package posture and typed command operations+ are enabled. The capability is admin-floor, `elevated` auto-authorization+ eligible, parameter-free, and routed through `host.package_updates`.+ Package names and versions are observed evidence, never caller-selected+ mutation input. The agent-authored inventory fingerprint binds execution to+ the observed set without turning that set into caller authority. API+ readiness must filter the capability when inventory is+ stale, erroneous, empty, unsupported, or its owning agent is disconnected;+ reboot-required state remains descriptive and does not imply a reboot+ capability.TrueNAS app inventory enters the model as native `TrueNASData.App`metadata on canonical `app-container` resources. The facet is sourced fromthe TrueNAS API app inventory (`app.query` plus active workload/statdiff --git a/frontend-modern/src/types/__tests__/resource.test.ts b/frontend-modern/src/types/__tests__/resource.test.tsindex 899aabcc7d..9ec9543d75 100644--- a/frontend-modern/src/types/__tests__/resource.test.ts+++ b/frontend-modern/src/types/__tests__/resource.test.ts@@ -44,6 +44,27 @@ function createResource(overrides: Partial<Resource> = {}): Resource {}describe('Resource Type Guards', () => {+ it('keeps host package-update posture scoped to agent metadata', () => {+ const resource = createResource({+ type: 'agent',+ agent: {+ packageUpdates: {+ supported: true,+ manager: 'apt',+ inventoryHash: `sha256:${'a'.repeat(64)}`,+ pendingCount: 2,+ checkedAt: '2026-07-11T00:00:00Z',+ rebootRequired: false,+ },+ },+ });++ expect(resource.agent?.packageUpdates).toEqual(+ expect.objectContaining({ manager: 'apt', pendingCount: 2 }),+ );+ expect(resource).not.toHaveProperty('packageUpdates');+ });+it('keeps platform types aligned with the governed platform manifest projection', () => {expect(PLATFORM_TYPES).toEqual([...SUPPORTED_PLATFORM_IDS, ...ADMITTED_PLATFORM_IDS]);for (const platform of PRESENTATION_ONLY_PLATFORM_IDS) {diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.tsindex 2c001dcea3..5f5f40c279 100644--- a/frontend-modern/src/types/api.ts+++ b/frontend-modern/src/types/api.ts@@ -462,6 +462,7 @@ export interface Agent {appliedConfig?: AgentConfigFingerprint;agentUpdate?: AgentUpdateStatus;agentModules?: AgentModuleStatus[];+ packageUpdates?: HostPackageUpdateStatus;tokenId?: string;tokenName?: string;tokenHint?: string;@@ -476,6 +477,23 @@ export interface Agent {linkedContainerId?: string; // ID of container this agent is running inside}+export interface HostPackageUpdateStatus {+ supported: boolean;+ manager?: string;+ inventoryHash?: string;+ pendingCount: number;+ packages?: HostPackageUpdate[];+ checkedAt?: string;+ rebootRequired?: boolean;+ error?: string;+}++export interface HostPackageUpdate {+ name: string;+ installedVersion?: string;+ availableVersion?: string;+}+export interface AgentConfigFingerprint {version: string;hash: string;diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.tsindex 84c6afd71f..e2a68b30cc 100644--- a/frontend-modern/src/types/resource.ts+++ b/frontend-modern/src/types/resource.ts@@ -11,6 +11,7 @@ import type {Disk,HostDiskIO,HostNetworkInterface,+ HostPackageUpdateStatus,HostSensorSummary,HostRAIDArray,Memory,@@ -618,6 +619,7 @@ export interface ResourceAgentMeta {rebuildInProgress?: boolean;rebuildSummary?: string;commandsEnabled?: boolean;+ packageUpdates?: HostPackageUpdateStatus;tokenId?: string;tokenName?: string;tokenHint?: string;diff --git a/internal/agentcontext/resource_context_sections.go b/internal/agentcontext/resource_context_sections.goindex c8f89e6ef4..47ae882e3a 100644--- a/internal/agentcontext/resource_context_sections.go+++ b/internal/agentcontext/resource_context_sections.go@@ -504,6 +504,19 @@ func addAgentDataFacts(facts *[]Fact, resource unified.Resource, observedAt *timaddAgentContextFact(facts, "Agent OS", strings.TrimSpace(resource.Agent.OSName+" "+resource.Agent.OSVersion), agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, observedAt)addAgentContextFact(facts, "Agent version", resource.Agent.AgentVersion, agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, observedAt)addAgentContextFact(facts, "Commands enabled", fmt.Sprintf("%t", resource.Agent.CommandsEnabled), agentContextSourceUnifiedResource, agentContextTrustPulseAuthored, observedAt)+ if updates := resource.Agent.PackageUpdates; updates != nil {+ updatesObservedAt := timePtrIfSet(updates.CheckedAt)+ inventoryState := "ready"+ if !updates.Supported {+ inventoryState = "unsupported"+ } else if strings.TrimSpace(updates.Error) != "" {+ inventoryState = "error"+ }+ addAgentContextFact(facts, "Package manager", updates.Manager, agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, updatesObservedAt)+ addAgentContextCountFact(facts, "Pending OS updates", updates.PendingCount, agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, updatesObservedAt)+ addAgentContextFact(facts, "OS update inventory", inventoryState, agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, updatesObservedAt)+ addAgentContextFact(facts, "Reboot required", fmt.Sprintf("%t", updates.RebootRequired), agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, updatesObservedAt)+ }}func addProxmoxFacts(facts *[]Fact, resource unified.Resource, observedAt *time.Time) {diff --git a/internal/agentcontext/resource_context_sections_test.go b/internal/agentcontext/resource_context_sections_test.goindex 637c608d08..a6c350ba1f 100644--- a/internal/agentcontext/resource_context_sections_test.go+++ b/internal/agentcontext/resource_context_sections_test.go@@ -40,6 +40,13 @@ func TestBuildResourceContextSectionsAppliesRedactionTrustAndFreshness(t *testinHasDocker: true,DockerCheckedAt: &dockerCheckedAt,}+ resource.Agent = &unified.AgentData{+ Hostname: "prod-node", Platform: "linux", OSName: "Debian", OSVersion: "12", CommandsEnabled: true,+ PackageUpdates: &unified.AgentPackageUpdateMeta{+ Supported: true, Manager: "apt", PendingCount: 4, CheckedAt: observedAt, RebootRequired: true,+ Packages: []unified.AgentPackageUpdate{{Name: "private-customer-package", InstalledVersion: "1", AvailableVersion: "2"}},+ },+ }resource.Docker = &unified.DockerData{Image: "registry.internal/finance-db:latest",ContainerState: "running",@@ -100,6 +107,22 @@ func TestBuildResourceContextSectionsAppliesRedactionTrustAndFreshness(t *testin}runtime := requireSection(t, sections, "runtime")+ if got := requireFact(t, runtime, "Pending OS updates").Value; got != "4" {+ t.Fatalf("pending OS updates = %q, want 4", got)+ }+ if got := requireFact(t, runtime, "Package manager").Value; got != "apt" {+ t.Fatalf("package manager = %q, want apt", got)+ }+ if got := requireFact(t, runtime, "Reboot required").Value; got != "true" {+ t.Fatalf("reboot required = %q, want true", got)+ }+ encodedSections, err := json.Marshal(sections)+ if err != nil {+ t.Fatalf("marshal sections: %v", err)+ }+ if strings.Contains(string(encodedSections), "private-customer-package") {+ t.Fatalf("resource context exposed package identifiers: %s", encodedSections)+ }for _, label := range []string{"Discovery agent", "Discovery resource", "Discovery hostname", "Proxmox node", "Proxmox VMID", "Image", "Storage path"} {fact := requireFact(t, runtime, label)if fact.Value != unified.ResourcePolicyRedactedLabel || !fact.Redacted {diff --git a/internal/agentexec/server.go b/internal/agentexec/server.goindex 9994590385..f2f5d9797a 100644--- a/internal/agentexec/server.go+++ b/internal/agentexec/server.go@@ -54,20 +54,22 @@ const ()var safeTargetIDPattern = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)+var hostUpdateInventoryHashPattern = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`)// Server manages WebSocket connections from agentstype Server struct {- mu sync.RWMutex- agents map[string]*agentConn // agentID -> connection- pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel- deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber- validateToken func(token string, agentID string, hostname string) bool- commandPolicy *CommandPolicy- ipConnCounts map[string]int- maxConnsPerIP int- shutdown chan struct{}- shutdownOnce sync.Once- pingInterval time.Duration+ mu sync.RWMutex+ agents map[string]*agentConn // agentID -> connection+ pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel+ pendingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update response+ deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber+ validateToken func(token string, agentID string, hostname string) bool+ commandPolicy *CommandPolicy+ ipConnCounts map[string]int+ maxConnsPerIP int+ shutdown chan struct{}+ shutdownOnce sync.Once+ pingInterval time.Duration}type agentConn struct {@@ -106,15 +108,16 @@ func NewServer(validateToken func(token string, agentID string, hostname string)}return &Server{- agents: make(map[string]*agentConn),- pendingReqs: make(map[string]chan CommandResultPayload),- deploySubs: make(map[string]chan DeployProgressPayload),- validateToken: validateToken,- commandPolicy: DefaultPolicy(),- ipConnCounts: make(map[string]int),- maxConnsPerIP: defaultMaxWebSocketConnectionsPerIP,- shutdown: make(chan struct{}),- pingInterval: defaultPingInterval,+ agents: make(map[string]*agentConn),+ pendingReqs: make(map[string]chan CommandResultPayload),+ pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),+ deploySubs: make(map[string]chan DeployProgressPayload),+ validateToken: validateToken,+ commandPolicy: DefaultPolicy(),+ ipConnCounts: make(map[string]int),+ maxConnsPerIP: defaultMaxWebSocketConnectionsPerIP,+ shutdown: make(chan struct{}),+ pingInterval: defaultPingInterval,}}@@ -251,6 +254,76 @@ func validateReadFilePayload(req *ReadFilePayload) error {return nil}+func validateHostUpdatePayload(req *HostUpdatePayload) error {+ if req == nil {+ return fmt.Errorf("host update payload is required")+ }+ req.RequestID = strings.TrimSpace(req.RequestID)+ req.ActionID = strings.TrimSpace(req.ActionID)+ req.Operation = strings.TrimSpace(req.Operation)+ req.ExpectedInventoryHash = strings.TrimSpace(req.ExpectedInventoryHash)+ if req.RequestID == "" {+ return fmt.Errorf("request id is required")+ }+ if len(req.RequestID) > maxRequestIDLength {+ return fmt.Errorf("request id exceeds %d characters", maxRequestIDLength)+ }+ if req.ActionID == "" {+ return fmt.Errorf("action id is required")+ }+ if len(req.ActionID) > maxRequestIDLength {+ return fmt.Errorf("action id exceeds %d characters", maxRequestIDLength)+ }+ if req.Operation != HostUpdateOperationInstall {+ return fmt.Errorf("unsupported host update operation %q", req.Operation)+ }+ if !hostUpdateInventoryHashPattern.MatchString(req.ExpectedInventoryHash) {+ return fmt.Errorf("expected inventory hash is required and must be sha256")+ }+ if req.Timeout < 0 || req.Timeout > 1800 {+ return fmt.Errorf("host update timeout must be between 0 and 1800 seconds")+ }+ if req.Timeout == 0 {+ req.Timeout = 900+ }+ return nil+}++func validateHostUpdateResultPayload(result *HostUpdateResultPayload) error {+ if result == nil {+ return fmt.Errorf("host update result is required")+ }+ result.RequestID = strings.TrimSpace(result.RequestID)+ result.Verification = strings.TrimSpace(result.Verification)+ if result.RequestID == "" || len(result.RequestID) > maxRequestIDLength {+ return fmt.Errorf("invalid request id")+ }+ if result.Before.PendingCount < 0 || result.After.PendingCount < 0 {+ return fmt.Errorf("pending package counts cannot be negative")+ }+ if len(result.Before.Packages) > 200 || len(result.After.Packages) > 200 {+ return fmt.Errorf("package evidence exceeds bounded limit")+ }+ for _, hash := range []string{result.Before.InventoryHash, result.After.InventoryHash} {+ if hash != "" && !hostUpdateInventoryHashPattern.MatchString(hash) {+ return fmt.Errorf("invalid package inventory hash")+ }+ }+ switch result.Verification {+ case HostUpdateVerificationVerified:+ if !result.Success || !result.After.Supported || result.After.Manager != "apt" || result.After.Error != "" || result.After.PendingCount != 0 || result.After.InventoryHash == "" {+ return fmt.Errorf("verified host update lacks a valid zero-pending postcondition")+ }+ case HostUpdateVerificationFailed, HostUpdateVerificationInconclusive:+ default:+ return fmt.Errorf("unsupported host update verification %q", result.Verification)+ }+ if len(result.Error) > 1024 {+ return fmt.Errorf("host update error exceeds bounded limit")+ }+ return nil+}+func isAllowedWebSocketOrigin(r *http.Request) bool {origin := strings.TrimSpace(r.Header.Get("Origin"))if origin == "" {@@ -654,6 +727,36 @@ func (s *Server) readLoop(ac *agentConn) {Msg("No pending request for result")}+ 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")+ 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")+ 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()+ if ok {+ select {+ case ch <- result:+ default:+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Host update result channel full, dropping")+ }+ }+case MsgTypeDeployProgress:var progress DeployProgressPayloadif err := msg.DecodePayload(&progress); err != nil {@@ -951,6 +1054,71 @@ func (s *Server) ExecuteCommand(ctx context.Context, agentID string, cmd Execute}}+// ExecuteHostUpdate dispatches the closed typed host-package operation. Unlike+// ExecuteCommand, no command text crosses this boundary; the agent owns the+// package-manager catalog, preflight, mutation, and read-after-write proof.+func (s *Server) ExecuteHostUpdate(ctx context.Context, agentID string, req HostUpdatePayload) (*HostUpdateResultPayload, error) {+ if s == nil {+ return nil, fmt.Errorf("agent execution server is unavailable")+ }+ agentID = strings.TrimSpace(agentID)+ if agentID == "" {+ return nil, fmt.Errorf("agent id is required")+ }+ if strings.TrimSpace(req.RequestID) == "" {+ req.RequestID = uuid.New().String()+ }+ if err := validateHostUpdatePayload(&req); err != nil {+ return nil, err+ }++ s.mu.RLock()+ ac, ok := s.agents[agentID]+ s.mu.RUnlock()+ if !ok {+ return nil, fmt.Errorf("agent %s not connected", agentID)+ }++ respCh := make(chan HostUpdateResultPayload, 1)+ reqKey := pendingRequestKey(agentID, req.RequestID)+ s.mu.Lock()+ if _, exists := s.pendingHostUpdates[reqKey]; exists {+ s.mu.Unlock()+ return nil, fmt.Errorf("host update request %q is already pending", req.RequestID)+ }+ s.pendingHostUpdates[reqKey] = respCh+ s.mu.Unlock()+ defer func() {+ s.mu.Lock()+ delete(s.pendingHostUpdates, reqKey)+ s.mu.Unlock()+ }()++ msg, err := NewMessage(MsgTypeHostUpdate, req.RequestID, req)+ if err != nil {+ return nil, fmt.Errorf("failed to encode host update request: %w", err)+ }+ ac.writeMu.Lock()+ err = s.sendMessage(ac.conn, msg)+ ac.writeMu.Unlock()+ if err != nil {+ return nil, fmt.Errorf("failed to send host update request: %w", err)+ }++ timer := time.NewTimer(time.Duration(req.Timeout) * time.Second)+ defer timer.Stop()+ select {+ case result := <-respCh:+ 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 <-s.shutdown:+ return nil, errServerShuttingDown+ }+}+// ReadFile reads a file from an agentfunc (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.goindex f1d6e7d5b2..91d907adba 100644--- a/internal/agentexec/server_websocket_test.go+++ b/internal/agentexec/server_websocket_test.go@@ -455,6 +455,104 @@ func TestExecuteCommand_RoundTripViaWebSocket(t *testing.T) {}}+func TestExecuteHostUpdateRoundTripUsesTypedCommandFreeEnvelope(t *testing.T) {+ inventoryHash := "sha256:" + strings.Repeat("a", 64)+ emptyInventoryHash := "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.Fatalf("Dial: %v", err)+ }+ defer conn.Close()++ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{+ AgentID: "host-agent-1", Hostname: "host1", Version: "6.0.6", Platform: "linux", Token: "any",+ }))+ _ = wsReadRegisteredPayload(t, conn)++ agentErr := make(chan error, 1)+ go func() {+ msg, err := wsReadRawMessageWithTimeout(conn, 2*time.Second)+ if err != nil {+ agentErr <- err+ return+ }+ if msg.Type != MsgTypeHostUpdate || msg.Payload == nil {+ agentErr <- fmt.Errorf("message = %#v, want typed host update", msg)+ return+ }+ if bytes.Contains(*msg.Payload, []byte(`"command"`)) || bytes.Contains(*msg.Payload, []byte(`"packages"`)) {+ agentErr <- fmt.Errorf("host update request exposed command or package authority: %s", string(*msg.Payload))+ return+ }+ var payload HostUpdatePayload+ if err := json.Unmarshal(*msg.Payload, &payload); err != nil {+ agentErr <- err+ return+ }+ if payload.ActionID != "action-1" || payload.Operation != HostUpdateOperationInstall {+ agentErr <- fmt.Errorf("payload = %#v", payload)+ 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,+ }+ if err := conn.WriteJSON(mustNewMessage(t, MsgTypeHostUpdateResult, payload.RequestID, response)); err != nil {+ agentErr <- err+ return+ }+ agentErr <- nil+ }()++ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ result, err := s.ExecuteHostUpdate(ctx, "host-agent-1", HostUpdatePayload{+ RequestID: "request-1", ActionID: "action-1", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: inventoryHash, Timeout: 1,+ })+ if err != nil {+ t.Fatalf("ExecuteHostUpdate: %v", err)+ }+ if result == nil || !result.Success || result.Verification != HostUpdateVerificationVerified || result.After.PendingCount != 0 || !result.After.RebootRequired {+ t.Fatalf("result = %#v", result)+ }+ if err := <-agentErr; err != nil {+ t.Fatalf("agent: %v", err)+ }+}++func TestValidateHostUpdatePayloadRejectsOpenEndedAuthority(t *testing.T) {+ for _, req := range []HostUpdatePayload{+ {RequestID: "r1", ActionID: "a1", Operation: "run_command", ExpectedInventoryHash: "sha256:" + strings.Repeat("a", 64)},+ {RequestID: "r1", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: "sha256:" + strings.Repeat("a", 64)},+ {RequestID: "r1", ActionID: "a1", Operation: HostUpdateOperationInstall, Timeout: 1801, ExpectedInventoryHash: "sha256:" + strings.Repeat("a", 64)},+ {RequestID: "r1", ActionID: "a1", Operation: HostUpdateOperationInstall},+ } {+ copy := req+ if err := validateHostUpdatePayload(©); err == nil {+ t.Fatalf("validateHostUpdatePayload(%#v) succeeded", req)+ }+ }+}++func TestValidateHostUpdateResultRejectsUnprovenVerifiedClaim(t *testing.T) {+ result := HostUpdateResultPayload{+ RequestID: "r1", Success: true, Verification: HostUpdateVerificationVerified,+ After: HostPackageUpdateSnapshot{+ Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 1,+ },+ }+ if err := validateHostUpdateResultPayload(&result); err == nil {+ t.Fatal("verified result with pending packages must fail closed")+ }+}+func TestHandleWebSocket_ReconnectSameAgentIDClosesOldConnection(t *testing.T) {s := NewServer(allowAllTestTokens)ts := newWSServer(t, s)diff --git a/internal/agentexec/types.go b/internal/agentexec/types.goindex 2a4976dfa4..a900135fbb 100644--- a/internal/agentexec/types.go+++ b/internal/agentexec/types.go@@ -11,15 +11,17 @@ type MessageType stringconst (// Agent -> Server messages- MsgTypeAgentRegister MessageType = "agent_register"- MsgTypeAgentPing MessageType = "agent_ping"- MsgTypeCommandResult MessageType = "command_result"+ MsgTypeAgentRegister MessageType = "agent_register"+ MsgTypeAgentPing MessageType = "agent_ping"+ MsgTypeCommandResult MessageType = "command_result"+ MsgTypeHostUpdateResult MessageType = "host_update_result"// Server -> Agent messagesMsgTypeRegistered MessageType = "registered"MsgTypePong MessageType = "pong"MsgTypeExecuteCmd MessageType = "execute_command"MsgTypeReadFile MessageType = "read_file"+ MsgTypeHostUpdate MessageType = "host_update"MsgTypeDeployPreflight MessageType = "deploy_preflight"MsgTypeDeployInstall MessageType = "deploy_install"MsgTypeDeployCancelJob MessageType = "deploy_cancel"@@ -126,6 +128,56 @@ type CommandResultPayload struct {Duration int64 `json:"duration_ms"`}+const HostUpdateOperationInstall = "install_os_updates"++// HostUpdatePayload is the closed, typed host-package operation sent to a+// Unified Agent. It intentionally has no command or package-name fields: the+// agent owns the package-manager command catalog and always updates the whole+// bounded set returned by its own preflight simulation.+type HostUpdatePayload struct {+ RequestID string `json:"request_id"`+ ActionID string `json:"action_id"`+ Operation string `json:"operation"`+ ExpectedInventoryHash string `json:"expected_inventory_hash"`+ Timeout int `json:"timeout,omitempty"`+}++type HostPackageUpdate struct {+ Name string `json:"name"`+ InstalledVersion string `json:"installed_version,omitempty"`+ AvailableVersion string `json:"available_version,omitempty"`+}++type HostPackageUpdateSnapshot struct {+ Supported bool `json:"supported"`+ Manager string `json:"manager,omitempty"`+ InventoryHash string `json:"inventory_hash,omitempty"`+ PendingCount int `json:"pending_count"`+ Packages []HostPackageUpdate `json:"packages,omitempty"`+ CheckedAt time.Time `json:"checked_at,omitempty"`+ RebootRequired bool `json:"reboot_required,omitempty"`+ Error string `json:"error,omitempty"`+}++const (+ HostUpdateVerificationVerified = "verified"+ HostUpdateVerificationFailed = "failed"+ HostUpdateVerificationInconclusive = "inconclusive"+)++// HostUpdateResultPayload carries execution and read-after-write evidence+// 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"`+}+// ConnectedAgent represents an agent connected via WebSockettype ConnectedAgent struct {AgentID stringdiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 3dea06991b..02e750e431 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -19881,6 +19881,7 @@ func TestContract_ProxmoxLifecycleActionsResolveNodeCommandAgentAndVerifyState(t"newRoutedActionExecutor(","newDockerContainerActionExecutor(r.resourceHandlers, r.agentExecServer)","newProxmoxGuestActionExecutor(r.resourceHandlers, r.agentExecServer)",+ "newHostUpdateActionExecutor(r.resourceHandlers, r.agentExecServer)",} {if !strings.Contains(routerSrc, snippet) {t.Fatalf("router must register Docker and Proxmox action executors through routed action executor; missing %q", snippet)@@ -19888,6 +19889,51 @@ func TestContract_ProxmoxLifecycleActionsResolveNodeCommandAgentAndVerifyState(t}}+func TestContract_HostUpdatesUseTypedFingerprintBoundAgentOperation(t *testing.T) {+ executorSource, err := os.ReadFile("host_update_action_executor.go")+ if err != nil {+ t.Fatalf("read host_update_action_executor.go: %v", err)+ }+ agentTypesSource, err := os.ReadFile("../agentexec/types.go")+ if err != nil {+ t.Fatalf("read agentexec types: %v", err)+ }+ agentRuntimeSource, err := os.ReadFile("../hostagent/package_updates.go")+ if err != nil {+ t.Fatalf("read package update runtime: %v", err)+ }++ executorSrc := string(executorSource)+ typesSrc := string(agentTypesSource)+ runtimeSrc := string(agentRuntimeSource)+ for _, snippet := range []string{+ "ExecuteHostUpdate(ctx context.Context, agentID string, req agentexec.HostUpdatePayload)",+ "ExpectedInventoryHash: resource.Agent.PackageUpdates.InventoryHash",+ "agentexec.HostUpdateOperationInstall",+ } {+ if !strings.Contains(executorSrc, snippet) {+ t.Fatalf("host update executor missing typed operation invariant %q", snippet)+ }+ }+ for _, snippet := range []string{+ "ExpectedInventoryHash string `json:\"expected_inventory_hash\"`",+ "const HostUpdateOperationInstall = \"install_os_updates\"",+ } {+ if !strings.Contains(typesSrc, snippet) {+ t.Fatalf("host update wire contract missing %q", snippet)+ }+ }+ for _, snippet := range []string{+ "if before.InventoryHash != strings.TrimSpace(req.ExpectedInventoryHash)",+ "\"--no-remove\"",+ "\"Dpkg::Options::=--force-confold\"",+ } {+ if !strings.Contains(runtimeSrc, snippet) {+ t.Fatalf("host update runtime missing fail-closed command-catalog invariant %q", snippet)+ }+ }+}+// TestContract_AgentCapabilitiesManifestIsPublic pins the auth// contract for the discovery surface: the manifest must be in the// router's publicPaths list so it serves without a token. Thediff --git a/internal/api/host_update_action_executor.go b/internal/api/host_update_action_executor.gonew file mode 100644index 0000000000..4dd5b8609d--- /dev/null+++ b/internal/api/host_update_action_executor.go@@ -0,0 +1,226 @@+package api++import (+ "context"+ "fmt"+ "regexp"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++const (+ hostPackageUpdateActionHandler = "host.package_updates"+ hostPackageUpdateCapability = "install_os_updates"+)++var hostPackageUpdateInventoryHashPattern = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`)++type hostUpdateAgentCommander interface {+ ExecuteHostUpdate(ctx context.Context, agentID string, req agentexec.HostUpdatePayload) (*agentexec.HostUpdateResultPayload, error)+ IsAgentConnected(agentID string) bool+}++type hostUpdateActionExecutor struct {+ resources *ResourceHandlers+ agents hostUpdateAgentCommander+ now func() time.Time+}++func newHostUpdateActionExecutor(resources *ResourceHandlers, agents hostUpdateAgentCommander) ActionExecutor {+ if resources == nil || agents == nil {+ return nil+ }+ return hostUpdateActionExecutor{resources: resources, agents: agents, now: time.Now}+}++func (e hostUpdateActionExecutor) ActionHandlerNames() []string {+ return []string{hostPackageUpdateActionHandler}+}++func (e hostUpdateActionExecutor) CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {+ if strings.TrimSpace(req.CapabilityName) != hostPackageUpdateCapability {+ return unified.ResourceActionReadiness{}+ }+ capability, ok := resourceCapabilityByName(resource.Capabilities, hostPackageUpdateCapability)+ if !ok || capability.InternalHandler != hostPackageUpdateActionHandler {+ return unified.ResourceActionReadiness{}+ }+ if err := e.validateResource(resource); err != nil {+ return unified.ResourceActionReadiness{+ Name: hostPackageUpdateCapability,+ Available: false,+ ReasonCode: hostUpdateUnavailableReasonCode(err),+ Reason: hostUpdateUnavailableReason(err),+ }+ }+ return unified.ResourceActionReadiness{Name: hostPackageUpdateCapability, Available: true}+}++func (e hostUpdateActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {+ record, err := unified.NormalizeActionAuditRecord(record)+ if err != nil {+ return nil, err+ }+ if strings.TrimSpace(record.Request.CapabilityName) != hostPackageUpdateCapability {+ return nil, fmt.Errorf("unsupported host update capability %q", record.Request.CapabilityName)+ }+ resource, err := e.currentResource(ctx, record.Request.ResourceID)+ if err != nil {+ return nil, err+ }+ agentID := strings.TrimSpace(resource.Agent.AgentID)+ result, err := e.agents.ExecuteHostUpdate(ctx, agentID, agentexec.HostUpdatePayload{+ RequestID: record.ID,+ ActionID: record.ID,+ Operation: agentexec.HostUpdateOperationInstall,+ ExpectedInventoryHash: resource.Agent.PackageUpdates.InventoryHash,+ Timeout: 900,+ })+ if err != nil {+ return nil, err+ }+ if result == nil {+ return nil, fmt.Errorf("host update agent returned no result")+ }++ 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+}++func (e hostUpdateActionExecutor) currentResource(ctx context.Context, resourceID string) (unified.Resource, error) {+ if e.resources == nil {+ return unified.Resource{}, fmt.Errorf("resource handler unavailable")+ }+ registry, err := e.resources.buildRegistry(GetOrgID(ctx))+ if err != nil {+ return unified.Resource{}, err+ }+ resource, ok := registry.Get(resourceID)+ if !ok || resource == nil {+ return unified.Resource{}, fmt.Errorf("resource %q is no longer present", resourceID)+ }+ if err := e.validateResource(*resource); err != nil {+ return unified.Resource{}, err+ }+ return *resource, nil+}++func (e hostUpdateActionExecutor) validateResource(resource unified.Resource) error {+ if resource.Type != unified.ResourceTypeAgent || resource.Agent == nil {+ return fmt.Errorf("resource is not an agent-managed host")+ }+ capability, ok := resourceCapabilityByName(resource.Capabilities, hostPackageUpdateCapability)+ if !ok || capability.InternalHandler != hostPackageUpdateActionHandler {+ return fmt.Errorf("host does not currently advertise typed OS updates")+ }+ if !resource.Agent.CommandsEnabled {+ return fmt.Errorf("host command operations are disabled")+ }+ status := resource.Agent.PackageUpdates+ if status == nil || !status.Supported || strings.TrimSpace(status.Manager) != "apt" {+ return fmt.Errorf("host package manager is unsupported")+ }+ if strings.TrimSpace(status.Error) != "" {+ return fmt.Errorf("host package update inventory has an error")+ }+ 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 {+ return fmt.Errorf("host package update inventory is stale")+ }+ if status.PendingCount <= 0 {+ return fmt.Errorf("host has no pending package updates")+ }+ agentID := strings.TrimSpace(resource.Agent.AgentID)+ if agentID == "" || e.agents == nil || !e.agents.IsAgentConnected(agentID) {+ return fmt.Errorf("host command agent is disconnected")+ }+ return nil+}++func (e hostUpdateActionExecutor) currentTime() time.Time {+ if e.now != nil {+ return e.now().UTC()+ }+ 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"+ }+ message := strings.ToLower(err.Error())+ switch {+ case strings.Contains(message, "not an agent-managed host"):+ return "unsupported_resource"+ case strings.Contains(message, "disabled"):+ return "host_commands_disabled"+ case strings.Contains(message, "unsupported"):+ return "unsupported_package_manager"+ case strings.Contains(message, "inventory") && strings.Contains(message, "error"):+ return "package_inventory_error"+ case strings.Contains(message, "fingerprint"):+ return "invalid_package_inventory"+ case strings.Contains(message, "stale"):+ return "stale_package_inventory"+ case strings.Contains(message, "no pending"):+ return "no_pending_updates"+ case strings.Contains(message, "disconnected"):+ return "command_agent_disconnected"+ default:+ return "capability_unavailable"+ }+}++func hostUpdateUnavailableReason(err error) string {+ switch hostUpdateUnavailableReasonCode(err) {+ case "unsupported_resource":+ return "This resource is not an agent-managed host."+ case "host_commands_disabled":+ return "Typed host operations are disabled for this agent."+ case "unsupported_package_manager":+ return "This host does not expose a supported package manager."+ case "package_inventory_error":+ return "Pulse could not inspect the host's package update state."+ case "invalid_package_inventory":+ return "The host package inventory cannot be verified safely."+ case "stale_package_inventory":+ return "The host package inventory is too old to update safely."+ case "no_pending_updates":+ return "The host has no pending standard package updates."+ case "command_agent_disconnected":+ return "The host command agent is not connected."+ default:+ return "Typed host package updates are not currently available."+ }+}diff --git a/internal/api/host_update_action_executor_test.go b/internal/api/host_update_action_executor_test.gonew file mode 100644index 0000000000..6e903c8f50--- /dev/null+++ b/internal/api/host_update_action_executor_test.go@@ -0,0 +1,200 @@+package api++import (+ "context"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"+)++type fakeHostUpdateAgent struct {+ connected bool+ result *agentexec.HostUpdateResultPayload+ err error+ agentID string+ requests []agentexec.HostUpdatePayload+}++var testHostPackageInventoryHash = "sha256:" + strings.Repeat("a", 64)+var testHostPackageEmptyInventoryHash = "sha256:" + strings.Repeat("b", 64)++func (f *fakeHostUpdateAgent) ExecuteHostUpdate(_ context.Context, agentID string, req agentexec.HostUpdatePayload) (*agentexec.HostUpdateResultPayload, error) {+ f.agentID = agentID+ f.requests = append(f.requests, req)+ return f.result, f.err+}++func (f *fakeHostUpdateAgent) IsAgentConnected(string) bool { return f.connected }++func TestHostUpdateActionExecutorDispatchesTypedOperationAndProjectsVerification(t *testing.T) {+ now := time.Now().UTC()+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})+ h.SetStateProvider(resourceUnifiedSeedProvider{+ snapshot: models.StateSnapshot{LastUpdate: now},+ resources: []unified.Resource{hostUpdateActionResource(now)},+ })+ 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},+ Verification: agentexec.HostUpdateVerificationVerified,+ }}+ executor := newHostUpdateActionExecutor(h, agents)++ result, err := executor.ExecuteAction(context.Background(), hostUpdateActionRecord("action-host-update"))+ if err != nil {+ t.Fatalf("ExecuteAction: %v", err)+ }+ if result == nil || !result.Success || result.Verification == nil || !result.Verification.Ran || !result.Verification.Success {+ t.Fatalf("result = %#v", result)+ }+ if !strings.Contains(result.Output, "3 pending before, 0 pending after") || !strings.Contains(result.Output, "reboot required: true") {+ t.Fatalf("output = %q", result.Output)+ }+ if len(agents.requests) != 1 || agents.agentID != "agent-1" {+ t.Fatalf("agent calls = %#v, agentID=%q", agents.requests, agents.agentID)+ }+ request := agents.requests[0]+ if request.ActionID != "action-host-update" || request.RequestID != "action-host-update" || request.Operation != agentexec.HostUpdateOperationInstall || request.ExpectedInventoryHash != testHostPackageInventoryHash || request.Timeout != 900 {+ t.Fatalf("typed request = %#v", request)+ }+}++func TestHostUpdateActionExecutorReportsInconclusiveVerificationHonestly(t *testing.T) {+ now := time.Now().UTC()+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})+ h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{hostUpdateActionResource(now)}})+ agents := &fakeHostUpdateAgent{connected: true, result: &agentexec.HostUpdateResultPayload{+ RequestID: "action-host-update", Success: true,+ Before: agentexec.HostPackageUpdateSnapshot{PendingCount: 2},+ After: agentexec.HostPackageUpdateSnapshot{PendingCount: 0},+ Verification: agentexec.HostUpdateVerificationInconclusive,+ Error: "package installation completed but verification was inconclusive",+ }}++ result, err := newHostUpdateActionExecutor(h, agents).ExecuteAction(context.Background(), hostUpdateActionRecord("action-host-update"))+ 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") {+ t.Fatalf("result = %#v", result)+ }+}++func TestPatrolFullModeRunsHostUpdateThroughCanonicalLifecycle(t *testing.T) {+ now := time.Now().UTC()+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})+ 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},+ Verification: agentexec.HostUpdateVerificationVerified,+ }}+ h.SetActionExecutor(newRoutedActionExecutor(h, newHostUpdateActionExecutor(h, agents)))+ store, err := h.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{+ CanonicalID: "agent:host-1",+ AutoRemediationPolicy: unified.AutoRemediationPolicy{+ Enabled: true, CapabilityNames: []string{hostPackageUpdateCapability},+ },+ SetAt: now, SetBy: "[email protected]",+ }); err != nil {+ t.Fatalf("SetResourceOperatorState: %v", err)+ }+ broker := NewPatrolActionBroker("default", h, func(context.Context, string) (PatrolActionPolicySnapshot, error) {+ return PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "full", FullModeUnlocked: true}, nil+ })+ disposition, err := broker.Submit(context.Background(), aicontracts.ActionProposal{+ ProposalID: "proposal-host-update", FindingID: "finding-host-update", InvestigationID: "investigation-host-update",+ ResourceID: "agent:host-1", CapabilityName: hostPackageUpdateCapability, Reason: "Install three pending OS updates",+ })+ if err != nil {+ t.Fatalf("Submit: %v", err)+ }+ if disposition.State != string(unified.ActionStateCompleted) || disposition.VerificationStatus != string(unified.VerificationVerified) {+ t.Fatalf("disposition = %#v", disposition)+ }+ if len(agents.requests) != 1 || agents.requests[0].Operation != agentexec.HostUpdateOperationInstall {+ t.Fatalf("typed agent requests = %#v", agents.requests)+ }+ audit, found, err := store.GetActionAudit(disposition.ActionID)+ if err != nil || !found {+ t.Fatalf("GetActionAudit: found=%v err=%v", found, err)+ }+ if len(audit.Approvals) != 1 || audit.Approvals[0].Actor != patrolActionPolicyActor || audit.Approvals[0].Method != unified.MethodPolicy || audit.Result == nil || audit.VerificationOutcome.Status != unified.VerificationVerified {+ t.Fatalf("audit = %#v", audit)+ }+}++func TestHostUpdateActionAvailabilityFailsClosed(t *testing.T) {+ now := time.Now().UTC()+ tests := []struct {+ name string+ mutate func(*unified.Resource)+ connected bool+ reasonCode string+ }{+ {name: "commands disabled", mutate: func(r *unified.Resource) { r.Agent.CommandsEnabled = false }, connected: true, reasonCode: "host_commands_disabled"},+ {name: "stale inventory", mutate: func(r *unified.Resource) { r.Agent.PackageUpdates.CheckedAt = now.Add(-time.Hour) }, connected: true, reasonCode: "stale_package_inventory"},+ {name: "inventory error", mutate: func(r *unified.Resource) { r.Agent.PackageUpdates.Error = "inspection failed" }, connected: true, reasonCode: "package_inventory_error"},+ {name: "invalid inventory fingerprint", mutate: func(r *unified.Resource) { r.Agent.PackageUpdates.InventoryHash = "sha256:bad" }, connected: true, reasonCode: "invalid_package_inventory"},+ {name: "no pending", mutate: func(r *unified.Resource) { r.Agent.PackageUpdates.PendingCount = 0 }, connected: true, reasonCode: "no_pending_updates"},+ {name: "disconnected", mutate: func(*unified.Resource) {}, connected: false, reasonCode: "command_agent_disconnected"},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ resource := hostUpdateActionResource(now)+ tc.mutate(&resource)+ executor := hostUpdateActionExecutor{agents: &fakeHostUpdateAgent{connected: tc.connected}, now: func() time.Time { return now }}+ readiness := executor.CheckActionAvailable(context.Background(), unified.ActionRequest{CapabilityName: hostPackageUpdateCapability}, resource)+ if readiness.Available || readiness.Name != hostPackageUpdateCapability || readiness.ReasonCode != tc.reasonCode {+ t.Fatalf("readiness = %#v", readiness)+ }+ })+ }+}++func hostUpdateActionResource(now time.Time) unified.Resource {+ return unified.Resource{+ ID: "agent:host-1", Type: unified.ResourceTypeAgent, Technology: "linux", Name: "host-1",+ Status: unified.StatusOnline, LastSeen: now, UpdatedAt: now,+ Sources: []unified.DataSource{unified.SourceAgent},+ 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},+ },+ Capabilities: []unified.ResourceCapability{{+ Name: hostPackageUpdateCapability, Type: unified.CapabilityTypeCommon,+ Description: "Install standard OS updates", MinimumApprovalLevel: unified.ApprovalAdmin,+ AutoAuthorization: unified.AutoAuthorizeElevated, Platform: "linux", InternalHandler: hostPackageUpdateActionHandler,+ }},+ }+}++func hostUpdateActionRecord(actionID string) unified.ActionAuditRecord {+ now := time.Now().UTC()+ return unified.ActionAuditRecord{+ ID: actionID, CreatedAt: now, UpdatedAt: now, State: unified.ActionStateExecuting,+ Request: unified.ActionRequest{+ RequestID: "request-" + actionID, ResourceID: "agent:host-1", CapabilityName: hostPackageUpdateCapability,+ Reason: "Install pending host updates", RequestedBy: "pulse_patrol", Params: map[string]any{},+ },+ Plan: unified.ActionPlan{+ ActionID: actionID, RequestID: "request-" + actionID, Allowed: true, RequiresApproval: true,+ ApprovalPolicy: unified.ApprovalAdmin, PlannedAt: now.Add(-time.Minute), ExpiresAt: now.Add(time.Minute),+ ResourceVersion: "resource:sha256:test", PolicyVersion: "policy:sha256:test", PlanHash: "sha256:test",+ },+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex 3ca9d4da9c..28f2462a0b 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -636,6 +636,7 @@ func (r *Router) setupRoutes() {r.resourceHandlers,newDockerContainerActionExecutor(r.resourceHandlers, r.agentExecServer),newProxmoxGuestActionExecutor(r.resourceHandlers, r.agentExecServer),+ newHostUpdateActionExecutor(r.resourceHandlers, r.agentExecServer),))}if r.monitor != nil {diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex affa7737f2..cf916bfca5 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -83,6 +83,7 @@ type Config struct {newCommandClientFn func(Config, string, string, string, string) *CommandClientrunCommandClientFn func(*CommandClient, context.Context) errorupdatedFromVersionFn func() string+ packageUpdates *packageUpdateManager}// Agent is responsible for collecting host metrics and shipping them to Pulse.@@ -117,6 +118,7 @@ type Agent struct {collector SystemCollectornewCommandClient func(Config, string, string, string, string) *CommandClientrunCommandClient func(*CommandClient, context.Context) error+ packageUpdates *packageUpdateManager// lastAuthFailureLog throttles the actionable 401 error so a permanently// rejected token does not spam the log every report interval. Only touched@@ -312,6 +314,12 @@ func New(cfg Config) (*Agent, error) {Msg("Agent was auto-updated")}+ packageUpdates := cfg.packageUpdates+ if packageUpdates == nil {+ packageUpdates = newPackageUpdateManager(platform)+ }+ cfg.packageUpdates = packageUpdates+agent := &Agent{cfg: cfg,logger: logger,@@ -337,6 +345,7 @@ func New(cfg Config) (*Agent, error) {collector: collector,newCommandClient: newCommandClientFn,runCommandClient: runCommandClientFn,+ packageUpdates: packageUpdates,}// Create command client for AI command execution (only if enabled)@@ -827,6 +836,10 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {// would be capped by collectCtx's 10s timeout.clusterSensors := a.collectClusterSensors(ctx)+ packageUpdateCtx, cancelPackageUpdates := context.WithTimeout(ctx, 20*time.Second)+ packageUpdates := a.currentPackageUpdateStatus(packageUpdateCtx)+ cancelPackageUpdates()+// 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.updatedFrom := a.updatedFrom@@ -849,20 +862,21 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {Modules: a.currentModuleStatus(),},Host: agentshost.HostInfo{- ID: a.machineID,- Hostname: a.hostname,- DisplayName: a.displayName,- MachineID: a.machineID,- Platform: a.platform,- OSName: a.osName,- OSVersion: a.osVersion,- KernelVersion: a.kernelVersion,- Architecture: a.architecture,- CPUModel: "",- CPUCount: snapshot.CPUCount,- UptimeSeconds: int64(uptime),- LoadAverage: append([]float64(nil), snapshot.LoadAverage...),- ReportIP: runtimeConfig.reportIP,+ ID: a.machineID,+ Hostname: a.hostname,+ DisplayName: a.displayName,+ MachineID: a.machineID,+ Platform: a.platform,+ OSName: a.osName,+ OSVersion: a.osVersion,+ KernelVersion: a.kernelVersion,+ Architecture: a.architecture,+ CPUModel: "",+ CPUCount: snapshot.CPUCount,+ UptimeSeconds: int64(uptime),+ LoadAverage: append([]float64(nil), snapshot.LoadAverage...),+ ReportIP: runtimeConfig.reportIP,+ PackageUpdates: packageUpdates,},Metrics: agentshost.Metrics{CPUUsagePercent: snapshot.CPUUsagePercent,@@ -883,6 +897,31 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {return report, nil}+func (a *Agent) currentPackageUpdateStatus(ctx context.Context) *agentshost.PackageUpdateStatus {+ if a == nil || a.packageUpdates == nil {+ return nil+ }+ snapshot := a.packageUpdates.Snapshot(ctx, false)+ packages := make([]agentshost.PackageUpdate, len(snapshot.Packages))+ for i, pkg := range snapshot.Packages {+ packages[i] = agentshost.PackageUpdate{+ Name: pkg.Name,+ InstalledVersion: pkg.InstalledVersion,+ AvailableVersion: pkg.AvailableVersion,+ }+ }+ return &agentshost.PackageUpdateStatus{+ Supported: snapshot.Supported,+ Manager: snapshot.Manager,+ InventoryHash: snapshot.InventoryHash,+ PendingCount: snapshot.PendingCount,+ Packages: packages,+ CheckedAt: snapshot.CheckedAt,+ RebootRequired: snapshot.RebootRequired,+ Error: snapshot.Error,+ }+}+func (a *Agent) sendReport(ctx context.Context, report agentshost.Report) error {payload, err := json.Marshal(report)if err != nil {diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.goindex 62b7c558a6..1c56965707 100644--- a/internal/hostagent/commands.go+++ b/internal/hostagent/commands.go@@ -104,6 +104,7 @@ type CommandClient struct {serverFingerprint stringdeploySSHUser stringcommandPolicy *agentexec.CommandPolicy+ packageUpdates *packageUpdateManagersshKnownHosts sshknownhosts.ManagersshKnownHostsOnce sync.OncesshKnownHostsErr error@@ -135,6 +136,7 @@ func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *serverFingerprint: cfg.ServerFingerprint,deploySSHUser: cfg.DeploySSHUser,commandPolicy: agentexec.DefaultPolicy(),+ packageUpdates: cfg.packageUpdates,logger: logger,done: make(chan struct{}),}@@ -155,17 +157,19 @@ func (c *CommandClient) stopChan() <-chan struct{} {type messageType stringconst (- msgTypeAgentRegister messageType = "agent_register"- msgTypeAgentPing messageType = "agent_ping"- msgTypeCommandResult messageType = "command_result"- msgTypeRegistered messageType = "registered"- msgTypePong messageType = "pong"- msgTypeExecuteCmd messageType = "execute_command"- msgTypeReadFile messageType = "read_file"- msgTypeDeployPreflight messageType = "deploy_preflight"- msgTypeDeployInstall messageType = "deploy_install"- msgTypeDeployCancel messageType = "deploy_cancel"- msgTypeDeployProgress messageType = "deploy_progress"+ msgTypeAgentRegister messageType = "agent_register"+ msgTypeAgentPing messageType = "agent_ping"+ msgTypeCommandResult messageType = "command_result"+ msgTypeRegistered messageType = "registered"+ msgTypePong messageType = "pong"+ msgTypeExecuteCmd messageType = "execute_command"+ msgTypeReadFile messageType = "read_file"+ msgTypeHostUpdate messageType = "host_update"+ msgTypeHostUpdateResult messageType = "host_update_result"+ msgTypeDeployPreflight messageType = "deploy_preflight"+ msgTypeDeployInstall messageType = "deploy_install"+ msgTypeDeployCancel messageType = "deploy_cancel"+ msgTypeDeployProgress messageType = "deploy_progress")type wsMessage struct {@@ -520,6 +524,14 @@ 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 {+ c.logger.Error().Err(err).Msg("Failed to parse host_update payload")+ continue+ }+ go c.handleHostUpdate(ctx, conn, payload)+case msgTypeDeployPreflight:var payload deployPreflightPayloadif err := json.Unmarshal(msg.Payload, &payload); err != nil {@@ -550,6 +562,43 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn}}+func (c *CommandClient) handleHostUpdate(ctx context.Context, conn *websocket.Conn, payload agentexec.HostUpdatePayload) {+ timeout := time.Duration(payload.Timeout) * time.Second+ if timeout <= 0 {+ timeout = 15 * time.Minute+ }+ updateCtx, cancel := context.WithTimeout(ctx, timeout)+ defer cancel()++ result := agentexec.HostUpdateResultPayload{+ RequestID: strings.TrimSpace(payload.RequestID),+ Verification: agentexec.HostUpdateVerificationInconclusive,+ }+ if c.packageUpdates == nil {+ result.Error = "host package update service is unavailable"+ } else {+ result = c.packageUpdates.Apply(updateCtx, payload)+ }++ 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")+ return+ }+ msg := wsMessage{+ Type: msgTypeHostUpdateResult,+ ID: payload.RequestID,+ Timestamp: time.Now(),+ Payload: encoded,+ }+ c.connMu.Lock()+ err = conn.WriteJSON(msg)+ c.connMu.Unlock()+ if err != nil {+ c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to send host update result")+ }+}+func (c *CommandClient) handleExecuteCommand(ctx context.Context, conn *websocket.Conn, payload executeCommandPayload) {startTime := time.Now()diff --git a/internal/hostagent/commands_host_update_test.go b/internal/hostagent/commands_host_update_test.gonew file mode 100644index 0000000000..8136d38a19--- /dev/null+++ b/internal/hostagent/commands_host_update_test.go@@ -0,0 +1,104 @@+package hostagent++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rs/zerolog"+)++func TestCommandClientHandlesTypedHostUpdateWithoutExecuteCommand(t *testing.T) {+ manager := newPackageUpdateManager("linux")+ 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+ manager.run = func(_ context.Context, _ []string, name string, args ...string) packageUpdateCommandResult {+ if name != "apt-get" {+ t.Fatalf("executable = %q, want apt-get", name)+ }+ if strings.Contains(strings.Join(args, " "), "-s") {+ simulations+++ if simulations <= 2 {+ return packageUpdateCommandResult{stdout: "Inst openssl [1.0] (1.1 repo [amd64])\n"}+ }+ }+ return packageUpdateCommandResult{}+ }+ expectedInventoryHash := aptUpgradeInventoryHash("Inst openssl [1.0] (1.1 repo [amd64])\n")++ upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}+ resultCh := make(chan agentexec.HostUpdateResultPayload, 1)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ conn, err := upgrader.Upgrade(w, r, nil)+ if err != nil {+ t.Errorf("upgrade: %v", err)+ return+ }+ defer conn.Close()+ var registration wsMessage+ if err := conn.ReadJSON(®istration); err != nil {+ t.Errorf("read registration: %v", err)+ return+ }+ registered, _ := json.Marshal(registeredPayload{Success: true, Message: "Registered"})+ if err := conn.WriteJSON(wsMessage{Type: msgTypeRegistered, Timestamp: time.Now(), Payload: registered}); err != nil {+ t.Errorf("write registered: %v", err)+ return+ }+ payload, _ := json.Marshal(agentexec.HostUpdatePayload{+ RequestID: "request-1", ActionID: "action-1", Operation: agentexec.HostUpdateOperationInstall, ExpectedInventoryHash: expectedInventoryHash, Timeout: 5,+ })+ if err := conn.WriteJSON(wsMessage{Type: msgTypeHostUpdate, ID: "request-1", Timestamp: time.Now(), Payload: payload}); err != nil {+ t.Errorf("write host update: %v", err)+ return+ }+ var response wsMessage+ if err := conn.ReadJSON(&response); err != nil {+ t.Errorf("read host update result: %v", err)+ return+ }+ if response.Type != msgTypeHostUpdateResult {+ t.Errorf("response type = %q", response.Type)+ return+ }+ var result agentexec.HostUpdateResultPayload+ if err := json.Unmarshal(response.Payload, &result); err != nil {+ t.Errorf("decode result: %v", err)+ return+ }+ resultCh <- result+ }))+ defer server.Close()++ ctx, cancel := context.WithCancel(context.Background())+ client := &CommandClient{+ pulseURL: strings.TrimRight(server.URL, "/"), apiToken: "token", agentID: "agent-1", hostname: "host-1",+ platform: "linux", version: "6.0.6", packageUpdates: manager, logger: zerolog.Nop(), done: make(chan struct{}),+ }+ errCh := make(chan error, 1)+ go func() { errCh <- client.connectAndHandle(ctx) }()++ select {+ case result := <-resultCh:+ if !result.Success || result.Verification != agentexec.HostUpdateVerificationVerified || result.Before.PendingCount != 1 || result.After.PendingCount != 0 {+ t.Fatalf("result = %#v", result)+ }+ cancel()+ case <-time.After(10 * time.Second):+ cancel()+ t.Fatal("timed out waiting for typed host update result")+ }+ select {+ case <-errCh:+ case <-time.After(5 * time.Second):+ t.Fatal("command client did not stop")+ }+}diff --git a/internal/hostagent/package_updates.go b/internal/hostagent/package_updates.gonew file mode 100644index 0000000000..2bc9353380--- /dev/null+++ b/internal/hostagent/package_updates.go@@ -0,0 +1,312 @@+package hostagent++import (+ "bufio"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "os"+ "os/exec"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+)++const (+ packageUpdateCacheTTL = 30 * time.Minute+ packageUpdateMaxPackages = 200+)++var (+ packageUpdateCommandContext = exec.CommandContext+ packageUpdateLookPath = exec.LookPath+ packageUpdateStat = os.Stat+)++// packageUpdateManager owns both host package telemetry and the only command+// catalog allowed to mutate OS packages. Callers select a typed operation;+// package-manager commands and flags never cross the network boundary.+type packageUpdateManager struct {+ platform string+ now func() time.Time+ cacheTTL time.Duration+ run func(context.Context, []string, string, ...string) packageUpdateCommandResult+ lookPath func(string) (string, error)+ stat func(string) (os.FileInfo, error)++ mu sync.Mutex+ cached *agentexec.HostPackageUpdateSnapshot+}++func newPackageUpdateManager(platform string) *packageUpdateManager {+ return &packageUpdateManager{+ platform: strings.ToLower(strings.TrimSpace(platform)),+ now: time.Now,+ cacheTTL: packageUpdateCacheTTL,+ run: runPackageUpdateCommand,+ lookPath: packageUpdateLookPath,+ stat: packageUpdateStat,+ }+}++func (m *packageUpdateManager) Snapshot(ctx context.Context, force bool) agentexec.HostPackageUpdateSnapshot {+ if m == nil {+ return agentexec.HostPackageUpdateSnapshot{}+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ return m.snapshotLocked(ctx, force)+}++func (m *packageUpdateManager) snapshotLocked(ctx context.Context, force bool) agentexec.HostPackageUpdateSnapshot {+ now := m.currentTime()+ if !force && m.cached != nil && now.Sub(m.cached.CheckedAt) < m.cacheTTL {+ return cloneHostPackageUpdateSnapshot(*m.cached)+ }++ snapshot := agentexec.HostPackageUpdateSnapshot{CheckedAt: now}+ if m.platform != "linux" {+ m.storeSnapshot(snapshot)+ return snapshot+ }+ if _, err := m.lookPath("apt-get"); err != nil {+ m.storeSnapshot(snapshot)+ return snapshot+ }++ snapshot.Supported = true+ snapshot.Manager = "apt"+ result := m.run(ctx, nil, "apt-get", "-s", "-o", "Debug::NoLocking=1", "upgrade")+ if result.err != nil || result.exitCode != 0 {+ snapshot.Error = "package update inspection failed"+ snapshot.RebootRequired = m.hostRebootRequired()+ m.storeSnapshot(snapshot)+ return snapshot+ }++ snapshot.Packages = parseAPTSimulatedUpgrades(result.stdout)+ snapshot.PendingCount = countAPTSimulatedUpgrades(result.stdout)+ snapshot.InventoryHash = aptUpgradeInventoryHash(result.stdout)+ snapshot.RebootRequired = m.hostRebootRequired()+ m.storeSnapshot(snapshot)+ return cloneHostPackageUpdateSnapshot(snapshot)+}++func (m *packageUpdateManager) Apply(ctx context.Context, req agentexec.HostUpdatePayload) (result agentexec.HostUpdateResultPayload) {+ startedAt := time.Now()+ result = agentexec.HostUpdateResultPayload{RequestID: strings.TrimSpace(req.RequestID)}+ defer func() { result.Duration = time.Since(startedAt).Milliseconds() }()++ if strings.TrimSpace(req.Operation) != agentexec.HostUpdateOperationInstall {+ result.Verification = agentexec.HostUpdateVerificationInconclusive+ result.Error = "unsupported typed host update operation"+ return result+ }++ m.mu.Lock()+ defer m.mu.Unlock()++ probe := m.snapshotLocked(ctx, true)+ if !probe.Supported {+ result.Before = probe+ result.After = probe+ result.Verification = agentexec.HostUpdateVerificationInconclusive+ result.Error = "host package updates are not supported by this agent"+ return result+ }++ refresh := m.run(ctx, nil, "apt-get", "update")+ if refresh.err != nil || refresh.exitCode != 0 {+ result.Before = probe+ result.After = probe+ result.Verification = agentexec.HostUpdateVerificationInconclusive+ result.Error = "package index refresh failed"+ return result+ }++ before := m.snapshotLocked(ctx, true)+ result.Before = before+ if before.Error != "" {+ result.After = before+ result.Verification = agentexec.HostUpdateVerificationInconclusive+ result.Error = "package update preflight failed"+ return result+ }+ if before.InventoryHash != strings.TrimSpace(req.ExpectedInventoryHash) {+ result.After = before+ result.Verification = agentexec.HostUpdateVerificationInconclusive+ result.Error = "package update inventory changed; replan required"+ return result+ }+ if before.PendingCount == 0 {+ result.Success = true+ result.After = before+ result.Verification = agentexec.HostUpdateVerificationVerified+ return result+ }++ env := []string{+ "DEBIAN_FRONTEND=noninteractive",+ "APT_LISTCHANGES_FRONTEND=none",+ "NEEDRESTART_MODE=a",+ }+ 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)+ result.After = after+ result.Verification = agentexec.HostUpdateVerificationFailed+ result.Error = "package installation failed"+ return result+ }++ result.Success = true+ after := m.snapshotLocked(ctx, true)+ result.After = after+ if after.Error != "" {+ result.Verification = agentexec.HostUpdateVerificationInconclusive+ result.Error = "package installation completed but verification was inconclusive"+ return result+ }+ if after.PendingCount != 0 {+ result.Verification = agentexec.HostUpdateVerificationFailed+ result.Error = "package installation completed but updates remain pending"+ return result+ }+ result.Verification = agentexec.HostUpdateVerificationVerified+ return result+}++type packageUpdateCommandResult struct {+ stdout string+ stderr string+ exitCode int+ err error+}++func runPackageUpdateCommand(ctx context.Context, env []string, name string, args ...string) packageUpdateCommandResult {+ cmd := packageUpdateCommandContext(ctx, name, args...)+ if len(env) > 0 {+ cmd.Env = append(os.Environ(), env...)+ }+ stdout := newCappedBuffer(maxCommandOutputSize)+ stderr := newCappedBuffer(maxCommandOutputSize)+ cmd.Stdout = stdout+ cmd.Stderr = stderr+ err := cmd.Run()+ result := packageUpdateCommandResult{stdout: stdout.String(), stderr: stderr.String(), err: err}+ if err == nil {+ return result+ }+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ result.exitCode = exitErr.ExitCode()+ } else {+ result.exitCode = -1+ }+ return result+}++func parseAPTSimulatedUpgrades(output string) []agentexec.HostPackageUpdate {+ updates := make([]agentexec.HostPackageUpdate, 0)+ scanner := bufio.NewScanner(strings.NewReader(output))+ for scanner.Scan() && len(updates) < packageUpdateMaxPackages {+ line := strings.TrimSpace(scanner.Text())+ if !strings.HasPrefix(line, "Inst ") {+ continue+ }+ fields := strings.Fields(line)+ if len(fields) < 2 {+ continue+ }+ name := strings.TrimSpace(fields[1])+ if name == "" {+ continue+ }+ updates = append(updates, agentexec.HostPackageUpdate{+ Name: name,+ InstalledVersion: delimitedValue(line, "[", "]"),+ AvailableVersion: firstParenthesizedField(line),+ })+ }+ return updates+}++func countAPTSimulatedUpgrades(output string) int {+ count := 0+ scanner := bufio.NewScanner(strings.NewReader(output))+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if strings.HasPrefix(line, "Inst ") && len(strings.Fields(line)) >= 2 {+ count+++ }+ }+ return count+}++func aptUpgradeInventoryHash(output string) string {+ lines := make([]string, 0)+ scanner := bufio.NewScanner(strings.NewReader(output))+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if strings.HasPrefix(line, "Inst ") && len(strings.Fields(line)) >= 2 {+ lines = append(lines, line)+ }+ }+ sort.Strings(lines)+ sum := sha256.Sum256([]byte(strings.Join(lines, "\n")))+ return "sha256:" + hex.EncodeToString(sum[:])+}++func delimitedValue(value, start, end string) string {+ startIndex := strings.Index(value, start)+ if startIndex < 0 {+ return ""+ }+ remainder := value[startIndex+len(start):]+ endIndex := strings.Index(remainder, end)+ if endIndex < 0 {+ return ""+ }+ return strings.TrimSpace(remainder[:endIndex])+}++func firstParenthesizedField(value string) string {+ start := strings.Index(value, "(")+ if start < 0 {+ return ""+ }+ remainder := strings.TrimSpace(value[start+1:])+ if end := strings.IndexAny(remainder, " )"); end >= 0 {+ return strings.TrimSpace(remainder[:end])+ }+ return strings.TrimSuffix(remainder, ")")+}++func (m *packageUpdateManager) hostRebootRequired() bool {+ if m == nil || m.stat == nil {+ return false+ }+ _, err := m.stat("/var/run/reboot-required")+ return err == nil+}++func (m *packageUpdateManager) currentTime() time.Time {+ if m != nil && m.now != nil {+ return m.now().UTC()+ }+ return time.Now().UTC()+}++func (m *packageUpdateManager) storeSnapshot(snapshot agentexec.HostPackageUpdateSnapshot) {+ copy := cloneHostPackageUpdateSnapshot(snapshot)+ m.cached = ©+}++func cloneHostPackageUpdateSnapshot(snapshot agentexec.HostPackageUpdateSnapshot) agentexec.HostPackageUpdateSnapshot {+ snapshot.Packages = append([]agentexec.HostPackageUpdate(nil), snapshot.Packages...)+ return snapshot+}diff --git a/internal/hostagent/package_updates_test.go b/internal/hostagent/package_updates_test.gonew file mode 100644index 0000000000..5c839aa407--- /dev/null+++ b/internal/hostagent/package_updates_test.go@@ -0,0 +1,187 @@+package hostagent++import (+ "context"+ "errors"+ "os"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+)++func TestParseAPTSimulatedUpgrades(t *testing.T) {+ output := `Reading package lists...+Inst openssl [3.0.11-1] (3.0.12-1 Debian-Security:12/stable-security [amd64])+Inst linux-image-amd64 [6.1.0-18] (6.1.0-19 Debian:12/stable [amd64])+Conf openssl (3.0.12-1 Debian-Security:12/stable-security [amd64])`++ got := parseAPTSimulatedUpgrades(output)+ want := []agentexec.HostPackageUpdate{+ {Name: "openssl", InstalledVersion: "3.0.11-1", AvailableVersion: "3.0.12-1"},+ {Name: "linux-image-amd64", InstalledVersion: "6.1.0-18", AvailableVersion: "6.1.0-19"},+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("updates = %#v, want %#v", got, want)+ }+ if count := countAPTSimulatedUpgrades(output); count != 2 {+ t.Fatalf("pending count = %d, want 2", count)+ }+}++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.lookPath = func(name string) (string, error) {+ if name != "apt-get" {+ t.Fatalf("lookPath(%q), want apt-get", name)+ }+ return "/usr/bin/apt-get", nil+ }+ fileInfo, err := os.Stat(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ m.stat = func(path string) (os.FileInfo, error) {+ if path != "/var/run/reboot-required" {+ t.Fatalf("stat path = %q", path)+ }+ return fileInfo, nil+ }++ type invocation struct {+ env []string+ name string+ args []string+ }+ var calls []invocation+ simulations := 0+ m.run = func(_ context.Context, env []string, name string, args ...string) packageUpdateCommandResult {+ calls = append(calls, invocation{env: append([]string(nil), env...), name: name, args: append([]string(nil), args...)})+ if name != "apt-get" {+ return packageUpdateCommandResult{exitCode: -1, err: errors.New("unexpected executable")}+ }+ if strings.Contains(strings.Join(args, " "), "-s") {+ simulations+++ if simulations <= 2 {+ return packageUpdateCommandResult{stdout: beforeOutput}+ }+ return packageUpdateCommandResult{}+ }+ return packageUpdateCommandResult{}+ }++ result := m.Apply(context.Background(), agentexec.HostUpdatePayload{+ RequestID: "request-1",+ ActionID: "action-1",+ Operation: agentexec.HostUpdateOperationInstall,+ ExpectedInventoryHash: aptUpgradeInventoryHash(beforeOutput),+ })+ if !result.Success || result.Verification != agentexec.HostUpdateVerificationVerified {+ t.Fatalf("result = %#v, want successful verified update", result)+ }+ if result.Before.PendingCount != 2 || result.After.PendingCount != 0 || !result.After.RebootRequired {+ t.Fatalf("before/after = %#v / %#v", result.Before, result.After)+ }+ if len(calls) != 5 {+ t.Fatalf("calls = %d, want probe, refresh, preflight, install, verify", len(calls))+ }+ if got := strings.Join(calls[1].args, " "); got != "update" {+ t.Fatalf("refresh args = %q", got)+ }+ install := calls[3]+ if install.name != "apt-get" || !strings.Contains(strings.Join(install.args, " "), "--no-remove") || !strings.Contains(strings.Join(install.args, " "), "--force-confold") {+ t.Fatalf("install invocation = %#v", install)+ }+ if !containsString(install.env, "DEBIAN_FRONTEND=noninteractive") || !containsString(install.env, "NEEDRESTART_MODE=a") {+ t.Fatalf("install env = %#v", install.env)+ }+ for _, call := range calls {+ if call.name == "sh" || call.name == "bash" {+ t.Fatalf("typed package update must not dispatch a shell: %#v", call)+ }+ }+}++func TestPackageUpdateManagerFailsClosedWhenRefreshFails(t *testing.T) {+ m := newPackageUpdateManager("linux")+ 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+ m.run = func(_ context.Context, _ []string, _ string, args ...string) packageUpdateCommandResult {+ calls+++ if strings.Join(args, " ") == "update" {+ return packageUpdateCommandResult{exitCode: 100, err: errors.New("exit status 100")}+ }+ 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.Success || result.Verification != agentexec.HostUpdateVerificationInconclusive || result.Error != "package index refresh failed" {+ t.Fatalf("result = %#v", result)+ }+ if calls != 2 {+ t.Fatalf("calls = %d, want probe and refresh only", calls)+ }+}++func TestPackageUpdateManagerRefusesRefreshTimeInventoryDriftBeforeInstall(t *testing.T) {+ m := newPackageUpdateManager("linux")+ 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"+ refreshed := stale + "Inst curl [8.0] (8.1 repo [amd64])\n"+ simulations := 0+ installCalls := 0+ m.run = func(_ context.Context, _ []string, _ string, args ...string) packageUpdateCommandResult {+ joined := strings.Join(args, " ")+ if strings.Contains(joined, "-s") {+ simulations+++ if simulations == 1 {+ return packageUpdateCommandResult{stdout: stale}+ }+ return packageUpdateCommandResult{stdout: refreshed}+ }+ if strings.Contains(joined, "upgrade") {+ installCalls+++ }+ return packageUpdateCommandResult{}+ }++ result := m.Apply(context.Background(), agentexec.HostUpdatePayload{+ RequestID: "r1", ActionID: "a1", Operation: agentexec.HostUpdateOperationInstall, ExpectedInventoryHash: aptUpgradeInventoryHash(stale),+ })+ if result.Success || result.Error != "package update inventory changed; replan required" || result.Before.InventoryHash != aptUpgradeInventoryHash(refreshed) {+ t.Fatalf("result = %#v", result)+ }+ if installCalls != 0 {+ t.Fatalf("install calls = %d, want zero on preflight drift", installCalls)+ }+}++func TestPackageUpdateSnapshotCachesAndUnsupportedPlatformsFailClosed(t *testing.T) {+ now := time.Date(2026, 7, 11, 1, 0, 0, 0, time.UTC)+ m := newPackageUpdateManager("windows")+ 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")+ return packageUpdateCommandResult{}+ }++ first := m.Snapshot(context.Background(), false)+ second := m.Snapshot(context.Background(), false)+ if first.Supported || second.Supported || !first.CheckedAt.Equal(now) || !second.CheckedAt.Equal(now) {+ t.Fatalf("snapshots = %#v / %#v", first, second)+ }+}++func containsString(values []string, want string) bool {+ for _, value := range values {+ if value == want {+ return true+ }+ }+ return false+}diff --git a/internal/models/converters.go b/internal/models/converters.goindex 7885af5cd8..5723aebafe 100644--- a/internal/models/converters.go+++ b/internal/models/converters.go@@ -511,6 +511,7 @@ func (h Host) ToFrontend() HostFrontend {AppliedConfig: cloneAgentConfigFingerprint(h.AppliedConfig),AgentUpdate: cloneAgentUpdateStatus(h.AgentUpdate),AgentModules: cloneAgentModuleStatuses(h.AgentModules),+ PackageUpdates: cloneHostPackageUpdateStatus(h.PackageUpdates),IsLegacy: h.IsLegacy,LinkedNodeID: h.LinkedNodeID,}diff --git a/internal/models/deepcopy.go b/internal/models/deepcopy.goindex 3eac9f6a56..c0de0ec0c4 100644--- a/internal/models/deepcopy.go+++ b/internal/models/deepcopy.go@@ -348,6 +348,15 @@ func cloneHostCephCluster(src *HostCephCluster) *HostCephCluster {return &normalized}+func cloneHostPackageUpdateStatus(src *HostPackageUpdateStatus) *HostPackageUpdateStatus {+ if src == nil {+ return nil+ }+ dest := *src+ dest.Packages = append([]HostPackageUpdate(nil), src.Packages...)+ return &dest+}+func cloneHost(src Host) Host {dest := srcdest.LoadAverage = append([]float64(nil), src.LoadAverage...)@@ -358,6 +367,7 @@ func cloneHost(src Host) Host {dest.RAID = cloneHostRAIDArrays(src.RAID)dest.Unraid = cloneHostUnraidStorage(src.Unraid)dest.Ceph = cloneHostCephCluster(src.Ceph)+ dest.PackageUpdates = cloneHostPackageUpdateStatus(src.PackageUpdates)dest.TokenLastUsedAt = cloneTimePtr(src.TokenLastUsedAt)dest.Tags = append([]string(nil), src.Tags...)dest.DiskExclude = append([]string(nil), src.DiskExclude...)diff --git a/internal/models/deepcopy_test.go b/internal/models/deepcopy_test.goindex fff6d83996..2f86ef0ebb 100644--- a/internal/models/deepcopy_test.go+++ b/internal/models/deepcopy_test.go@@ -298,12 +298,17 @@ func TestCloneHost_MapIsolation(t *testing.T) {LimitsPercent: map[string]int{"cpu_speed_limit": 100},},},+ PackageUpdates: &HostPackageUpdateStatus{+ Supported: true,+ Packages: []HostPackageUpdate{{Name: "openssl"}},+ },}dst := cloneHost(src)dst.Tags = append(dst.Tags, "new:val")dst.Sensors.TemperatureCelsius["gpu"] = 65.0dst.Sensors.ThermalState.LimitsPercent["cpu_speed_limit"] = 80*dst.Sensors.ThermalState.ThermalWarningLevel = 1+ dst.PackageUpdates.Packages[0].Name = "mutated"if len(src.Tags) != 1 {t.Error("clone tags should be independent")}@@ -316,6 +321,9 @@ func TestCloneHost_MapIsolation(t *testing.T) {if *src.Sensors.ThermalState.ThermalWarningLevel != 0 {t.Error("clone thermal warning pointer should be independent")}+ if src.PackageUpdates.Packages[0].Name != "openssl" {+ t.Error("clone package update inventory should be independent")+ }}func TestCloneHosts_Nil(t *testing.T) {diff --git a/internal/models/models.go b/internal/models/models.goindex edf3ee162f..628b9522cb 100644--- a/internal/models/models.go+++ b/internal/models/models.go@@ -247,43 +247,44 @@ func (c Container) NormalizeCollections() Container {// Host represents a generic infrastructure host reporting via external agents.type Host struct {- ID string `json:"id"`- Hostname string `json:"hostname"`- DisplayName string `json:"displayName,omitempty"`- Platform string `json:"platform,omitempty"`- OSName string `json:"osName,omitempty"`- OSVersion string `json:"osVersion,omitempty"`- KernelVersion string `json:"kernelVersion,omitempty"`- Architecture string `json:"architecture,omitempty"`- CPUCount int `json:"cpuCount,omitempty"`- CPUUsage float64 `json:"cpuUsage,omitempty"`- Memory Memory `json:"memory"`- LoadAverage []float64 `json:"loadAverage,omitempty"`- Disks []Disk `json:"disks,omitempty"`- DiskIO []DiskIO `json:"diskIO,omitempty"`- NetworkInterfaces []HostNetworkInterface `json:"networkInterfaces,omitempty"`- Sensors HostSensorSummary `json:"sensors,omitempty"`- RAID []HostRAIDArray `json:"raid,omitempty"`- Unraid *HostUnraidStorage `json:"unraid,omitempty"`- Ceph *HostCephCluster `json:"ceph,omitempty"`- Status string `json:"status"`- UptimeSeconds int64 `json:"uptimeSeconds,omitempty"`- IntervalSeconds int `json:"intervalSeconds,omitempty"`- LastSeen time.Time `json:"lastSeen"`- AgentVersion string `json:"agentVersion,omitempty"`- MachineID string `json:"machineId,omitempty"`- CommandsEnabled bool `json:"commandsEnabled,omitempty"` // Whether AI command execution is enabled- ReportIP string `json:"reportIp,omitempty"` // User-specified IP for multi-NIC systems- TokenID string `json:"tokenId,omitempty"`- TokenName string `json:"tokenName,omitempty"`- TokenHint string `json:"tokenHint,omitempty"`- TokenLastUsedAt *time.Time `json:"tokenLastUsedAt,omitempty"`- Tags []string `json:"tags,omitempty"`- DiskExclude []string `json:"diskExclude,omitempty"` // Agent's --disk-exclude patterns- AppliedConfig *AgentConfigFingerprint `json:"appliedConfig,omitempty"`- AgentUpdate *AgentUpdateStatus `json:"agentUpdate,omitempty"`- AgentModules []AgentModuleStatus `json:"agentModules,omitempty"`- IsLegacy bool `json:"isLegacy,omitempty"`+ ID string `json:"id"`+ Hostname string `json:"hostname"`+ DisplayName string `json:"displayName,omitempty"`+ Platform string `json:"platform,omitempty"`+ OSName string `json:"osName,omitempty"`+ OSVersion string `json:"osVersion,omitempty"`+ KernelVersion string `json:"kernelVersion,omitempty"`+ Architecture string `json:"architecture,omitempty"`+ CPUCount int `json:"cpuCount,omitempty"`+ CPUUsage float64 `json:"cpuUsage,omitempty"`+ Memory Memory `json:"memory"`+ LoadAverage []float64 `json:"loadAverage,omitempty"`+ Disks []Disk `json:"disks,omitempty"`+ DiskIO []DiskIO `json:"diskIO,omitempty"`+ NetworkInterfaces []HostNetworkInterface `json:"networkInterfaces,omitempty"`+ Sensors HostSensorSummary `json:"sensors,omitempty"`+ RAID []HostRAIDArray `json:"raid,omitempty"`+ Unraid *HostUnraidStorage `json:"unraid,omitempty"`+ Ceph *HostCephCluster `json:"ceph,omitempty"`+ Status string `json:"status"`+ UptimeSeconds int64 `json:"uptimeSeconds,omitempty"`+ IntervalSeconds int `json:"intervalSeconds,omitempty"`+ LastSeen time.Time `json:"lastSeen"`+ AgentVersion string `json:"agentVersion,omitempty"`+ MachineID string `json:"machineId,omitempty"`+ CommandsEnabled bool `json:"commandsEnabled,omitempty"` // Whether AI command execution is enabled+ ReportIP string `json:"reportIp,omitempty"` // User-specified IP for multi-NIC systems+ TokenID string `json:"tokenId,omitempty"`+ TokenName string `json:"tokenName,omitempty"`+ TokenHint string `json:"tokenHint,omitempty"`+ TokenLastUsedAt *time.Time `json:"tokenLastUsedAt,omitempty"`+ Tags []string `json:"tags,omitempty"`+ DiskExclude []string `json:"diskExclude,omitempty"` // Agent's --disk-exclude patterns+ AppliedConfig *AgentConfigFingerprint `json:"appliedConfig,omitempty"`+ AgentUpdate *AgentUpdateStatus `json:"agentUpdate,omitempty"`+ AgentModules []AgentModuleStatus `json:"agentModules,omitempty"`+ PackageUpdates *HostPackageUpdateStatus `json:"packageUpdates,omitempty"`+ IsLegacy bool `json:"isLegacy,omitempty"`// Computed I/O rates (bytes/sec), populated from cumulative counters by rate trackerNetInRate float64 `json:"netInRate,omitempty"`@@ -297,6 +298,25 @@ type Host struct {LinkedContainerID string `json:"linkedContainerId,omitempty"` // ID of the container this agent is running inside}+// HostPackageUpdateStatus is the server-side normalized package posture+// reported by a Unified Agent.+type HostPackageUpdateStatus struct {+ Supported bool `json:"supported"`+ Manager string `json:"manager,omitempty"`+ InventoryHash string `json:"inventoryHash,omitempty"`+ PendingCount int `json:"pendingCount"`+ Packages []HostPackageUpdate `json:"packages,omitempty"`+ CheckedAt time.Time `json:"checkedAt,omitempty"`+ RebootRequired bool `json:"rebootRequired,omitempty"`+ Error string `json:"error,omitempty"`+}++type HostPackageUpdate struct {+ Name string `json:"name"`+ InstalledVersion string `json:"installedVersion,omitempty"`+ AvailableVersion string `json:"availableVersion,omitempty"`+}+type AgentConfigFingerprint struct {Version string `json:"version"`Hash string `json:"hash"`diff --git a/internal/models/models_frontend.go b/internal/models/models_frontend.goindex 6a09242a42..ae17321310 100644--- a/internal/models/models_frontend.go+++ b/internal/models/models_frontend.go@@ -724,6 +724,7 @@ type HostFrontend struct {AppliedConfig *AgentConfigFingerprint `json:"appliedConfig,omitempty"`AgentUpdate *AgentUpdateStatus `json:"agentUpdate,omitempty"`AgentModules []AgentModuleStatus `json:"agentModules,omitempty"`+ PackageUpdates *HostPackageUpdateStatus `json:"packageUpdates,omitempty"`IsLegacy bool `json:"isLegacy,omitempty"` // True if using legacy agent protocolLinkedNodeID string `json:"linkedNodeId,omitempty"` // ID of linked PVE node (if running on a node)}diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex f0bce80c75..7a70a140af 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -1996,6 +1996,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.AppliedConfig: convertAgentConfigFingerprint(report.Agent.AppliedConfig),AgentUpdate: agentUpdate,AgentModules: convertAgentModuleStatuses(report.Agent.Modules),+ PackageUpdates: convertHostPackageUpdateStatus(report.Host.PackageUpdates, observedAt),IsLegacy: isLegacyAgent(report.Agent.Type),}@@ -2210,6 +2211,30 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.return host, nil}+func convertHostPackageUpdateStatus(status *agentshost.PackageUpdateStatus, observedAt time.Time) *models.HostPackageUpdateStatus {+ if status == nil {+ return nil+ }+ packages := make([]models.HostPackageUpdate, len(status.Packages))+ for i, pkg := range status.Packages {+ packages[i] = models.HostPackageUpdate{+ Name: strings.TrimSpace(pkg.Name),+ InstalledVersion: strings.TrimSpace(pkg.InstalledVersion),+ AvailableVersion: strings.TrimSpace(pkg.AvailableVersion),+ }+ }+ return &models.HostPackageUpdateStatus{+ Supported: status.Supported,+ Manager: strings.TrimSpace(status.Manager),+ InventoryHash: strings.TrimSpace(status.InventoryHash),+ PendingCount: max(0, status.PendingCount),+ Packages: packages,+ CheckedAt: observedAt.UTC(),+ RebootRequired: status.RebootRequired,+ Error: strings.TrimSpace(status.Error),+ }+}+func convertAgentConfigFingerprint(value *agentshost.ConfigFingerprint) *models.AgentConfigFingerprint {if value == nil {return nildiff --git a/internal/monitoring/monitor_package_updates_test.go b/internal/monitoring/monitor_package_updates_test.gonew file mode 100644index 0000000000..d8b8143218--- /dev/null+++ b/internal/monitoring/monitor_package_updates_test.go@@ -0,0 +1,28 @@+package monitoring++import (+ "strings"+ "testing"+ "time"++ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++func TestConvertHostPackageUpdateStatusPreservesTypedInventoryWithoutAliasing(t *testing.T) {+ now := time.Now().UTC()+ input := &agentshost.PackageUpdateStatus{+ Supported: true, Manager: " apt ", InventoryHash: " sha256:" + strings.Repeat("a", 64) + " ", PendingCount: 2, CheckedAt: now.Add(24 * time.Hour), RebootRequired: true,+ 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) {+ 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" {+ t.Fatalf("packages = %#v", got.Packages)+ }+ input.Packages[0].Name = "mutated"+ if got.Packages[0].Name != "openssl" {+ t.Fatalf("converted package state aliases report input: %#v", got.Packages)+ }+}diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.goindex 221069d8b5..1e7e1cb3c9 100644--- a/internal/unifiedresources/adapters.go+++ b/internal/unifiedresources/adapters.go@@ -165,6 +165,26 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {LinkedVMID: host.LinkedVMID,LinkedContainerID: host.LinkedContainerID,}+ if host.PackageUpdates != nil {+ packages := make([]AgentPackageUpdate, len(host.PackageUpdates.Packages))+ for i, pkg := range host.PackageUpdates.Packages {+ packages[i] = AgentPackageUpdate{+ Name: pkg.Name,+ InstalledVersion: pkg.InstalledVersion,+ AvailableVersion: pkg.AvailableVersion,+ }+ }+ agent.PackageUpdates = &AgentPackageUpdateMeta{+ Supported: host.PackageUpdates.Supported,+ Manager: host.PackageUpdates.Manager,+ InventoryHash: host.PackageUpdates.InventoryHash,+ PendingCount: host.PackageUpdates.PendingCount,+ Packages: packages,+ CheckedAt: host.PackageUpdates.CheckedAt,+ RebootRequired: host.PackageUpdates.RebootRequired,+ Error: host.PackageUpdates.Error,+ }+ }// Surface agent staleness so a row that stays online via another source// (e.g. a Proxmox node still reachable over the PVE API) does not present a@@ -456,22 +476,41 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {metrics := metricsFromHost(host)resource := Resource{- Type: ResourceTypeAgent,- Technology: strings.TrimSpace(platform),- Name: name,- Status: storageStatus(statusFromString(host.Status), agent.StorageRisk),- LastSeen: host.LastSeen,- UpdatedAt: time.Now().UTC(),- Metrics: metrics,- Uptime: host.UptimeSeconds,- Temperature: agent.Temperature,- Agent: agent,- Tags: host.Tags,+ Type: ResourceTypeAgent,+ Technology: strings.TrimSpace(platform),+ Name: name,+ Status: storageStatus(statusFromString(host.Status), agent.StorageRisk),+ LastSeen: host.LastSeen,+ UpdatedAt: time.Now().UTC(),+ Metrics: metrics,+ Uptime: host.UptimeSeconds,+ Temperature: agent.Temperature,+ Agent: agent,+ Tags: host.Tags,+ Capabilities: hostPackageUpdateCapabilities(host),}return resource, identity}+const hostPackageUpdateHandler = "host.package_updates"++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 {+ return nil+ }+ return []ResourceCapability{{+ Name: "install_os_updates",+ Type: CapabilityTypeCommon,+ Description: "Refresh APT metadata and install standard OS package upgrades without removing packages or rebooting the host.",+ MinimumApprovalLevel: ApprovalAdmin,+ AutoAuthorization: AutoAuthorizeElevated,+ Platform: "linux",+ InternalHandler: hostPackageUpdateHandler,+ }}+}+func hostThermalStateToMeta(in *models.HostThermalState) *HostThermalState {if in == nil {return nildiff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.goindex 056a0b412e..b168675c86 100644--- a/internal/unifiedresources/adapters_test.go+++ b/internal/unifiedresources/adapters_test.go@@ -67,6 +67,59 @@ func TestResourceFromProxmoxNodeUsesDisplayNameWithoutChangingRawNodeIdentity(t}}+func TestResourceFromHostAdvertisesElevatedTypedPackageUpdateCapability(t *testing.T) {+ now := time.Now().UTC()+ 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,+ 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 {+ t.Fatalf("package update projection = %#v", resource.Agent)+ }+ if len(resource.Capabilities) != 1 {+ t.Fatalf("capabilities = %#v", resource.Capabilities)+ }+ capability := resource.Capabilities[0]+ if capability.Name != "install_os_updates" || capability.MinimumApprovalLevel != ApprovalAdmin || capability.AutoAuthorization != AutoAuthorizeElevated || capability.InternalHandler != "host.package_updates" {+ t.Fatalf("capability = %#v", capability)+ }+ if len(capability.Params) != 0 {+ t.Fatalf("package update capability must not accept model-selected packages: %#v", capability.Params)+ }++ host.PackageUpdates.Packages[0].Name = "mutated"+ if resource.Agent.PackageUpdates.Packages[0].Name != "openssl" {+ t.Fatalf("resource package inventory aliases model input: %#v", resource.Agent.PackageUpdates.Packages)+ }+}++func TestResourceFromHostDoesNotAdvertiseUnsupportedOrCommandDisabledPackageUpdates(t *testing.T) {+ base := models.Host{+ ID: "agent-1", Hostname: "host-1", Platform: "linux", Status: "online", LastSeen: time.Now().UTC(), CommandsEnabled: true,+ PackageUpdates: &models.HostPackageUpdateStatus{Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 1, CheckedAt: time.Now().UTC()},+ }+ for _, mutate := range []func(*models.Host){+ func(host *models.Host) { host.CommandsEnabled = false },+ func(host *models.Host) { host.PackageUpdates.Supported = false },+ func(host *models.Host) { host.PackageUpdates.Manager = "dnf" },+ func(host *models.Host) { host.PackageUpdates = nil },+ } {+ host := base+ status := *base.PackageUpdates+ host.PackageUpdates = &status+ mutate(&host)+ resource, _ := resourceFromHost(host)+ if len(resource.Capabilities) != 0 {+ t.Fatalf("host %#v advertised capabilities %#v", host.PackageUpdates, resource.Capabilities)+ }+ }+}+func TestResourceFromDockerContainerAdvertisesLifecycleCapabilities(t *testing.T) {now := time.Now().UTC()host := models.DockerHost{diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex c18021be59..8dfd25ec65 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -1496,6 +1496,25 @@ func TestResourceParentBySourceStateRemainsInternal(t *testing.T) {}}+func TestHostPackageUpdatePostureRemainsAgentScoped(t *testing.T) {+ agentType := reflect.TypeOf(AgentData{})+ field, ok := agentType.FieldByName("PackageUpdates")+ if !ok {+ t.Fatal("expected AgentData.PackageUpdates field")+ }+ if got := field.Tag.Get("json"); got != "packageUpdates,omitempty" {+ t.Fatalf("expected package-update posture to use the agent-scoped wire key, got %q", got)+ }+ if field.Type != reflect.TypeOf((*AgentPackageUpdateMeta)(nil)) {+ t.Fatalf("expected typed package-update metadata, got %v", field.Type)+ }++ resourceType := reflect.TypeOf(Resource{})+ if _, ok := resourceType.FieldByName("PackageUpdates"); ok {+ t.Fatal("package-update posture must not become an unscoped top-level Resource field")+ }+}+// TestNoLegacyMigrationHintsInRuntimeCode prevents reintroducing runtime// messages that point removed aliases at the wrong token guidance.func TestNoLegacyMigrationHintsInRuntimeCode(t *testing.T) {diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.goindex 650ceea5fb..46b9a23bb0 100644--- a/internal/unifiedresources/types.go+++ b/internal/unifiedresources/types.go@@ -772,6 +772,25 @@ type AgentMemoryMeta struct {SwapTotal int64 `json:"swapTotal,omitempty"`}+const HostPackageUpdateFreshness = 45 * time.Minute++type AgentPackageUpdateMeta struct {+ Supported bool `json:"supported"`+ Manager string `json:"manager,omitempty"`+ InventoryHash string `json:"inventoryHash,omitempty"`+ PendingCount int `json:"pendingCount"`+ Packages []AgentPackageUpdate `json:"packages,omitempty"`+ CheckedAt time.Time `json:"checkedAt,omitempty"`+ RebootRequired bool `json:"rebootRequired,omitempty"`+ Error string `json:"error,omitempty"`+}++type AgentPackageUpdate struct {+ Name string `json:"name"`+ InstalledVersion string `json:"installedVersion,omitempty"`+ AvailableVersion string `json:"availableVersion,omitempty"`+}+// AgentData contains host agent-specific data.type AgentData struct {AgentID string `json:"agentId,omitempty"`@@ -786,47 +805,48 @@ type AgentData struct {// multi-source row (for example a Proxmox node also polled over the PVE// API) this differs from the row's LastSeen, which reflects the freshest// source rather than the agent.- LastReportAt *time.Time `json:"lastReportAt,omitempty"`- Hostname string `json:"hostname,omitempty"`- MachineID string `json:"machineId,omitempty"`- TokenID string `json:"tokenId,omitempty"`- TokenName string `json:"tokenName,omitempty"`- TokenHint string `json:"tokenHint,omitempty"`- TokenLastUsedAt *time.Time `json:"tokenLastUsedAt,omitempty"`- Platform string `json:"platform,omitempty"`- HostProfile string `json:"hostProfile,omitempty"`- OSName string `json:"osName,omitempty"`- OSVersion string `json:"osVersion,omitempty"`- KernelVersion string `json:"kernelVersion,omitempty"`- Architecture string `json:"architecture,omitempty"`- CPUCount int `json:"cpuCount,omitempty"`- LoadAverage []float64 `json:"loadAverage,omitempty"`- UptimeSeconds int64 `json:"uptimeSeconds,omitempty"`- IntervalSeconds int `json:"intervalSeconds,omitempty"`- Temperature *float64 `json:"temperature,omitempty"` // Max CPU temp in Celsius- NetworkInterfaces []NetworkInterface `json:"networkInterfaces,omitempty"`- Disks []DiskInfo `json:"disks,omitempty"`- Memory *AgentMemoryMeta `json:"memory,omitempty"`- Sensors *HostSensorMeta `json:"sensors,omitempty"`- RAID []HostRAIDMeta `json:"raid,omitempty"`- Unraid *HostUnraidMeta `json:"unraid,omitempty"`- DiskIO []HostDiskIOMeta `json:"diskIo,omitempty"`- Ceph *HostCephMeta `json:"ceph,omitempty"`- StorageRisk *StorageRisk `json:"storageRisk,omitempty"`- StorageRiskSummary string `json:"storageRiskSummary,omitempty"`- StoragePostureSummary string `json:"storagePostureSummary,omitempty"`- ProtectionReduced bool `json:"protectionReduced,omitempty"`- ProtectionSummary string `json:"protectionSummary,omitempty"`- RebuildInProgress bool `json:"rebuildInProgress,omitempty"`- RebuildSummary string `json:"rebuildSummary,omitempty"`- CommandsEnabled bool `json:"commandsEnabled,omitempty"`- ReportIP string `json:"reportIp,omitempty"`- DiskExclude []string `json:"diskExclude,omitempty"`- IsLegacy bool `json:"isLegacy,omitempty"`- NetInRate float64 `json:"netInRate,omitempty"`- NetOutRate float64 `json:"netOutRate,omitempty"`- DiskReadRate float64 `json:"diskReadRate,omitempty"`- DiskWriteRate float64 `json:"diskWriteRate,omitempty"`+ LastReportAt *time.Time `json:"lastReportAt,omitempty"`+ Hostname string `json:"hostname,omitempty"`+ MachineID string `json:"machineId,omitempty"`+ TokenID string `json:"tokenId,omitempty"`+ TokenName string `json:"tokenName,omitempty"`+ TokenHint string `json:"tokenHint,omitempty"`+ TokenLastUsedAt *time.Time `json:"tokenLastUsedAt,omitempty"`+ Platform string `json:"platform,omitempty"`+ HostProfile string `json:"hostProfile,omitempty"`+ OSName string `json:"osName,omitempty"`+ OSVersion string `json:"osVersion,omitempty"`+ KernelVersion string `json:"kernelVersion,omitempty"`+ Architecture string `json:"architecture,omitempty"`+ CPUCount int `json:"cpuCount,omitempty"`+ LoadAverage []float64 `json:"loadAverage,omitempty"`+ UptimeSeconds int64 `json:"uptimeSeconds,omitempty"`+ IntervalSeconds int `json:"intervalSeconds,omitempty"`+ Temperature *float64 `json:"temperature,omitempty"` // Max CPU temp in Celsius+ NetworkInterfaces []NetworkInterface `json:"networkInterfaces,omitempty"`+ Disks []DiskInfo `json:"disks,omitempty"`+ Memory *AgentMemoryMeta `json:"memory,omitempty"`+ Sensors *HostSensorMeta `json:"sensors,omitempty"`+ RAID []HostRAIDMeta `json:"raid,omitempty"`+ Unraid *HostUnraidMeta `json:"unraid,omitempty"`+ DiskIO []HostDiskIOMeta `json:"diskIo,omitempty"`+ Ceph *HostCephMeta `json:"ceph,omitempty"`+ StorageRisk *StorageRisk `json:"storageRisk,omitempty"`+ StorageRiskSummary string `json:"storageRiskSummary,omitempty"`+ StoragePostureSummary string `json:"storagePostureSummary,omitempty"`+ ProtectionReduced bool `json:"protectionReduced,omitempty"`+ ProtectionSummary string `json:"protectionSummary,omitempty"`+ RebuildInProgress bool `json:"rebuildInProgress,omitempty"`+ RebuildSummary string `json:"rebuildSummary,omitempty"`+ CommandsEnabled bool `json:"commandsEnabled,omitempty"`+ PackageUpdates *AgentPackageUpdateMeta `json:"packageUpdates,omitempty"`+ ReportIP string `json:"reportIp,omitempty"`+ DiskExclude []string `json:"diskExclude,omitempty"`+ IsLegacy bool `json:"isLegacy,omitempty"`+ NetInRate float64 `json:"netInRate,omitempty"`+ NetOutRate float64 `json:"netOutRate,omitempty"`+ DiskReadRate float64 `json:"diskReadRate,omitempty"`+ DiskWriteRate float64 `json:"diskWriteRate,omitempty"`// Internal link hints to proxmox resources.LinkedNodeID string `json:"-"`LinkedVMID string `json:"-"`diff --git a/pkg/agents/host/report.go b/pkg/agents/host/report.goindex 7cda5aef00..344a5408ba 100644--- a/pkg/agents/host/report.go+++ b/pkg/agents/host/report.go@@ -79,20 +79,43 @@ type UpdateStatus struct {// HostInfo contains platform and identification details about the monitored host.type HostInfo struct {- ID string `json:"id,omitempty"`- Hostname string `json:"hostname"`- DisplayName string `json:"displayName,omitempty"`- MachineID string `json:"machineId,omitempty"`- Platform string `json:"platform,omitempty"`- OSName string `json:"osName,omitempty"`- OSVersion string `json:"osVersion,omitempty"`- KernelVersion string `json:"kernelVersion,omitempty"`- Architecture string `json:"architecture,omitempty"`- CPUModel string `json:"cpuModel,omitempty"`- CPUCount int `json:"cpuCount,omitempty"`- UptimeSeconds int64 `json:"uptimeSeconds,omitempty"`- LoadAverage []float64 `json:"loadAverage,omitempty"`- ReportIP string `json:"reportIp,omitempty"` // User-specified IP for multi-NIC systems+ ID string `json:"id,omitempty"`+ Hostname string `json:"hostname"`+ DisplayName string `json:"displayName,omitempty"`+ MachineID string `json:"machineId,omitempty"`+ Platform string `json:"platform,omitempty"`+ OSName string `json:"osName,omitempty"`+ OSVersion string `json:"osVersion,omitempty"`+ KernelVersion string `json:"kernelVersion,omitempty"`+ Architecture string `json:"architecture,omitempty"`+ CPUModel string `json:"cpuModel,omitempty"`+ CPUCount int `json:"cpuCount,omitempty"`+ UptimeSeconds int64 `json:"uptimeSeconds,omitempty"`+ LoadAverage []float64 `json:"loadAverage,omitempty"`+ ReportIP string `json:"reportIp,omitempty"` // User-specified IP for multi-NIC systems+ PackageUpdates *PackageUpdateStatus `json:"packageUpdates,omitempty"`+}++// PackageUpdateStatus is the agent-authored, read-only package posture for+// the host OS. It reports only package identifiers and versions; execution is+// a separate typed agent operation and never accepts model-authored commands.+type PackageUpdateStatus struct {+ Supported bool `json:"supported"`+ Manager string `json:"manager,omitempty"`+ InventoryHash string `json:"inventoryHash,omitempty"`+ PendingCount int `json:"pendingCount"`+ Packages []PackageUpdate `json:"packages,omitempty"`+ CheckedAt time.Time `json:"checkedAt,omitempty"`+ RebootRequired bool `json:"rebootRequired,omitempty"`+ Error string `json:"error,omitempty"`+}++// PackageUpdate identifies one package visible in the package manager's+// bounded upgrade simulation. Values are informational and never executed.+type PackageUpdate struct {+ Name string `json:"name"`+ InstalledVersion string `json:"installedVersion,omitempty"`+ AvailableVersion string `json:"availableVersion,omitempty"`}// Metrics encapsulates primary resource metrics for a host.diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.pyindex e15539db31..47f814813d 100644--- a/scripts/release_control/canonical_completion_guard_test.py+++ b/scripts/release_control/canonical_completion_guard_test.py@@ -338,6 +338,7 @@ class CanonicalCompletionGuardTest(unittest.TestCase):"test_prefixes": [],"exact_files": ["internal/monitoring/monitor_host_agents_test.go",+ "internal/monitoring/monitor_package_updates_test.go","internal/unifiedresources/code_standards_test.go",],}@@ -550,6 +551,8 @@ class CanonicalCompletionGuardTest(unittest.TestCase):"internal/hostagent/agent_new_test.go","internal/hostagent/command_client_test.go","internal/hostagent/commands_deploy_test.go",+ "internal/hostagent/commands_host_update_test.go",+ "internal/hostagent/package_updates_test.go","internal/hostagent/send_report_test.go",],}diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex d21d35dc33..1f447616cf 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -2919,8 +2919,8 @@ class SubsystemLookupTest(unittest.TestCase):{"heading": "## Shared Boundaries","path": "internal/api/access_control_handlers.go",- "line": 1203,- "heading_line": 141,+ "line": 1204,+ "heading_line": 142,}],)@@ -4069,6 +4069,7 @@ class SubsystemLookupTest(unittest.TestCase):match["verification_requirement"]["exact_files"],["internal/monitoring/monitor_host_agents_test.go",+ "internal/monitoring/monitor_package_updates_test.go","internal/unifiedresources/code_standards_test.go",],)@@ -4363,6 +4364,8 @@ class SubsystemLookupTest(unittest.TestCase):"internal/hostagent/agent_new_test.go","internal/hostagent/command_client_test.go","internal/hostagent/commands_deploy_test.go",+ "internal/hostagent/commands_host_update_test.go",+ "internal/hostagent/package_updates_test.go","internal/hostagent/send_report_test.go",],)