Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Add governed storage pressure cleanup

rcourtmaneb9954618a04
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 5e06de9a6a..dd9f5c4380 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -3963,6 +3963,20 @@
],
"release_gate_ids": [],
"proof_commands": [
+ {
+ "id": "ra35-typed-host-storage-cleanup-vertical",
+ "run": [
+ "go",
+ "test",
+ "./internal/api",
+ "./internal/agentexec",
+ "./internal/hostagent",
+ "./internal/unifiedresources",
+ "-run",
+ "TestPatrolFullModeRunsStorageCleanupThroughCanonicalLifecycle|TestExecuteHostStorageCleanupRoundTripUsesPathAndCommandFreeEnvelope|TestStorageCleanupManagerApplyUsesClosedAPTCatalogAndVerifiesBytes|TestStorageCleanupManagerRefusesFingerprintDriftBeforeMutation|TestHostStorageCleanupTargetDiskUsesLongestContainingMount",
+ "-count=1"
+ ]
+ },
{
"id": "ra35-typed-host-update-vertical",
"run": [
@@ -4030,6 +4044,11 @@
"path": "internal/ai/tools/tools_propose.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/host_storage_cleanup_action_executor.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/api/host_update_action_executor.go",
@@ -4045,6 +4064,11 @@
"path": "internal/hostagent/package_updates.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/hostagent/storage_cleanup.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "pkg/aicontracts/action_broker.go",
@@ -5618,7 +5642,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. 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.",
+ "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. Three 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. Agent-managed package-cache cleanup is capability-owned low-risk eligible and crosses a separate fingerprint-bound host_storage_cleanup protocol with no command, path, package selector, installed-package removal, or reboot authority; it is available only for meaningful reclaimable bytes on the actual pressured cache filesystem, and the audit verifies the bytes reclaimed. All three 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 or cleanup inventories, cleared storage pressure, 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, richer dry-run providers, multi-actor approvals, additional package-manager and bounded cleanup providers beyond APT, separately governed reboot orchestration, and a real-lab detect-plan-execute-verify-rollback journey proof.",
"tracking": [
{
"kind": "lane-followup",
@@ -5794,6 +5818,17 @@
"path": "internal/api/contract_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/host_storage_cleanup_action_executor.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/api/host_storage_cleanup_action_executor_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/api/host_update_action_executor.go",
@@ -5831,6 +5866,17 @@
"kind": "file",
"evidence_tier": "test-proof"
},
+ {
+ "repo": "pulse",
+ "path": "internal/hostagent/storage_cleanup.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/hostagent/storage_cleanup_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/unifiedresources/actions.go",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f0ec72ab49..20a3c16abc 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -257,7 +257,7 @@ 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. `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.
+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 maintenance 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 that
can run before Administrator-only install work, must accept token-file
@@ -423,6 +423,16 @@ 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.
+Host storage-pressure cleanup is a second closed agent operation. The report
+may expose only the bounded `apt-package-cache` provider, its reclaimable byte
+count, freshness, and a SHA-256 fingerprint; cache entry names and paths remain
+agent-local. Execution crosses `host_storage_cleanup` with the exact
+`clean_package_cache` operation and expected fingerprint only. The agent owns
+the fixed `/var/cache/apt/archives` scan, bounded entry/byte limits, and sole
+`apt-get clean` command. Fingerprint drift, unsupported providers, empty cache,
+inspection failure, command failure, and unconfirmed reclaimed bytes all fail
+closed. The envelope has no command, path, package selector, arbitrary
+argument, installed-package removal, or reboot authority.
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`, but
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 4ab56e57e9..6808d11d95 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1945,6 +1945,18 @@ a new API state machine, queue contract, or verification-accounting field.
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.
+ Agent-managed package-cache cleanup is the third complete typed action
+ vertical. `clean_package_cache` is admin-floor and low-risk-policy eligible,
+ accepts no model parameters, and is advertised only when the canonical
+ cache filesystem is under pressure and the fresh agent-authored cache
+ posture reports meaningful reclaimable bytes. Dispatch uses only
+ `ExecuteHostStorageCleanup` with the closed `host_storage_cleanup` envelope
+ and injects the observed fingerprint; command text, paths, packages, and
+ arbitrary arguments never cross the API. The agent owns the sole
+ `apt-get clean` mutation and read-after-write cache scan. The terminal audit
+ records before/after/reclaimed byte counts and distinguishes verified,
+ failed, and honestly inconclusive outcomes; inconsistent or unbounded byte
+ evidence fails closed.
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
@@ -3449,6 +3461,10 @@ 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.
+Package-cache cleanup context follows the same privacy boundary: the model may
+see cleanup readiness, reclaimable byte count, and the containing filesystem's
+usage percentage. The cache fingerprint, fixed target path, entry names, raw
+APT output, and agent error text remain outside model context.
`aicontracts.Finding` (the shape Patrol hands the investigation
orchestrator) carries optional `OperatorContext` and
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 1997debbae..29ce2430e7 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -138,7 +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.
+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 maintenance posture.
## Extension Points
@@ -477,6 +477,12 @@ 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.
+The host report also carries bounded package-cache cleanup posture: supported
+provider, reclaimable byte count, fingerprint, inspection time, and an
+operator-safe error. Monitoring stamps freshness from server receipt time and
+normalizes that scalar evidence without receiving cache entry names or paths.
+It does not infer cleanup eligibility, run cache scans server-side, or turn
+reclaimable bytes into mutation authority.
HTTP availability probes consume the shared explicitly unverified,
parseable-peer-certificate capture
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 97780286ed..6ad88aca94 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -358,6 +358,13 @@ regression protection.
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.
+ Package-cache cleanup follows the same rule: router construction may
+ register the typed executor once, while cache inspection, fingerprint
+ comparison, `apt-get clean`, and post-cleanup measurement remain agent/action
+ work. Generic request admission must not walk cache directories, inspect
+ mounts, or wait for cleanup; the agent scan is entry/byte bounded and the
+ unified-resource mount lookup is an in-memory pass over already-reported
+ disks.
The Patrol action-broker and proposal-catalog factories are wired the same
bounded way: `internal/api/router.go` installs the per-org factory closures
on the AI settings handler once at startup, and each broker or catalog is
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 49bb08f6eb..8746cda8c7 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -966,7 +966,7 @@
},
{
"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",
+ "rationale": "the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture",
"subsystems": [
"agent-lifecycle",
"monitoring"
@@ -1226,8 +1226,10 @@
"internal/hostagent/command_client_test.go",
"internal/hostagent/commands_deploy_test.go",
"internal/hostagent/commands_host_update_test.go",
+ "internal/hostagent/commands_storage_cleanup_test.go",
"internal/hostagent/package_updates_test.go",
- "internal/hostagent/send_report_test.go"
+ "internal/hostagent/send_report_test.go",
+ "internal/hostagent/storage_cleanup_test.go"
]
},
{
@@ -4708,8 +4710,8 @@
]
},
{
- "id": "docker-runtime-report-model",
- "label": "docker runtime report model proof",
+ "id": "runtime-report-model",
+ "label": "runtime report model proof",
"match_prefixes": [],
"match_files": [
"internal/models/converters.go",
@@ -6192,6 +6194,7 @@
"match_prefixes": [],
"match_files": [
"internal/unifiedresources/adapters.go",
+ "internal/unifiedresources/host_storage_cleanup.go",
"internal/unifiedresources/monitor_adapter.go",
"internal/unifiedresources/read_state.go",
"internal/unifiedresources/views.go"
@@ -6202,6 +6205,7 @@
"frontend-modern/src/stores/__tests__/websocket-unified.test.ts",
"internal/unifiedresources/adapter_coverage_test.go",
"internal/unifiedresources/adapters_test.go",
+ "internal/unifiedresources/host_storage_cleanup_test.go",
"internal/unifiedresources/monitor_adapter_read_state_test.go",
"internal/unifiedresources/views_test.go"
]
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index be7af87d7a..05b85913d6 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -339,6 +339,12 @@ the `white_label` branding entitlement.
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.
+ The typed storage-cleanup executor is equally closed: only
+ `clean_package_cache` may cross the boundary, bound to the server-observed
+ fingerprint and canonical approval. The model and API never supply a path,
+ command, package selector, or deletion rule. Cache entry names,
+ fingerprint, raw APT output, and agent error text remain out of model
+ context and terminal action output.
Router glue may also pass monitor-owned source freshness thresholds into
unified-resource adapters, but those thresholds are operational cadence
metadata only. They must not disclose credentials, command output, raw
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 280721eb54..1dfc8b2555 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -391,6 +391,13 @@ 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.
+The API-owned `internal/api/host_storage_cleanup_action_executor.go` is a
+narrow exception only in product purpose, not ownership: it may reclaim the
+fixed APT package cache through the canonical action lifecycle when the cache's
+actual filesystem is pressured. Storage/recovery consumers may observe its
+redacted byte outcome as operational context, but package-cache deletion is
+not backup pruning, restore evidence, arbitrary path cleanup, or a
+storage-owned executor.
Storage and recovery surfaces may consume Discovery context from the shared
API boundary when it helps explain protected workloads or storage-adjacent
services, including mock-mode config/data/log path examples. That context is
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 18fff5c3b6..0ebf16de9c 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -654,6 +654,15 @@ container inventory table.
stale, erroneous, empty, unsupported, or its owning agent is disconnected;
reboot-required state remains descriptive and does not imply a reboot
capability.
+ Agent-managed hosts may advertise `clean_package_cache` only when typed
+ commands are enabled, the agent reports a fresh error-free
+ `apt-package-cache` fingerprint with at least 64 MiB reclaimable, and the
+ actual longest-prefix filesystem containing the fixed cache target is at
+ least 90% used. A healthy separate `/var` mount must override pressure on
+ `/`; sibling-prefix mounts must never match. The capability is admin-floor,
+ `low_risk` auto-authorization eligible, parameter-free, and routed through
+ `host.storage_cleanup`. API consumers must reuse the canonical target-disk
+ resolver and may not infer cleanup authority from generic disk usage.
TrueNAS app inventory enters the model as native `TrueNASData.App`
metadata on canonical `app-container` resources. The facet is sourced from
the TrueNAS API app inventory (`app.query` plus active workload/stat
diff --git a/frontend-modern/src/types/__tests__/resource.test.ts b/frontend-modern/src/types/__tests__/resource.test.ts
index 9ec9543d75..6b85c0d1b9 100644
--- a/frontend-modern/src/types/__tests__/resource.test.ts
+++ b/frontend-modern/src/types/__tests__/resource.test.ts
@@ -44,7 +44,7 @@ function createResource(overrides: Partial<Resource> = {}): Resource {
}
describe('Resource Type Guards', () => {
- it('keeps host package-update posture scoped to agent metadata', () => {
+ it('keeps host maintenance posture scoped to agent metadata', () => {
const resource = createResource({
type: 'agent',
agent: {
@@ -56,13 +56,24 @@ describe('Resource Type Guards', () => {
checkedAt: '2026-07-11T00:00:00Z',
rebootRequired: false,
},
+ storageCleanup: {
+ supported: true,
+ provider: 'apt-package-cache',
+ fingerprint: `sha256:${'b'.repeat(64)}`,
+ reclaimableBytes: 536_870_912,
+ checkedAt: '2026-07-11T00:00:00Z',
+ },
},
});
expect(resource.agent?.packageUpdates).toEqual(
expect.objectContaining({ manager: 'apt', pendingCount: 2 }),
);
+ expect(resource.agent?.storageCleanup).toEqual(
+ expect.objectContaining({ provider: 'apt-package-cache', reclaimableBytes: 536_870_912 }),
+ );
expect(resource).not.toHaveProperty('packageUpdates');
+ expect(resource).not.toHaveProperty('storageCleanup');
});
it('keeps platform types aligned with the governed platform manifest projection', () => {
diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.ts
index 5f5f40c279..47e825001d 100644
--- a/frontend-modern/src/types/api.ts
+++ b/frontend-modern/src/types/api.ts
@@ -463,6 +463,7 @@ export interface Agent {
agentUpdate?: AgentUpdateStatus;
agentModules?: AgentModuleStatus[];
packageUpdates?: HostPackageUpdateStatus;
+ storageCleanup?: HostStorageCleanupStatus;
tokenId?: string;
tokenName?: string;
tokenHint?: string;
@@ -494,6 +495,15 @@ export interface HostPackageUpdate {
availableVersion?: string;
}
+export interface HostStorageCleanupStatus {
+ supported: boolean;
+ provider?: string;
+ fingerprint?: string;
+ reclaimableBytes: number;
+ checkedAt?: string;
+ error?: string;
+}
+
export interface AgentConfigFingerprint {
version: string;
hash: string;
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index e2a68b30cc..ede228a687 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -12,6 +12,7 @@ import type {
HostDiskIO,
HostNetworkInterface,
HostPackageUpdateStatus,
+ HostStorageCleanupStatus,
HostSensorSummary,
HostRAIDArray,
Memory,
@@ -620,6 +621,7 @@ export interface ResourceAgentMeta {
rebuildSummary?: string;
commandsEnabled?: boolean;
packageUpdates?: HostPackageUpdateStatus;
+ storageCleanup?: HostStorageCleanupStatus;
tokenId?: string;
tokenName?: string;
tokenHint?: string;
diff --git a/internal/agentcontext/resource_context_sections.go b/internal/agentcontext/resource_context_sections.go
index 47ae882e3a..bd0f0e71f0 100644
--- a/internal/agentcontext/resource_context_sections.go
+++ b/internal/agentcontext/resource_context_sections.go
@@ -517,6 +517,20 @@ func addAgentDataFacts(facts *[]Fact, resource unified.Resource, observedAt *tim
addAgentContextFact(facts, "OS update inventory", inventoryState, agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, updatesObservedAt)
addAgentContextFact(facts, "Reboot required", fmt.Sprintf("%t", updates.RebootRequired), agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, updatesObservedAt)
}
+ if cleanup := resource.Agent.StorageCleanup; cleanup != nil {
+ cleanupObservedAt := timePtrIfSet(cleanup.CheckedAt)
+ cleanupState := "ready"
+ if !cleanup.Supported {
+ cleanupState = "unsupported"
+ } else if strings.TrimSpace(cleanup.Error) != "" {
+ cleanupState = "error"
+ }
+ addAgentContextFact(facts, "Package cache cleanup", cleanupState, agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, cleanupObservedAt)
+ addAgentContextFact(facts, "Reclaimable package cache", fmt.Sprintf("%d bytes", cleanup.ReclaimableBytes), agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, cleanupObservedAt)
+ if disk, ok := unified.HostStorageCleanupTargetDisk(resource.Agent.Disks); ok {
+ addAgentContextFact(facts, "Package cache filesystem usage", fmt.Sprintf("%.1f%%", disk.Usage), agentContextSourceUnifiedResource, agentContextTrustRuntimeObserved, observedAt)
+ }
+ }
}
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.go
index a6c350ba1f..2593f6738d 100644
--- a/internal/agentcontext/resource_context_sections_test.go
+++ b/internal/agentcontext/resource_context_sections_test.go
@@ -42,10 +42,14 @@ func TestBuildResourceContextSectionsAppliesRedactionTrustAndFreshness(t *testin
}
resource.Agent = &unified.AgentData{
Hostname: "prod-node", Platform: "linux", OSName: "Debian", OSVersion: "12", CommandsEnabled: true,
+ Disks: []unified.DiskInfo{{Mountpoint: "/", Usage: 95}},
PackageUpdates: &unified.AgentPackageUpdateMeta{
Supported: true, Manager: "apt", PendingCount: 4, CheckedAt: observedAt, RebootRequired: true,
Packages: []unified.AgentPackageUpdate{{Name: "private-customer-package", InstalledVersion: "1", AvailableVersion: "2"}},
},
+ StorageCleanup: &unified.AgentStorageCleanupMeta{
+ Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:private-cleanup-fingerprint", ReclaimableBytes: 536870912, CheckedAt: observedAt,
+ },
}
resource.Docker = &unified.DockerData{
Image: "registry.internal/finance-db:latest",
@@ -116,6 +120,15 @@ func TestBuildResourceContextSectionsAppliesRedactionTrustAndFreshness(t *testin
if got := requireFact(t, runtime, "Reboot required").Value; got != "true" {
t.Fatalf("reboot required = %q, want true", got)
}
+ if got := requireFact(t, runtime, "Package cache cleanup").Value; got != "ready" {
+ t.Fatalf("package cache cleanup = %q, want ready", got)
+ }
+ if got := requireFact(t, runtime, "Reclaimable package cache").Value; got != "536870912 bytes" {
+ t.Fatalf("reclaimable package cache = %q", got)
+ }
+ if got := requireFact(t, runtime, "Package cache filesystem usage").Value; got != "95.0%" {
+ t.Fatalf("package cache filesystem usage = %q", got)
+ }
encodedSections, err := json.Marshal(sections)
if err != nil {
t.Fatalf("marshal sections: %v", err)
@@ -123,6 +136,9 @@ func TestBuildResourceContextSectionsAppliesRedactionTrustAndFreshness(t *testin
if strings.Contains(string(encodedSections), "private-customer-package") {
t.Fatalf("resource context exposed package identifiers: %s", encodedSections)
}
+ if strings.Contains(string(encodedSections), "private-cleanup-fingerprint") || strings.Contains(string(encodedSections), "/var/cache/apt/archives") {
+ t.Fatalf("resource context exposed cleanup fingerprint or fixed agent path: %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.go
index f2f5d9797a..0f475d85f8 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -55,21 +55,23 @@ const (
var safeTargetIDPattern = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
var hostUpdateInventoryHashPattern = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`)
+var hostStorageCleanupFingerprintPattern = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`)
// Server manages WebSocket connections from agents
type Server struct {
- mu sync.RWMutex
- agents map[string]*agentConn // agentID -> connection
- pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
- 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
+ mu sync.RWMutex
+ agents map[string]*agentConn // agentID -> connection
+ pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
+ pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup response
+ pendingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update response
+ 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 {
@@ -108,16 +110,17 @@ func NewServer(validateToken func(token string, agentID string, hostname string)
}
return &Server{
- 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,
+ agents: make(map[string]*agentConn),
+ pendingReqs: make(map[string]chan CommandResultPayload),
+ pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),
+ 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,
}
}
@@ -324,6 +327,73 @@ func validateHostUpdateResultPayload(result *HostUpdateResultPayload) error {
return nil
}
+func validateHostStorageCleanupPayload(req *HostStorageCleanupPayload) error {
+ if req == nil {
+ return fmt.Errorf("host storage cleanup payload is required")
+ }
+ req.RequestID = strings.TrimSpace(req.RequestID)
+ req.ActionID = strings.TrimSpace(req.ActionID)
+ req.Operation = strings.TrimSpace(req.Operation)
+ req.ExpectedFingerprint = strings.TrimSpace(req.ExpectedFingerprint)
+ if req.RequestID == "" || len(req.RequestID) > maxRequestIDLength {
+ return fmt.Errorf("invalid request id")
+ }
+ if req.ActionID == "" || len(req.ActionID) > maxRequestIDLength {
+ return fmt.Errorf("invalid action id")
+ }
+ if req.Operation != HostStorageCleanupOperationPackageCache {
+ return fmt.Errorf("unsupported host storage cleanup operation %q", req.Operation)
+ }
+ if !hostStorageCleanupFingerprintPattern.MatchString(req.ExpectedFingerprint) {
+ return fmt.Errorf("expected cleanup fingerprint is required and must be sha256")
+ }
+ if req.Timeout < 0 || req.Timeout > 900 {
+ return fmt.Errorf("host storage cleanup timeout must be between 0 and 900 seconds")
+ }
+ if req.Timeout == 0 {
+ req.Timeout = 300
+ }
+ return nil
+}
+
+func validateHostStorageCleanupResultPayload(result *HostStorageCleanupResultPayload) error {
+ if result == nil {
+ return fmt.Errorf("host storage cleanup 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.ReclaimableBytes < 0 || result.After.ReclaimableBytes < 0 || result.ReclaimedBytes < 0 {
+ return fmt.Errorf("storage cleanup byte counts cannot be negative")
+ }
+ if result.Before.ReclaimableBytes > HostStorageCleanupMaxReportedBytes || result.After.ReclaimableBytes > HostStorageCleanupMaxReportedBytes || result.ReclaimedBytes > HostStorageCleanupMaxReportedBytes {
+ return fmt.Errorf("storage cleanup byte counts exceed bounded limit")
+ }
+ for _, fingerprint := range []string{result.Before.Fingerprint, result.After.Fingerprint} {
+ if fingerprint != "" && !hostStorageCleanupFingerprintPattern.MatchString(fingerprint) {
+ return fmt.Errorf("invalid storage cleanup fingerprint")
+ }
+ }
+ switch result.Verification {
+ case HostStorageCleanupVerificationVerified:
+ if !result.Success || !result.After.Supported || result.After.Provider != "apt-package-cache" || result.After.Error != "" || result.After.Fingerprint == "" {
+ return fmt.Errorf("verified storage cleanup lacks a valid postcondition")
+ }
+ if result.Before.ReclaimableBytes <= 0 || result.ReclaimedBytes <= 0 || result.After.ReclaimableBytes >= result.Before.ReclaimableBytes || result.ReclaimedBytes != result.Before.ReclaimableBytes-result.After.ReclaimableBytes {
+ return fmt.Errorf("verified storage cleanup did not reclaim reported bytes")
+ }
+ case HostStorageCleanupVerificationFailed, HostStorageCleanupVerificationInconclusive:
+ default:
+ return fmt.Errorf("unsupported host storage cleanup verification %q", result.Verification)
+ }
+ if len(result.Error) > 1024 {
+ return fmt.Errorf("host storage cleanup error exceeds bounded limit")
+ }
+ return nil
+}
+
func isAllowedWebSocketOrigin(r *http.Request) bool {
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
@@ -757,6 +827,36 @@ func (s *Server) readLoop(ac *agentConn) {
}
}
+ case MsgTypeHostStorageCleanupResult:
+ var result HostStorageCleanupResultPayload
+ if err := msg.DecodePayload(&result); err != nil {
+ log.Error().Err(err).Str("agent_id", ac.agent.AgentID).Msg("Failed to parse host storage cleanup result")
+ continue
+ }
+ requestID := strings.TrimSpace(result.RequestID)
+ if requestID == "" || len(requestID) > maxRequestIDLength {
+ log.Warn().Str("agent_id", ac.agent.AgentID).Msg("Dropping host storage cleanup result with invalid request id")
+ continue
+ }
+ if err := validateHostStorageCleanupResultPayload(&result); err != nil {
+ log.Warn().Err(err).Str("agent_id", ac.agent.AgentID).Str("request_id", requestID).Msg("Replacing invalid host storage cleanup result with a safe failure")
+ result = HostStorageCleanupResultPayload{
+ RequestID: requestID,
+ Verification: HostStorageCleanupVerificationInconclusive,
+ Error: "agent returned invalid host storage cleanup evidence",
+ }
+ }
+ s.mu.RLock()
+ ch, ok := s.pendingHostStorageCleanups[pendingRequestKey(ac.agent.AgentID, result.RequestID)]
+ s.mu.RUnlock()
+ if ok {
+ select {
+ case ch <- result:
+ default:
+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Host storage cleanup result channel full, dropping")
+ }
+ }
+
case MsgTypeDeployProgress:
var progress DeployProgressPayload
if err := msg.DecodePayload(&progress); err != nil {
@@ -1119,6 +1219,71 @@ func (s *Server) ExecuteHostUpdate(ctx context.Context, agentID string, req Host
}
}
+// ExecuteHostStorageCleanup dispatches the closed package-cache cleanup
+// operation. No command text, path, package selector, or removal policy crosses
+// the server/agent boundary.
+func (s *Server) ExecuteHostStorageCleanup(ctx context.Context, agentID string, req HostStorageCleanupPayload) (*HostStorageCleanupResultPayload, 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 := validateHostStorageCleanupPayload(&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 HostStorageCleanupResultPayload, 1)
+ reqKey := pendingRequestKey(agentID, req.RequestID)
+ s.mu.Lock()
+ if _, exists := s.pendingHostStorageCleanups[reqKey]; exists {
+ s.mu.Unlock()
+ return nil, fmt.Errorf("host storage cleanup request %q is already pending", req.RequestID)
+ }
+ s.pendingHostStorageCleanups[reqKey] = respCh
+ s.mu.Unlock()
+ defer func() {
+ s.mu.Lock()
+ delete(s.pendingHostStorageCleanups, reqKey)
+ s.mu.Unlock()
+ }()
+
+ msg, err := NewMessage(MsgTypeHostStorageCleanup, req.RequestID, req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encode host storage cleanup 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 storage cleanup 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 storage cleanup 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 agent
func (s *Server) ReadFile(ctx context.Context, agentID string, req ReadFilePayload) (*CommandResultPayload, error) {
agentID = strings.TrimSpace(agentID)
diff --git a/internal/agentexec/server_test.go b/internal/agentexec/server_test.go
index e9bcda3724..bdf643778e 100644
--- a/internal/agentexec/server_test.go
+++ b/internal/agentexec/server_test.go
@@ -2,12 +2,26 @@ package agentexec
import (
"context"
+ "reflect"
"strings"
"sync"
"testing"
"time"
)
+func TestHostStorageCleanupPayloadIsClosedAndSelectorFree(t *testing.T) {
+ typeOf := reflect.TypeOf(HostStorageCleanupPayload{})
+ want := []string{"RequestID", "ActionID", "Operation", "ExpectedFingerprint", "Timeout"}
+ if typeOf.NumField() != len(want) {
+ t.Fatalf("host storage cleanup payload fields = %d, want %d", typeOf.NumField(), len(want))
+ }
+ for i, name := range want {
+ if field := typeOf.Field(i); field.Name != name {
+ t.Fatalf("field %d = %s, want %s", i, field.Name, name)
+ }
+ }
+}
+
func allowAllTestTokens(string, string, string) bool { return true }
func TestNewServerRequiresValidateToken(t *testing.T) {
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index 91d907adba..b9674620b3 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -553,6 +553,103 @@ func TestValidateHostUpdateResultRejectsUnprovenVerifiedClaim(t *testing.T) {
}
}
+func TestExecuteHostStorageCleanupRoundTripUsesPathAndCommandFreeEnvelope(t *testing.T) {
+ fingerprint := "sha256:" + strings.Repeat("a", 64)
+ afterFingerprint := "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-cleanup", 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 != MsgTypeHostStorageCleanup || msg.Payload == nil {
+ agentErr <- fmt.Errorf("message = %#v, want typed host storage cleanup", msg)
+ return
+ }
+ for _, forbidden := range []string{`"command"`, `"path"`, `"packages"`} {
+ if bytes.Contains(*msg.Payload, []byte(forbidden)) {
+ agentErr <- fmt.Errorf("storage cleanup request exposed forbidden authority %s: %s", forbidden, string(*msg.Payload))
+ return
+ }
+ }
+ var payload HostStorageCleanupPayload
+ if err := json.Unmarshal(*msg.Payload, &payload); err != nil {
+ agentErr <- err
+ return
+ }
+ if payload.ActionID != "action-cleanup" || payload.Operation != HostStorageCleanupOperationPackageCache {
+ agentErr <- fmt.Errorf("payload = %#v", payload)
+ return
+ }
+ response := HostStorageCleanupResultPayload{
+ RequestID: payload.RequestID,
+ Success: true,
+ Before: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: fingerprint, ReclaimableBytes: 500},
+ After: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: afterFingerprint, ReclaimableBytes: 20},
+ ReclaimedBytes: 480,
+ Verification: HostStorageCleanupVerificationVerified,
+ }
+ if err := conn.WriteJSON(mustNewMessage(t, MsgTypeHostStorageCleanupResult, payload.RequestID, response)); err != nil {
+ agentErr <- err
+ return
+ }
+ agentErr <- nil
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ result, err := s.ExecuteHostStorageCleanup(ctx, "host-agent-cleanup", HostStorageCleanupPayload{
+ RequestID: "cleanup-1", ActionID: "action-cleanup", Operation: HostStorageCleanupOperationPackageCache, ExpectedFingerprint: fingerprint, Timeout: 1,
+ })
+ if err != nil {
+ t.Fatalf("ExecuteHostStorageCleanup: %v", err)
+ }
+ if result == nil || !result.Success || result.Verification != HostStorageCleanupVerificationVerified || result.ReclaimedBytes != 480 {
+ t.Fatalf("result = %#v", result)
+ }
+ if err := <-agentErr; err != nil {
+ t.Fatalf("agent: %v", err)
+ }
+}
+
+func TestValidateHostStorageCleanupRejectsOpenEndedOrUnprovenClaims(t *testing.T) {
+ fingerprint := "sha256:" + strings.Repeat("a", 64)
+ for _, req := range []HostStorageCleanupPayload{
+ {RequestID: "r1", ActionID: "a1", Operation: "delete_path", ExpectedFingerprint: fingerprint},
+ {RequestID: "r1", Operation: HostStorageCleanupOperationPackageCache, ExpectedFingerprint: fingerprint},
+ {RequestID: "r1", ActionID: "a1", Operation: HostStorageCleanupOperationPackageCache, ExpectedFingerprint: "bad"},
+ {RequestID: "r1", ActionID: "a1", Operation: HostStorageCleanupOperationPackageCache, ExpectedFingerprint: fingerprint, Timeout: 901},
+ } {
+ copy := req
+ if err := validateHostStorageCleanupPayload(&copy); err == nil {
+ t.Fatalf("validateHostStorageCleanupPayload(%#v) succeeded", req)
+ }
+ }
+ result := HostStorageCleanupResultPayload{
+ RequestID: "r1", Success: true, Verification: HostStorageCleanupVerificationVerified,
+ Before: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: fingerprint, ReclaimableBytes: 500},
+ After: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: fingerprint, ReclaimableBytes: 500},
+ }
+ if err := validateHostStorageCleanupResultPayload(&result); err == nil {
+ t.Fatal("verified result without reclaimed bytes 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.go
index a900135fbb..dc3b433ee4 100644
--- a/internal/agentexec/types.go
+++ b/internal/agentexec/types.go
@@ -11,20 +11,22 @@ type MessageType string
const (
// Agent -> Server messages
- MsgTypeAgentRegister MessageType = "agent_register"
- MsgTypeAgentPing MessageType = "agent_ping"
- MsgTypeCommandResult MessageType = "command_result"
- MsgTypeHostUpdateResult MessageType = "host_update_result"
+ MsgTypeAgentRegister MessageType = "agent_register"
+ MsgTypeAgentPing MessageType = "agent_ping"
+ MsgTypeCommandResult MessageType = "command_result"
+ MsgTypeHostStorageCleanupResult MessageType = "host_storage_cleanup_result"
+ MsgTypeHostUpdateResult MessageType = "host_update_result"
// Server -> Agent messages
- MsgTypeRegistered 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"
+ MsgTypeRegistered MessageType = "registered"
+ MsgTypePong MessageType = "pong"
+ MsgTypeExecuteCmd MessageType = "execute_command"
+ MsgTypeHostStorageCleanup MessageType = "host_storage_cleanup"
+ MsgTypeReadFile MessageType = "read_file"
+ MsgTypeHostUpdate MessageType = "host_update"
+ MsgTypeDeployPreflight MessageType = "deploy_preflight"
+ MsgTypeDeployInstall MessageType = "deploy_install"
+ MsgTypeDeployCancelJob MessageType = "deploy_cancel"
// Agent -> Server messages (deploy)
MsgTypeDeployProgress MessageType = "deploy_progress"
@@ -178,6 +180,49 @@ type HostUpdateResultPayload struct {
Duration int64 `json:"duration_ms"`
}
+const HostStorageCleanupOperationPackageCache = "clean_package_cache"
+
+const HostStorageCleanupMaxReportedBytes int64 = 1 << 60
+
+// HostStorageCleanupPayload is the closed storage-pressure operation sent to
+// a Unified Agent. The model cannot select paths or commands: the agent owns
+// the single APT package-cache target and command catalog.
+type HostStorageCleanupPayload struct {
+ RequestID string `json:"request_id"`
+ ActionID string `json:"action_id"`
+ Operation string `json:"operation"`
+ ExpectedFingerprint string `json:"expected_fingerprint"`
+ Timeout int `json:"timeout,omitempty"`
+}
+
+type HostStorageCleanupSnapshot struct {
+ Supported bool `json:"supported"`
+ Provider string `json:"provider,omitempty"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+ ReclaimableBytes int64 `json:"reclaimable_bytes"`
+ CheckedAt time.Time `json:"checked_at,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+const (
+ HostStorageCleanupVerificationVerified = "verified"
+ HostStorageCleanupVerificationFailed = "failed"
+ HostStorageCleanupVerificationInconclusive = "inconclusive"
+)
+
+// HostStorageCleanupResultPayload separates mutation success from the
+// read-after-write observation of reclaimed cache bytes.
+type HostStorageCleanupResultPayload struct {
+ RequestID string `json:"request_id"`
+ Success bool `json:"success"`
+ Before HostStorageCleanupSnapshot `json:"before"`
+ After HostStorageCleanupSnapshot `json:"after"`
+ ReclaimedBytes int64 `json:"reclaimed_bytes"`
+ Verification string `json:"verification"`
+ Error string `json:"error,omitempty"`
+ Duration int64 `json:"duration_ms"`
+}
+
// ConnectedAgent represents an agent connected via WebSocket
type ConnectedAgent struct {
AgentID string
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index e010a924f7..01ddedd616 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)",
+ "newHostStorageCleanupActionExecutor(r.resourceHandlers, r.agentExecServer)",
"newHostUpdateActionExecutor(r.resourceHandlers, r.agentExecServer)",
} {
if !strings.Contains(routerSrc, snippet) {
@@ -19934,6 +19935,57 @@ func TestContract_HostUpdatesUseTypedFingerprintBoundAgentOperation(t *testing.T
}
}
+func TestContract_HostStorageCleanupIsTypedFingerprintBoundAndPathFree(t *testing.T) {
+ executorSource, err := os.ReadFile("host_storage_cleanup_action_executor.go")
+ if err != nil {
+ t.Fatalf("read host storage cleanup executor: %v", err)
+ }
+ agentTypesSource, err := os.ReadFile("../agentexec/types.go")
+ if err != nil {
+ t.Fatalf("read agentexec types: %v", err)
+ }
+ agentRuntimeSource, err := os.ReadFile("../hostagent/storage_cleanup.go")
+ if err != nil {
+ t.Fatalf("read storage cleanup runtime: %v", err)
+ }
+
+ executorSrc := string(executorSource)
+ typesSrc := string(agentTypesSource)
+ runtimeSrc := string(agentRuntimeSource)
+ for _, snippet := range []string{
+ "ExecuteHostStorageCleanup(ctx context.Context, agentID string, req agentexec.HostStorageCleanupPayload)",
+ "resource.Agent.StorageCleanup.Fingerprint",
+ "agentexec.HostStorageCleanupOperationPackageCache",
+ "unified.HostStorageCleanupPressureDisk(resource.Agent.Disks)",
+ } {
+ if !strings.Contains(executorSrc, snippet) {
+ t.Fatalf("host storage cleanup executor missing invariant %q", snippet)
+ }
+ }
+ for _, snippet := range []string{
+ "ExpectedFingerprint string `json:\"expected_fingerprint\"`",
+ "const HostStorageCleanupOperationPackageCache = \"clean_package_cache\"",
+ } {
+ if !strings.Contains(typesSrc, snippet) {
+ t.Fatalf("host storage cleanup wire contract missing %q", snippet)
+ }
+ }
+ for _, forbidden := range []string{"Command string", "Path string", "Packages []"} {
+ if strings.Contains(typesSrc[strings.Index(typesSrc, "type HostStorageCleanupPayload struct"):strings.Index(typesSrc, "type HostStorageCleanupSnapshot struct")], forbidden) {
+ t.Fatalf("host storage cleanup payload exposes forbidden authority %q", forbidden)
+ }
+ }
+ for _, snippet := range []string{
+ "if before.Fingerprint != strings.TrimSpace(req.ExpectedFingerprint)",
+ "\"apt-get\", \"clean\"",
+ "if result.ReclaimedBytes <= 0",
+ } {
+ if !strings.Contains(runtimeSrc, snippet) {
+ t.Fatalf("host storage cleanup runtime missing fail-closed 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. The
diff --git a/internal/api/host_storage_cleanup_action_executor.go b/internal/api/host_storage_cleanup_action_executor.go
new file mode 100644
index 0000000000..239843d318
--- /dev/null
+++ b/internal/api/host_storage_cleanup_action_executor.go
@@ -0,0 +1,232 @@
+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 (
+ hostStorageCleanupActionHandler = "host.storage_cleanup"
+ hostStorageCleanupCapability = "clean_package_cache"
+)
+
+var hostStorageCleanupFingerprintPattern = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`)
+
+type hostStorageCleanupAgentCommander interface {
+ ExecuteHostStorageCleanup(ctx context.Context, agentID string, req agentexec.HostStorageCleanupPayload) (*agentexec.HostStorageCleanupResultPayload, error)
+ IsAgentConnected(agentID string) bool
+}
+
+type hostStorageCleanupActionExecutor struct {
+ resources *ResourceHandlers
+ agents hostStorageCleanupAgentCommander
+ now func() time.Time
+}
+
+func newHostStorageCleanupActionExecutor(resources *ResourceHandlers, agents hostStorageCleanupAgentCommander) ActionExecutor {
+ if resources == nil || agents == nil {
+ return nil
+ }
+ return hostStorageCleanupActionExecutor{resources: resources, agents: agents, now: time.Now}
+}
+
+func (e hostStorageCleanupActionExecutor) ActionHandlerNames() []string {
+ return []string{hostStorageCleanupActionHandler}
+}
+
+func (e hostStorageCleanupActionExecutor) CheckActionAvailable(_ context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {
+ if strings.TrimSpace(req.CapabilityName) != hostStorageCleanupCapability {
+ return unified.ResourceActionReadiness{}
+ }
+ capability, ok := resourceCapabilityByName(resource.Capabilities, hostStorageCleanupCapability)
+ if !ok || capability.InternalHandler != hostStorageCleanupActionHandler {
+ return unified.ResourceActionReadiness{}
+ }
+ if err := e.validateResource(resource); err != nil {
+ return unified.ResourceActionReadiness{
+ Name: hostStorageCleanupCapability,
+ Available: false,
+ ReasonCode: hostStorageCleanupUnavailableReasonCode(err),
+ Reason: hostStorageCleanupUnavailableReason(err),
+ }
+ }
+ return unified.ResourceActionReadiness{Name: hostStorageCleanupCapability, Available: true}
+}
+
+func (e hostStorageCleanupActionExecutor) 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) != hostStorageCleanupCapability {
+ return nil, fmt.Errorf("unsupported host storage cleanup capability %q", record.Request.CapabilityName)
+ }
+ resource, err := e.currentResource(ctx, record.Request.ResourceID)
+ if err != nil {
+ return nil, err
+ }
+ result, err := e.agents.ExecuteHostStorageCleanup(ctx, strings.TrimSpace(resource.Agent.AgentID), agentexec.HostStorageCleanupPayload{
+ RequestID: record.ID,
+ ActionID: record.ID,
+ Operation: agentexec.HostStorageCleanupOperationPackageCache,
+ ExpectedFingerprint: resource.Agent.StorageCleanup.Fingerprint,
+ Timeout: 300,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if result == nil {
+ return nil, fmt.Errorf("host storage cleanup agent returned no result")
+ }
+
+ output := fmt.Sprintf("APT package cache: %d bytes before, %d bytes after, %d bytes reclaimed", result.Before.ReclaimableBytes, result.After.ReclaimableBytes, result.ReclaimedBytes)
+ execution := &unified.ExecutionResult{
+ Success: result.Success,
+ Output: output,
+ Verification: projectHostStorageCleanupVerification(result),
+ }
+ if !result.Success {
+ execution.ErrorMessage = "host package-cache cleanup failed on the agent"
+ }
+ return execution, nil
+}
+
+func (e hostStorageCleanupActionExecutor) 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 hostStorageCleanupActionExecutor) 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, hostStorageCleanupCapability)
+ if !ok || capability.InternalHandler != hostStorageCleanupActionHandler {
+ return fmt.Errorf("host does not currently advertise typed package-cache cleanup")
+ }
+ if !resource.Agent.CommandsEnabled {
+ return fmt.Errorf("host command operations are disabled")
+ }
+ status := resource.Agent.StorageCleanup
+ if status == nil || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" {
+ return fmt.Errorf("host storage cleanup provider is unsupported")
+ }
+ if strings.TrimSpace(status.Error) != "" {
+ return fmt.Errorf("host storage cleanup inventory has an error")
+ }
+ if !hostStorageCleanupFingerprintPattern.MatchString(strings.TrimSpace(status.Fingerprint)) {
+ return fmt.Errorf("host storage cleanup fingerprint is invalid")
+ }
+ if status.CheckedAt.IsZero() || e.currentTime().Sub(status.CheckedAt.UTC()) > unified.HostStorageCleanupFreshness {
+ return fmt.Errorf("host storage cleanup inventory is stale")
+ }
+ if status.ReclaimableBytes < unified.HostStorageCleanupMinReclaimableBytes {
+ return fmt.Errorf("host package cache has insufficient reclaimable space")
+ }
+ if _, ok := unified.HostStorageCleanupPressureDisk(resource.Agent.Disks); !ok {
+ return fmt.Errorf("package cache filesystem is not under storage pressure")
+ }
+ 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 hostStorageCleanupActionExecutor) currentTime() time.Time {
+ if e.now != nil {
+ return e.now().UTC()
+ }
+ return time.Now().UTC()
+}
+
+func projectHostStorageCleanupVerification(result *agentexec.HostStorageCleanupResultPayload) *unified.ActionVerificationResult {
+ if result == nil {
+ return &unified.ActionVerificationResult{Ran: false, Note: "agent returned no verification evidence"}
+ }
+ note := fmt.Sprintf("package cache bytes %d -> %d; reclaimed=%d", result.Before.ReclaimableBytes, result.After.ReclaimableBytes, result.ReclaimedBytes)
+ switch strings.TrimSpace(result.Verification) {
+ case agentexec.HostStorageCleanupVerificationVerified:
+ if !result.Success || !result.After.Supported || result.After.Provider != "apt-package-cache" || result.After.Error != "" || !hostStorageCleanupFingerprintPattern.MatchString(result.After.Fingerprint) || result.ReclaimedBytes <= 0 || result.After.ReclaimableBytes >= result.Before.ReclaimableBytes {
+ return &unified.ActionVerificationResult{Ran: false, Note: "agent returned invalid verification evidence"}
+ }
+ return &unified.ActionVerificationResult{Ran: true, Success: true, Command: "typed:host_storage_cleanup/clean_package_cache", Output: note, Note: note, RanAt: time.Now().UTC()}
+ case agentexec.HostStorageCleanupVerificationFailed:
+ return &unified.ActionVerificationResult{Ran: true, Success: false, Command: "typed:host_storage_cleanup/clean_package_cache", Output: note, Note: "post-cleanup cache inspection did not confirm reclaimed space", RanAt: time.Now().UTC()}
+ default:
+ return &unified.ActionVerificationResult{Ran: false, Note: "post-cleanup package-cache inspection was inconclusive"}
+ }
+}
+
+func hostStorageCleanupUnavailableReasonCode(err error) string {
+ if err == nil {
+ return "unavailable"
+ }
+ 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_cleanup_provider"
+ case strings.Contains(message, "inventory") && strings.Contains(message, "error"):
+ return "cleanup_inventory_error"
+ case strings.Contains(message, "fingerprint"):
+ return "invalid_cleanup_inventory"
+ case strings.Contains(message, "stale"):
+ return "stale_cleanup_inventory"
+ case strings.Contains(message, "insufficient"):
+ return "insufficient_reclaimable_space"
+ case strings.Contains(message, "not under storage pressure"):
+ return "storage_pressure_cleared"
+ case strings.Contains(message, "disconnected"):
+ return "command_agent_disconnected"
+ default:
+ return "capability_unavailable"
+ }
+}
+
+func hostStorageCleanupUnavailableReason(err error) string {
+ switch hostStorageCleanupUnavailableReasonCode(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_cleanup_provider":
+ return "This host does not expose a supported package-cache cleanup provider."
+ case "cleanup_inventory_error":
+ return "Pulse could not inspect reclaimable package-cache storage."
+ case "invalid_cleanup_inventory":
+ return "The package-cache inventory cannot be verified safely."
+ case "stale_cleanup_inventory":
+ return "The package-cache inventory is too old to clean safely."
+ case "insufficient_reclaimable_space":
+ return "The package cache no longer contains enough reclaimable data."
+ case "storage_pressure_cleared":
+ return "The filesystem containing the package cache is no longer under storage pressure."
+ case "command_agent_disconnected":
+ return "The host command agent is not connected."
+ default:
+ return "Typed package-cache cleanup is not currently available."
+ }
+}
diff --git a/internal/api/host_storage_cleanup_action_executor_test.go b/internal/api/host_storage_cleanup_action_executor_test.go
new file mode 100644
index 0000000000..d72f18d70a
--- /dev/null
+++ b/internal/api/host_storage_cleanup_action_executor_test.go
@@ -0,0 +1,201 @@
+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 fakeHostStorageCleanupAgent struct {
+ connected bool
+ result *agentexec.HostStorageCleanupResultPayload
+ err error
+ agentID string
+ requests []agentexec.HostStorageCleanupPayload
+}
+
+var testHostStorageCleanupFingerprint = "sha256:" + strings.Repeat("c", 64)
+var testHostStorageCleanupAfterFingerprint = "sha256:" + strings.Repeat("d", 64)
+
+func (f *fakeHostStorageCleanupAgent) ExecuteHostStorageCleanup(_ context.Context, agentID string, req agentexec.HostStorageCleanupPayload) (*agentexec.HostStorageCleanupResultPayload, error) {
+ f.agentID = agentID
+ f.requests = append(f.requests, req)
+ return f.result, f.err
+}
+
+func (f *fakeHostStorageCleanupAgent) IsAgentConnected(string) bool { return f.connected }
+
+func TestHostStorageCleanupActionExecutorDispatchesFingerprintBoundOperation(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{hostStorageCleanupActionResource(now)}})
+ agents := verifiedHostStorageCleanupAgent()
+
+ result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(context.Background(), hostStorageCleanupActionRecord("action-cleanup"))
+ 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, "536870912 bytes before") || !strings.Contains(result.Output, "528482304 bytes reclaimed") {
+ 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-cleanup" || request.Operation != agentexec.HostStorageCleanupOperationPackageCache || request.ExpectedFingerprint != testHostStorageCleanupFingerprint || request.Timeout != 300 {
+ t.Fatalf("typed request = %#v", request)
+ }
+}
+
+func TestHostStorageCleanupActionExecutorDoesNotExposeAgentErrorText(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{hostStorageCleanupActionResource(now)}})
+ agents := &fakeHostStorageCleanupAgent{connected: true, result: &agentexec.HostStorageCleanupResultPayload{
+ RequestID: "action-cleanup", Verification: agentexec.HostStorageCleanupVerificationFailed,
+ Before: agentexec.HostStorageCleanupSnapshot{ReclaimableBytes: 512 * 1024 * 1024},
+ After: agentexec.HostStorageCleanupSnapshot{ReclaimableBytes: 512 * 1024 * 1024},
+ Error: "private repository package path and token",
+ }}
+
+ result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(context.Background(), hostStorageCleanupActionRecord("action-cleanup"))
+ if err != nil {
+ t.Fatalf("ExecuteAction: %v", err)
+ }
+ encoded := result.Output + " " + result.ErrorMessage + " " + result.Verification.Note + " " + result.Verification.Output
+ if strings.Contains(encoded, "private repository") || strings.Contains(encoded, "token") {
+ t.Fatalf("executor exposed agent error text: %q", encoded)
+ }
+}
+
+func TestPatrolFullModeRunsStorageCleanupThroughCanonicalLifecycle(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{hostStorageCleanupActionResource(now)}})
+ agents := verifiedHostStorageCleanupAgent()
+ h.SetActionExecutor(newRoutedActionExecutor(h, newHostStorageCleanupActionExecutor(h, agents)))
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{
+ CanonicalID: "agent:host-cleanup",
+ AutoRemediationPolicy: unified.AutoRemediationPolicy{
+ Enabled: true, CapabilityNames: []string{hostStorageCleanupCapability},
+ },
+ 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-cleanup", FindingID: "finding-disk-pressure", InvestigationID: "investigation-disk-pressure",
+ ResourceID: "agent:host-cleanup", CapabilityName: hostStorageCleanupCapability, Reason: "Reclaim the package cache on the pressured filesystem",
+ })
+ 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.HostStorageCleanupOperationPackageCache {
+ 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 TestHostStorageCleanupAvailabilityFailsClosed(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.StorageCleanup.CheckedAt = now.Add(-time.Hour) }, connected: true, reasonCode: "stale_cleanup_inventory"},
+ {name: "inventory error", mutate: func(r *unified.Resource) { r.Agent.StorageCleanup.Error = "inspection failed" }, connected: true, reasonCode: "cleanup_inventory_error"},
+ {name: "invalid fingerprint", mutate: func(r *unified.Resource) { r.Agent.StorageCleanup.Fingerprint = "sha256:bad" }, connected: true, reasonCode: "invalid_cleanup_inventory"},
+ {name: "insufficient bytes", mutate: func(r *unified.Resource) {
+ r.Agent.StorageCleanup.ReclaimableBytes = unified.HostStorageCleanupMinReclaimableBytes - 1
+ }, connected: true, reasonCode: "insufficient_reclaimable_space"},
+ {name: "pressure cleared", mutate: func(r *unified.Resource) { r.Agent.Disks[0].Usage = 80 }, connected: true, reasonCode: "storage_pressure_cleared"},
+ {name: "separate var filesystem healthy", mutate: func(r *unified.Resource) {
+ r.Agent.Disks = append(r.Agent.Disks, unified.DiskInfo{Mountpoint: "/var", Usage: 50})
+ }, connected: true, reasonCode: "storage_pressure_cleared"},
+ {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 := hostStorageCleanupActionResource(now)
+ tc.mutate(&resource)
+ executor := hostStorageCleanupActionExecutor{agents: &fakeHostStorageCleanupAgent{connected: tc.connected}, now: func() time.Time { return now }}
+ readiness := executor.CheckActionAvailable(context.Background(), unified.ActionRequest{CapabilityName: hostStorageCleanupCapability}, resource)
+ if readiness.Available || readiness.Name != hostStorageCleanupCapability || readiness.ReasonCode != tc.reasonCode {
+ t.Fatalf("readiness = %#v", readiness)
+ }
+ })
+ }
+}
+
+func verifiedHostStorageCleanupAgent() *fakeHostStorageCleanupAgent {
+ return &fakeHostStorageCleanupAgent{connected: true, result: &agentexec.HostStorageCleanupResultPayload{
+ RequestID: "filled-by-executor", Success: true,
+ Before: agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupFingerprint, ReclaimableBytes: 512 * 1024 * 1024},
+ After: agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupAfterFingerprint, ReclaimableBytes: 8 * 1024 * 1024},
+ ReclaimedBytes: 504 * 1024 * 1024,
+ Verification: agentexec.HostStorageCleanupVerificationVerified,
+ }}
+}
+
+func hostStorageCleanupActionResource(now time.Time) unified.Resource {
+ return unified.Resource{
+ ID: "agent:host-cleanup", Type: unified.ResourceTypeAgent, Technology: "linux", Name: "host-cleanup",
+ 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,
+ Disks: []unified.DiskInfo{{Mountpoint: "/", Usage: 95}},
+ StorageCleanup: &unified.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupFingerprint, ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now},
+ },
+ Capabilities: []unified.ResourceCapability{{
+ Name: hostStorageCleanupCapability, Type: unified.CapabilityTypeCommon,
+ Description: "Clean the bounded APT package cache", MinimumApprovalLevel: unified.ApprovalAdmin,
+ AutoAuthorization: unified.AutoAuthorizeLowRisk, Platform: "linux", InternalHandler: hostStorageCleanupActionHandler,
+ }},
+ }
+}
+
+func hostStorageCleanupActionRecord(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-cleanup", CapabilityName: hostStorageCleanupCapability,
+ Reason: "Reclaim package cache storage", 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.go
index 28f2462a0b..cc5ccbe328 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),
+ newHostStorageCleanupActionExecutor(r.resourceHandlers, r.agentExecServer),
newHostUpdateActionExecutor(r.resourceHandlers, r.agentExecServer),
))
}
diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.go
index cf916bfca5..6b2c16ca28 100644
--- a/internal/hostagent/agent.go
+++ b/internal/hostagent/agent.go
@@ -84,6 +84,7 @@ type Config struct {
runCommandClientFn func(*CommandClient, context.Context) error
updatedFromVersionFn func() string
packageUpdates *packageUpdateManager
+ storageCleanup *storageCleanupManager
}
// Agent is responsible for collecting host metrics and shipping them to Pulse.
@@ -119,6 +120,7 @@ type Agent struct {
newCommandClient func(Config, string, string, string, string) *CommandClient
runCommandClient func(*CommandClient, context.Context) error
packageUpdates *packageUpdateManager
+ storageCleanup *storageCleanupManager
// lastAuthFailureLog throttles the actionable 401 error so a permanently
// rejected token does not spam the log every report interval. Only touched
@@ -319,6 +321,11 @@ func New(cfg Config) (*Agent, error) {
packageUpdates = newPackageUpdateManager(platform)
}
cfg.packageUpdates = packageUpdates
+ storageCleanup := cfg.storageCleanup
+ if storageCleanup == nil {
+ storageCleanup = newStorageCleanupManager(platform)
+ }
+ cfg.storageCleanup = storageCleanup
agent := &Agent{
cfg: cfg,
@@ -346,6 +353,7 @@ func New(cfg Config) (*Agent, error) {
newCommandClient: newCommandClientFn,
runCommandClient: runCommandClientFn,
packageUpdates: packageUpdates,
+ storageCleanup: storageCleanup,
}
// Create command client for AI command execution (only if enabled)
@@ -839,6 +847,7 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {
packageUpdateCtx, cancelPackageUpdates := context.WithTimeout(ctx, 20*time.Second)
packageUpdates := a.currentPackageUpdateStatus(packageUpdateCtx)
cancelPackageUpdates()
+ storageCleanup := a.currentStorageCleanupStatus()
// 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.
@@ -877,6 +886,7 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {
LoadAverage: append([]float64(nil), snapshot.LoadAverage...),
ReportIP: runtimeConfig.reportIP,
PackageUpdates: packageUpdates,
+ StorageCleanup: storageCleanup,
},
Metrics: agentshost.Metrics{
CPUUsagePercent: snapshot.CPUUsagePercent,
@@ -922,6 +932,21 @@ func (a *Agent) currentPackageUpdateStatus(ctx context.Context) *agentshost.Pack
}
}
+func (a *Agent) currentStorageCleanupStatus() *agentshost.StorageCleanupStatus {
+ if a == nil || a.storageCleanup == nil {
+ return nil
+ }
+ snapshot := a.storageCleanup.Snapshot(false)
+ return &agentshost.StorageCleanupStatus{
+ Supported: snapshot.Supported,
+ Provider: snapshot.Provider,
+ Fingerprint: snapshot.Fingerprint,
+ ReclaimableBytes: snapshot.ReclaimableBytes,
+ CheckedAt: snapshot.CheckedAt,
+ 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.go
index 1c56965707..f8a185ba58 100644
--- a/internal/hostagent/commands.go
+++ b/internal/hostagent/commands.go
@@ -105,6 +105,7 @@ type CommandClient struct {
deploySSHUser string
commandPolicy *agentexec.CommandPolicy
packageUpdates *packageUpdateManager
+ storageCleanup *storageCleanupManager
sshKnownHosts sshknownhosts.Manager
sshKnownHostsOnce sync.Once
sshKnownHostsErr error
@@ -137,6 +138,7 @@ func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *
deploySSHUser: cfg.DeploySSHUser,
commandPolicy: agentexec.DefaultPolicy(),
packageUpdates: cfg.packageUpdates,
+ storageCleanup: cfg.storageCleanup,
logger: logger,
done: make(chan struct{}),
}
@@ -157,19 +159,21 @@ func (c *CommandClient) stopChan() <-chan struct{} {
type messageType string
const (
- msgTypeAgentRegister messageType = "agent_register"
- msgTypeAgentPing messageType = "agent_ping"
- msgTypeCommandResult messageType = "command_result"
- msgTypeRegistered messageType = "registered"
- msgTypePong messageType = "pong"
- msgTypeExecuteCmd messageType = "execute_command"
- msgTypeReadFile messageType = "read_file"
- 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"
+ msgTypeAgentRegister messageType = "agent_register"
+ msgTypeAgentPing messageType = "agent_ping"
+ msgTypeCommandResult messageType = "command_result"
+ msgTypeRegistered messageType = "registered"
+ msgTypePong messageType = "pong"
+ msgTypeExecuteCmd messageType = "execute_command"
+ msgTypeReadFile messageType = "read_file"
+ msgTypeHostStorageCleanup messageType = "host_storage_cleanup"
+ msgTypeHostStorageCleanupResult messageType = "host_storage_cleanup_result"
+ msgTypeHostUpdate messageType = "host_update"
+ msgTypeHostUpdateResult messageType = "host_update_result"
+ msgTypeDeployPreflight messageType = "deploy_preflight"
+ msgTypeDeployInstall messageType = "deploy_install"
+ msgTypeDeployCancel messageType = "deploy_cancel"
+ msgTypeDeployProgress messageType = "deploy_progress"
)
type wsMessage struct {
@@ -532,6 +536,14 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn
}
go c.handleHostUpdate(ctx, conn, payload)
+ case msgTypeHostStorageCleanup:
+ var payload agentexec.HostStorageCleanupPayload
+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {
+ c.logger.Error().Err(err).Msg("Failed to parse host_storage_cleanup payload")
+ continue
+ }
+ go c.handleHostStorageCleanup(ctx, conn, payload)
+
case msgTypeDeployPreflight:
var payload deployPreflightPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
@@ -599,6 +611,43 @@ func (c *CommandClient) handleHostUpdate(ctx context.Context, conn *websocket.Co
}
}
+func (c *CommandClient) handleHostStorageCleanup(ctx context.Context, conn *websocket.Conn, payload agentexec.HostStorageCleanupPayload) {
+ timeout := time.Duration(payload.Timeout) * time.Second
+ if timeout <= 0 {
+ timeout = 5 * time.Minute
+ }
+ cleanupCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+
+ result := agentexec.HostStorageCleanupResultPayload{
+ RequestID: strings.TrimSpace(payload.RequestID),
+ Verification: agentexec.HostStorageCleanupVerificationInconclusive,
+ }
+ if c.storageCleanup == nil {
+ result.Error = "host storage cleanup service is unavailable"
+ } else {
+ result = c.storageCleanup.Apply(cleanupCtx, payload)
+ }
+
+ encoded, err := json.Marshal(result)
+ if err != nil {
+ c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to marshal host storage cleanup result")
+ return
+ }
+ msg := wsMessage{
+ Type: msgTypeHostStorageCleanupResult,
+ 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 storage cleanup result")
+ }
+}
+
func (c *CommandClient) handleExecuteCommand(ctx context.Context, conn *websocket.Conn, payload executeCommandPayload) {
startTime := time.Now()
diff --git a/internal/hostagent/commands_storage_cleanup_test.go b/internal/hostagent/commands_storage_cleanup_test.go
new file mode 100644
index 0000000000..0cf6aaba3d
--- /dev/null
+++ b/internal/hostagent/commands_storage_cleanup_test.go
@@ -0,0 +1,102 @@
+package hostagent
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rs/zerolog"
+)
+
+func TestCommandClientHandlesTypedHostStorageCleanup(t *testing.T) {
+ before := agentexec.HostStorageCleanupSnapshot{Fingerprint: "sha256:" + strings.Repeat("a", 64), ReclaimableBytes: 512}
+ after := agentexec.HostStorageCleanupSnapshot{Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 12}
+ snapshots := []agentexec.HostStorageCleanupSnapshot{before, after}
+ manager := newStorageCleanupManager("linux")
+ manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
+ manager.scan = func() (agentexec.HostStorageCleanupSnapshot, error) {
+ snapshot := snapshots[0]
+ snapshots = snapshots[1:]
+ return snapshot, nil
+ }
+ manager.run = func(_ context.Context, _ []string, name string, args ...string) packageUpdateCommandResult {
+ if name != "apt-get" || strings.Join(args, " ") != "clean" {
+ t.Fatalf("unexpected cleanup command: %s %v", name, args)
+ }
+ return packageUpdateCommandResult{}
+ }
+
+ upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
+ resultCh := make(chan agentexec.HostStorageCleanupResultPayload, 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(&registration); 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.HostStorageCleanupPayload{
+ RequestID: "cleanup-1", ActionID: "action-1", Operation: agentexec.HostStorageCleanupOperationPackageCache, ExpectedFingerprint: before.Fingerprint, Timeout: 5,
+ })
+ if err := conn.WriteJSON(wsMessage{Type: msgTypeHostStorageCleanup, ID: "cleanup-1", Timestamp: time.Now(), Payload: payload}); err != nil {
+ t.Errorf("write host storage cleanup: %v", err)
+ return
+ }
+ var response wsMessage
+ if err := conn.ReadJSON(&response); err != nil {
+ t.Errorf("read host storage cleanup result: %v", err)
+ return
+ }
+ if response.Type != msgTypeHostStorageCleanupResult {
+ t.Errorf("response type = %q", response.Type)
+ return
+ }
+ var result agentexec.HostStorageCleanupResultPayload
+ 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", storageCleanup: 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.HostStorageCleanupVerificationVerified || result.ReclaimedBytes != 500 {
+ t.Fatalf("result = %#v", result)
+ }
+ cancel()
+ case <-time.After(10 * time.Second):
+ cancel()
+ t.Fatal("timed out waiting for typed host storage cleanup result")
+ }
+ select {
+ case <-errCh:
+ case <-time.After(5 * time.Second):
+ t.Fatal("command client did not stop")
+ }
+}
diff --git a/internal/hostagent/storage_cleanup.go b/internal/hostagent/storage_cleanup.go
new file mode 100644
index 0000000000..52faf2d5fa
--- /dev/null
+++ b/internal/hostagent/storage_cleanup.go
@@ -0,0 +1,211 @@
+package hostagent
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+)
+
+const (
+ storageCleanupCacheTTL = 30 * time.Minute
+ storageCleanupMaxCacheEntries = 100000
+ aptPackageCachePath = "/var/cache/apt/archives"
+)
+
+type storageCleanupManager struct {
+ platform string
+ now func() time.Time
+ cacheTTL time.Duration
+ run func(context.Context, []string, string, ...string) packageUpdateCommandResult
+ lookPath func(string) (string, error)
+ scan func() (agentexec.HostStorageCleanupSnapshot, error)
+
+ mu sync.Mutex
+ cached *agentexec.HostStorageCleanupSnapshot
+}
+
+func newStorageCleanupManager(platform string) *storageCleanupManager {
+ return &storageCleanupManager{
+ platform: strings.ToLower(strings.TrimSpace(platform)),
+ now: time.Now,
+ cacheTTL: storageCleanupCacheTTL,
+ run: runPackageUpdateCommand,
+ lookPath: packageUpdateLookPath,
+ scan: scanAPTPackageCache,
+ }
+}
+
+func (m *storageCleanupManager) Snapshot(force bool) agentexec.HostStorageCleanupSnapshot {
+ if m == nil {
+ return agentexec.HostStorageCleanupSnapshot{}
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.snapshotLocked(force)
+}
+
+func (m *storageCleanupManager) snapshotLocked(force bool) agentexec.HostStorageCleanupSnapshot {
+ now := m.currentTime()
+ if !force && m.cached != nil && now.Sub(m.cached.CheckedAt) < m.cacheTTL {
+ return *m.cached
+ }
+
+ snapshot := agentexec.HostStorageCleanupSnapshot{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.Provider = "apt-package-cache"
+ scanned, err := m.scan()
+ if err != nil {
+ snapshot.Error = "package cache inspection failed"
+ m.storeSnapshot(snapshot)
+ return snapshot
+ }
+ snapshot.Fingerprint = scanned.Fingerprint
+ snapshot.ReclaimableBytes = scanned.ReclaimableBytes
+ m.storeSnapshot(snapshot)
+ return snapshot
+}
+
+func (m *storageCleanupManager) Apply(ctx context.Context, req agentexec.HostStorageCleanupPayload) (result agentexec.HostStorageCleanupResultPayload) {
+ startedAt := time.Now()
+ result = agentexec.HostStorageCleanupResultPayload{
+ RequestID: strings.TrimSpace(req.RequestID),
+ Verification: agentexec.HostStorageCleanupVerificationInconclusive,
+ }
+ defer func() { result.Duration = time.Since(startedAt).Milliseconds() }()
+
+ if strings.TrimSpace(req.Operation) != agentexec.HostStorageCleanupOperationPackageCache {
+ result.Error = "unsupported typed host storage cleanup operation"
+ return result
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ before := m.snapshotLocked(true)
+ result.Before = before
+ if !before.Supported {
+ result.After = before
+ result.Error = "host package-cache cleanup is not supported by this agent"
+ return result
+ }
+ if before.Error != "" {
+ result.After = before
+ result.Error = "package cache cleanup preflight failed"
+ return result
+ }
+ if before.Fingerprint != strings.TrimSpace(req.ExpectedFingerprint) {
+ result.After = before
+ result.Error = "package cache inventory changed; replan required"
+ return result
+ }
+ if before.ReclaimableBytes <= 0 {
+ result.After = before
+ result.Error = "package cache is already empty; replan required"
+ return result
+ }
+
+ clean := m.run(ctx, []string{"DEBIAN_FRONTEND=noninteractive"}, "apt-get", "clean")
+ if clean.err != nil || clean.exitCode != 0 {
+ result.After = m.snapshotLocked(true)
+ result.Verification = agentexec.HostStorageCleanupVerificationFailed
+ result.Error = "package cache cleanup failed"
+ return result
+ }
+
+ result.Success = true
+ after := m.snapshotLocked(true)
+ result.After = after
+ if after.Error != "" {
+ result.Error = "package cache cleanup completed but verification was inconclusive"
+ return result
+ }
+ if before.ReclaimableBytes > after.ReclaimableBytes {
+ result.ReclaimedBytes = before.ReclaimableBytes - after.ReclaimableBytes
+ }
+ if result.ReclaimedBytes <= 0 {
+ result.Verification = agentexec.HostStorageCleanupVerificationFailed
+ result.Error = "package cache cleanup completed but no space was reclaimed"
+ return result
+ }
+ result.Verification = agentexec.HostStorageCleanupVerificationVerified
+ return result
+}
+
+func scanAPTPackageCache() (agentexec.HostStorageCleanupSnapshot, error) {
+ return scanAPTPackageCacheAt(aptPackageCachePath)
+}
+
+func scanAPTPackageCacheAt(cachePath string) (agentexec.HostStorageCleanupSnapshot, error) {
+ hasher := sha256.New()
+ entries := 0
+ var total int64
+ err := filepath.WalkDir(cachePath, func(path string, entry fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ if os.IsNotExist(walkErr) {
+ return nil
+ }
+ return walkErr
+ }
+ if entry.IsDir() || !strings.HasSuffix(strings.ToLower(entry.Name()), ".deb") {
+ return nil
+ }
+ info, err := entry.Info()
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() || info.Size() < 0 {
+ return nil
+ }
+ entries++
+ if entries > storageCleanupMaxCacheEntries {
+ return fmt.Errorf("package cache entry count exceeds bounded limit")
+ }
+ if info.Size() > agentexec.HostStorageCleanupMaxReportedBytes-total {
+ return fmt.Errorf("package cache exceeds bounded size")
+ }
+ rel, err := filepath.Rel(cachePath, path)
+ if err != nil {
+ return err
+ }
+ total += info.Size()
+ _, _ = fmt.Fprintf(hasher, "%s\x00%d\x00%d\n", filepath.ToSlash(rel), info.Size(), info.ModTime().UnixNano())
+ return nil
+ })
+ if err != nil && !os.IsNotExist(err) {
+ return agentexec.HostStorageCleanupSnapshot{}, err
+ }
+ return agentexec.HostStorageCleanupSnapshot{
+ Fingerprint: "sha256:" + hex.EncodeToString(hasher.Sum(nil)),
+ ReclaimableBytes: total,
+ }, nil
+}
+
+func (m *storageCleanupManager) currentTime() time.Time {
+ if m != nil && m.now != nil {
+ return m.now().UTC()
+ }
+ return time.Now().UTC()
+}
+
+func (m *storageCleanupManager) storeSnapshot(snapshot agentexec.HostStorageCleanupSnapshot) {
+ copy := snapshot
+ m.cached = &copy
+}
diff --git a/internal/hostagent/storage_cleanup_test.go b/internal/hostagent/storage_cleanup_test.go
new file mode 100644
index 0000000000..72433ccee8
--- /dev/null
+++ b/internal/hostagent/storage_cleanup_test.go
@@ -0,0 +1,102 @@
+package hostagent
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+)
+
+func TestScanAPTPackageCacheCountsOnlyRegularDebArchives(t *testing.T) {
+ dir := t.TempDir()
+ partial := filepath.Join(dir, "partial")
+ if err := os.MkdirAll(partial, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "one.deb"), []byte("12345"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(partial, "two.DEB"), []byte("1234567"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "lock"), []byte("not reclaimable"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(filepath.Join(dir, "one.deb"), filepath.Join(dir, "alias.deb")); err != nil {
+ t.Fatal(err)
+ }
+
+ snapshot, err := scanAPTPackageCacheAt(dir)
+ if err != nil {
+ t.Fatalf("scan cache: %v", err)
+ }
+ if snapshot.ReclaimableBytes != 12 {
+ t.Fatalf("reclaimable bytes = %d, want 12", snapshot.ReclaimableBytes)
+ }
+ if !strings.HasPrefix(snapshot.Fingerprint, "sha256:") || len(snapshot.Fingerprint) != 71 {
+ t.Fatalf("unexpected fingerprint %q", snapshot.Fingerprint)
+ }
+ again, err := scanAPTPackageCacheAt(dir)
+ if err != nil || again.Fingerprint != snapshot.Fingerprint {
+ t.Fatalf("cache fingerprint is not deterministic: first=%q second=%q err=%v", snapshot.Fingerprint, again.Fingerprint, err)
+ }
+}
+
+func TestStorageCleanupManagerApplyUsesClosedAPTCatalogAndVerifiesBytes(t *testing.T) {
+ before := agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("a", 64), ReclaimableBytes: 400, CheckedAt: time.Now().UTC()}
+ after := agentexec.HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 40, CheckedAt: time.Now().UTC()}
+ snapshots := []agentexec.HostStorageCleanupSnapshot{before, after}
+ var calls [][]string
+ manager := newStorageCleanupManager("linux")
+ manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
+ manager.scan = func() (agentexec.HostStorageCleanupSnapshot, error) {
+ snapshot := snapshots[0]
+ snapshots = snapshots[1:]
+ return snapshot, nil
+ }
+ manager.run = func(_ context.Context, env []string, name string, args ...string) packageUpdateCommandResult {
+ calls = append(calls, append([]string{name}, args...))
+ if !reflect.DeepEqual(env, []string{"DEBIAN_FRONTEND=noninteractive"}) {
+ t.Fatalf("unexpected environment: %#v", env)
+ }
+ return packageUpdateCommandResult{}
+ }
+
+ result := manager.Apply(context.Background(), agentexec.HostStorageCleanupPayload{
+ RequestID: "cleanup-1",
+ Operation: agentexec.HostStorageCleanupOperationPackageCache,
+ ExpectedFingerprint: before.Fingerprint,
+ })
+ if !result.Success || result.Verification != agentexec.HostStorageCleanupVerificationVerified || result.ReclaimedBytes != 360 {
+ t.Fatalf("unexpected result: %#v", result)
+ }
+ if !reflect.DeepEqual(calls, [][]string{{"apt-get", "clean"}}) {
+ t.Fatalf("unexpected command catalog: %#v", calls)
+ }
+}
+
+func TestStorageCleanupManagerRefusesFingerprintDriftBeforeMutation(t *testing.T) {
+ manager := newStorageCleanupManager("linux")
+ manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }
+ manager.scan = func() (agentexec.HostStorageCleanupSnapshot, error) {
+ return agentexec.HostStorageCleanupSnapshot{Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 400}, nil
+ }
+ manager.run = func(context.Context, []string, string, ...string) packageUpdateCommandResult {
+ t.Fatal("cleanup command must not run after fingerprint drift")
+ return packageUpdateCommandResult{}
+ }
+
+ result := manager.Apply(context.Background(), agentexec.HostStorageCleanupPayload{
+ RequestID: "cleanup-drift",
+ Operation: agentexec.HostStorageCleanupOperationPackageCache,
+ ExpectedFingerprint: "sha256:" + strings.Repeat("a", 64),
+ })
+ if result.Success || result.Verification != agentexec.HostStorageCleanupVerificationInconclusive || !strings.Contains(result.Error, "replan") {
+ t.Fatalf("unexpected drift result: %#v", result)
+ }
+}
diff --git a/internal/models/converters.go b/internal/models/converters.go
index 5723aebafe..b77074cb61 100644
--- a/internal/models/converters.go
+++ b/internal/models/converters.go
@@ -512,6 +512,7 @@ func (h Host) ToFrontend() HostFrontend {
AgentUpdate: cloneAgentUpdateStatus(h.AgentUpdate),
AgentModules: cloneAgentModuleStatuses(h.AgentModules),
PackageUpdates: cloneHostPackageUpdateStatus(h.PackageUpdates),
+ StorageCleanup: cloneHostStorageCleanupStatus(h.StorageCleanup),
IsLegacy: h.IsLegacy,
LinkedNodeID: h.LinkedNodeID,
}
diff --git a/internal/models/deepcopy.go b/internal/models/deepcopy.go
index c0de0ec0c4..abcd236af8 100644
--- a/internal/models/deepcopy.go
+++ b/internal/models/deepcopy.go
@@ -357,6 +357,14 @@ func cloneHostPackageUpdateStatus(src *HostPackageUpdateStatus) *HostPackageUpda
return &dest
}
+func cloneHostStorageCleanupStatus(src *HostStorageCleanupStatus) *HostStorageCleanupStatus {
+ if src == nil {
+ return nil
+ }
+ dest := *src
+ return &dest
+}
+
func cloneHost(src Host) Host {
dest := src
dest.LoadAverage = append([]float64(nil), src.LoadAverage...)
@@ -368,6 +376,7 @@ func cloneHost(src Host) Host {
dest.Unraid = cloneHostUnraidStorage(src.Unraid)
dest.Ceph = cloneHostCephCluster(src.Ceph)
dest.PackageUpdates = cloneHostPackageUpdateStatus(src.PackageUpdates)
+ dest.StorageCleanup = cloneHostStorageCleanupStatus(src.StorageCleanup)
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.go
index 2f86ef0ebb..d2f1977b7f 100644
--- a/internal/models/deepcopy_test.go
+++ b/internal/models/deepcopy_test.go
@@ -302,6 +302,7 @@ func TestCloneHost_MapIsolation(t *testing.T) {
Supported: true,
Packages: []HostPackageUpdate{{Name: "openssl"}},
},
+ StorageCleanup: &HostStorageCleanupStatus{Provider: "apt-package-cache", ReclaimableBytes: 512},
}
dst := cloneHost(src)
dst.Tags = append(dst.Tags, "new:val")
@@ -309,6 +310,7 @@ func TestCloneHost_MapIsolation(t *testing.T) {
dst.Sensors.ThermalState.LimitsPercent["cpu_speed_limit"] = 80
*dst.Sensors.ThermalState.ThermalWarningLevel = 1
dst.PackageUpdates.Packages[0].Name = "mutated"
+ dst.StorageCleanup.Provider = "mutated"
if len(src.Tags) != 1 {
t.Error("clone tags should be independent")
}
@@ -324,6 +326,9 @@ func TestCloneHost_MapIsolation(t *testing.T) {
if src.PackageUpdates.Packages[0].Name != "openssl" {
t.Error("clone package update inventory should be independent")
}
+ if src.StorageCleanup.Provider != "apt-package-cache" {
+ t.Error("clone storage cleanup posture should be independent")
+ }
}
func TestCloneHosts_Nil(t *testing.T) {
diff --git a/internal/models/models.go b/internal/models/models.go
index 628b9522cb..9b1f740c78 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -247,44 +247,45 @@ 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"`
- PackageUpdates *HostPackageUpdateStatus `json:"packageUpdates,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"`
+ StorageCleanup *HostStorageCleanupStatus `json:"storageCleanup,omitempty"`
+ IsLegacy bool `json:"isLegacy,omitempty"`
// Computed I/O rates (bytes/sec), populated from cumulative counters by rate tracker
NetInRate float64 `json:"netInRate,omitempty"`
@@ -317,6 +318,15 @@ type HostPackageUpdate struct {
AvailableVersion string `json:"availableVersion,omitempty"`
}
+type HostStorageCleanupStatus struct {
+ Supported bool `json:"supported"`
+ Provider string `json:"provider,omitempty"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+ ReclaimableBytes int64 `json:"reclaimableBytes"`
+ CheckedAt time.Time `json:"checkedAt,omitempty"`
+ Error string `json:"error,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.go
index ae17321310..d8517e9feb 100644
--- a/internal/models/models_frontend.go
+++ b/internal/models/models_frontend.go
@@ -725,6 +725,7 @@ type HostFrontend struct {
AgentUpdate *AgentUpdateStatus `json:"agentUpdate,omitempty"`
AgentModules []AgentModuleStatus `json:"agentModules,omitempty"`
PackageUpdates *HostPackageUpdateStatus `json:"packageUpdates,omitempty"`
+ StorageCleanup *HostStorageCleanupStatus `json:"storageCleanup,omitempty"`
IsLegacy bool `json:"isLegacy,omitempty"` // True if using legacy agent protocol
LinkedNodeID 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.go
index 7a70a140af..114d0de0dd 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -1997,6 +1997,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
AgentUpdate: agentUpdate,
AgentModules: convertAgentModuleStatuses(report.Agent.Modules),
PackageUpdates: convertHostPackageUpdateStatus(report.Host.PackageUpdates, observedAt),
+ StorageCleanup: convertHostStorageCleanupStatus(report.Host.StorageCleanup, observedAt),
IsLegacy: isLegacyAgent(report.Agent.Type),
}
@@ -2235,6 +2236,20 @@ func convertHostPackageUpdateStatus(status *agentshost.PackageUpdateStatus, obse
}
}
+func convertHostStorageCleanupStatus(status *agentshost.StorageCleanupStatus, observedAt time.Time) *models.HostStorageCleanupStatus {
+ if status == nil {
+ return nil
+ }
+ return &models.HostStorageCleanupStatus{
+ Supported: status.Supported,
+ Provider: strings.TrimSpace(status.Provider),
+ Fingerprint: strings.TrimSpace(status.Fingerprint),
+ ReclaimableBytes: status.ReclaimableBytes,
+ CheckedAt: observedAt.UTC(),
+ Error: strings.TrimSpace(status.Error),
+ }
+}
+
func convertAgentConfigFingerprint(value *agentshost.ConfigFingerprint) *models.AgentConfigFingerprint {
if value == nil {
return nil
diff --git a/internal/monitoring/monitor_package_updates_test.go b/internal/monitoring/monitor_package_updates_test.go
index d8b8143218..1d39c6b91e 100644
--- a/internal/monitoring/monitor_package_updates_test.go
+++ b/internal/monitoring/monitor_package_updates_test.go
@@ -26,3 +26,14 @@ func TestConvertHostPackageUpdateStatusPreservesTypedInventoryWithoutAliasing(t
t.Fatalf("converted package state aliases report input: %#v", got.Packages)
}
}
+
+func TestConvertHostStorageCleanupStatusUsesServerReceiptFreshness(t *testing.T) {
+ now := time.Now().UTC()
+ input := &agentshost.StorageCleanupStatus{
+ Supported: true, Provider: " apt-package-cache ", Fingerprint: " sha256:" + strings.Repeat("b", 64) + " ", ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now.Add(48 * time.Hour), Error: " ",
+ }
+ got := convertHostStorageCleanupStatus(input, now)
+ if got == nil || !got.Supported || got.Provider != "apt-package-cache" || got.Fingerprint != "sha256:"+strings.Repeat("b", 64) || got.ReclaimableBytes != 512*1024*1024 || !got.CheckedAt.Equal(now) || got.Error != "" {
+ t.Fatalf("status = %#v", got)
+ }
+}
diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.go
index 1e7e1cb3c9..4f0ec64306 100644
--- a/internal/unifiedresources/adapters.go
+++ b/internal/unifiedresources/adapters.go
@@ -185,6 +185,16 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {
Error: host.PackageUpdates.Error,
}
}
+ if host.StorageCleanup != nil {
+ agent.StorageCleanup = &AgentStorageCleanupMeta{
+ Supported: host.StorageCleanup.Supported,
+ Provider: host.StorageCleanup.Provider,
+ Fingerprint: host.StorageCleanup.Fingerprint,
+ ReclaimableBytes: host.StorageCleanup.ReclaimableBytes,
+ CheckedAt: host.StorageCleanup.CheckedAt,
+ Error: host.StorageCleanup.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
@@ -487,7 +497,7 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {
Temperature: agent.Temperature,
Agent: agent,
Tags: host.Tags,
- Capabilities: hostPackageUpdateCapabilities(host),
+ Capabilities: hostActionCapabilities(host),
}
return resource, identity
@@ -495,6 +505,16 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {
const hostPackageUpdateHandler = "host.package_updates"
+const hostStorageCleanupHandler = "host.storage_cleanup"
+
+func hostActionCapabilities(host models.Host) []ResourceCapability {
+ capabilities := hostPackageUpdateCapabilities(host)
+ if capability, ok := hostStorageCleanupCapability(host); ok {
+ capabilities = append(capabilities, capability)
+ }
+ return capabilities
+}
+
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 {
@@ -511,6 +531,25 @@ func hostPackageUpdateCapabilities(host models.Host) []ResourceCapability {
}}
}
+func hostStorageCleanupCapability(host models.Host) (ResourceCapability, bool) {
+ status := host.StorageCleanup
+ if !host.CommandsEnabled || status == nil || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" || strings.TrimSpace(status.Fingerprint) == "" || status.ReclaimableBytes < HostStorageCleanupMinReclaimableBytes || strings.TrimSpace(status.Error) != "" || status.CheckedAt.IsZero() || time.Since(status.CheckedAt.UTC()) > HostStorageCleanupFreshness {
+ return ResourceCapability{}, false
+ }
+ if _, ok := HostStorageCleanupPressureDisk(convertDisks(host.Disks)); !ok {
+ return ResourceCapability{}, false
+ }
+ return ResourceCapability{
+ Name: "clean_package_cache",
+ Type: CapabilityTypeCommon,
+ Description: "Reclaim the agent-managed APT package cache without selecting paths, removing installed packages, or rebooting the host.",
+ MinimumApprovalLevel: ApprovalAdmin,
+ AutoAuthorization: AutoAuthorizeLowRisk,
+ Platform: "linux",
+ InternalHandler: hostStorageCleanupHandler,
+ }, true
+}
+
func hostThermalStateToMeta(in *models.HostThermalState) *HostThermalState {
if in == nil {
return nil
diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.go
index b168675c86..179ea51d77 100644
--- a/internal/unifiedresources/adapters_test.go
+++ b/internal/unifiedresources/adapters_test.go
@@ -120,6 +120,70 @@ func TestResourceFromHostDoesNotAdvertiseUnsupportedOrCommandDisabledPackageUpda
}
}
+func TestResourceFromHostAdvertisesPressureBoundPackageCacheCleanup(t *testing.T) {
+ now := time.Now().UTC()
+ host := models.Host{
+ ID: "agent-cleanup", Hostname: "host-cleanup", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true,
+ Disks: []models.Disk{{Mountpoint: "/", Usage: 95}},
+ StorageCleanup: &models.HostStorageCleanupStatus{
+ Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("c", 64), ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now,
+ },
+ }
+
+ resource, _ := resourceFromHost(host)
+ if resource.Agent == nil || resource.Agent.StorageCleanup == nil || resource.Agent.StorageCleanup.ReclaimableBytes != 512*1024*1024 {
+ t.Fatalf("storage cleanup projection = %#v", resource.Agent)
+ }
+ if len(resource.Capabilities) != 1 {
+ t.Fatalf("capabilities = %#v", resource.Capabilities)
+ }
+ capability := resource.Capabilities[0]
+ if capability.Name != "clean_package_cache" || capability.MinimumApprovalLevel != ApprovalAdmin || capability.AutoAuthorization != AutoAuthorizeLowRisk || capability.InternalHandler != "host.storage_cleanup" {
+ t.Fatalf("capability = %#v", capability)
+ }
+ if len(capability.Params) != 0 {
+ t.Fatalf("storage cleanup capability must not accept paths or selectors: %#v", capability.Params)
+ }
+}
+
+func TestResourceFromHostStorageCleanupUsesActualCacheFilesystemAndFailsClosed(t *testing.T) {
+ now := time.Now().UTC()
+ base := models.Host{
+ ID: "agent-cleanup", Hostname: "host-cleanup", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true,
+ Disks: []models.Disk{{Mountpoint: "/", Usage: 95}},
+ StorageCleanup: &models.HostStorageCleanupStatus{
+ Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("c", 64), ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now,
+ },
+ }
+ mutations := []func(*models.Host){
+ func(host *models.Host) { host.CommandsEnabled = false },
+ func(host *models.Host) { host.StorageCleanup.Supported = false },
+ func(host *models.Host) { host.StorageCleanup.Provider = "arbitrary-path" },
+ func(host *models.Host) { host.StorageCleanup.Fingerprint = "" },
+ func(host *models.Host) {
+ host.StorageCleanup.ReclaimableBytes = HostStorageCleanupMinReclaimableBytes - 1
+ },
+ func(host *models.Host) {
+ host.StorageCleanup.CheckedAt = now.Add(-HostStorageCleanupFreshness - time.Minute)
+ },
+ func(host *models.Host) { host.StorageCleanup.Error = "inspection failed" },
+ func(host *models.Host) { host.Disks[0].Usage = HostStoragePressureThreshold - 1 },
+ func(host *models.Host) { host.Disks = append(host.Disks, models.Disk{Mountpoint: "/var", Usage: 50}) },
+ func(host *models.Host) { host.StorageCleanup = nil },
+ }
+ for i, mutate := range mutations {
+ host := base
+ host.Disks = append([]models.Disk(nil), base.Disks...)
+ status := *base.StorageCleanup
+ host.StorageCleanup = &status
+ mutate(&host)
+ resource, _ := resourceFromHost(host)
+ if len(resource.Capabilities) != 0 {
+ t.Fatalf("case %d advertised capabilities %#v", i, resource.Capabilities)
+ }
+ }
+}
+
func TestResourceFromDockerContainerAdvertisesLifecycleCapabilities(t *testing.T) {
now := time.Now().UTC()
host := models.DockerHost{
diff --git a/internal/unifiedresources/clone.go b/internal/unifiedresources/clone.go
index 5511b88a64..18ae3834af 100644
--- a/internal/unifiedresources/clone.go
+++ b/internal/unifiedresources/clone.go
@@ -197,10 +197,29 @@ func cloneAgentData(in *AgentData) *AgentData {
out.DiskIO = cloneHostDiskIOMetaSlice(in.DiskIO)
out.Ceph = cloneHostCephMeta(in.Ceph)
out.StorageRisk = cloneStorageRisk(in.StorageRisk)
+ out.PackageUpdates = cloneAgentPackageUpdateMeta(in.PackageUpdates)
+ out.StorageCleanup = cloneAgentStorageCleanupMeta(in.StorageCleanup)
out.DiskExclude = cloneStringSlice(in.DiskExclude)
return &out
}
+func cloneAgentPackageUpdateMeta(in *AgentPackageUpdateMeta) *AgentPackageUpdateMeta {
+ if in == nil {
+ return nil
+ }
+ out := *in
+ out.Packages = append([]AgentPackageUpdate(nil), in.Packages...)
+ return &out
+}
+
+func cloneAgentStorageCleanupMeta(in *AgentStorageCleanupMeta) *AgentStorageCleanupMeta {
+ if in == nil {
+ return nil
+ }
+ out := *in
+ return &out
+}
+
func cloneDockerData(in *DockerData) *DockerData {
if in == nil {
return nil
diff --git a/internal/unifiedresources/clone_test.go b/internal/unifiedresources/clone_test.go
index 72c9bf97b7..ccd255458a 100644
--- a/internal/unifiedresources/clone_test.go
+++ b/internal/unifiedresources/clone_test.go
@@ -438,6 +438,8 @@ func TestCloneAgentData_DeepIsolation(t *testing.T) {
RAID: []HostRAIDMeta{
{Device: "/dev/md0", Level: "raid1", Risk: &StorageRisk{Level: storagehealth.RiskHealthy}},
},
+ PackageUpdates: &AgentPackageUpdateMeta{Packages: []AgentPackageUpdate{{Name: "openssl"}}},
+ StorageCleanup: &AgentStorageCleanupMeta{Provider: "apt-package-cache", ReclaimableBytes: 512},
}
cloned := cloneAgentData(original)
@@ -455,6 +457,11 @@ func TestCloneAgentData_DeepIsolation(t *testing.T) {
if original.RAID[0].Risk.Level == storagehealth.RiskCritical {
t.Error("mutating cloned RAID risk should not affect original")
}
+ cloned.PackageUpdates.Packages[0].Name = "mutated"
+ cloned.StorageCleanup.Provider = "mutated"
+ if original.PackageUpdates.Packages[0].Name != "openssl" || original.StorageCleanup.Provider != "apt-package-cache" {
+ t.Fatal("mutating cloned agent maintenance posture should not affect original")
+ }
}
// --- cloneDockerData ---
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 8dfd25ec65..15eafe8b72 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -1496,7 +1496,7 @@ func TestResourceParentBySourceStateRemainsInternal(t *testing.T) {
}
}
-func TestHostPackageUpdatePostureRemainsAgentScoped(t *testing.T) {
+func TestHostMaintenancePostureRemainsAgentScoped(t *testing.T) {
agentType := reflect.TypeOf(AgentData{})
field, ok := agentType.FieldByName("PackageUpdates")
if !ok {
@@ -1508,11 +1508,24 @@ func TestHostPackageUpdatePostureRemainsAgentScoped(t *testing.T) {
if field.Type != reflect.TypeOf((*AgentPackageUpdateMeta)(nil)) {
t.Fatalf("expected typed package-update metadata, got %v", field.Type)
}
+ cleanupField, ok := agentType.FieldByName("StorageCleanup")
+ if !ok {
+ t.Fatal("expected AgentData.StorageCleanup field")
+ }
+ if got := cleanupField.Tag.Get("json"); got != "storageCleanup,omitempty" {
+ t.Fatalf("expected storage-cleanup posture to use the agent-scoped wire key, got %q", got)
+ }
+ if cleanupField.Type != reflect.TypeOf((*AgentStorageCleanupMeta)(nil)) {
+ t.Fatalf("expected typed storage-cleanup metadata, got %v", cleanupField.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")
}
+ if _, ok := resourceType.FieldByName("StorageCleanup"); ok {
+ t.Fatal("storage-cleanup posture must not become an unscoped top-level Resource field")
+ }
}
// TestNoLegacyMigrationHintsInRuntimeCode prevents reintroducing runtime
diff --git a/internal/unifiedresources/host_storage_cleanup.go b/internal/unifiedresources/host_storage_cleanup.go
new file mode 100644
index 0000000000..a02008b317
--- /dev/null
+++ b/internal/unifiedresources/host_storage_cleanup.go
@@ -0,0 +1,42 @@
+package unifiedresources
+
+import "strings"
+
+const hostStorageCleanupTargetPath = "/var/cache/apt/archives"
+
+// HostStorageCleanupTargetDisk resolves the actual filesystem containing the
+// fixed package-cache target. Longest-prefix selection is required when /var
+// is a separate mount; root filesystem pressure must not authorize cleanup on
+// a healthy /var filesystem.
+func HostStorageCleanupTargetDisk(disks []DiskInfo) (DiskInfo, bool) {
+ selectedLength := -1
+ var selected DiskInfo
+ for _, disk := range disks {
+ mountpoint := strings.TrimSpace(disk.Mountpoint)
+ if !hostStorageCleanupMountContainsPath(mountpoint) {
+ continue
+ }
+ if len(mountpoint) > selectedLength {
+ selected = disk
+ selectedLength = len(mountpoint)
+ }
+ }
+ return selected, selectedLength >= 0
+}
+
+func HostStorageCleanupPressureDisk(disks []DiskInfo) (DiskInfo, bool) {
+ disk, ok := HostStorageCleanupTargetDisk(disks)
+ return disk, ok && disk.Usage >= HostStoragePressureThreshold
+}
+
+func hostStorageCleanupMountContainsPath(mountpoint string) bool {
+ mountpoint = strings.TrimSpace(mountpoint)
+ if mountpoint == "" {
+ return false
+ }
+ if mountpoint == "/" {
+ return true
+ }
+ mountpoint = strings.TrimRight(mountpoint, "/")
+ return mountpoint != "" && (hostStorageCleanupTargetPath == mountpoint || strings.HasPrefix(hostStorageCleanupTargetPath, mountpoint+"/"))
+}
diff --git a/internal/unifiedresources/host_storage_cleanup_test.go b/internal/unifiedresources/host_storage_cleanup_test.go
new file mode 100644
index 0000000000..e264a24966
--- /dev/null
+++ b/internal/unifiedresources/host_storage_cleanup_test.go
@@ -0,0 +1,24 @@
+package unifiedresources
+
+import "testing"
+
+func TestHostStorageCleanupTargetDiskUsesLongestContainingMount(t *testing.T) {
+ disks := []DiskInfo{
+ {Mountpoint: "/", Usage: 96},
+ {Mountpoint: "/var", Usage: 55},
+ {Mountpoint: "/var/cache/apt", Usage: 91},
+ {Mountpoint: "/var/cache/apt/archives-other", Usage: 99},
+ }
+ disk, ok := HostStorageCleanupTargetDisk(disks)
+ if !ok || disk.Mountpoint != "/var/cache/apt" {
+ t.Fatalf("target disk = %#v ok=%v", disk, ok)
+ }
+ if _, pressured := HostStorageCleanupPressureDisk(disks); !pressured {
+ t.Fatal("expected actual package-cache filesystem to be under pressure")
+ }
+
+ disks[2].Usage = 89
+ if _, pressured := HostStorageCleanupPressureDisk(disks); pressured {
+ t.Fatal("root or sibling pressure must not authorize cleanup on a healthy package-cache filesystem")
+ }
+}
diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.go
index 46b9a23bb0..7b41510e87 100644
--- a/internal/unifiedresources/types.go
+++ b/internal/unifiedresources/types.go
@@ -774,6 +774,12 @@ type AgentMemoryMeta struct {
const HostPackageUpdateFreshness = 45 * time.Minute
+const (
+ HostStorageCleanupFreshness = 45 * time.Minute
+ HostStoragePressureThreshold = 90.0
+ HostStorageCleanupMinReclaimableBytes = int64(64 * 1024 * 1024)
+)
+
type AgentPackageUpdateMeta struct {
Supported bool `json:"supported"`
Manager string `json:"manager,omitempty"`
@@ -791,6 +797,15 @@ type AgentPackageUpdate struct {
AvailableVersion string `json:"availableVersion,omitempty"`
}
+type AgentStorageCleanupMeta struct {
+ Supported bool `json:"supported"`
+ Provider string `json:"provider,omitempty"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+ ReclaimableBytes int64 `json:"reclaimableBytes"`
+ CheckedAt time.Time `json:"checkedAt,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
// AgentData contains host agent-specific data.
type AgentData struct {
AgentID string `json:"agentId,omitempty"`
@@ -805,48 +820,49 @@ 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"`
- 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"`
+ 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"`
+ StorageCleanup *AgentStorageCleanupMeta `json:"storageCleanup,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.go
index 344a5408ba..04fbcddf36 100644
--- a/pkg/agents/host/report.go
+++ b/pkg/agents/host/report.go
@@ -79,21 +79,22 @@ 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
- PackageUpdates *PackageUpdateStatus `json:"packageUpdates,omitempty"`
+ 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"`
+ StorageCleanup *StorageCleanupStatus `json:"storageCleanup,omitempty"`
}
// PackageUpdateStatus is the agent-authored, read-only package posture for
@@ -118,6 +119,18 @@ type PackageUpdate struct {
AvailableVersion string `json:"availableVersion,omitempty"`
}
+// StorageCleanupStatus is the agent-authored read-only posture for the
+// bounded package-cache cleanup provider. Paths and cache entry names never
+// leave the agent; the fingerprint binds a later typed cleanup request.
+type StorageCleanupStatus struct {
+ Supported bool `json:"supported"`
+ Provider string `json:"provider,omitempty"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+ ReclaimableBytes int64 `json:"reclaimableBytes"`
+ CheckedAt time.Time `json:"checkedAt,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
// Metrics encapsulates primary resource metrics for a host.
type Metrics struct {
CPUUsagePercent float64 `json:"cpuUsagePercent,omitempty"`
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index 47f814813d..a1f730786e 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -224,7 +224,7 @@ class CanonicalCompletionGuardTest(unittest.TestCase):
"docker-collect-runtime",
"docker-swarm-runtime",
"kubernetes-native-agent-runtime",
- "docker-runtime-report-model",
+ "runtime-report-model",
"proxmox-zfs-runtime",
"proxmox-ceph-runtime",
"proxmox-backup-identity-monitoring",
@@ -552,8 +552,10 @@ class CanonicalCompletionGuardTest(unittest.TestCase):
"internal/hostagent/command_client_test.go",
"internal/hostagent/commands_deploy_test.go",
"internal/hostagent/commands_host_update_test.go",
+ "internal/hostagent/commands_storage_cleanup_test.go",
"internal/hostagent/package_updates_test.go",
"internal/hostagent/send_report_test.go",
+ "internal/hostagent/storage_cleanup_test.go",
],
}
],
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 1f447616cf..bb997b38a4 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -4365,8 +4365,10 @@ class SubsystemLookupTest(unittest.TestCase):
"internal/hostagent/command_client_test.go",
"internal/hostagent/commands_deploy_test.go",
"internal/hostagent/commands_host_update_test.go",
+ "internal/hostagent/commands_storage_cleanup_test.go",
"internal/hostagent/package_updates_test.go",
"internal/hostagent/send_report_test.go",
+ "internal/hostagent/storage_cleanup_test.go",
],
)