Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add durable agent operation receipts
rcourtman4aac79dc7214
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 6c412472f7..37b74c913d 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -7981,7 +7981,7 @@},{"id": "action-governance-auditability-post-rc-hardening",- "summary": "Task 07 Phase B1 has landed the core durable delivery/reconnect foundation: transactional action admission plus deterministic attempt/outbox, one-shot pre-send CAS, receipt correlation, explicit expiry, query-only restart reconciliation, and tenant-scoped detail/pending/settled APIs. Phase B2 remains planned after Task 10, which solely owns terminal execution, verification, evidence, compensation, and rollback truth; B2 then owns compensation/verification-attempt recovery plus mobile/relay inbox and push-dedup consumption, with no local workaround for absent core APIs. Task 12 owns the final L1/governance verdict and administrative-exception review. Raw model command, file write, arbitrary pod exec, legacy run_command, /api/ai/run-command, and enterprise command remediation remain retired with no replacement or executable historical authority.",+ "summary": "Task 07 Phase B1 has landed the core durable delivery/reconnect foundation: transactional action admission plus deterministic attempt/outbox, one-shot pre-send CAS, receipt correlation, explicit expiry, query-only restart reconciliation, and tenant-scoped detail/pending/settled APIs. Phase B2 generic agent-operation receipt continuity is implemented locally pending commit gate: keyed SQLite admission/start/terminal transitions, immutable attempt/action/operation/digest/agent binding, strict versioned sanitized terminal envelopes, payload compaction to permanent replay-denial tombstones, exact authenticated query correlation, legacy capability fail-closed gating, and APT update/cleanup adapters over the generic owner. Tombstone metadata is monotonic and not claimed bounded. Task 10 remains sole owner of execution, verification, evidence, compensation, and rollback truth. Claims 16 and 17 remain open until Task 09 resumes, browser/lab evidence passes, and Task 12 certifies. Mobile/relay consumption remains separate with no local workaround for absent core APIs. Raw model command, file write, arbitrary pod exec, legacy run_command, /api/ai/run-command, and enterprise command remediation remain retired with no replacement or executable historical authority.","owner": "project-owner","status": "planned","recorded_at": "2026-04-25",diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex bd02303080..02343b7171 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -4357,7 +4357,7 @@ two-axis result contract. API tokens are ineligible for the human Autopilotacknowledgement even where an owner-bound token remains compatible with anauthenticated action capability.-### Task 09 typed APT transport and shared package-manager authority (partial)+### Task 07 generic durable agent-operation receipts and Task 09 APT adapterHost update and package-cache cleanup use one strict server/agent codec;unknown fields, trailing JSON, malformed identity, and open command, path,@@ -4367,8 +4367,36 @@ inspection, refresh, update, and cleanup paths share one composition-root-injected lease; nil authority fails closed. Metadata refresh is the firstpossible external effect.-This slice contains no APT-specific journal or replay store. Accepted Task 07-has server dispatch attempts and query-only reconciliation but no reusable-agent-side durable typed-operation receipt primitive. Disconnect, restart,-late-receipt, and no-blind-replay proof stay open until that generic crash-safe-contract exists and Task 09 consumes it.+The agent-side authority is the generic SQLite operation-receipt store in+`internal/operationreceipt/`, not an APT-specific journal. Before any typed+mutation, it durably binds the canonical dispatch attempt, action, operation+kind/version, request digest, and authenticated agent identity. Admission and+start are atomic keyed transitions; a process reopen conservatively converts+accepted or started work to `interrupted_unknown`, which is queryable but never+automatically executable. Strict versioned terminal envelopes remain exactly+replayable while recent, then compact to immutable identity-and-digest+replay-denial tombstones. Replayable payload bytes are TTL/byte bounded;+tombstone metadata grows monotonically by design so no prior attempt can become+new authority. Disk exhaustion fails the current admission before mutation and+recovers when storage capacity returns; operator disk monitoring remains+required and total tombstone disk use is not described as bounded.++The server derives operation version and request digest after canonical request+fields are fixed, persists that binding on the action dispatch attempt, and+queries the authenticated agent by the exact binding after callback loss or+restart. `not_found`, interrupted, tombstoned, malformed, late, duplicate,+wrong-agent, and mismatched responses never authorize resend or terminal truth.+Terminal payload kind/version and strict adapter codecs are revalidated on+write, read, query, and reopen. APT update and cleanup are adapters over this+generic owner, persist only bounded sanitized typed results, and still share+the package-manager lease. Raw commands, paths, package selectors, stderr,+secrets, and unbounded output are outside the receipt schema.++Durable receipt protocol support is explicit agent-reported and server-observed+capability metadata. Missing, legacy, or future versions stay connected for+monitoring but advertise no APT mutation capability, emit no actionable APT+finding, and fail dispatch readiness. Product version strings never imply this+authority. The raw protocol integer stays internal to ingest, registry, and+live dispatch checks; customer/frontend resource JSON consumes only derived+capabilities and readiness. Claims 16 and 17 remain open until Task 09 resumes and the required+browser/lab evidence plus Task 12 certification are complete.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 05a47af53d..df6411590e 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -7345,11 +7345,18 @@ receipt and terminal audit/event atomically, eliminating thereceipt-recorded/result-lost crash window without extending Task 10's schema.Legacy executing rows without an attempt remain readable but inert.-This Task 07 Phase B1 contract intentionally stops at transport continuity.-Task 10 remains sole schema owner for execution, verification, evidence, and-compensation truth. Compensation and verification-attempt recovery, plus-mobile and relay inbox/push-dedup consumption, remain Phase B2 work after Task-10; no mobile or relay-local workaround may compensate for a missing core API.+Task 07 Phase B1 owns server transport continuity. Phase B2 now adds the+generic agent-side durable operation-receipt owner, exact server/agent binding,+query-only reconciliation, payload-to-tombstone retention, and explicit agent+receipt-protocol capability gate consumed by the APT adapters. A query+`not_found`, interrupted record, or replay-denial tombstone leaves the action+`executing` with its dispatch `receipt_pending`; it never authorizes executor+or transport resend. Task 10 remains sole schema owner for execution,+verification, evidence, and compensation truth. Compensation and+verification-attempt recovery plus mobile/relay inbox and push-dedup+consumption remain separate work; no mobile or relay-local workaround may+compensate for a missing core API. Claims 16 and 17 remain open pending Task 09+resumption, real browser/lab evidence, and Task 12 certification.### Canonical mutation planediff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 2ae9f5a4cc..d3621a701f 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -483,6 +483,18 @@ operator-safe error. Monitoring stamps freshness from server receipt time andnormalizes that scalar evidence without receiving cache entry names or paths.It does not infer cleanup eligibility, run cache scans server-side, or turnreclaimable bytes into mutation authority.+The authenticated Unified Agent report also carries `OperationReceiptVersion`+as monitoring-owned runtime ingest metadata. Absence, zero, unknown, and future+versions are unsupported; monitoring must never infer support from an agent or+product version string. Each accepted report replaces the prior value, so an+agent replacement or compatible-to-legacy downgrade immediately removes the+receipt-protocol prerequisite for actionable update and cleanup capabilities.+The raw protocol integer stays internal to agent transport, monitoring ingest,+canonical capability construction, and dispatch readiness. Customer-facing+resource and frontend contracts expose only the derived capabilities. A+compatible report is necessary but never sufficient mutation authority: the+agent execution server's live, authenticated connection recheck remains+authoritative immediately before durable action admission and dispatch.HTTP availability probes consume the shared explicitly unverified,parseable-peer-certificate capturediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 1a588043ba..be4dae04bd 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -116,6 +116,15 @@ payload. Raw per-core CPU evidence and normalized capacity CPU must not be usedas backup coverage, restore readiness, storage-health, or recovery-pointsignals.+Unified Agent durable-operation-receipt metadata is likewise an internal+monitoring and agent-lifecycle boundary. The exact current protocol may be a+fail-closed prerequisite when unified resources derive the bounded+`clean_package_cache` APT capability, but the raw version is not a public+resource field and is never storage truth, pressure truth, mutation authority,+verification truth, or recovery evidence. Storage pressure and cleanup posture+remain independently observed inputs, and the live authenticated agent-server+readiness check remains authoritative before any action admission or dispatch.+Per-member cluster endpoint connection-address overrides accepted by`internal/api/config_node_handlers.go` (`clusterEndpointOverrides` on the nodeupdate payload writing `ClusterEndpoints[n].IPOverride`) are monitoringdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex afe8e0a9b3..e455776e7b 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -3059,6 +3059,11 @@ When a correlated response includes the existing `ExecutionResult`, SQLite andMemoryStore commit the receipt, `receipt_recorded` attempt, terminal audit, andlifecycle event atomically. Standalone callbacks without a result remaintransport-only receipts and do not invent terminal truth.+Current typed agent attempts also persist the transport-derived operation kind,+operation version, request digest, and agent identity with that admission.+Pre-B2 rows migrate with empty binding columns and remain readable but inert;+they are never rebound from current resource telemetry or resent. Agent+operation reconciliation requires exact equality with this persisted binding.Queued, claimed, forged, conflicting, duplicate, late, and out-of-order receipthandling is monotonic and tenant-scoped, and the in-memory store mirrors theSQLite crash-boundary behavior.diff --git a/internal/actionlifecycle/server_reconciliation_integration_test.go b/internal/actionlifecycle/server_reconciliation_integration_test.gonew file mode 100644index 0000000000..a7da7f68cb--- /dev/null+++ b/internal/actionlifecycle/server_reconciliation_integration_test.go@@ -0,0 +1,115 @@+package actionlifecycle++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++type serverQueryReconciler struct {+ server *agentexec.Server+ identity operationreceipt.Identity+ executeCalls, reconcileCalls int+}++func (e *serverQueryReconciler) ExecuteAction(context.Context, unified.ActionAuditRecord) (*unified.ExecutionResult, error) {+ e.executeCalls+++ return nil, context.DeadlineExceeded+}+func (e *serverQueryReconciler) BindActionDispatch(_ context.Context, _ unified.ActionAuditRecord, a unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {+ e.identity.AttemptID = a.ID+ e.identity.ActionID = a.ActionID+ return unified.BindActionDispatchAttempt(a, unified.ActionDispatchBinding{OperationKind: e.identity.OperationKind, OperationVersion: e.identity.OperationVersion, RequestDigest: e.identity.RequestDigest, AgentID: e.identity.AgentID})+}+func (e *serverQueryReconciler) ReconcileActionDispatch(ctx context.Context, _ unified.ActionAuditRecord, _ unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {+ e.reconcileCalls+++ result, err := e.server.QueryAgentOperation(ctx, e.identity.AgentID, e.identity)+ if err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ return nil, unified.ActionDispatchReceipt{}, result.Status == operationreceipt.QueryFoundTerminal, nil+}++func TestAuthenticatedServerNotFoundRecoveryStaysQueryOnlyAndReceiptPending(t *testing.T) {+ server := agentexec.NewServer(func(token, agent, host string) bool { return token == "ok" })+ httpServer := httptest.NewServer(http.HandlerFunc(server.HandleWebSocket))+ defer httpServer.Close()+ wsURL := "ws" + strings.TrimPrefix(httpServer.URL, "http")+ headers := http.Header{"Origin": []string{httpServer.URL}}+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, headers)+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Close()+ register, _ := agentexec.NewMessage(agentexec.MsgTypeAgentRegister, "", agentexec.AgentRegisterPayload{AgentID: "agent-1", Hostname: "host", Version: "6", Platform: "linux", Token: "ok", OperationReceiptVersion: operationreceipt.ProtocolVersion})+ if err := conn.WriteJSON(register); err != nil {+ t.Fatal(err)+ }+ var registered agentexec.Message+ if err := conn.ReadJSON(®istered); err != nil {+ t.Fatal(err)+ }+ queryCount := make(chan struct{}, 4)+ go func() {+ for {+ var message agentexec.Message+ if err := conn.ReadJSON(&message); err != nil {+ return+ }+ if message.Type != agentexec.MsgTypeOperationQuery {+ continue+ }+ reply, _ := agentexec.NewMessage(agentexec.MsgTypeOperationQueryResult, message.ID, operationreceipt.QueryResult{Version: operationreceipt.ProtocolVersion, Status: operationreceipt.QueryNotFound})+ if err := conn.WriteJSON(reply); err != nil {+ return+ }+ queryCount <- struct{}{}+ }+ }()+ digest, _ := operationreceipt.DigestCanonicalJSON(map[string]string{"intent": "fake typed mutation"})+ executor := &serverQueryReconciler{server: server, identity: operationreceipt.Identity{OperationKind: "fake.typed", OperationVersion: 1, RequestDigest: digest, AgentID: "agent-1"}}+ store := unified.NewMemoryStore()+ now := time.Now().UTC()+ service := serviceForStore(t, store, testResource(now, unified.ApprovalNone), executor)+ plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))+ if err != nil {+ t.Fatal(err)+ }+ if _, err := service.Execute(context.Background(), "default", plan.ActionID, testActionActor("operator", "default"), "initial"); err == nil {+ t.Fatal("expected unresolved initial transport")+ }+ baseline := executor.executeCalls+ for n := 0; n < 2; n++ {+ records, err := service.RecoverExecutingActions(context.Background(), "default", "system:recovery", 10)+ if err != nil || len(records) != 1 || records[0].State != unified.ActionStateExecuting {+ t.Fatalf("pass=%d records=%#v err=%v", n, records, err)+ }+ select {+ case <-queryCount:+ case <-time.After(2 * time.Second):+ t.Fatal("authenticated query not observed")+ }+ }+ if executor.executeCalls != baseline || executor.reconcileCalls != 2 {+ t.Fatalf("execute=%d baseline=%d reconcile=%d", executor.executeCalls, baseline, executor.reconcileCalls)+ }+ attempt, found, err := store.GetActionDispatchAttempt(plan.ActionID)+ if err != nil || !found || attempt.State != unified.ActionDispatchReceiptPending {+ t.Fatalf("attempt=%#v found=%v err=%v", attempt, found, err)+ }+ if _, found, err := store.GetActionDispatchReceipt(attempt.ID); err != nil || found {+ t.Fatalf("receipt found=%v err=%v", found, err)+ }+ audit, found, err := store.GetActionAudit(plan.ActionID)+ if err != nil || !found || audit.State != unified.ActionStateExecuting || audit.Result != nil {+ t.Fatalf("audit=%#v found=%v err=%v", audit, found, err)+ }+}diff --git a/internal/actionlifecycle/service.go b/internal/actionlifecycle/service.goindex e36155a2d4..73b3445d65 100644--- a/internal/actionlifecycle/service.go+++ b/internal/actionlifecycle/service.go@@ -34,6 +34,10 @@ type DispatchReconciler interface {ReconcileActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (result *unified.ExecutionResult, receipt unified.ActionDispatchReceipt, found bool, err error)}+type DispatchBinder interface {+ BindActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error)+}+// AvailabilityChecker lets an executor contribute live readiness checks// before Pulse advertises or persists an executable action plan.type AvailabilityChecker interface {@@ -920,6 +924,12 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID string, actor uniif err != nil {return unified.ActionAuditRecord{}, err}+ if binder, ok := s.Executor.(DispatchBinder); ok {+ attempt, err = binder.BindActionDispatch(ctx, started, attempt)+ if err != nil {+ return unified.ActionAuditRecord{}, err+ }+ }if err := store.RecordActionExecutionAdmission(started, startEvent, attempt); err != nil {if errors.Is(err, unified.ErrActionAlreadyExecuting) || errors.Is(err, unified.ErrActionExecutionFinal) {current, found, queryErr := store.GetActionAudit(actionID)@@ -1032,6 +1042,12 @@ func (s *Service) beginPolicyExecution(ctx context.Context, orgID, actionID, actif err != nil {return unified.ActionAuditRecord{}, store, false, err}+ if binder, ok := s.Executor.(DispatchBinder); ok {+ attempt, err = binder.BindActionDispatch(ctx, started, attempt)+ if err != nil {+ return unified.ActionAuditRecord{}, store, false, err+ }+ }if err := store.RecordActionPolicyExecutionAdmission(started, approvedEvent, startEvent, attempt); err != nil {if errors.Is(err, unified.ErrActionAlreadyExecuting) || errors.Is(err, unified.ErrActionExecutionFinal) {current, ok, queryErr := store.GetActionAudit(actionID)@@ -1110,6 +1126,9 @@ func (s *Service) dispatchCommitted(ctx context.Context, orgID string, store Sto}func (s *Service) reconcileCommitted(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt, actor string) (unified.ActionAuditRecord, error) {+ if _, bindingOwned := s.Executor.(DispatchBinder); bindingOwned && !attempt.HasOperationBinding() {+ return record, nil+ }reconciler, ok := s.Executor.(DispatchReconciler)if !ok {return record, nildiff --git a/internal/actionlifecycle/service_test.go b/internal/actionlifecycle/service_test.goindex 1131af6435..7e3a30bd7a 100644--- a/internal/actionlifecycle/service_test.go+++ b/internal/actionlifecycle/service_test.go@@ -428,6 +428,45 @@ func TestSQLiteRestartRecoveryReconcilesReceiptPendingWithoutResend(t *testing.T}}+func TestSQLiteRestartRecoveryNotFoundRemainsReceiptPendingWithoutResend(t *testing.T) {+ dir := t.TempDir()+ now := time.Now().UTC()+ store, err := unified.NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ executor := &reconcilingExecutor{executeErr: context.DeadlineExceeded, found: false}+ service := serviceForStore(t, store, testResource(now, unified.ApprovalNone), executor)+ plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))+ if err != nil {+ t.Fatal(err)+ }+ if _, err := service.Execute(context.Background(), "default", plan.ActionID, testActionActor("operator", "default"), "initial"); !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("execute err=%v", err)+ }+ for n := 0; n < 2; n++ {+ recovered, err := service.RecoverExecutingActions(context.Background(), "default", "system:restart-recovery", 100)+ if err != nil || len(recovered) != 1 || recovered[0].State != unified.ActionStateExecuting {+ t.Fatalf("pass=%d recovered=%#v err=%v", n, recovered, err)+ }+ }+ attempt, found, err := store.GetActionDispatchAttempt(plan.ActionID)+ if err != nil || !found || attempt.State != unified.ActionDispatchReceiptPending {+ t.Fatalf("attempt=%#v found=%v err=%v", attempt, found, err)+ }+ if _, found, err := store.GetActionDispatchReceipt(attempt.ID); err != nil || found {+ t.Fatalf("receipt found=%v err=%v", found, err)+ }+ audit, found, err := store.GetActionAudit(plan.ActionID)+ if err != nil || !found || audit.State != unified.ActionStateExecuting || audit.Result != nil {+ t.Fatalf("audit=%#v found=%v err=%v", audit, found, err)+ }+ if executor.executeCalls != 1 || executor.reconcileCalls != 2 {+ t.Fatalf("execute=%d reconcile=%d", executor.executeCalls, executor.reconcileCalls)+ }+}+func TestActionDetailAndInboxMaterializeExplicitExpiry(t *testing.T) {now := time.Date(2026, 7, 11, 14, 0, 0, 0, time.UTC)store := unified.NewMemoryStore()@@ -783,6 +822,11 @@ type reconcilingExecutor struct {found boolresult *unified.ExecutionResult}+type bindingReconcilingExecutor struct{ reconcilingExecutor }++func (e *bindingReconcilingExecutor) BindActionDispatch(_ context.Context, _ unified.ActionAuditRecord, a unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {+ return a, nil+}func (e *reconcilingExecutor) ExecuteAction(_ context.Context, _ unified.ActionAuditRecord) (*unified.ExecutionResult, error) {e.executeCalls++@@ -799,6 +843,46 @@ func (e *reconcilingExecutor) ReconcileActionDispatch(_ context.Context, record}, true, nil}+func TestLegacyUnboundReceiptPendingAttemptIsInertForBindingOwnedExecutor(t *testing.T) {+ now := time.Now().UTC()+ store := unified.NewMemoryStore()+ executor := &bindingReconcilingExecutor{}+ service := serviceForStore(t, store, testResource(now, unified.ApprovalNone), executor)+ plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))+ if err != nil {+ t.Fatal(err)+ }+ record, found, err := store.GetActionAudit(plan.ActionID)+ if err != nil || !found {+ t.Fatal(err)+ }+ started, event, err := unified.BeginActionExecution(record, "operator", now)+ if err != nil {+ t.Fatal(err)+ }+ attempt, err := unified.NewActionDispatchAttempt(started.ID, now)+ if err != nil {+ t.Fatal(err)+ }+ if err := store.RecordActionExecutionAdmission(started, event, attempt); err != nil {+ t.Fatal(err)+ }+ claimed, won, err := store.ClaimActionDispatch(started.ID, "legacy-worker", now, time.Minute)+ if err != nil || !won {+ t.Fatalf("claim=%#v won=%v err=%v", claimed, won, err)+ }+ if _, err := store.MarkActionDispatchStarted(claimed.ID, "legacy-worker", now); err != nil {+ t.Fatal(err)+ }+ recovered, err := service.RecoverExecutingActions(context.Background(), "default", "system:recovery", 10)+ if err != nil || len(recovered) != 1 || recovered[0].State != unified.ActionStateExecuting {+ t.Fatalf("recovered=%#v err=%v", recovered, err)+ }+ if executor.executeCalls != 0 || executor.reconcileCalls != 0 {+ t.Fatalf("execute=%d reconcile=%d", executor.executeCalls, executor.reconcileCalls)+ }+}+func (s *stubExecutor) ExecuteAction(_ context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {s.calls++s.received = recorddiff --git a/internal/agentexec/apt_codec.go b/internal/agentexec/apt_codec.goindex 5dfa323082..7d8c7eb409 100644--- a/internal/agentexec/apt_codec.go+++ b/internal/agentexec/apt_codec.go@@ -7,6 +7,8 @@ import ("io""strings""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt")func decodeStrictAPTPayload(data []byte, target any) error {@@ -79,6 +81,108 @@ func ValidateHostStorageCleanupPayload(payload *HostStorageCleanupPayload) errorreturn validateHostStorageCleanupPayload(payload)}+const HostAPTOperationVersion = 1++const (+ HostUpdateReceiptKind = "pulse.host_update_result"+ HostStorageCleanupReceiptKind = "pulse.host_storage_cleanup_result"+ HostAPTReceiptVersion = 1+)++func ValidateOperationQueryResultForIdentity(result operationreceipt.QueryResult, identity operationreceipt.Identity, receivedAt time.Time) error {+ if result.Status == operationreceipt.QueryNotFound {+ return nil+ }+ if result.Record == nil || result.Record.Identity != identity {+ return fmt.Errorf("operation query result identity mismatch")+ }+ if result.Status != operationreceipt.QueryFoundTerminal {+ return nil+ }+ switch identity.OperationKind {+ case HostUpdateOperationInstall:+ if result.Record.ResultKind != HostUpdateReceiptKind || result.Record.ResultVersion != HostAPTReceiptVersion {+ return fmt.Errorf("host update query result envelope mismatch")+ }+ payload, err := DecodeHostUpdateResultPayload(result.Record.Result)+ if err != nil {+ return err+ }+ req := HostUpdatePayload{RequestID: identity.AttemptID, ActionID: identity.ActionID, Operation: identity.OperationKind, OperationVersion: identity.OperationVersion, RequestDigest: identity.RequestDigest, ExpectedInventoryHash: payload.Before.InventoryHash}+ if err := ValidateHostUpdatePayload(&req); err != nil {+ return err+ }+ return ValidateHostUpdateResultForRequestAt(req, payload, receivedAt)+ case HostStorageCleanupOperationPackageCache:+ if result.Record.ResultKind != HostStorageCleanupReceiptKind || result.Record.ResultVersion != HostAPTReceiptVersion {+ return fmt.Errorf("host cleanup query result envelope mismatch")+ }+ payload, err := DecodeHostStorageCleanupResultPayload(result.Record.Result)+ if err != nil {+ return err+ }+ req := HostStorageCleanupPayload{RequestID: identity.AttemptID, ActionID: identity.ActionID, Operation: identity.OperationKind, OperationVersion: identity.OperationVersion, RequestDigest: identity.RequestDigest, ExpectedFingerprint: payload.Before.Fingerprint}+ if err := ValidateHostStorageCleanupPayload(&req); err != nil {+ return err+ }+ return ValidateHostStorageCleanupResultForRequestAt(req, payload, receivedAt)+ default:+ return fmt.Errorf("unsupported operation query kind %q", identity.OperationKind)+ }+}++func BindHostUpdatePayload(payload *HostUpdatePayload) error {+ if payload == nil {+ return fmt.Errorf("host update payload is required")+ }+ payload.OperationVersion = HostAPTOperationVersion+ digest, err := hostUpdateRequestDigest(*payload)+ if err != nil {+ return err+ }+ payload.RequestDigest = digest+ return nil+}++func hostUpdateRequestDigest(payload HostUpdatePayload) (string, error) {+ return operationreceipt.DigestCanonicalJSON(struct {+ ActionID string `json:"action_id"`+ Operation string `json:"operation"`+ OperationVersion int `json:"operation_version"`+ ExpectedInventoryHash string `json:"expected_inventory_hash"`+ }{strings.TrimSpace(payload.ActionID), strings.TrimSpace(payload.Operation), payload.OperationVersion, strings.TrimSpace(payload.ExpectedInventoryHash)})+}++func BindHostStorageCleanupPayload(payload *HostStorageCleanupPayload) error {+ if payload == nil {+ return fmt.Errorf("host storage cleanup payload is required")+ }+ payload.OperationVersion = HostAPTOperationVersion+ digest, err := hostStorageCleanupRequestDigest(*payload)+ if err != nil {+ return err+ }+ payload.RequestDigest = digest+ return nil+}++func hostStorageCleanupRequestDigest(payload HostStorageCleanupPayload) (string, error) {+ return operationreceipt.DigestCanonicalJSON(struct {+ ActionID string `json:"action_id"`+ Operation string `json:"operation"`+ OperationVersion int `json:"operation_version"`+ ExpectedFingerprint string `json:"expected_fingerprint"`+ }{strings.TrimSpace(payload.ActionID), strings.TrimSpace(payload.Operation), payload.OperationVersion, strings.TrimSpace(payload.ExpectedFingerprint)})+}++func HostUpdateOperationIdentity(agentID string, payload HostUpdatePayload) operationreceipt.Identity {+ return operationreceipt.Identity{AttemptID: payload.RequestID, ActionID: payload.ActionID, OperationKind: payload.Operation, OperationVersion: payload.OperationVersion, RequestDigest: payload.RequestDigest, AgentID: agentID}+}++func HostStorageCleanupOperationIdentity(agentID string, payload HostStorageCleanupPayload) operationreceipt.Identity {+ return operationreceipt.Identity{AttemptID: payload.RequestID, ActionID: payload.ActionID, OperationKind: payload.Operation, OperationVersion: payload.OperationVersion, RequestDigest: payload.RequestDigest, AgentID: agentID}+}+func ValidateHostUpdateResultPayload(result *HostUpdateResultPayload) error {if err := validateHostUpdateResultPayload(result); err != nil {return errdiff --git a/internal/agentexec/apt_codec_test.go b/internal/agentexec/apt_codec_test.goindex 60008c4747..22c94c7db1 100644--- a/internal/agentexec/apt_codec_test.go+++ b/internal/agentexec/apt_codec_test.go@@ -7,6 +7,8 @@ import ("strings""testing""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt")func TestStrictAPTCodecsRejectUnknownTrailingAndOpenAuthorityFields(t *testing.T) {@@ -42,7 +44,7 @@ func TestMalformedOrCrossTypeAPTResultCannotPoisonPendingUpdate(t *testing.T) {t.Fatal(err)}defer conn.Close()- wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "apt-agent", Hostname: "host", Version: "6", Platform: "linux", Token: "any"}))+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "apt-agent", Hostname: "host", Version: "6", Platform: "linux", Token: "any", OperationReceiptVersion: operationreceipt.ProtocolVersion}))_ = wsReadRegisteredPayload(t, conn)done := make(chan error, 1)@@ -91,7 +93,7 @@ func TestCrossTypeSameRequestCollisionRefusesSecondMutation(t *testing.T) {t.Fatal(err)}defer conn.Close()- wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "apt-agent", Hostname: "host", Version: "6", Platform: "linux", Token: "any"}))+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "apt-agent", Hostname: "host", Version: "6", Platform: "linux", Token: "any", OperationReceiptVersion: operationreceipt.ProtocolVersion}))_ = wsReadRegisteredPayload(t, conn)ctx, cancel := context.WithCancel(context.Background())diff --git a/internal/agentexec/operation_query_test.go b/internal/agentexec/operation_query_test.gonew file mode 100644index 0000000000..f94479c1e3--- /dev/null+++ b/internal/agentexec/operation_query_test.go@@ -0,0 +1,221 @@+package agentexec++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"+)++func testOperationIdentity(t *testing.T, agentID string) operationreceipt.Identity {+ t.Helper()+ req := HostUpdatePayload{RequestID: "action-1.dispatch.1", ActionID: "action-1", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: "sha256:" + strings.Repeat("a", 64)}+ if err := BindHostUpdatePayload(&req); err != nil {+ t.Fatal(err)+ }+ return HostUpdateOperationIdentity(agentID, req)+}+func registeredTestAgent(t *testing.T, s *Server, agentID string) (*websocket.Conn, func()) {+ t.Helper()+ ts := newWSServer(t, s)+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)+ if err != nil {+ t.Fatal(err)+ }+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: agentID, Hostname: "host", Version: "6", Platform: "linux", Token: "ok", OperationReceiptVersion: operationreceipt.ProtocolVersion}))+ if !wsReadRegisteredPayload(t, conn).Success {+ t.Fatal("registration failed")+ }+ return conn, func() { conn.Close(); ts.Close() }+}+func interruptedQueryResult(id operationreceipt.Identity, state operationreceipt.State) operationreceipt.QueryResult {+ now := time.Now().UTC()+ record := operationreceipt.Record{Identity: id, State: state, AcceptedAt: now, StartedAt: now}+ if state == operationreceipt.StateTombstone {+ record.TerminalAt = now+ }+ return operationreceipt.QueryResult{Version: operationreceipt.ProtocolVersion, Status: operationreceipt.QueryFoundInterrupted, Record: &record}+}+func hostileTerminalQueryResult(id operationreceipt.Identity, kind string, version int, payload json.RawMessage) operationreceipt.QueryResult {+ now := time.Now().UTC()+ record := operationreceipt.Record{Identity: id, State: operationreceipt.StateTerminal, AcceptedAt: now.Add(-2 * time.Second), StartedAt: now.Add(-time.Second), TerminalAt: now, ResultKind: kind, ResultVersion: version, Result: payload}+ return operationreceipt.QueryResult{Version: 1, Status: operationreceipt.QueryFoundTerminal, Record: &record}+}++func TestQueryAgentOperationRejectsHostileCorrelations(t *testing.T) {+ old := operationQueryTimeout+ operationQueryTimeout = 80 * time.Millisecond+ defer func() { operationQueryTimeout = old }()+ cases := []struct {+ name string+ reply func(t *testing.T, conn *websocket.Conn, query wsRawMessage, id operationreceipt.Identity)+ }{+ {"wrong_message_id", func(t *testing.T, c *websocket.Conn, q wsRawMessage, id operationreceipt.Identity) {+ wsWriteMessage(t, c, mustNewMessage(t, MsgTypeOperationQueryResult, "other", interruptedQueryResult(id, operationreceipt.StateInterrupted)))+ }},+ {"wrong_identity", func(t *testing.T, c *websocket.Conn, q wsRawMessage, id operationreceipt.Identity) {+ id.ActionID = "other"+ wsWriteMessage(t, c, mustNewMessage(t, MsgTypeOperationQueryResult, q.ID, interruptedQueryResult(id, operationreceipt.StateInterrupted)))+ }},+ {"malformed_unknown", func(t *testing.T, c *websocket.Conn, q wsRawMessage, id operationreceipt.Identity) {+ raw := json.RawMessage(`{"version":1,"status":"not_found","unknown":true}`)+ wsWriteMessage(t, c, Message{Type: MsgTypeOperationQueryResult, ID: q.ID, Timestamp: time.Now(), Payload: raw})+ }},+ {"trailing", func(t *testing.T, c *websocket.Conn, q wsRawMessage, id operationreceipt.Identity) {+ raw := []byte(`{"type":"agent_operation_query_result","id":"` + q.ID + `","payload":{"version":1,"status":"not_found"} {}}`)+ if err := c.WriteMessage(websocket.TextMessage, raw); err != nil {+ t.Fatalf("write trailing result: %v", err)+ }+ }},+ {"unknown_terminal_kind", func(t *testing.T, c *websocket.Conn, q wsRawMessage, id operationreceipt.Identity) {+ wsWriteMessage(t, c, mustNewMessage(t, MsgTypeOperationQueryResult, q.ID, hostileTerminalQueryResult(id, "unknown", 1, json.RawMessage(`{"safe":true}`))))+ }},+ {"unknown_terminal_version", func(t *testing.T, c *websocket.Conn, q wsRawMessage, id operationreceipt.Identity) {+ wsWriteMessage(t, c, mustNewMessage(t, MsgTypeOperationQueryResult, q.ID, hostileTerminalQueryResult(id, HostUpdateReceiptKind, 99, json.RawMessage(`{"safe":true}`))))+ }},+ {"malformed_terminal_payload", func(t *testing.T, c *websocket.Conn, q wsRawMessage, id operationreceipt.Identity) {+ wsWriteMessage(t, c, mustNewMessage(t, MsgTypeOperationQueryResult, q.ID, hostileTerminalQueryResult(id, HostUpdateReceiptKind, 1, json.RawMessage(`{"request_id":"x","unknown":true}`))))+ }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ s := NewServer(func(token, agent, host string) bool { return token == "ok" })+ conn, cleanup := registeredTestAgent(t, s, "agent-1")+ defer cleanup()+ id := testOperationIdentity(t, "agent-1")+ done := make(chan error, 1)+ go func() { _, err := s.QueryAgentOperation(context.Background(), "agent-1", id); done <- err }()+ query := wsReadRawMessage(t, conn)+ tc.reply(t, conn, query, id)+ if err := <-done; err == nil || !strings.Contains(err.Error(), "timed out") {+ t.Fatalf("query err=%v", err)+ }+ })+ }+}++func TestQueryAgentOperationWrongAgentLateDuplicateAndInterruptedAreInert(t *testing.T) {+ old := operationQueryTimeout+ operationQueryTimeout = 80 * time.Millisecond+ defer func() { operationQueryTimeout = old }()+ s := NewServer(func(token, agent, host string) bool { return token == "ok" })+ first, cleanupFirst := registeredTestAgent(t, s, "agent-1")+ defer cleanupFirst()+ second, cleanupSecond := registeredTestAgent(t, s, "agent-2")+ defer cleanupSecond()+ id := testOperationIdentity(t, "agent-1")+ done := make(chan error, 1)+ go func() { _, err := s.QueryAgentOperation(context.Background(), "agent-1", id); done <- err }()+ query := wsReadRawMessage(t, first)+ wsWriteMessage(t, second, mustNewMessage(t, MsgTypeOperationQueryResult, query.ID, interruptedQueryResult(id, operationreceipt.StateInterrupted)))+ if err := <-done; err == nil {+ t.Fatal("wrong-agent response completed query")+ }+ wsWriteMessage(t, first, mustNewMessage(t, MsgTypeOperationQueryResult, query.ID, interruptedQueryResult(id, operationreceipt.StateInterrupted)))+ // A fresh query accepts interrupted/tombstone state but never turns it into a terminal result.+ resultCh := make(chan operationreceipt.QueryResult, 1)+ errCh := make(chan error, 1)+ go func() {+ r, err := s.QueryAgentOperation(context.Background(), "agent-1", id)+ if err != nil {+ errCh <- err+ return+ }+ resultCh <- r+ }()+ q2 := wsReadRawMessage(t, first)+ response := interruptedQueryResult(id, operationreceipt.StateTombstone)+ wsWriteMessage(t, first, mustNewMessage(t, MsgTypeOperationQueryResult, q2.ID, response))+ wsWriteMessage(t, first, mustNewMessage(t, MsgTypeOperationQueryResult, q2.ID, response))+ select {+ case err := <-errCh:+ t.Fatal(err)+ case got := <-resultCh:+ if got.Status != operationreceipt.QueryFoundInterrupted || got.Record.State != operationreceipt.StateTombstone {+ t.Fatalf("result=%+v", got)+ }+ }+}++func TestOperationQueryBeforeStateDigestMismatchFailsClosed(t *testing.T) {+ now := time.Now().UTC()+ for _, tc := range []struct {+ name string+ identity operationreceipt.Identity+ record operationreceipt.Record+ }{+ func() struct {+ name string+ identity operationreceipt.Identity+ record operationreceipt.Record+ } {+ req := HostUpdatePayload{RequestID: "u.dispatch.1", ActionID: "u", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: "sha256:" + strings.Repeat("a", 64)}+ _ = BindHostUpdatePayload(&req)+ id := HostUpdateOperationIdentity("agent", req)+ result := HostUpdateResultPayload{RequestID: req.RequestID, ActionID: req.ActionID, Success: true, ExecutionPhase: HostUpdatePhaseComplete, MutationStarted: true, Before: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("b", 64), PendingCount: 1, CheckedAt: now.Add(-time.Second)}, After: HostPackageUpdateSnapshot{Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("c", 64), PendingCount: 0, CheckedAt: now}, Verification: HostUpdateVerificationVerified}+ raw, _ := json.Marshal(result)+ return struct {+ name string+ identity operationreceipt.Identity+ record operationreceipt.Record+ }{"update", id, operationreceipt.Record{Identity: id, State: operationreceipt.StateTerminal, AcceptedAt: now.Add(-2 * time.Second), StartedAt: now.Add(-time.Second), TerminalAt: now, ResultKind: HostUpdateReceiptKind, ResultVersion: 1, Result: raw}}+ }(),+ func() struct {+ name string+ identity operationreceipt.Identity+ record operationreceipt.Record+ } {+ req := HostStorageCleanupPayload{RequestID: "c.dispatch.1", ActionID: "c", Operation: HostStorageCleanupOperationPackageCache, ExpectedFingerprint: "sha256:" + strings.Repeat("a", 64)}+ _ = BindHostStorageCleanupPayload(&req)+ id := HostStorageCleanupOperationIdentity("agent", req)+ result := HostStorageCleanupResultPayload{RequestID: req.RequestID, ActionID: req.ActionID, Success: true, ExecutionPhase: HostStorageCleanupPhaseComplete, MutationStarted: true, Before: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 10, CheckedAt: now.Add(-time.Second)}, After: HostStorageCleanupSnapshot{Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("c", 64), ReclaimableBytes: 1, CheckedAt: now}, ReclaimedBytes: 9, Verification: HostStorageCleanupVerificationVerified}+ raw, _ := json.Marshal(result)+ return struct {+ name string+ identity operationreceipt.Identity+ record operationreceipt.Record+ }{"cleanup", id, operationreceipt.Record{Identity: id, State: operationreceipt.StateTerminal, AcceptedAt: now.Add(-2 * time.Second), StartedAt: now.Add(-time.Second), TerminalAt: now, ResultKind: HostStorageCleanupReceiptKind, ResultVersion: 1, Result: raw}}+ }(),+ } {+ t.Run(tc.name, func(t *testing.T) {+ query := operationreceipt.QueryResult{Version: 1, Status: operationreceipt.QueryFoundTerminal, Record: &tc.record}+ if err := ValidateOperationQueryResultForIdentity(query, tc.identity, now); err == nil {+ t.Fatal("mismatched before-state digest accepted")+ }+ })+ }+}++func TestLegacyAgentWithoutReceiptProtocolRemainsConnectedButTypedMutationFailsClosed(t *testing.T) {+ s := NewServer(func(token, agent, host string) bool { return token == "ok" })+ conn, cleanup := registeredTestAgentLegacy(t, s, "legacy-agent")+ defer cleanup()+ req := HostUpdatePayload{RequestID: "legacy.dispatch.1", ActionID: "legacy", Operation: HostUpdateOperationInstall, ExpectedInventoryHash: "sha256:" + strings.Repeat("a", 64), Timeout: 1}+ if _, err := s.ExecuteHostUpdate(context.Background(), "legacy-agent", req); err == nil || !strings.Contains(err.Error(), "does not support durable operation receipts") {+ t.Fatalf("err=%v", err)+ }+ if _, err := wsReadRawMessageWithTimeout(conn, 50*time.Millisecond); err == nil {+ t.Fatal("legacy agent received typed mutation")+ }+}++func registeredTestAgentLegacy(t *testing.T, s *Server, agentID string) (*websocket.Conn, func()) {+ t.Helper()+ ts := newWSServer(t, s)+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)+ if err != nil {+ t.Fatal(err)+ }+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: agentID, Hostname: "host", Version: "5", Platform: "linux", Token: "ok"}))+ if !wsReadRegisteredPayload(t, conn).Success {+ t.Fatal("registration failed")+ }+ return conn, func() { conn.Close(); ts.Close() }+}++var _ = errors.Isdiff --git a/internal/agentexec/server.go b/internal/agentexec/server.goindex fa5f106266..fdec3fa2e3 100644--- a/internal/agentexec/server.go+++ b/internal/agentexec/server.go@@ -14,6 +14,7 @@ import ("github.com/google/uuid""github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rcourtman/pulse-go-rewrite/internal/securityutil""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rs/zerolog/log"@@ -32,9 +33,10 @@ var (writeTextMessage = func(conn *websocket.Conn, data []byte) error {return conn.WriteMessage(websocket.TextMessage, data)}- defaultPingInterval = 5 * time.Second- pingWriteWait = 5 * time.Second- readFileTimeout = 30 * time.Second+ defaultPingInterval = 5 * time.Second+ pingWriteWait = 5 * time.Second+ readFileTimeout = 30 * time.Second+ operationQueryTimeout = 10 * time.SeconderrServerShuttingDown = errors.New("agent execution server is shutting down"))@@ -65,7 +67,8 @@ type Server struct {pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup responsependingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update responsependingHostOperations map[string]pendingHostOperation // scoped request key -> exact typed APT operation/query identity- deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber+ pendingOperationQueries map[string]pendingOperationQuery+ deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscribervalidateToken func(token string, agentID string, hostname string) boolcommandPolicy *CommandPolicyipConnCounts map[string]int@@ -104,6 +107,11 @@ type pendingHostOperation struct {operation string}+type pendingOperationQuery struct {+ identity operationreceipt.Identity+ ch chan operationreceipt.QueryResult+}+func (ac *agentConn) signalDone() {ac.doneOnce.Do(func() {defer func() {@@ -136,6 +144,7 @@ func NewServer(validateToken func(token string, agentID string, hostname string)pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),pendingHostOperations: make(map[string]pendingHostOperation),+ pendingOperationQueries: make(map[string]pendingOperationQuery),deploySubs: make(map[string]chan DeployProgressPayload),validateToken: validateToken,commandPolicy: DefaultPolicy(),@@ -347,6 +356,16 @@ func validateHostUpdatePayload(req *HostUpdatePayload) error {if req.Operation != HostUpdateOperationInstall {return fmt.Errorf("unsupported host update operation %q", req.Operation)}+ if req.OperationVersion != HostAPTOperationVersion {+ return fmt.Errorf("unsupported host update operation version %d", req.OperationVersion)+ }+ expectedDigest, err := hostUpdateRequestDigest(*req)+ if err != nil {+ return err+ }+ if req.RequestDigest != expectedDigest {+ return fmt.Errorf("host update request digest mismatch")+ }if !hostUpdateInventoryHashPattern.MatchString(req.ExpectedInventoryHash) {return fmt.Errorf("expected inventory hash is required and must be sha256")}@@ -411,6 +430,16 @@ func validateHostStorageCleanupPayload(req *HostStorageCleanupPayload) error {if req.Operation != HostStorageCleanupOperationPackageCache {return fmt.Errorf("unsupported host storage cleanup operation %q", req.Operation)}+ if req.OperationVersion != HostAPTOperationVersion {+ return fmt.Errorf("unsupported host storage cleanup operation version %d", req.OperationVersion)+ }+ expectedDigest, err := hostStorageCleanupRequestDigest(*req)+ if err != nil {+ return err+ }+ if req.RequestDigest != expectedDigest {+ return fmt.Errorf("host storage cleanup request digest mismatch")+ }if !hostStorageCleanupFingerprintPattern.MatchString(req.ExpectedFingerprint) {return fmt.Errorf("expected cleanup fingerprint is required and must be sha256")}@@ -665,12 +694,13 @@ func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {ac := &agentConn{conn: conn,agent: ConnectedAgent{- AgentID: reg.AgentID,- Hostname: reg.Hostname,- Version: reg.Version,- Platform: reg.Platform,- Tags: reg.Tags,- ConnectedAt: time.Now(),+ AgentID: reg.AgentID,+ Hostname: reg.Hostname,+ Version: reg.Version,+ Platform: reg.Platform,+ Tags: reg.Tags,+ ConnectedAt: time.Now(),+ OperationReceiptVersion: reg.OperationReceiptVersion,},approvalGrantKey: DeriveApprovalGrantKey(reg.Token),done: make(chan struct{}),@@ -906,6 +936,31 @@ func (s *Server) readLoop(ac *agentConn) {}}+ case MsgTypeOperationQueryResult:+ result, decodeErr := operationreceipt.DecodeQueryResult(msg.Payload)+ if decodeErr != nil {+ log.Warn().Err(decodeErr).Str("agent_id", ac.agent.AgentID).Msg("Dropping invalid operation query result")+ continue+ }+ key := pendingRequestKey(ac.agent.AgentID, strings.TrimSpace(msg.ID))+ s.mu.RLock()+ pending, ok := s.pendingOperationQueries[key]+ s.mu.RUnlock()+ if !ok {+ continue+ }+ if result.Record != nil && result.Record.Identity != pending.identity {+ log.Warn().Str("agent_id", ac.agent.AgentID).Msg("Dropping mismatched operation query result")+ continue+ }+ if err := ValidateOperationQueryResultForIdentity(result, pending.identity, s.currentTime()); err != nil {+ log.Warn().Err(err).Str("agent_id", ac.agent.AgentID).Msg("Dropping invalid correlated operation query result")+ continue+ }+ select {+ case pending.ch <- result:+ default:+ }case MsgTypeDeployProgress:var progress DeployProgressPayloadif err := msg.DecodePayload(&progress); err != nil {@@ -1236,6 +1291,9 @@ func (s *Server) ExecuteHostUpdate(ctx context.Context, agentID string, req Hostif strings.TrimSpace(req.RequestID) == "" {req.RequestID = uuid.New().String()}+ if err := BindHostUpdatePayload(&req); err != nil {+ return nil, err+ }if err := ValidateHostUpdatePayload(&req); err != nil {return nil, err}@@ -1246,6 +1304,9 @@ func (s *Server) ExecuteHostUpdate(ctx context.Context, agentID string, req Hostif !ok {return nil, fmt.Errorf("agent %s not connected", agentID)}+ if ac.agent.OperationReceiptVersion != operationreceipt.ProtocolVersion {+ return nil, fmt.Errorf("agent does not support durable operation receipts")+ }respCh := make(chan HostUpdateResultPayload, 1)reqKey := pendingRequestKey(agentID, req.RequestID)@@ -1311,6 +1372,9 @@ func (s *Server) ExecuteHostStorageCleanup(ctx context.Context, agentID string,if strings.TrimSpace(req.RequestID) == "" {req.RequestID = uuid.New().String()}+ if err := BindHostStorageCleanupPayload(&req); err != nil {+ return nil, err+ }if err := ValidateHostStorageCleanupPayload(&req); err != nil {return nil, err}@@ -1321,6 +1385,9 @@ func (s *Server) ExecuteHostStorageCleanup(ctx context.Context, agentID string,if !ok {return nil, fmt.Errorf("agent %s not connected", agentID)}+ if ac.agent.OperationReceiptVersion != operationreceipt.ProtocolVersion {+ return nil, fmt.Errorf("agent does not support durable operation receipts")+ }respCh := make(chan HostStorageCleanupResultPayload, 1)reqKey := pendingRequestKey(agentID, req.RequestID)@@ -1379,6 +1446,75 @@ func (s *Server) currentTime() time.Time {return time.Now().UTC()}+func (s *Server) AgentOperationReceiptVersion(agentID string) int {+ if s == nil {+ return 0+ }+ s.mu.RLock()+ defer s.mu.RUnlock()+ connection, ok := s.agents[strings.TrimSpace(agentID)]+ if !ok {+ return 0+ }+ return connection.agent.OperationReceiptVersion+}++// QueryAgentOperation reconciles a committed attempt without mutation or resend.+func (s *Server) QueryAgentOperation(ctx context.Context, agentID string, identity operationreceipt.Identity) (operationreceipt.QueryResult, error) {+ identity, err := operationreceipt.NormalizeIdentity(identity)+ if err != nil {+ return operationreceipt.QueryResult{}, err+ }+ agentID = strings.TrimSpace(agentID)+ if identity.AgentID != agentID {+ return operationreceipt.QueryResult{}, operationreceipt.ErrBindingConflict+ }+ s.mu.RLock()+ ac, ok := s.agents[agentID]+ s.mu.RUnlock()+ if !ok {+ return operationreceipt.QueryResult{}, fmt.Errorf("agent %s not connected", agentID)+ }+ if ac.agent.OperationReceiptVersion != operationreceipt.ProtocolVersion {+ return operationreceipt.QueryResult{}, fmt.Errorf("agent does not support durable operation receipts")+ }+ queryID := identity.AttemptID + ".query." + uuid.NewString()+ key := pendingRequestKey(agentID, queryID)+ ch := make(chan operationreceipt.QueryResult, 1)+ s.mu.Lock()+ if _, exists := s.pendingOperationQueries[key]; exists {+ s.mu.Unlock()+ return operationreceipt.QueryResult{}, fmt.Errorf("operation query %q is already pending", identity.AttemptID)+ }+ s.pendingOperationQueries[key] = pendingOperationQuery{identity: identity, ch: ch}+ s.mu.Unlock()+ defer func() { s.mu.Lock(); delete(s.pendingOperationQueries, key); s.mu.Unlock() }()+ msg, err := NewMessage(MsgTypeOperationQuery, queryID, operationreceipt.Query{Version: operationreceipt.ProtocolVersion, Identity: identity})+ if err != nil {+ return operationreceipt.QueryResult{}, err+ }+ ac.writeMu.Lock()+ err = s.sendMessage(ac.conn, msg)+ ac.writeMu.Unlock()+ if err != nil {+ return operationreceipt.QueryResult{}, err+ }+ timer := time.NewTimer(operationQueryTimeout)+ defer timer.Stop()+ select {+ case result := <-ch:+ return result, nil+ case <-ctx.Done():+ return operationreceipt.QueryResult{}, ctx.Err()+ case <-timer.C:+ return operationreceipt.QueryResult{}, fmt.Errorf("operation receipt query timed out")+ case <-ac.done:+ return operationreceipt.QueryResult{}, fmt.Errorf("agent %s disconnected during operation query", agentID)+ case <-s.shutdown:+ return operationreceipt.QueryResult{}, errServerShuttingDown+ }+}+// ReadFile reads a file from an agentfunc (s *Server) ReadFile(ctx context.Context, agentID string, req ReadFilePayload) (*CommandResultPayload, error) {agentID = strings.TrimSpace(agentID)diff --git a/internal/agentexec/server_test.go b/internal/agentexec/server_test.goindex bdf643778e..bdbee2fc82 100644--- a/internal/agentexec/server_test.go+++ b/internal/agentexec/server_test.go@@ -11,7 +11,7 @@ import (func TestHostStorageCleanupPayloadIsClosedAndSelectorFree(t *testing.T) {typeOf := reflect.TypeOf(HostStorageCleanupPayload{})- want := []string{"RequestID", "ActionID", "Operation", "ExpectedFingerprint", "Timeout"}+ want := []string{"RequestID", "ActionID", "Operation", "OperationVersion", "RequestDigest", "ExpectedFingerprint", "Timeout"}if typeOf.NumField() != len(want) {t.Fatalf("host storage cleanup payload fields = %d, want %d", typeOf.NumField(), len(want))}diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.goindex 7c13ba7d61..2db45ca839 100644--- a/internal/agentexec/server_websocket_test.go+++ b/internal/agentexec/server_websocket_test.go@@ -533,7 +533,7 @@ func TestExecuteHostUpdateRoundTripUsesTypedCommandFreeEnvelope(t *testing.T) {defer conn.Close()wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{- AgentID: "host-agent-1", Hostname: "host1", Version: "6.0.6", Platform: "linux", Token: "any",+ AgentID: "host-agent-1", Hostname: "host1", Version: "6.0.6", Platform: "linux", Token: "any", OperationReceiptVersion: 1,}))_ = wsReadRegisteredPayload(t, conn)@@ -632,7 +632,7 @@ func TestExecuteHostStorageCleanupRoundTripUsesPathAndCommandFreeEnvelope(t *tes}defer conn.Close()wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{- AgentID: "host-agent-cleanup", Hostname: "host1", Version: "6.0.6", Platform: "linux", Token: "any",+ AgentID: "host-agent-cleanup", Hostname: "host1", Version: "6.0.6", Platform: "linux", Token: "any", OperationReceiptVersion: 1,}))_ = wsReadRegisteredPayload(t, conn)diff --git a/internal/agentexec/types.go b/internal/agentexec/types.goindex 5bd707ee36..cfbc3e2134 100644--- a/internal/agentexec/types.go+++ b/internal/agentexec/types.go@@ -17,6 +17,7 @@ const (MsgTypeCommandResult MessageType = "command_result"MsgTypeHostStorageCleanupResult MessageType = "host_storage_cleanup_result"MsgTypeHostUpdateResult MessageType = "host_update_result"+ MsgTypeOperationQueryResult MessageType = "agent_operation_query_result"// Server -> Agent messagesMsgTypeRegistered MessageType = "registered"@@ -25,6 +26,7 @@ const (MsgTypeHostStorageCleanup MessageType = "host_storage_cleanup"MsgTypeReadFile MessageType = "read_file"MsgTypeHostUpdate MessageType = "host_update"+ MsgTypeOperationQuery MessageType = "agent_operation_query"MsgTypeDeployPreflight MessageType = "deploy_preflight"MsgTypeDeployInstall MessageType = "deploy_install"MsgTypeDeployCancelJob MessageType = "deploy_cancel"@@ -79,12 +81,13 @@ func (m Message) DecodePayload(target any) error {// AgentRegisterPayload is sent by agent on connectiontype AgentRegisterPayload struct {- AgentID string `json:"agent_id"`- Hostname string `json:"hostname"`- Version string `json:"version"`- Platform string `json:"platform"` // "linux", "windows", "darwin"- Tags []string `json:"tags,omitempty"`- Token string `json:"token"` // API token for authentication+ AgentID string `json:"agent_id"`+ Hostname string `json:"hostname"`+ Version string `json:"version"`+ Platform string `json:"platform"` // "linux", "windows", "darwin"+ Tags []string `json:"tags,omitempty"`+ Token string `json:"token"` // API token for authentication+ OperationReceiptVersion int `json:"operation_receipt_version,omitempty"`}// RegisteredPayload is sent by server after successful registration@@ -161,6 +164,8 @@ type HostUpdatePayload struct {RequestID string `json:"request_id"`ActionID string `json:"action_id"`Operation string `json:"operation"`+ OperationVersion int `json:"operation_version"`+ RequestDigest string `json:"request_digest"`ExpectedInventoryHash string `json:"expected_inventory_hash"`Timeout int `json:"timeout,omitempty"`}@@ -223,6 +228,8 @@ type HostStorageCleanupPayload struct {RequestID string `json:"request_id"`ActionID string `json:"action_id"`Operation string `json:"operation"`+ OperationVersion int `json:"operation_version"`+ RequestDigest string `json:"request_digest"`ExpectedFingerprint string `json:"expected_fingerprint"`Timeout int `json:"timeout,omitempty"`}@@ -267,12 +274,13 @@ const (// ConnectedAgent represents an agent connected via WebSockettype ConnectedAgent struct {- AgentID string- Hostname string- Version string- Platform string- Tags []string- ConnectedAt time.Time+ AgentID string+ Hostname string+ Version string+ Platform string+ Tags []string+ ConnectedAt time.Time+ OperationReceiptVersion int}// --- Deploy protocol payloads ---diff --git a/internal/ai/findings_apt_workflows_test.go b/internal/ai/findings_apt_workflows_test.goindex c2329a20dc..229675274c 100644--- a/internal/ai/findings_apt_workflows_test.go+++ b/internal/ai/findings_apt_workflows_test.go@@ -18,7 +18,7 @@ func aptWorkflowTestHost(now time.Time) *ur.HostView {{Name: "clean_package_cache", InternalHandler: "host.storage_cleanup"},},Agent: &ur.AgentData{- AgentID: "host-1", CommandsEnabled: true,+ AgentID: "host-1", CommandsEnabled: true, OperationReceiptVersion: 1,PackageUpdates: &ur.AgentPackageUpdateMeta{Supported: true, Manager: "apt", InventoryHash: digestA, PendingCount: 3, CheckedAt: now.Add(-time.Minute), ObservedAt: now},StorageCleanup: &ur.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: digestB, ReclaimableBytes: 128 * 1024 * 1024, CheckedAt: now.Add(-time.Minute), ObservedAt: now},Disks: []ur.DiskInfo{{Mountpoint: "/", Usage: 95}},@@ -48,6 +48,18 @@ func TestAPTWorkflowWatcherEmitsDeterministicCapabilityBoundFindings(t *testing.}}+func TestAPTWorkflowWatcherLegacyReceiptProtocolWithFreshTelemetryEmitsNothing(t *testing.T) {+ now := time.Date(2026, 7, 12, 8, 0, 0, 0, time.UTC)+ resource := hostResourceForAPTTest(aptWorkflowTestHost(now), now)+ resource.Agent.OperationReceiptVersion = 0+ resource.Capabilities = nil+ view := ur.NewHostView(resource)+ emit, resolve := newAPTWorkflowWatcher().Observe(patrolRuntimeState{readState: &mockReadState{hosts: []*ur.HostView{&view}}}, nil, now)+ if len(emit) != 0 || len(resolve) != 0 {+ t.Fatalf("emit=%d resolve=%d", len(emit), len(resolve))+ }+}+func TestAPTWorkflowWatcherReplayAndFutureTimesRemainUnresolved(t *testing.T) {now := time.Date(2026, 7, 12, 8, 0, 0, 0, time.UTC)active := []*Finding{{ID: "apt:host-update:agent:host-1", ResourceID: "agent:host-1", Source: aptWorkflowFindingSource}}@@ -117,7 +129,7 @@ func hostResourceForAPTTest(_ *ur.HostView, now time.Time) *ur.Resource {return &ur.Resource{ID: "agent:host-1", Type: ur.ResourceTypeAgent, Name: "host-1", Status: ur.StatusOnline,Capabilities: []ur.ResourceCapability{{Name: "install_os_updates", InternalHandler: "host.package_updates"}, {Name: "clean_package_cache", InternalHandler: "host.storage_cleanup"}},- Agent: &ur.AgentData{AgentID: "host-1", CommandsEnabled: true,+ Agent: &ur.AgentData{AgentID: "host-1", CommandsEnabled: true, OperationReceiptVersion: 1,PackageUpdates: &ur.AgentPackageUpdateMeta{Supported: true, Manager: "apt", InventoryHash: digestA, PendingCount: 3, CheckedAt: now.Add(-time.Minute), ObservedAt: now},StorageCleanup: &ur.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: digestB, ReclaimableBytes: 128 * 1024 * 1024, CheckedAt: now.Add(-time.Minute), ObservedAt: now},Disks: []ur.DiskInfo{{Mountpoint: "/", Usage: 95}}},diff --git a/internal/api/action_executor.go b/internal/api/action_executor.goindex 574400c63f..6a47c50ab8 100644--- a/internal/api/action_executor.go+++ b/internal/api/action_executor.go@@ -5,6 +5,7 @@ import ("fmt""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -65,6 +66,30 @@ func (e routedActionExecutor) ExecuteAction(ctx context.Context, record unified.return executor.ExecuteAction(ctx, normalized)}+func (e routedActionExecutor) BindActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {+ executor, err := e.executorForAction(ctx, record.Request)+ if err != nil {+ return unified.ActionDispatchAttempt{}, err+ }+ binder, ok := executor.(actionlifecycle.DispatchBinder)+ if !ok {+ return attempt, nil+ }+ return binder.BindActionDispatch(ctx, record, attempt)+}++func (e routedActionExecutor) ReconcileActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {+ executor, err := e.executorForAction(ctx, record.Request)+ if err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ reconciler, ok := executor.(actionlifecycle.DispatchReconciler)+ if !ok {+ return nil, unified.ActionDispatchReceipt{}, false, nil+ }+ return reconciler.ReconcileActionDispatch(ctx, record, attempt)+}+func (e routedActionExecutor) CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {capability, ok := resourceCapabilityByName(resource.Capabilities, req.CapabilityName)if !ok || strings.TrimSpace(capability.InternalHandler) == "" {diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex d3d6baf0e9..44b44503b3 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -20132,6 +20132,45 @@ func TestContract_HostStorageCleanupIsTypedFingerprintBoundAndPathFree(t *testin}}+func TestContract_DurableOperationReceiptCapabilityGatesAPTActions(t *testing.T) {+ files := map[string][]string{+ "../../pkg/agents/host/report.go": {"OperationReceiptVersion int", `json:"operationReceiptVersion,omitempty"`},+ "../unifiedresources/adapters.go": {"host.OperationReceiptVersion != operationreceipt.ProtocolVersion", "hostPackageUpdateCapabilities(host)", "hostStorageCleanupCapability(host)"},+ "host_update_action_executor.go": {"resource.Agent.OperationReceiptVersion != operationreceipt.ProtocolVersion", "AgentOperationReceiptVersion(agentID) != operationreceipt.ProtocolVersion"},+ "host_storage_cleanup_action_executor.go": {"resource.Agent.OperationReceiptVersion != operationreceipt.ProtocolVersion", "AgentOperationReceiptVersion(agentID) != operationreceipt.ProtocolVersion"},+ "../ai/findings_apt_workflows.go": {"aptHostHasCapability(host, \"install_os_updates\", \"host.package_updates\")", "aptHostHasCapability(host, \"clean_package_cache\", \"host.storage_cleanup\")"},+ }+ for path, fragments := range files {+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ source := string(data)+ for _, fragment := range fragments {+ if !strings.Contains(source, fragment) {+ t.Errorf("%s missing durable receipt capability guard %q", path, fragment)+ }+ }+ }+}++func TestContract_OperationReceiptProtocolStaysOutOfCustomerDTOs(t *testing.T) {+ frontend, err := os.ReadFile("../models/models_frontend.go")+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(frontend), "OperationReceiptVersion") || strings.Contains(string(frontend), "operationReceiptVersion") {+ t.Fatal("frontend DTO learned raw operation receipt protocol")+ }+ resourceTypes, err := os.ReadFile("../unifiedresources/types.go")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(resourceTypes), "OperationReceiptVersion int") || !strings.Contains(string(resourceTypes), "`json:\"-\"`") {+ t.Fatal("canonical registry must retain receipt protocol as internal-only metadata")+ }+}+// TestContract_AgentCapabilitiesManifestIsPublic pins the auth// contract for the discovery surface: the manifest must be in the// router's publicPaths list so it serves without a token. Thediff --git a/internal/api/host_storage_cleanup_action_executor.go b/internal/api/host_storage_cleanup_action_executor.goindex 82020f432e..a88c5d754a 100644--- a/internal/api/host_storage_cleanup_action_executor.go+++ b/internal/api/host_storage_cleanup_action_executor.go@@ -9,6 +9,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -24,6 +25,18 @@ type hostStorageCleanupAgentCommander interface {IsAgentConnected(agentID string) bool}+func (e hostStorageCleanupActionExecutor) BindActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {+ resource, err := e.currentResource(ctx, record.Request.ResourceID)+ if err != nil {+ return unified.ActionDispatchAttempt{}, err+ }+ req := agentexec.HostStorageCleanupPayload{RequestID: attempt.ID, ActionID: record.ID, Operation: agentexec.HostStorageCleanupOperationPackageCache, ExpectedFingerprint: resource.Agent.StorageCleanup.Fingerprint}+ if err := agentexec.BindHostStorageCleanupPayload(&req); err != nil {+ return unified.ActionDispatchAttempt{}, err+ }+ return unified.BindActionDispatchAttempt(attempt, unified.ActionDispatchBinding{OperationKind: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, AgentID: resource.Agent.AgentID})+}+type hostStorageCleanupActionExecutor struct {resources *ResourceHandlersagents hostStorageCleanupAgentCommander@@ -76,13 +89,21 @@ func (e hostStorageCleanupActionExecutor) ExecuteAction(ctx context.Context, recif err != nil {return nil, err}- result, err := e.agents.ExecuteHostStorageCleanup(ctx, strings.TrimSpace(resource.Agent.AgentID), agentexec.HostStorageCleanupPayload{+ agentID := strings.TrimSpace(resource.Agent.AgentID)+ req := agentexec.HostStorageCleanupPayload{RequestID: attempt.ID,ActionID: record.ID,Operation: agentexec.HostStorageCleanupOperationPackageCache,ExpectedFingerprint: resource.Agent.StorageCleanup.Fingerprint,Timeout: 300,- })+ }+ if err := agentexec.BindHostStorageCleanupPayload(&req); err != nil {+ return nil, err+ }+ if agentexec.HostStorageCleanupOperationIdentity(agentID, req) != (operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}) {+ return nil, fmt.Errorf("host cleanup dispatch binding drift")+ }+ result, err := e.agents.ExecuteHostStorageCleanup(ctx, agentID, req)if err != nil {return nil, err}@@ -95,6 +116,39 @@ func (e hostStorageCleanupActionExecutor) ExecuteAction(ctx context.Context, recreturn hostAPTExecutionResult(record.Request.ResourceID, resource.Agent.AgentID, agentexec.HostStorageCleanupOperationPackageCache, output, result.Success, result.MutationStarted, result.Verification, beforeBound, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())}+func (e hostStorageCleanupActionExecutor) ReconcileActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {+ identity := operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}+ querier, ok := e.agents.(operationReceiptQuerier)+ if !ok {+ return nil, unified.ActionDispatchReceipt{}, false, nil+ }+ query, err := querier.QueryAgentOperation(ctx, attempt.AgentID, identity)+ if err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ if query.Status != operationreceipt.QueryFoundTerminal {+ return nil, unified.ActionDispatchReceipt{}, false, nil+ }+ if err := agentexec.ValidateOperationQueryResultForIdentity(query, identity, e.currentTime()); err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ result, err := agentexec.DecodeHostStorageCleanupResultPayload(query.Record.Result)+ if err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ req := agentexec.HostStorageCleanupPayload{RequestID: attempt.ID, ActionID: record.ID, Operation: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, ExpectedFingerprint: result.Before.Fingerprint}+ if err := agentexec.ValidateHostStorageCleanupResultForRequestAt(req, result, e.currentTime()); err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ output := fmt.Sprintf("APT package cache: %d bytes before, %d bytes after, %d bytes reclaimed", result.Before.ReclaimableBytes, result.After.ReclaimableBytes, result.ReclaimedBytes)+ execution, buildErr := hostAPTExecutionResult(record.Request.ResourceID, attempt.AgentID, attempt.OperationKind, output, result.Success, result.MutationStarted, result.Verification, true, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())+ if buildErr != nil {+ return nil, unified.ActionDispatchReceipt{}, false, buildErr+ }+ receipt := unified.ActionDispatchReceipt{AttemptID: attempt.ID, ActionID: record.ID, TransportRequestID: attempt.ID, ReceivedAt: e.currentTime()}+ return execution, receipt, true, 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")@@ -124,6 +178,9 @@ func (e hostStorageCleanupActionExecutor) validateResource(resource unified.Resoif !resource.Agent.CommandsEnabled {return fmt.Errorf("host command operations are disabled")}+ if resource.Agent.OperationReceiptVersion != operationreceipt.ProtocolVersion {+ return fmt.Errorf("durable operation receipt protocol is unsupported")+ }status := resource.Agent.StorageCleanupif status == nil || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" {return fmt.Errorf("host storage cleanup provider is unsupported")@@ -144,9 +201,13 @@ func (e hostStorageCleanupActionExecutor) validateResource(resource unified.Resoreturn fmt.Errorf("package cache filesystem is not under storage pressure")}agentID := strings.TrimSpace(resource.Agent.AgentID)+ liveCapability, supported := e.agents.(agentOperationReceiptCapability)if agentID == "" || e.agents == nil || !e.agents.IsAgentConnected(agentID) {return fmt.Errorf("host command agent is disconnected")}+ if !supported || liveCapability.AgentOperationReceiptVersion(agentID) != operationreceipt.ProtocolVersion {+ return fmt.Errorf("live durable operation receipt protocol is unsupported")+ }return nil}@@ -167,6 +228,8 @@ func hostStorageCleanupUnavailableReasonCode(err error) string {return "unsupported_resource"case strings.Contains(message, "disabled"):return "host_commands_disabled"+ case strings.Contains(message, "receipt protocol"):+ return "operation_receipt_unsupported"case strings.Contains(message, "unsupported"):return "unsupported_cleanup_provider"case strings.Contains(message, "inventory") && strings.Contains(message, "error"):@@ -192,6 +255,8 @@ func hostStorageCleanupUnavailableReason(err error) string {return "This resource is not an agent-managed host."case "host_commands_disabled":return "Typed host operations are disabled for this agent."+ case "operation_receipt_unsupported":+ return "This agent does not support durable typed-operation receipts."case "unsupported_cleanup_provider":return "This host does not expose a supported package-cache cleanup provider."case "cleanup_inventory_error":diff --git a/internal/api/host_storage_cleanup_action_executor_test.go b/internal/api/host_storage_cleanup_action_executor_test.goindex f392f48633..88d29caec5 100644--- a/internal/api/host_storage_cleanup_action_executor_test.go+++ b/internal/api/host_storage_cleanup_action_executor_test.go@@ -6,19 +6,23 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"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+ connected bool+ result *agentexec.HostStorageCleanupResultPayload+ err error+ agentID string+ requests []agentexec.HostStorageCleanupPayload+ receiptVersion int+ receiptVersionSet bool}var testHostStorageCleanupFingerprint = "sha256:" + strings.Repeat("c", 64)@@ -31,6 +35,29 @@ func (f *fakeHostStorageCleanupAgent) ExecuteHostStorageCleanup(_ context.Contex}func (f *fakeHostStorageCleanupAgent) IsAgentConnected(string) bool { return f.connected }+func (f *fakeHostStorageCleanupAgent) AgentOperationReceiptVersion(string) int {+ if f.receiptVersionSet {+ return f.receiptVersion+ }+ return operationreceipt.ProtocolVersion+}++func hostCleanupDispatchTestContext(t *testing.T, actionID string) context.Context {+ t.Helper()+ attempt, err := unified.NewActionDispatchAttempt(actionID, time.Now())+ if err != nil {+ t.Fatal(err)+ }+ req := agentexec.HostStorageCleanupPayload{RequestID: attempt.ID, ActionID: actionID, Operation: agentexec.HostStorageCleanupOperationPackageCache, ExpectedFingerprint: testHostStorageCleanupFingerprint}+ if err := agentexec.BindHostStorageCleanupPayload(&req); err != nil {+ t.Fatal(err)+ }+ attempt, err = unified.BindActionDispatchAttempt(attempt, unified.ActionDispatchBinding{OperationKind: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, AgentID: "agent-1"})+ if err != nil {+ t.Fatal(err)+ }+ return actionlifecycle.ContextWithCommittedDispatchAttempt(context.Background(), attempt)+}func TestHostStorageCleanupActionExecutorDispatchesFingerprintBoundOperation(t *testing.T) {now := time.Now().UTC()@@ -38,7 +65,7 @@ func TestHostStorageCleanupActionExecutorDispatchesFingerprintBoundOperation(t *h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{hostStorageCleanupActionResource(now)}})agents := verifiedHostStorageCleanupAgent()- result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(actionDispatchTestContext(t, "action-cleanup"), hostStorageCleanupActionRecord("action-cleanup"))+ result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(hostCleanupDispatchTestContext(t, "action-cleanup"), hostStorageCleanupActionRecord("action-cleanup"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -68,7 +95,7 @@ func TestHostStorageCleanupActionExecutorDoesNotExposeAgentErrorText(t *testing.Error: "private repository package path and token",}}- result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(actionDispatchTestContext(t, "action-cleanup"), hostStorageCleanupActionRecord("action-cleanup"))+ result, err := newHostStorageCleanupActionExecutor(h, agents).ExecuteAction(hostCleanupDispatchTestContext(t, "action-cleanup"), hostStorageCleanupActionRecord("action-cleanup"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -131,6 +158,8 @@ func TestHostStorageCleanupAvailabilityFailsClosed(t *testing.T) {reasonCode string}{{name: "commands disabled", mutate: func(r *unified.Resource) { r.Agent.CommandsEnabled = false }, connected: true, reasonCode: "host_commands_disabled"},+ {name: "missing receipt protocol", mutate: func(r *unified.Resource) { r.Agent.OperationReceiptVersion = 0 }, connected: true, reasonCode: "operation_receipt_unsupported"},+ {name: "future receipt protocol", mutate: func(r *unified.Resource) { r.Agent.OperationReceiptVersion = operationreceipt.ProtocolVersion + 1 }, connected: true, reasonCode: "operation_receipt_unsupported"},{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"},@@ -156,6 +185,18 @@ func TestHostStorageCleanupAvailabilityFailsClosed(t *testing.T) {}}+func TestHostCleanupSelfReportedReceiptSupportCannotBypassLiveServerVersion(t *testing.T) {+ now := time.Now().UTC()+ resource := hostStorageCleanupActionResource(now)+ for _, version := range []int{0, operationreceipt.ProtocolVersion + 1} {+ agents := &fakeHostStorageCleanupAgent{connected: true, receiptVersion: version, receiptVersionSet: true}+ readiness := hostStorageCleanupActionExecutor{agents: agents, now: func() time.Time { return now }}.CheckActionAvailable(context.Background(), unified.ActionRequest{CapabilityName: hostStorageCleanupCapability}, resource)+ if readiness.Available || readiness.ReasonCode != "operation_receipt_unsupported" {+ t.Fatalf("version=%d readiness=%#v", version, readiness)+ }+ }+}+func verifiedHostStorageCleanupAgent() *fakeHostStorageCleanupAgent {now := time.Now().UTC()return &fakeHostStorageCleanupAgent{connected: true, result: &agentexec.HostStorageCleanupResultPayload{@@ -173,7 +214,7 @@ func hostStorageCleanupActionResource(now time.Time) unified.Resource {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,+ AgentID: "agent-1", Platform: "linux", CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion,Disks: []unified.DiskInfo{{Mountpoint: "/", Usage: 95}},StorageCleanup: &unified.AgentStorageCleanupMeta{Supported: true, Provider: "apt-package-cache", Fingerprint: testHostStorageCleanupFingerprint, ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now, ObservedAt: now},},diff --git a/internal/api/host_update_action_executor.go b/internal/api/host_update_action_executor.goindex af7ffa945a..81ec711cc5 100644--- a/internal/api/host_update_action_executor.go+++ b/internal/api/host_update_action_executor.go@@ -9,6 +9,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -24,6 +25,23 @@ type hostUpdateAgentCommander interface {IsAgentConnected(agentID string) bool}+type operationReceiptQuerier interface {+ QueryAgentOperation(context.Context, string, operationreceipt.Identity) (operationreceipt.QueryResult, error)+}+type agentOperationReceiptCapability interface{ AgentOperationReceiptVersion(string) int }++func (e hostUpdateActionExecutor) BindActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {+ resource, err := e.currentResource(ctx, record.Request.ResourceID)+ if err != nil {+ return unified.ActionDispatchAttempt{}, err+ }+ req := agentexec.HostUpdatePayload{RequestID: attempt.ID, ActionID: record.ID, Operation: agentexec.HostUpdateOperationInstall, ExpectedInventoryHash: resource.Agent.PackageUpdates.InventoryHash}+ if err := agentexec.BindHostUpdatePayload(&req); err != nil {+ return unified.ActionDispatchAttempt{}, err+ }+ return unified.BindActionDispatchAttempt(attempt, unified.ActionDispatchBinding{OperationKind: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, AgentID: resource.Agent.AgentID})+}+type hostUpdateActionExecutor struct {resources *ResourceHandlersagents hostUpdateAgentCommander@@ -77,13 +95,20 @@ func (e hostUpdateActionExecutor) ExecuteAction(ctx context.Context, record unifreturn nil, err}agentID := strings.TrimSpace(resource.Agent.AgentID)- result, err := e.agents.ExecuteHostUpdate(ctx, agentID, agentexec.HostUpdatePayload{+ req := agentexec.HostUpdatePayload{RequestID: attempt.ID,ActionID: record.ID,Operation: agentexec.HostUpdateOperationInstall,ExpectedInventoryHash: resource.Agent.PackageUpdates.InventoryHash,Timeout: 900,- })+ }+ if err := agentexec.BindHostUpdatePayload(&req); err != nil {+ return nil, err+ }+ if agentexec.HostUpdateOperationIdentity(agentID, req) != (operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}) {+ return nil, fmt.Errorf("host update dispatch binding drift")+ }+ result, err := e.agents.ExecuteHostUpdate(ctx, agentID, req)if err != nil {return nil, err}@@ -96,6 +121,39 @@ func (e hostUpdateActionExecutor) ExecuteAction(ctx context.Context, record unifreturn hostAPTExecutionResult(record.Request.ResourceID, agentID, agentexec.HostUpdateOperationInstall, output, result.Success, result.MutationStarted, result.Verification, beforeBound, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())}+func (e hostUpdateActionExecutor) ReconcileActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {+ identity := operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}+ querier, ok := e.agents.(operationReceiptQuerier)+ if !ok {+ return nil, unified.ActionDispatchReceipt{}, false, nil+ }+ query, err := querier.QueryAgentOperation(ctx, attempt.AgentID, identity)+ if err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ if query.Status != operationreceipt.QueryFoundTerminal {+ return nil, unified.ActionDispatchReceipt{}, false, nil+ }+ if err := agentexec.ValidateOperationQueryResultForIdentity(query, identity, e.currentTime()); err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ result, err := agentexec.DecodeHostUpdateResultPayload(query.Record.Result)+ if err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ req := agentexec.HostUpdatePayload{RequestID: attempt.ID, ActionID: record.ID, Operation: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, ExpectedInventoryHash: result.Before.InventoryHash}+ if err := agentexec.ValidateHostUpdateResultForRequestAt(req, result, e.currentTime()); err != nil {+ return nil, unified.ActionDispatchReceipt{}, false, err+ }+ output := fmt.Sprintf("APT package updates: %d pending before, %d pending after; reboot required: %t", result.Before.PendingCount, result.After.PendingCount, result.After.RebootRequired)+ execution, buildErr := hostAPTExecutionResult(record.Request.ResourceID, attempt.AgentID, attempt.OperationKind, output, result.Success, result.MutationStarted, result.Verification, true, result.Before.CheckedAt, result.After.CheckedAt, e.currentTime())+ if buildErr != nil {+ return nil, unified.ActionDispatchReceipt{}, false, buildErr+ }+ receipt := unified.ActionDispatchReceipt{AttemptID: attempt.ID, ActionID: record.ID, TransportRequestID: attempt.ID, ReceivedAt: e.currentTime()}+ return execution, receipt, true, nil+}+func (e hostUpdateActionExecutor) currentResource(ctx context.Context, resourceID string) (unified.Resource, error) {if e.resources == nil {return unified.Resource{}, fmt.Errorf("resource handler unavailable")@@ -125,6 +183,9 @@ func (e hostUpdateActionExecutor) validateResource(resource unified.Resource) erif !resource.Agent.CommandsEnabled {return fmt.Errorf("host command operations are disabled")}+ if resource.Agent.OperationReceiptVersion != operationreceipt.ProtocolVersion {+ return fmt.Errorf("durable operation receipt protocol is unsupported")+ }status := resource.Agent.PackageUpdatesif status == nil || !status.Supported || strings.TrimSpace(status.Manager) != "apt" {return fmt.Errorf("host package manager is unsupported")@@ -142,9 +203,13 @@ func (e hostUpdateActionExecutor) validateResource(resource unified.Resource) erreturn fmt.Errorf("host has no pending package updates")}agentID := strings.TrimSpace(resource.Agent.AgentID)+ liveCapability, supported := e.agents.(agentOperationReceiptCapability)if agentID == "" || e.agents == nil || !e.agents.IsAgentConnected(agentID) {return fmt.Errorf("host command agent is disconnected")}+ if !supported || liveCapability.AgentOperationReceiptVersion(agentID) != operationreceipt.ProtocolVersion {+ return fmt.Errorf("live durable operation receipt protocol is unsupported")+ }return nil}@@ -165,6 +230,8 @@ func hostUpdateUnavailableReasonCode(err error) string {return "unsupported_resource"case strings.Contains(message, "disabled"):return "host_commands_disabled"+ case strings.Contains(message, "receipt protocol"):+ return "operation_receipt_unsupported"case strings.Contains(message, "unsupported"):return "unsupported_package_manager"case strings.Contains(message, "inventory") && strings.Contains(message, "error"):@@ -188,6 +255,8 @@ func hostUpdateUnavailableReason(err error) string {return "This resource is not an agent-managed host."case "host_commands_disabled":return "Typed host operations are disabled for this agent."+ case "operation_receipt_unsupported":+ return "This agent does not support durable typed-operation receipts."case "unsupported_package_manager":return "This host does not expose a supported package manager."case "package_inventory_error":diff --git a/internal/api/host_update_action_executor_test.go b/internal/api/host_update_action_executor_test.goindex 6e634402bc..ee4064b97a 100644--- a/internal/api/host_update_action_executor_test.go+++ b/internal/api/host_update_action_executor_test.go@@ -6,19 +6,23 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts")type fakeHostUpdateAgent struct {- connected bool- result *agentexec.HostUpdateResultPayload- err error- agentID string- requests []agentexec.HostUpdatePayload+ connected bool+ result *agentexec.HostUpdateResultPayload+ err error+ agentID string+ requests []agentexec.HostUpdatePayload+ receiptVersion int+ receiptVersionSet bool}var testHostPackageInventoryHash = "sha256:" + strings.Repeat("a", 64)@@ -31,6 +35,29 @@ func (f *fakeHostUpdateAgent) ExecuteHostUpdate(_ context.Context, agentID strin}func (f *fakeHostUpdateAgent) IsAgentConnected(string) bool { return f.connected }+func (f *fakeHostUpdateAgent) AgentOperationReceiptVersion(string) int {+ if f.receiptVersionSet {+ return f.receiptVersion+ }+ return operationreceipt.ProtocolVersion+}++func hostUpdateDispatchTestContext(t *testing.T, actionID string) context.Context {+ t.Helper()+ attempt, err := unified.NewActionDispatchAttempt(actionID, time.Now())+ if err != nil {+ t.Fatal(err)+ }+ req := agentexec.HostUpdatePayload{RequestID: attempt.ID, ActionID: actionID, Operation: agentexec.HostUpdateOperationInstall, ExpectedInventoryHash: testHostPackageInventoryHash}+ if err := agentexec.BindHostUpdatePayload(&req); err != nil {+ t.Fatal(err)+ }+ attempt, err = unified.BindActionDispatchAttempt(attempt, unified.ActionDispatchBinding{OperationKind: req.Operation, OperationVersion: req.OperationVersion, RequestDigest: req.RequestDigest, AgentID: "agent-1"})+ if err != nil {+ t.Fatal(err)+ }+ return actionlifecycle.ContextWithCommittedDispatchAttempt(context.Background(), attempt)+}func TestHostUpdateActionExecutorDispatchesTypedOperationAndProjectsVerification(t *testing.T) {now := time.Now().UTC()@@ -48,7 +75,7 @@ func TestHostUpdateActionExecutorDispatchesTypedOperationAndProjectsVerification}}executor := newHostUpdateActionExecutor(h, agents)- result, err := executor.ExecuteAction(actionDispatchTestContext(t, "action-host-update"), hostUpdateActionRecord("action-host-update"))+ result, err := executor.ExecuteAction(hostUpdateDispatchTestContext(t, "action-host-update"), hostUpdateActionRecord("action-host-update"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -79,7 +106,7 @@ func TestHostUpdateActionExecutorReportsInconclusiveVerificationHonestly(t *testError: "package installation completed but verification was inconclusive",}}- result, err := newHostUpdateActionExecutor(h, agents).ExecuteAction(actionDispatchTestContext(t, "action-host-update"), hostUpdateActionRecord("action-host-update"))+ result, err := newHostUpdateActionExecutor(h, agents).ExecuteAction(hostUpdateDispatchTestContext(t, "action-host-update"), hostUpdateActionRecord("action-host-update"))if err != nil {t.Fatalf("ExecuteAction: %v", err)}@@ -146,6 +173,8 @@ func TestHostUpdateActionAvailabilityFailsClosed(t *testing.T) {reasonCode string}{{name: "commands disabled", mutate: func(r *unified.Resource) { r.Agent.CommandsEnabled = false }, connected: true, reasonCode: "host_commands_disabled"},+ {name: "missing receipt protocol", mutate: func(r *unified.Resource) { r.Agent.OperationReceiptVersion = 0 }, connected: true, reasonCode: "operation_receipt_unsupported"},+ {name: "future receipt protocol", mutate: func(r *unified.Resource) { r.Agent.OperationReceiptVersion = operationreceipt.ProtocolVersion + 1 }, connected: true, reasonCode: "operation_receipt_unsupported"},{name: "stale inventory", mutate: func(r *unified.Resource) { r.Agent.PackageUpdates.CheckedAt = now.Add(-time.Hour) }, connected: true, reasonCode: "stale_package_inventory"},{name: "inventory error", mutate: func(r *unified.Resource) { r.Agent.PackageUpdates.Error = "inspection failed" }, connected: true, reasonCode: "package_inventory_error"},{name: "invalid inventory fingerprint", mutate: func(r *unified.Resource) { r.Agent.PackageUpdates.InventoryHash = "sha256:bad" }, connected: true, reasonCode: "invalid_package_inventory"},@@ -165,6 +194,53 @@ func TestHostUpdateActionAvailabilityFailsClosed(t *testing.T) {}}+func TestHostUpdateCompatibleProposalRefusesLiveAgentDowngradeBeforeExecuting(t *testing.T) {+ now := time.Now().UTC()+ resource := hostUpdateActionResource(now)+ resource.Capabilities[0].MinimumApprovalLevel = unified.ApprovalNone+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})+ h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{resource}})+ agents := &fakeHostUpdateAgent{connected: true}+ h.SetActionExecutor(newRoutedActionExecutor(h, newHostUpdateActionExecutor(h, agents)))+ service := h.ActionLifecycle()+ actor := unified.ActionActor{SubjectID: "requester", Kind: unified.ActionActorService, CredentialID: "service:test", OrgID: "default"}+ plan, err := service.Plan(context.Background(), "default", unified.ActionRequest{RequestID: "downgrade", ResourceID: resource.ID, CapabilityName: hostPackageUpdateCapability, Reason: "test", RequestedBy: "requester", Actor: actor}, actor)+ if err != nil {+ t.Fatal(err)+ }+ agents.receiptVersionSet = true+ agents.receiptVersion = 0+ if _, err := service.Execute(context.Background(), "default", plan.ActionID, actor, "downgrade"); err == nil {+ t.Fatal("downgraded agent executed")+ }+ store, err := h.getStore("default")+ if err != nil {+ t.Fatal(err)+ }+ audit, found, err := store.GetActionAudit(plan.ActionID)+ if err != nil || !found || audit.State == unified.ActionStateExecuting {+ t.Fatalf("audit=%#v found=%v err=%v", audit, found, err)+ }+ if _, found, err := store.GetActionDispatchAttempt(plan.ActionID); err != nil || found {+ t.Fatalf("dispatch found=%v err=%v", found, err)+ }+ if len(agents.requests) != 0 {+ t.Fatalf("requests=%#v", agents.requests)+ }+}++func TestHostUpdateSelfReportedReceiptSupportCannotBypassLiveServerVersion(t *testing.T) {+ now := time.Now().UTC()+ resource := hostUpdateActionResource(now)+ for _, version := range []int{0, operationreceipt.ProtocolVersion + 1} {+ agents := &fakeHostUpdateAgent{connected: true, receiptVersion: version, receiptVersionSet: true}+ readiness := hostUpdateActionExecutor{agents: agents, now: func() time.Time { return now }}.CheckActionAvailable(context.Background(), unified.ActionRequest{CapabilityName: hostPackageUpdateCapability}, resource)+ if readiness.Available || readiness.ReasonCode != "operation_receipt_unsupported" {+ t.Fatalf("version=%d readiness=%#v", version, readiness)+ }+ }+}+func hostUpdateActionResource(now time.Time) unified.Resource {return unified.Resource{ID: "agent:host-1", Type: unified.ResourceTypeAgent, Technology: "linux", Name: "host-1",@@ -172,7 +248,7 @@ func hostUpdateActionResource(now time.Time) unified.Resource {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,+ AgentID: "agent-1", Platform: "linux", CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion,PackageUpdates: &unified.AgentPackageUpdateMeta{Supported: true, Manager: "apt", InventoryHash: testHostPackageInventoryHash, PendingCount: 3, CheckedAt: now, ObservedAt: now},},Capabilities: []unified.ResourceCapability{{diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex edcbb85a8f..9b3c9d546f 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -548,6 +548,15 @@ func (a *Agent) signalRemoteConfigChanged() {}}+func (a *Agent) currentOperationReceiptVersion() int {+ a.commandClientMu.Lock()+ defer a.commandClientMu.Unlock()+ if a.commandClient == nil {+ return 0+ }+ return a.commandClient.operationReceiptVersion()+}+func (a *Agent) startCommandClient(client *CommandClient) bool {if client == nil {return false@@ -855,17 +864,18 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {report := agentshost.Report{Agent: agentshost.AgentInfo{- ID: a.agentID,- Version: a.agentVersion,- Type: runtimeConfig.agentType,- IntervalSeconds: int(runtimeConfig.interval / time.Second),- Hostname: a.hostname,- UpdatedFrom: updatedFrom,- CommandsEnabled: runtimeConfig.commandsEnabled,- DiskExclude: append([]string(nil), runtimeConfig.diskExclude...),- AppliedConfig: runtimeConfig.appliedConfig,- Update: a.currentUpdateStatus(),- Modules: a.currentModuleStatus(),+ ID: a.agentID,+ Version: a.agentVersion,+ Type: runtimeConfig.agentType,+ IntervalSeconds: int(runtimeConfig.interval / time.Second),+ Hostname: a.hostname,+ UpdatedFrom: updatedFrom,+ CommandsEnabled: runtimeConfig.commandsEnabled,+ OperationReceiptVersion: a.currentOperationReceiptVersion(),+ DiskExclude: append([]string(nil), runtimeConfig.diskExclude...),+ AppliedConfig: runtimeConfig.appliedConfig,+ Update: a.currentUpdateStatus(),+ Modules: a.currentModuleStatus(),},Host: agentshost.HostInfo{ID: a.machineID,diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.goindex c43bdaea2e..3f47ff1c6d 100644--- a/internal/hostagent/commands.go+++ b/internal/hostagent/commands.go@@ -23,6 +23,7 @@ import ("github.com/prometheus/client_golang/prometheus/promauto""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/agenttls"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rcourtman/pulse-go-rewrite/internal/securityutil"sshknownhosts "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts""github.com/rcourtman/pulse-go-rewrite/internal/utils"@@ -92,24 +93,28 @@ func (b *cappedBuffer) String() string {// CommandClient handles WebSocket connection to Pulse for AI command executiontype CommandClient struct {- pulseURL string- apiToken string- agentID string- hostname string- platform string- version string- stateDir string- insecureSkipVerify bool- caCertPath string- serverFingerprint string- deploySSHUser string- commandPolicy *agentexec.CommandPolicy- packageUpdates *packageUpdateManager- storageCleanup *storageCleanupManager- sshKnownHosts sshknownhosts.Manager- sshKnownHostsOnce sync.Once- sshKnownHostsErr error- logger zerolog.Logger+ pulseURL string+ apiToken string+ agentID string+ hostname string+ platform string+ version string+ stateDir string+ insecureSkipVerify bool+ caCertPath string+ serverFingerprint string+ deploySSHUser string+ commandPolicy *agentexec.CommandPolicy+ packageUpdates *packageUpdateManager+ storageCleanup *storageCleanupManager+ operationReceipts *operationreceipt.Store+ operationReceiptErr error+ operationReceiptCloseOnce sync.Once+ operationReceiptCloseErr error+ sshKnownHosts sshknownhosts.Manager+ sshKnownHostsOnce sync.Once+ sshKnownHostsErr error+ logger zerolog.Loggerconn *websocket.ConnconnMu sync.Mutex@@ -124,23 +129,26 @@ func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *stateDir = defaultStateDir}+ receipts, receiptErr := operationreceipt.Open(filepath.Join(stateDir, "operation-receipts.db"), hostOperationReceiptConfig())return &CommandClient{- pulseURL: strings.TrimRight(cfg.PulseURL, "/"),- apiToken: cfg.APIToken,- agentID: agentID,- hostname: hostname,- platform: platform,- version: version,- stateDir: stateDir,- insecureSkipVerify: cfg.InsecureSkipVerify,- caCertPath: cfg.CACertPath,- serverFingerprint: cfg.ServerFingerprint,- deploySSHUser: cfg.DeploySSHUser,- commandPolicy: agentexec.DefaultPolicy(),- packageUpdates: cfg.packageUpdates,- storageCleanup: cfg.storageCleanup,- logger: logger,- done: make(chan struct{}),+ pulseURL: strings.TrimRight(cfg.PulseURL, "/"),+ apiToken: cfg.APIToken,+ agentID: agentID,+ hostname: hostname,+ platform: platform,+ version: version,+ stateDir: stateDir,+ insecureSkipVerify: cfg.InsecureSkipVerify,+ caCertPath: cfg.CACertPath,+ serverFingerprint: cfg.ServerFingerprint,+ deploySSHUser: cfg.DeploySSHUser,+ commandPolicy: agentexec.DefaultPolicy(),+ packageUpdates: cfg.packageUpdates,+ storageCleanup: cfg.storageCleanup,+ operationReceipts: receipts,+ operationReceiptErr: receiptErr,+ logger: logger,+ done: make(chan struct{}),}}@@ -170,6 +178,8 @@ const (msgTypeHostStorageCleanupResult messageType = "host_storage_cleanup_result"msgTypeHostUpdate messageType = "host_update"msgTypeHostUpdateResult messageType = "host_update_result"+ msgTypeOperationQuery messageType = "agent_operation_query"+ msgTypeOperationQueryResult messageType = "agent_operation_query_result"msgTypeDeployPreflight messageType = "deploy_preflight"msgTypeDeployInstall messageType = "deploy_install"msgTypeDeployCancel messageType = "deploy_cancel"@@ -184,12 +194,13 @@ type wsMessage struct {}type registerPayload struct {- AgentID string `json:"agent_id"`- Hostname string `json:"hostname"`- Version string `json:"version"`- Platform string `json:"platform"`- Tags []string `json:"tags,omitempty"`- Token string `json:"token"`+ AgentID string `json:"agent_id"`+ Hostname string `json:"hostname"`+ Version string `json:"version"`+ Platform string `json:"platform"`+ Tags []string `json:"tags,omitempty"`+ Token string `json:"token"`+ OperationReceiptVersion int `json:"operation_receipt_version,omitempty"`}type registeredPayload struct {@@ -409,11 +420,12 @@ func (c *CommandClient) buildWebSocketOrigin() (string, error) {func (c *CommandClient) sendRegistration(conn *websocket.Conn) error {payload, err := json.Marshal(registerPayload{- AgentID: c.agentID,- Hostname: c.hostname,- Version: c.version,- Platform: c.platform,- Token: c.apiToken,+ AgentID: c.agentID,+ Hostname: c.hostname,+ Version: c.version,+ Platform: c.platform,+ Token: c.apiToken,+ OperationReceiptVersion: c.operationReceiptVersion(),})if err != nil {return fmt.Errorf("marshal registration payload: %w", err)@@ -428,6 +440,13 @@ func (c *CommandClient) sendRegistration(conn *websocket.Conn) error {return conn.WriteJSON(msg)}+func (c *CommandClient) operationReceiptVersion() int {+ if c != nil && c.operationReceiptErr == nil && c.operationReceipts != nil {+ return operationreceipt.ProtocolVersion+ }+ return 0+}+func (c *CommandClient) waitForRegistration(conn *websocket.Conn) error {if err := conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {return fmt.Errorf("set registration read deadline: %w", err)@@ -544,6 +563,14 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn}go c.handleHostStorageCleanup(ctx, conn, payload)+ case msgTypeOperationQuery:+ query, err := operationreceipt.DecodeQuery(msg.Payload)+ if err != nil {+ c.logger.Warn().Err(err).Msg("Rejected malformed operation receipt query")+ continue+ }+ go c.handleOperationQuery(conn, msg.ID, query)+case msgTypeDeployPreflight:var payload deployPreflightPayloadif err := json.Unmarshal(msg.Payload, &payload); err != nil {@@ -575,6 +602,22 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn}func (c *CommandClient) handleHostUpdate(ctx context.Context, conn *websocket.Conn, payload agentexec.HostUpdatePayload) {+ identity := agentexec.HostUpdateOperationIdentity(c.agentID, payload)+ record, admitted, err := c.admitOperation(identity)+ if err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Host update durable admission refused")+ return+ }+ if !admitted {+ if record.State == operationreceipt.StateTerminal {+ c.replayHostUpdate(conn, record)+ }+ return+ }+ if _, err := c.operationReceipts.MarkStarted(identity); err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Host update durable start refused")+ return+ }timeout := time.Duration(payload.Timeout) * time.Secondif timeout <= 0 {timeout = 15 * time.Minute@@ -591,6 +634,15 @@ func (c *CommandClient) handleHostUpdate(ctx context.Context, conn *websocket.Co} else {result = c.packageUpdates.Apply(updateCtx, payload)}+ result = sanitizeHostUpdateReceipt(result)+ encoded, err := json.Marshal(result)+ if err != nil {+ return+ }+ if _, err := c.operationReceipts.Complete(identity, operationreceipt.TerminalEnvelope{Kind: agentexec.HostUpdateReceiptKind, Version: agentexec.HostAPTReceiptVersion, Payload: encoded}); err != nil {+ c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to persist host update terminal receipt")+ return+ }c.sendHostUpdateResult(conn, result)}@@ -615,6 +667,22 @@ func (c *CommandClient) sendHostUpdateResult(conn *websocket.Conn, result agente}func (c *CommandClient) handleHostStorageCleanup(ctx context.Context, conn *websocket.Conn, payload agentexec.HostStorageCleanupPayload) {+ identity := agentexec.HostStorageCleanupOperationIdentity(c.agentID, payload)+ record, admitted, err := c.admitOperation(identity)+ if err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Host cleanup durable admission refused")+ return+ }+ if !admitted {+ if record.State == operationreceipt.StateTerminal {+ c.replayHostStorageCleanup(conn, record)+ }+ return+ }+ if _, err := c.operationReceipts.MarkStarted(identity); err != nil {+ c.logger.Warn().Err(err).Str("request_id", payload.RequestID).Msg("Host cleanup durable start refused")+ return+ }timeout := time.Duration(payload.Timeout) * time.Secondif timeout <= 0 {timeout = 5 * time.Minute@@ -631,9 +699,121 @@ func (c *CommandClient) handleHostStorageCleanup(ctx context.Context, conn *webs} else {result = c.storageCleanup.Apply(cleanupCtx, payload)}+ result = sanitizeHostStorageCleanupReceipt(result)+ encoded, err := json.Marshal(result)+ if err != nil {+ return+ }+ if _, err := c.operationReceipts.Complete(identity, operationreceipt.TerminalEnvelope{Kind: agentexec.HostStorageCleanupReceiptKind, Version: agentexec.HostAPTReceiptVersion, Payload: encoded}); err != nil {+ c.logger.Error().Err(err).Str("request_id", payload.RequestID).Msg("Failed to persist host cleanup terminal receipt")+ return+ }c.sendHostStorageCleanupResult(conn, result)}+func (c *CommandClient) admitOperation(identity operationreceipt.Identity) (operationreceipt.Record, bool, error) {+ if c.operationReceiptErr != nil {+ return operationreceipt.Record{}, false, c.operationReceiptErr+ }+ if c.operationReceipts == nil {+ return operationreceipt.Record{}, false, fmt.Errorf("operation receipt store unavailable")+ }+ return c.operationReceipts.Admit(identity)+}++func (c *CommandClient) handleOperationQuery(conn *websocket.Conn, correlationID string, query operationreceipt.Query) {+ var result operationreceipt.QueryResult+ var err error+ if query.Identity.AgentID != c.agentID {+ err = operationreceipt.ErrBindingConflict+ } else if c.operationReceiptErr != nil {+ err = c.operationReceiptErr+ } else if c.operationReceipts == nil {+ err = fmt.Errorf("operation receipt store unavailable")+ } else {+ result, err = c.operationReceipts.Query(query.Identity)+ }+ if err != nil {+ c.logger.Warn().Err(err).Str("request_id", query.Identity.AttemptID).Msg("Operation receipt query refused")+ return+ }+ encoded, err := json.Marshal(result)+ if err != nil {+ return+ }+ msg := wsMessage{Type: msgTypeOperationQueryResult, ID: strings.TrimSpace(correlationID), Timestamp: time.Now(), Payload: encoded}+ c.connMu.Lock()+ err = conn.WriteJSON(msg)+ c.connMu.Unlock()+ if err != nil {+ c.logger.Debug().Err(err).Str("request_id", query.Identity.AttemptID).Msg("Failed to send operation receipt query result")+ }+}++func (c *CommandClient) replayHostUpdate(conn *websocket.Conn, record operationreceipt.Record) {+ var result agentexec.HostUpdateResultPayload+ if err := json.Unmarshal(record.Result, &result); err == nil {+ c.sendHostUpdateResult(conn, result)+ }+}++func (c *CommandClient) replayHostStorageCleanup(conn *websocket.Conn, record operationreceipt.Record) {+ var result agentexec.HostStorageCleanupResultPayload+ if err := json.Unmarshal(record.Result, &result); err == nil {+ c.sendHostStorageCleanupResult(conn, result)+ }+}++func sanitizeHostUpdateReceipt(result agentexec.HostUpdateResultPayload) agentexec.HostUpdateResultPayload {+ result.Before.Packages, result.After.Packages = nil, nil+ result.Before.Error, result.After.Error = "", ""+ if result.Error != "" {+ result.Error = "typed host update did not complete"+ }+ return result+}++func sanitizeHostStorageCleanupReceipt(result agentexec.HostStorageCleanupResultPayload) agentexec.HostStorageCleanupResultPayload {+ result.Before.Error, result.After.Error = "", ""+ if result.Error != "" {+ result.Error = "typed host cleanup did not complete"+ }+ return result+}++func hostOperationReceiptConfig() operationreceipt.Config {+ return operationreceipt.Config{Validators: map[string]map[int]operationreceipt.TerminalValidator{+ agentexec.HostUpdateReceiptKind: {agentexec.HostAPTReceiptVersion: func(identity operationreceipt.Identity, payload json.RawMessage) error {+ result, err := agentexec.DecodeHostUpdateResultPayload(payload)+ if err != nil {+ return err+ }+ if len(result.Before.Packages) > 0 || len(result.After.Packages) > 0 || result.Before.Error != "" || result.After.Error != "" {+ return fmt.Errorf("host update receipt contains non-persistable detail")+ }+ req := agentexec.HostUpdatePayload{RequestID: identity.AttemptID, ActionID: identity.ActionID, Operation: identity.OperationKind, OperationVersion: identity.OperationVersion, RequestDigest: identity.RequestDigest, ExpectedInventoryHash: result.Before.InventoryHash}+ if err := agentexec.ValidateHostUpdatePayload(&req); err != nil {+ return err+ }+ return agentexec.ValidateHostUpdateResultForRequest(req, result)+ }},+ agentexec.HostStorageCleanupReceiptKind: {agentexec.HostAPTReceiptVersion: func(identity operationreceipt.Identity, payload json.RawMessage) error {+ result, err := agentexec.DecodeHostStorageCleanupResultPayload(payload)+ if err != nil {+ return err+ }+ if result.Before.Error != "" || result.After.Error != "" {+ return fmt.Errorf("host cleanup receipt contains non-persistable detail")+ }+ req := agentexec.HostStorageCleanupPayload{RequestID: identity.AttemptID, ActionID: identity.ActionID, Operation: identity.OperationKind, OperationVersion: identity.OperationVersion, RequestDigest: identity.RequestDigest, ExpectedFingerprint: result.Before.Fingerprint}+ if err := agentexec.ValidateHostStorageCleanupPayload(&req); err != nil {+ return err+ }+ return agentexec.ValidateHostStorageCleanupResultForRequest(req, result)+ }},+ }}+}+func (c *CommandClient) sendHostStorageCleanupResult(conn *websocket.Conn, result agentexec.HostStorageCleanupResultPayload) {encoded, err := json.Marshal(result)if err != nil {@@ -894,10 +1074,18 @@ func (c *CommandClient) Close() error {close(c.done)}+ var closeErr errorif c.conn != nil {- err := c.conn.Close()+ closeErr = c.conn.Close()c.conn = nil- return err}- return nil+ c.operationReceiptCloseOnce.Do(func() {+ if c.operationReceipts != nil {+ c.operationReceiptCloseErr = c.operationReceipts.Close()+ }+ })+ if closeErr != nil {+ return closeErr+ }+ return c.operationReceiptCloseErr}diff --git a/internal/hostagent/commands_host_update_test.go b/internal/hostagent/commands_host_update_test.goindex 6e6b5a937d..df87988ac4 100644--- a/internal/hostagent/commands_host_update_test.go+++ b/internal/hostagent/commands_host_update_test.go@@ -6,12 +6,14 @@ import ("net/http""net/http/httptest""os"+ "path/filepath""strings""testing""time""github.com/gorilla/websocket""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rs/zerolog")@@ -20,6 +22,7 @@ func TestCommandClientHandlesTypedHostUpdateWithoutExecuteCommand(t *testing.T)manager.lookPath = func(string) (string, error) { return "/usr/bin/apt-get", nil }manager.stat = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }simulations := 0+ mutations := 0manager.run = func(_ context.Context, _ []string, name string, args ...string) packageUpdateCommandResult {if name != "apt-get" {t.Fatalf("executable = %q, want apt-get", name)@@ -29,7 +32,9 @@ func TestCommandClientHandlesTypedHostUpdateWithoutExecuteCommand(t *testing.T)if simulations <= 2 {return packageUpdateCommandResult{stdout: "Inst openssl [1.0] (1.1 repo [amd64])\n"}}+ return packageUpdateCommandResult{}}+ mutations++return packageUpdateCommandResult{}}expectedInventoryHash := aptUpgradeInventoryHash("Inst openssl [1.0] (1.1 repo [amd64])\n")@@ -53,9 +58,14 @@ func TestCommandClientHandlesTypedHostUpdateWithoutExecuteCommand(t *testing.T)t.Errorf("write registered: %v", err)return}- payload, _ := json.Marshal(agentexec.HostUpdatePayload{+ request := agentexec.HostUpdatePayload{RequestID: "request-1", ActionID: "action-1", Operation: agentexec.HostUpdateOperationInstall, ExpectedInventoryHash: expectedInventoryHash, Timeout: 5,- })+ }+ if err := agentexec.BindHostUpdatePayload(&request); err != nil {+ t.Errorf("bind request: %v", err)+ return+ }+ payload, _ := json.Marshal(request)if err := conn.WriteJSON(wsMessage{Type: msgTypeHostUpdate, ID: "request-1", Timestamp: time.Now(), Payload: payload}); err != nil {t.Errorf("write host update: %v", err)return@@ -75,13 +85,31 @@ func TestCommandClientHandlesTypedHostUpdateWithoutExecuteCommand(t *testing.T)return}resultCh <- result+ if err := conn.WriteJSON(wsMessage{Type: msgTypeHostUpdate, ID: "request-1", Timestamp: time.Now(), Payload: payload}); err != nil {+ t.Errorf("write duplicate: %v", err)+ return+ }+ if err := conn.ReadJSON(&response); err != nil {+ t.Errorf("read duplicate result: %v", err)+ return+ }+ if response.Type != msgTypeHostUpdateResult {+ t.Errorf("duplicate response type=%q", response.Type)+ return+ }+ resultCh <- result}))defer server.Close()ctx, cancel := context.WithCancel(context.Background())+ receipts, err := operationreceipt.Open(filepath.Join(t.TempDir(), "receipts.db"), hostOperationReceiptConfig())+ if err != nil {+ t.Fatal(err)+ }+ defer receipts.Close()client := &CommandClient{pulseURL: strings.TrimRight(server.URL, "/"), apiToken: "token", agentID: "agent-1", hostname: "host-1",- platform: "linux", version: "6.0.6", packageUpdates: manager, logger: zerolog.Nop(), done: make(chan struct{}),+ platform: "linux", version: "6.0.6", packageUpdates: manager, operationReceipts: receipts, logger: zerolog.Nop(), done: make(chan struct{}),}errCh := make(chan error, 1)go func() { errCh <- client.connectAndHandle(ctx) }()@@ -91,6 +119,14 @@ func TestCommandClientHandlesTypedHostUpdateWithoutExecuteCommand(t *testing.T)if !result.Success || result.Verification != agentexec.HostUpdateVerificationVerified || result.Before.PendingCount != 1 || result.After.PendingCount != 0 {t.Fatalf("result = %#v", result)}+ select {+ case <-resultCh:+ case <-time.After(5 * time.Second):+ t.Fatal("timed out waiting for durable duplicate replay")+ }+ if mutations != 2 {+ t.Fatalf("package-manager mutation calls=%d, want one update/install workflow", mutations)+ }cancel()case <-time.After(10 * time.Second):cancel()diff --git a/internal/hostagent/commands_storage_cleanup_test.go b/internal/hostagent/commands_storage_cleanup_test.goindex d1dcb576d4..1072d3e12a 100644--- a/internal/hostagent/commands_storage_cleanup_test.go+++ b/internal/hostagent/commands_storage_cleanup_test.go@@ -5,12 +5,14 @@ import ("encoding/json""net/http""net/http/httptest"+ "path/filepath""strings""testing""time""github.com/gorilla/websocket""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rs/zerolog")@@ -51,9 +53,14 @@ func TestCommandClientHandlesTypedHostStorageCleanup(t *testing.T) {t.Errorf("write registered: %v", err)return}- payload, _ := json.Marshal(agentexec.HostStorageCleanupPayload{+ request := agentexec.HostStorageCleanupPayload{RequestID: "cleanup-1", ActionID: "action-1", Operation: agentexec.HostStorageCleanupOperationPackageCache, ExpectedFingerprint: before.Fingerprint, Timeout: 5,- })+ }+ if err := agentexec.BindHostStorageCleanupPayload(&request); err != nil {+ t.Errorf("bind request: %v", err)+ return+ }+ payload, _ := json.Marshal(request)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@@ -77,9 +84,14 @@ func TestCommandClientHandlesTypedHostStorageCleanup(t *testing.T) {defer server.Close()ctx, cancel := context.WithCancel(context.Background())+ receipts, err := operationreceipt.Open(filepath.Join(t.TempDir(), "receipts.db"), hostOperationReceiptConfig())+ if err != nil {+ t.Fatal(err)+ }+ defer receipts.Close()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{}),+ platform: "linux", version: "6.0.6", storageCleanup: manager, operationReceipts: receipts, logger: zerolog.Nop(), done: make(chan struct{}),}errCh := make(chan error, 1)go func() { errCh <- client.connectAndHandle(ctx) }()diff --git a/internal/hostagent/operation_receipt_failure_test.go b/internal/hostagent/operation_receipt_failure_test.gonew file mode 100644index 0000000000..f924839ea4--- /dev/null+++ b/internal/hostagent/operation_receipt_failure_test.go@@ -0,0 +1,28 @@+package hostagent++import (+ "context"+ "errors"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rs/zerolog"+)++func TestHostUpdateStoreFailurePrecedesPackageManagerMutation(t *testing.T) {+ manager := newPackageUpdateManager("linux", newPackageManagerLease())+ calls := 0+ manager.run = func(context.Context, []string, string, ...string) packageUpdateCommandResult {+ calls+++ return packageUpdateCommandResult{}+ }+ client := &CommandClient{agentID: "agent-1", packageUpdates: manager, operationReceiptErr: errors.New("disk full"), logger: zerolog.Nop()}+ req := agentexec.HostUpdatePayload{RequestID: "a.dispatch.1", ActionID: "a", Operation: agentexec.HostUpdateOperationInstall, ExpectedInventoryHash: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}+ if err := agentexec.BindHostUpdatePayload(&req); err != nil {+ t.Fatal(err)+ }+ client.handleHostUpdate(context.Background(), nil, req)+ if calls != 0 {+ t.Fatalf("package manager calls=%d", calls)+ }+}diff --git a/internal/hostagent/operation_receipt_websocket_integration_test.go b/internal/hostagent/operation_receipt_websocket_integration_test.gonew file mode 100644index 0000000000..6b55c5804c--- /dev/null+++ b/internal/hostagent/operation_receipt_websocket_integration_test.go@@ -0,0 +1,62 @@+package hostagent++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"+ "github.com/rs/zerolog"+)++func TestRealServerAndUnifiedAgentWebSocketQueriesFakeTypedOperationWithoutPackageManager(t *testing.T) {+ server := agentexec.NewServer(func(token, agent, host string) bool { return token == "token" })+ httpServer := httptest.NewServer(http.HandlerFunc(server.HandleWebSocket))+ defer httpServer.Close()+ logger := zerolog.Nop()+ client := NewCommandClient(Config{PulseURL: httpServer.URL, APIToken: "token", StateDir: t.TempDir(), Logger: &logger}, "agent-real", "host", "linux", "6")+ if client.packageUpdates != nil || client.storageCleanup != nil {+ t.Fatal("test must not install package-manager adapters")+ }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() { done <- client.Run(ctx) }()+ deadline := time.Now().Add(3 * time.Second)+ for !server.IsAgentConnected("agent-real") && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ if !server.IsAgentConnected("agent-real") {+ t.Fatal("real command client did not connect")+ }+ digest, _ := operationreceipt.DigestCanonicalJSON(map[string]string{"fake": "typed-read-only-proof"})+ identity := operationreceipt.Identity{AttemptID: "fake.dispatch.1", ActionID: "fake", OperationKind: "fake.typed", OperationVersion: 1, RequestDigest: digest, AgentID: "agent-real"}+ result, err := server.QueryAgentOperation(context.Background(), "agent-real", identity)+ if err != nil || result.Status != operationreceipt.QueryNotFound {+ t.Fatalf("query=%+v err=%v", result, err)+ }+ if _, fresh, err := client.operationReceipts.Admit(identity); err != nil || !fresh {+ t.Fatalf("admit fresh=%v err=%v", fresh, err)+ }+ if _, err := client.operationReceipts.MarkStarted(identity); err != nil {+ t.Fatal(err)+ }+ result, err = server.QueryAgentOperation(context.Background(), "agent-real", identity)+ if err != nil || result.Status != operationreceipt.QueryFoundInterrupted {+ t.Fatalf("interrupted query=%+v err=%v", result, err)+ }+ cancel()+ _ = client.Close()+ select {+ case err := <-done:+ if err != nil && !strings.Contains(err.Error(), "context canceled") {+ t.Fatal(err)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("client did not stop")+ }+}diff --git a/internal/models/converters_test.go b/internal/models/converters_test.goindex c65346dd91..623fc60ede 100644--- a/internal/models/converters_test.go+++ b/internal/models/converters_test.go@@ -1,11 +1,23 @@package modelsimport (+ "encoding/json""strings""testing""time")+func TestHostFrontendDoesNotExposeOperationReceiptProtocol(t *testing.T) {+ host := Host{ID: "agent", OperationReceiptVersion: 1}+ encoded, err := json.Marshal(host.ToFrontend())+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(encoded), "operationReceiptVersion") {+ t.Fatalf("frontend payload exposed protocol: %s", encoded)+ }+}+func TestZeroIfNegative(t *testing.T) {tests := []struct {name stringdiff --git a/internal/models/models.go b/internal/models/models.goindex 942f9b4701..736b9f1c07 100644--- a/internal/models/models.go+++ b/internal/models/models.go@@ -247,45 +247,46 @@ 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"`- StorageCleanup *HostStorageCleanupStatus `json:"storageCleanup,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+ OperationReceiptVersion int `json:"-"`+ 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 trackerNetInRate float64 `json:"netInRate,omitempty"`diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex c0b248b4f9..c11a757d0d 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -1981,25 +1981,26 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.ThermalState: convertAgentThermalStateToModels(report.Sensors.ThermalState),SMART: convertAgentSMARTToModels(report.Sensors.SMART),},- RAID: raid,- Unraid: unraidData,- Ceph: cephData,- Status: "online",- UptimeSeconds: report.Host.UptimeSeconds,- IntervalSeconds: report.Agent.IntervalSeconds,- LastSeen: observedAt,- AgentVersion: strings.TrimSpace(report.Agent.Version),- MachineID: strings.TrimSpace(report.Host.MachineID),- CommandsEnabled: report.Agent.CommandsEnabled,- ReportIP: strings.TrimSpace(report.Host.ReportIP),- Tags: append([]string(nil), report.Tags...),- DiskExclude: append([]string(nil), report.Agent.DiskExclude...),- AppliedConfig: convertAgentConfigFingerprint(report.Agent.AppliedConfig),- AgentUpdate: agentUpdate,- AgentModules: convertAgentModuleStatuses(report.Agent.Modules),- PackageUpdates: convertHostPackageUpdateStatus(report.Host.PackageUpdates, observedAt),- StorageCleanup: convertHostStorageCleanupStatus(report.Host.StorageCleanup, observedAt),- IsLegacy: isLegacyAgent(report.Agent.Type),+ RAID: raid,+ Unraid: unraidData,+ Ceph: cephData,+ Status: "online",+ UptimeSeconds: report.Host.UptimeSeconds,+ IntervalSeconds: report.Agent.IntervalSeconds,+ LastSeen: observedAt,+ AgentVersion: strings.TrimSpace(report.Agent.Version),+ MachineID: strings.TrimSpace(report.Host.MachineID),+ CommandsEnabled: report.Agent.CommandsEnabled,+ OperationReceiptVersion: report.Agent.OperationReceiptVersion,+ ReportIP: strings.TrimSpace(report.Host.ReportIP),+ Tags: append([]string(nil), report.Tags...),+ DiskExclude: append([]string(nil), report.Agent.DiskExclude...),+ AppliedConfig: convertAgentConfigFingerprint(report.Agent.AppliedConfig),+ AgentUpdate: agentUpdate,+ AgentModules: convertAgentModuleStatuses(report.Agent.Modules),+ PackageUpdates: convertHostPackageUpdateStatus(report.Host.PackageUpdates, observedAt),+ StorageCleanup: convertHostStorageCleanupStatus(report.Host.StorageCleanup, observedAt),+ IsLegacy: isLegacyAgent(report.Agent.Type),}// Normalize vendor-managed internal RAID arrays out of host state so they dodiff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.goindex 76f2a8d7b1..6dddbcb8a2 100644--- a/internal/monitoring/monitor_host_agents_test.go+++ b/internal/monitoring/monitor_host_agents_test.go@@ -1,6 +1,7 @@package monitoringimport (+ "encoding/json""fmt""net""strings"@@ -11,6 +12,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/mock""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rcourtman/pulse-go-rewrite/internal/storagehealth""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"@@ -18,6 +20,106 @@ import ("github.com/rcourtman/pulse-go-rewrite/pkg/metrics")+func TestApplyHostReportOperationReceiptProtocolReplacesCapabilityAuthority(t *testing.T) {+ now := time.Now().UTC()+ baseReport := func(version int) agentshost.Report {+ return agentshost.Report{+ Agent: agentshost.AgentInfo{+ ID: "receipt-agent",+ Version: "6.0.6",+ Type: "unified",+ IntervalSeconds: 30,+ CommandsEnabled: true,+ OperationReceiptVersion: version,+ },+ Host: agentshost.HostInfo{+ ID: "receipt-machine",+ Hostname: "receipt-host",+ Platform: "linux",+ OSName: "debian",+ OSVersion: "12",+ PackageUpdates: &agentshost.PackageUpdateStatus{+ Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 2, CheckedAt: now,+ },+ StorageCleanup: &agentshost.StorageCleanupStatus{+ Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 512 << 20, CheckedAt: now,+ },+ },+ Disks: []agentshost.Disk{{Mountpoint: "/", TotalBytes: 100 << 30, UsedBytes: 95 << 30, FreeBytes: 5 << 30, Usage: 95}},+ Timestamp: now,+ }+ }+ capabilityNames := func(host models.Host) map[string]bool {+ names := map[string]bool{}+ for _, capability := range unifiedresources.HostIngestRecord(host).Resource.Capabilities {+ names[capability.Name] = true+ }+ return names+ }+ t.Run("legacy absent", func(t *testing.T) {+ encoded, err := json.Marshal(baseReport(0))+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(encoded), "operationReceiptVersion") {+ t.Fatalf("legacy fixture unexpectedly contains receipt protocol: %s", encoded)+ }+ var legacy agentshost.Report+ if err := json.Unmarshal(encoded, &legacy); err != nil {+ t.Fatal(err)+ }+ monitor := newTestMonitor(t)+ host, err := monitor.ApplyHostReport(legacy, &config.APITokenRecord{ID: "receipt-token"})+ if err != nil {+ t.Fatalf("ApplyHostReport: %v", err)+ }+ if host.OperationReceiptVersion != 0 || len(capabilityNames(host)) != 0 {+ t.Fatalf("legacy absent protocol gained capability authority: version=%d capabilities=%#v", host.OperationReceiptVersion, capabilityNames(host))+ }+ })++ for _, test := range []struct {+ name string+ version int+ want bool+ }{+ {name: "explicit zero unsupported", version: 0, want: false},+ {name: "current supported", version: operationreceipt.ProtocolVersion, want: true},+ {name: "future unsupported", version: operationreceipt.ProtocolVersion + 1, want: false},+ } {+ t.Run(test.name, func(t *testing.T) {+ monitor := newTestMonitor(t)+ host, err := monitor.ApplyHostReport(baseReport(test.version), &config.APITokenRecord{ID: "receipt-token"})+ if err != nil {+ t.Fatalf("ApplyHostReport: %v", err)+ }+ if host.OperationReceiptVersion != test.version {+ t.Fatalf("ingested receipt version = %d, want %d", host.OperationReceiptVersion, test.version)+ }+ names := capabilityNames(host)+ got := names["install_os_updates"] && names["clean_package_cache"] && len(names) == 2+ if got != test.want {+ t.Fatalf("derived capabilities = %#v, want both=%v", names, test.want)+ }+ })+ }++ monitor := newTestMonitor(t)+ compatible, err := monitor.ApplyHostReport(baseReport(operationreceipt.ProtocolVersion), &config.APITokenRecord{ID: "receipt-token"})+ if err != nil || len(capabilityNames(compatible)) != 2 {+ t.Fatalf("compatible ingest: capabilities=%#v err=%v", capabilityNames(compatible), err)+ }+ downgradedReport := baseReport(0)+ downgradedReport.Timestamp = now.Add(time.Second)+ downgraded, err := monitor.ApplyHostReport(downgradedReport, &config.APITokenRecord{ID: "receipt-token"})+ if err != nil {+ t.Fatalf("downgrade ApplyHostReport: %v", err)+ }+ if downgraded.OperationReceiptVersion != 0 || len(capabilityNames(downgraded)) != 0 {+ t.Fatalf("downgrade retained capability authority: version=%d capabilities=%#v", downgraded.OperationReceiptVersion, capabilityNames(downgraded))+ }+}+func TestMonitor_GetConfiguredHostIPs_ResolvesOutsideMonitorLock(t *testing.T) {originalLookup := lookupConfiguredHostIPlookupStarted := make(chan struct{})diff --git a/internal/operationreceipt/store.go b/internal/operationreceipt/store.gonew file mode 100644index 0000000000..328e73160f--- /dev/null+++ b/internal/operationreceipt/store.go@@ -0,0 +1,327 @@+package operationreceipt++import (+ "context"+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ _ "modernc.org/sqlite"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "time"+)++type TerminalValidator func(Identity, json.RawMessage) error+type Config struct {+ RecentTerminalTTL time.Duration+ MaxRecentPayloadBytes int64+ Validators map[string]map[int]TerminalValidator+}+type Store struct {+ mu sync.Mutex+ db *sql.DB+ config Config+ now func() time.Time+}++func Open(path string, config Config) (*Store, error) {+ if strings.TrimSpace(path) == "" {+ return nil, fmt.Errorf("operation receipt store path is required")+ }+ if config.RecentTerminalTTL <= 0 {+ config.RecentTerminalTTL = 30 * 24 * time.Hour+ }+ if config.MaxRecentPayloadBytes <= 0 {+ config.MaxRecentPayloadBytes = 32 << 20+ }+ if len(config.Validators) == 0 {+ return nil, fmt.Errorf("operation receipt terminal validators are required")+ }+ config.Validators = freezeValidators(config.Validators)+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ return nil, err+ }+ db, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(FULL)&_pragma=foreign_keys(ON)")+ if err != nil {+ return nil, err+ }+ db.SetMaxOpenConns(1)+ s := &Store{db: db, config: config, now: time.Now}+ if err := s.init(); err != nil {+ db.Close()+ return nil, fmt.Errorf("%w: %v", ErrStoreCorrupt, err)+ }+ if err := os.Chmod(path, 0600); err != nil {+ db.Close()+ return nil, err+ }+ if err := s.validateAll(); err != nil {+ db.Close()+ return nil, err+ }+ if err := s.recoverInterrupted(); err != nil {+ db.Close()+ return nil, err+ }+ if err := s.validateAll(); err != nil {+ db.Close()+ return nil, err+ }+ if err := s.Compact(context.Background()); err != nil {+ db.Close()+ return nil, err+ }+ return s, nil+}+func (s *Store) Close() error {+ if s == nil || s.db == nil {+ return nil+ }+ return s.db.Close()+}+func (s *Store) init() error {+ _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operation_receipts(attempt_id TEXT PRIMARY KEY,action_id TEXT NOT NULL,operation_kind TEXT NOT NULL,operation_version INTEGER NOT NULL,request_digest TEXT NOT NULL,agent_id TEXT NOT NULL,state TEXT NOT NULL,accepted_at DATETIME NOT NULL,started_at DATETIME,terminal_at DATETIME,result_kind TEXT NOT NULL DEFAULT '',result_version INTEGER NOT NULL DEFAULT 0,result_json BLOB);CREATE INDEX IF NOT EXISTS idx_operation_receipts_terminal ON operation_receipts(state,terminal_at);`)+ if err != nil {+ return err+ }+ var quick string+ if err := s.db.QueryRow("PRAGMA quick_check").Scan(&quick); err != nil || quick != "ok" {+ return fmt.Errorf("sqlite quick_check failed: %s: %v", quick, err)+ }+ return nil+}+func (s *Store) recoverInterrupted() error {+ _, err := s.db.Exec(`UPDATE operation_receipts SET state=?,started_at=COALESCE(started_at,accepted_at) WHERE state IN (?,?)`, string(StateInterrupted), string(StateAccepted), string(StateStarted))+ return err+}++func (s *Store) validateAll() error {+ rows, err := s.db.Query(`SELECT attempt_id FROM operation_receipts ORDER BY attempt_id`)+ if err != nil {+ return err+ }+ var ids []string+ for rows.Next() {+ var id string+ if err := rows.Scan(&id); err != nil {+ rows.Close()+ return err+ }+ ids = append(ids, id)+ }+ if err := rows.Close(); err != nil {+ return err+ }+ for _, id := range ids {+ if _, _, err := s.query(id); err != nil {+ return err+ }+ }+ return nil+}+func (s *Store) Admit(i Identity) (Record, bool, error) {+ i, err := NormalizeIdentity(i)+ if err != nil {+ return Record{}, false, err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if err := s.compactLocked(context.Background()); err != nil {+ return Record{}, false, err+ }+ if r, ok, err := s.query(i.AttemptID); err != nil {+ return Record{}, false, err+ } else if ok {+ if r.Identity != i {+ return Record{}, false, ErrBindingConflict+ }+ return r, false, nil+ }+ now := s.currentTime()+ _, err = s.db.Exec(`INSERT INTO operation_receipts(attempt_id,action_id,operation_kind,operation_version,request_digest,agent_id,state,accepted_at)VALUES(?,?,?,?,?,?,?,?)`, i.AttemptID, i.ActionID, i.OperationKind, i.OperationVersion, i.RequestDigest, i.AgentID, string(StateAccepted), now)+ if err != nil {+ return Record{}, false, err+ }+ return Record{Identity: i, State: StateAccepted, AcceptedAt: now}, true, nil+}+func (s *Store) MarkStarted(i Identity) (Record, error) {+ i, err := NormalizeIdentity(i)+ if err != nil {+ return Record{}, err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ now := s.currentTime()+ res, err := s.db.Exec(`UPDATE operation_receipts SET state=?,started_at=? WHERE attempt_id=? AND action_id=? AND operation_kind=? AND operation_version=? AND request_digest=? AND agent_id=? AND state=?`, string(StateStarted), now, i.AttemptID, i.ActionID, i.OperationKind, i.OperationVersion, i.RequestDigest, i.AgentID, string(StateAccepted))+ if err != nil {+ return Record{}, err+ }+ n, _ := res.RowsAffected()+ if n != 1 {+ if r, ok, qerr := s.query(i.AttemptID); qerr == nil && ok && r.Identity != i {+ return Record{}, ErrBindingConflict+ }+ return Record{}, ErrNotStartable+ }+ return s.mustQuery(i.AttemptID)+}+func (s *Store) Complete(i Identity, e TerminalEnvelope) (Record, error) {+ i, err := NormalizeIdentity(i)+ if err != nil {+ return Record{}, err+ }+ e.Kind = strings.TrimSpace(e.Kind)+ versions := s.config.Validators[e.Kind]+ validator := versions[e.Version]+ if validator == nil {+ return Record{}, fmt.Errorf("unknown terminal envelope kind/version")+ }+ if len(e.Payload) == 0 || len(e.Payload) > MaxResultBytes {+ return Record{}, ErrCapacity+ }+ if err := validator(i, e.Payload); err != nil {+ return Record{}, fmt.Errorf("invalid terminal envelope: %w", err)+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ now := s.currentTime()+ res, err := s.db.Exec(`UPDATE operation_receipts SET state=?,terminal_at=?,result_kind=?,result_version=?,result_json=? WHERE attempt_id=? AND action_id=? AND operation_kind=? AND operation_version=? AND request_digest=? AND agent_id=? AND state=?`, string(StateTerminal), now, e.Kind, e.Version, []byte(e.Payload), i.AttemptID, i.ActionID, i.OperationKind, i.OperationVersion, i.RequestDigest, i.AgentID, string(StateStarted))+ if err != nil {+ return Record{}, err+ }+ n, _ := res.RowsAffected()+ if n != 1 {+ r, ok, qerr := s.query(i.AttemptID)+ if qerr == nil && ok && r.Identity != i {+ return Record{}, ErrBindingConflict+ }+ if qerr == nil && ok && r.State == StateTerminal && r.ResultKind == e.Kind && r.ResultVersion == e.Version && string(r.Result) == string(e.Payload) {+ return r, nil+ }+ return Record{}, ErrNotCompletable+ }+ record, err := s.mustQuery(i.AttemptID)+ if err != nil {+ return Record{}, err+ }+ if err := s.compactLocked(context.Background()); err != nil {+ return Record{}, err+ }+ return record, nil+}+func (s *Store) Query(i Identity) (QueryResult, error) {+ i, err := NormalizeIdentity(i)+ if err != nil {+ return QueryResult{}, err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ r, ok, err := s.query(i.AttemptID)+ if err != nil {+ return QueryResult{}, err+ }+ if !ok {+ return QueryResult{Version: ProtocolVersion, Status: QueryNotFound}, nil+ }+ if r.Identity != i {+ return QueryResult{}, ErrBindingConflict+ }+ status := QueryFoundInterrupted+ if r.State == StateTerminal {+ status = QueryFoundTerminal+ }+ return QueryResult{Version: ProtocolVersion, Status: status, Record: &r}, nil+}+func (s *Store) Compact(ctx context.Context) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.compactLocked(ctx)+}++func (s *Store) compactLocked(ctx context.Context) error {+ cutoff := s.currentTime().Add(-s.config.RecentTerminalTTL)+ if _, err := s.db.ExecContext(ctx, `UPDATE operation_receipts SET state=?,result_kind='',result_version=0,result_json=NULL WHERE state=? AND terminal_at<?`, string(StateTombstone), string(StateTerminal), cutoff); err != nil {+ return err+ }+ var total int64+ if err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(length(result_json)),0) FROM operation_receipts WHERE state=?`, string(StateTerminal)).Scan(&total); err != nil {+ return err+ }+ for total > s.config.MaxRecentPayloadBytes {+ var id string+ var size int64+ if err := s.db.QueryRowContext(ctx, `SELECT attempt_id,length(result_json) FROM operation_receipts WHERE state=? ORDER BY terminal_at ASC LIMIT 1`, string(StateTerminal)).Scan(&id, &size); err != nil {+ return err+ }+ if _, err := s.db.ExecContext(ctx, `UPDATE operation_receipts SET state=?,result_kind='',result_version=0,result_json=NULL WHERE attempt_id=? AND state=?`, string(StateTombstone), id, string(StateTerminal)); err != nil {+ return err+ }+ total -= size+ }+ return nil+}+func (s *Store) query(id string) (Record, bool, error) {+ row := s.db.QueryRow(`SELECT attempt_id,action_id,operation_kind,operation_version,request_digest,agent_id,state,accepted_at,started_at,terminal_at,result_kind,result_version,result_json FROM operation_receipts WHERE attempt_id=?`, id)+ var r Record+ var state string+ var started, terminal sql.NullTime+ var payload []byte+ if err := row.Scan(&r.Identity.AttemptID, &r.Identity.ActionID, &r.Identity.OperationKind, &r.Identity.OperationVersion, &r.Identity.RequestDigest, &r.Identity.AgentID, &state, &r.AcceptedAt, &started, &terminal, &r.ResultKind, &r.ResultVersion, &payload); errors.Is(err, sql.ErrNoRows) {+ return Record{}, false, nil+ } else if err != nil {+ return Record{}, false, err+ }+ r.State = State(state)+ if started.Valid {+ r.StartedAt = started.Time+ }+ if terminal.Valid {+ r.TerminalAt = terminal.Time+ }+ r.Result = append([]byte(nil), payload...)+ if err := ValidateRecord(r); err != nil {+ return Record{}, false, fmt.Errorf("%w: %v", ErrStoreCorrupt, err)+ }+ if r.State == StateTerminal {+ versions := s.config.Validators[r.ResultKind]+ validator := versions[r.ResultVersion]+ if validator == nil {+ return Record{}, false, fmt.Errorf("%w: unknown terminal envelope kind/version", ErrStoreCorrupt)+ }+ if err := validator(r.Identity, r.Result); err != nil {+ return Record{}, false, fmt.Errorf("%w: invalid terminal envelope: %v", ErrStoreCorrupt, err)+ }+ }+ return r, true, nil+}++func freezeValidators(source map[string]map[int]TerminalValidator) map[string]map[int]TerminalValidator {+ frozen := make(map[string]map[int]TerminalValidator, len(source))+ for kind, versions := range source {+ copyVersions := make(map[int]TerminalValidator, len(versions))+ for version, validator := range versions {+ copyVersions[version] = validator+ }+ frozen[kind] = copyVersions+ }+ return frozen+}+func (s *Store) mustQuery(id string) (Record, error) {+ r, ok, err := s.query(id)+ if err != nil {+ return Record{}, err+ }+ if !ok {+ return Record{}, ErrNotFound+ }+ return r, nil+}+func (s *Store) currentTime() time.Time {+ if s.now != nil {+ return s.now().UTC()+ }+ return time.Now().UTC()+}diff --git a/internal/operationreceipt/store_test.go b/internal/operationreceipt/store_test.gonew file mode 100644index 0000000000..072406bf82--- /dev/null+++ b/internal/operationreceipt/store_test.go@@ -0,0 +1,353 @@+package operationreceipt++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++const testKind = "test.safe_result"++func testConfig() Config {+ return Config{+ RecentTerminalTTL: time.Hour,+ MaxRecentPayloadBytes: 1 << 20,+ Validators: map[string]map[int]TerminalValidator{+ testKind: {1: func(_ Identity, raw json.RawMessage) error {+ var value struct {+ Status string `json:"status"`+ }+ return decodeStrict(raw, &value)+ }},+ },+ }+}+func testIdentity(id string) Identity {+ digest, _ := DigestCanonicalJSON(map[string]string{"id": id})+ return Identity{AttemptID: id, ActionID: "action-" + id, OperationKind: "test.operation", OperationVersion: 1, RequestDigest: digest, AgentID: "agent-1"}+}+func testEnvelope(status string) TerminalEnvelope {+ raw, _ := json.Marshal(struct {+ Status string `json:"status"`+ }{status})+ return TerminalEnvelope{Kind: testKind, Version: 1, Payload: raw}+}+func openTestStore(t *testing.T, path string, config Config) *Store {+ t.Helper()+ s, err := Open(path, config)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = s.Close() })+ return s+}++func TestSQLiteOperationReceiptDuplicateBindingAndTerminalReplay(t *testing.T) {+ path := filepath.Join(t.TempDir(), "receipts.db")+ s := openTestStore(t, path, testConfig())+ id := testIdentity("attempt-1")+ if _, fresh, err := s.Admit(id); err != nil || !fresh {+ t.Fatalf("admit fresh=%v err=%v", fresh, err)+ }+ if _, fresh, err := s.Admit(id); err != nil || fresh {+ t.Fatalf("duplicate fresh=%v err=%v", fresh, err)+ }+ changed := id+ changed.ActionID = "other"+ if _, _, err := s.Admit(changed); !errors.Is(err, ErrBindingConflict) {+ t.Fatalf("mismatch err=%v", err)+ }+ if _, err := s.MarkStarted(id); err != nil {+ t.Fatal(err)+ }+ terminal, err := s.Complete(id, testEnvelope("ok"))+ if err != nil {+ t.Fatal(err)+ }+ if terminal.State != StateTerminal {+ t.Fatalf("state=%s", terminal.State)+ }+ replay, err := s.Complete(id, testEnvelope("ok"))+ if err != nil || string(replay.Result) != string(terminal.Result) {+ t.Fatalf("replay=%s err=%v", replay.Result, err)+ }+ if _, err := s.Complete(id, testEnvelope("different")); !errors.Is(err, ErrNotCompletable) {+ t.Fatalf("conflicting terminal err=%v", err)+ }+}++func TestSQLiteOperationReceiptCrashBoundariesAndReopen(t *testing.T) {+ for _, tc := range []struct {+ name string+ start, complete bool+ want State+ }{{"after_admit", false, false, StateInterrupted}, {"after_start_before_result", true, false, StateInterrupted}, {"after_terminal", true, true, StateTerminal}} {+ t.Run(tc.name, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "receipts.db")+ s := openTestStore(t, path, testConfig())+ id := testIdentity(tc.name)+ if _, _, err := s.Admit(id); err != nil {+ t.Fatal(err)+ }+ if tc.start {+ if _, err := s.MarkStarted(id); err != nil {+ t.Fatal(err)+ }+ }+ if tc.complete {+ if _, err := s.Complete(id, testEnvelope("ok")); err != nil {+ t.Fatal(err)+ }+ }+ if err := s.Close(); err != nil {+ t.Fatal(err)+ }+ s2, err := Open(path, testConfig())+ if err != nil {+ t.Fatal(err)+ }+ defer s2.Close()+ q, err := s2.Query(id)+ if err != nil {+ t.Fatal(err)+ }+ if q.Record.State != tc.want {+ t.Fatalf("state=%s want=%s", q.Record.State, tc.want)+ }+ if tc.complete && string(q.Record.Result) != (string(testEnvelope("ok").Payload)) {+ t.Fatalf("terminal replay=%s", q.Record.Result)+ }+ if _, fresh, err := s2.Admit(id); err != nil || fresh {+ t.Fatalf("reopen duplicate fresh=%v err=%v", fresh, err)+ }+ })+ }+}++func TestSQLiteOperationReceiptCompletionRollbackLeavesUnknown(t *testing.T) {+ s := openTestStore(t, filepath.Join(t.TempDir(), "receipts.db"), testConfig())+ id := testIdentity("rollback")+ _, _, _ = s.Admit(id)+ _, _ = s.MarkStarted(id)+ if _, err := s.db.Exec(`CREATE TRIGGER fail_terminal BEFORE UPDATE ON operation_receipts WHEN NEW.state='terminal' BEGIN SELECT RAISE(ABORT,'injected'); END`); err != nil {+ t.Fatal(err)+ }+ if _, err := s.Complete(id, testEnvelope("ok")); err == nil {+ t.Fatal("expected injected failure")+ }+ q, err := s.Query(id)+ if err != nil || q.Status != QueryFoundInterrupted || q.Record.State != StateStarted {+ t.Fatalf("query=%+v err=%v", q, err)+ }+}++func TestSQLiteOperationReceiptCompactionRetainsReplayDenialAndCapacityForNewWork(t *testing.T) {+ cfg := testConfig()+ cfg.MaxRecentPayloadBytes = 20+ path := filepath.Join(t.TempDir(), "receipts.db")+ s := openTestStore(t, path, cfg)+ first := testIdentity("old")+ _, _, _ = s.Admit(first)+ _, _ = s.MarkStarted(first)+ _, err := s.Complete(first, testEnvelope("payload-large-enough"))+ if err != nil {+ t.Fatal(err)+ }+ q, err := s.Query(first)+ if err != nil || q.Record.State != StateTombstone || q.Status != QueryFoundInterrupted {+ t.Fatalf("compacted query=%+v err=%v", q, err)+ }+ if _, fresh, err := s.Admit(first); err != nil || fresh {+ t.Fatalf("tombstone replay fresh=%v err=%v", fresh, err)+ }+ for n := 0; n < 500; n++ {+ id := testIdentity("volume-" + time.Unix(int64(n), 0).Format("150405.000000000"))+ if _, fresh, err := s.Admit(id); err != nil || !fresh {+ t.Fatalf("volume %d fresh=%v err=%v", n, fresh, err)+ }+ }+ unrelated := testIdentity("unrelated")+ if _, fresh, err := s.Admit(unrelated); err != nil || !fresh {+ t.Fatalf("unrelated fresh=%v err=%v", fresh, err)+ }+ if err := s.Close(); err != nil {+ t.Fatal(err)+ }+ reopened, err := Open(path, cfg)+ if err != nil {+ t.Fatal(err)+ }+ defer reopened.Close()+ q, err = reopened.Query(first)+ if err != nil || q.Record.State != StateTombstone {+ t.Fatalf("reopened tombstone=%+v err=%v", q, err)+ }+}++func TestSQLiteOperationReceiptTTLCompactionRetainsIdentityDigestTombstone(t *testing.T) {+ cfg := testConfig()+ cfg.RecentTerminalTTL = time.Minute+ s := openTestStore(t, filepath.Join(t.TempDir(), "receipts.db"), cfg)+ base := time.Date(2026, 7, 12, 1, 0, 0, 0, time.UTC)+ s.now = func() time.Time { return base }+ id := testIdentity("ttl")+ _, _, _ = s.Admit(id)+ _, _ = s.MarkStarted(id)+ _, _ = s.Complete(id, testEnvelope("ok"))+ s.now = func() time.Time { return base.Add(2 * time.Minute) }+ if err := s.Compact(context.Background()); err != nil {+ t.Fatal(err)+ }+ q, err := s.Query(id)+ if err != nil || q.Record.State != StateTombstone || q.Record.Identity != id || len(q.Record.Result) != 0 {+ t.Fatalf("query=%+v err=%v", q, err)+ }+}++func TestSQLiteOperationReceiptConcurrentDuplicateHasOneAdmission(t *testing.T) {+ s := openTestStore(t, filepath.Join(t.TempDir(), "receipts.db"), testConfig())+ id := testIdentity("concurrent")+ var admitted atomic.Int32+ var wg sync.WaitGroup+ for n := 0; n < 32; n++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, fresh, err := s.Admit(id)+ if err != nil {+ t.Errorf("admit: %v", err)+ return+ }+ if fresh {+ admitted.Add(1)+ }+ }()+ }+ wg.Wait()+ if admitted.Load() != 1 {+ t.Fatalf("admissions=%d", admitted.Load())+ }+}++func TestSQLiteOperationReceiptConcurrentLifecycleAndCompaction(t *testing.T) {+ cfg := testConfig()+ cfg.MaxRecentPayloadBytes = 256+ s := openTestStore(t, filepath.Join(t.TempDir(), "receipts.db"), cfg)+ var wg sync.WaitGroup+ for n := 0; n < 64; n++ {+ n := n+ wg.Add(1)+ go func() {+ defer wg.Done()+ id := testIdentity("parallel-" + time.Unix(int64(n), 0).Format("150405.000000000"))+ if _, fresh, err := s.Admit(id); err != nil || !fresh {+ t.Errorf("admit %d fresh=%v err=%v", n, fresh, err)+ return+ }+ if _, err := s.MarkStarted(id); err != nil {+ t.Errorf("start %d: %v", n, err)+ return+ }+ if _, err := s.Complete(id, testEnvelope("ok")); err != nil {+ t.Errorf("complete %d: %v", n, err)+ }+ }()+ }+ for n := 0; n < 16; n++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ if err := s.Compact(context.Background()); err != nil {+ t.Errorf("compact: %v", err)+ }+ }()+ }+ wg.Wait()+ for n := 0; n < 64; n++ {+ id := testIdentity("parallel-" + time.Unix(int64(n), 0).Format("150405.000000000"))+ q, err := s.Query(id)+ if err != nil || q.Status == QueryNotFound {+ t.Fatalf("query %d=%+v err=%v", n, q, err)+ }+ }+}++func TestSQLiteOperationReceiptCorruptionAndEnvelopeRefusal(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "receipts.db")+ if err := os.WriteFile(path, []byte("truncated-not-sqlite"), 0600); err != nil {+ t.Fatal(err)+ }+ if _, err := Open(path, testConfig()); !errors.Is(err, ErrStoreCorrupt) {+ t.Fatalf("corrupt open err=%v", err)+ }+ s := openTestStore(t, filepath.Join(dir, "valid.db"), testConfig())+ id := testIdentity("bad-envelope")+ _, _, _ = s.Admit(id)+ _, _ = s.MarkStarted(id)+ if _, err := s.Complete(id, TerminalEnvelope{Kind: "unknown", Version: 1, Payload: json.RawMessage(`{"status":"ok"}`)}); err == nil {+ t.Fatal("unknown kind accepted")+ }+ if _, err := s.Complete(id, TerminalEnvelope{Kind: testKind, Version: 2, Payload: json.RawMessage(`{"status":"ok"}`)}); err == nil {+ t.Fatal("unknown version accepted")+ }+ if _, err := s.Complete(id, TerminalEnvelope{Kind: testKind, Version: 1, Payload: json.RawMessage(`{"status":"ok","stderr":"secret"}`)}); err == nil {+ t.Fatal("unknown result field accepted")+ }+}++func TestSQLiteOperationReceiptRevalidatesFrozenTerminalCodecOnReadAndReopen(t *testing.T) {+ cfg := testConfig()+ source := cfg.Validators+ path := filepath.Join(t.TempDir(), "receipts.db")+ s := openTestStore(t, path, cfg)+ id := testIdentity("tamper")+ _, _, _ = s.Admit(id)+ _, _ = s.MarkStarted(id)+ _, _ = s.Complete(id, testEnvelope("ok"))+ // Mutating the caller's registry after Open must not alter store policy.+ source[testKind][1] = func(Identity, json.RawMessage) error { return nil }+ if _, err := s.db.Exec(`UPDATE operation_receipts SET result_json=? WHERE attempt_id=?`, []byte(`{"status":"ok","stderr":"secret"}`), id.AttemptID); err != nil {+ t.Fatal(err)+ }+ if _, err := s.Query(id); !errors.Is(err, ErrStoreCorrupt) {+ t.Fatalf("tampered query err=%v", err)+ }+ if err := s.Close(); err != nil {+ t.Fatal(err)+ }+ if _, err := Open(path, testConfig()); !errors.Is(err, ErrStoreCorrupt) {+ t.Fatalf("tampered reopen err=%v", err)+ }+}++func TestOperationReceiptQueryCodecRejectsMalformedUnknownAndTrailing(t *testing.T) {+ id := testIdentity("codec")+ record := Record{Identity: id, State: StateInterrupted, AcceptedAt: time.Now().UTC(), StartedAt: time.Now().UTC()}+ valid, _ := json.Marshal(QueryResult{Version: ProtocolVersion, Status: QueryFoundInterrupted, Record: &record})+ for _, raw := range [][]byte{[]byte(`{"version":99,"status":"not_found"}`), append(valid, []byte(` {}`)...), []byte(`{"version":1,"status":"not_found","unknown":true}`), []byte(`{"version":1,"status":"found_terminal","record":{"identity":{}}}`)} {+ if _, err := DecodeQueryResult(raw); err == nil {+ t.Fatalf("accepted %s", raw)+ }+ }+ if _, err := DecodeQueryResult(valid); err != nil {+ t.Fatal(err)+ }+}++func TestSQLiteOperationReceiptNotFoundIsNonAuthorizingState(t *testing.T) {+ s := openTestStore(t, filepath.Join(t.TempDir(), "receipts.db"), testConfig())+ q, err := s.Query(testIdentity("missing"))+ if err != nil || q.Status != QueryNotFound || q.Record != nil {+ t.Fatalf("query=%+v err=%v", q, err)+ }+ if err := s.Compact(context.Background()); err != nil {+ t.Fatal(err)+ }+}diff --git a/internal/operationreceipt/types.go b/internal/operationreceipt/types.gonew file mode 100644index 0000000000..e841844f4c--- /dev/null+++ b/internal/operationreceipt/types.go@@ -0,0 +1,212 @@+package operationreceipt++import (+ "bytes"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "strings"+ "time"+)++const (+ ProtocolVersion = 1+ MaxResultBytes = 64 << 10+)++type State string++const (+ StateAccepted State = "accepted"+ StateStarted State = "started"+ StateInterrupted State = "interrupted_unknown"+ StateTerminal State = "terminal"+ StateTombstone State = "replay_denied_tombstone"+)++type QueryStatus string++const (+ QueryNotFound QueryStatus = "not_found"+ QueryFoundTerminal QueryStatus = "found_terminal"+ QueryFoundInterrupted QueryStatus = "found_interrupted_unknown"+)++var (+ ErrBindingConflict = errors.New("operation receipt identity binding conflict")+ ErrNotFound = errors.New("operation receipt not found")+ ErrNotStartable = errors.New("operation receipt is not startable")+ ErrNotCompletable = errors.New("operation receipt is not completable")+ ErrStoreCorrupt = errors.New("operation receipt store is corrupt")+ ErrCapacity = errors.New("operation receipt capacity unavailable")+)++type Identity struct {+ AttemptID string `json:"attempt_id"`+ ActionID string `json:"action_id"`+ OperationKind string `json:"operation_kind"`+ OperationVersion int `json:"operation_version"`+ RequestDigest string `json:"request_digest"`+ AgentID string `json:"agent_id"`+}+type Record struct {+ Identity Identity `json:"identity"`+ State State `json:"state"`+ AcceptedAt time.Time `json:"accepted_at"`+ StartedAt time.Time `json:"started_at,omitempty"`+ TerminalAt time.Time `json:"terminal_at,omitempty"`+ ResultKind string `json:"result_kind,omitempty"`+ ResultVersion int `json:"result_version,omitempty"`+ Result json.RawMessage `json:"result,omitempty"`+}+type TerminalEnvelope struct {+ Kind string+ Version int+ Payload json.RawMessage+}+type Query struct {+ Version int `json:"version"`+ Identity Identity `json:"identity"`+}+type QueryResult struct {+ Version int `json:"version"`+ Status QueryStatus `json:"status"`+ Record *Record `json:"record,omitempty"`+}++func DigestCanonicalJSON(value any) (string, error) {+ encoded, err := json.Marshal(value)+ if err != nil {+ return "", err+ }+ sum := sha256.Sum256(encoded)+ return "sha256:" + hex.EncodeToString(sum[:]), nil+}+func NormalizeIdentity(i Identity) (Identity, error) {+ i.AttemptID = strings.TrimSpace(i.AttemptID)+ i.ActionID = strings.TrimSpace(i.ActionID)+ i.OperationKind = strings.TrimSpace(i.OperationKind)+ i.RequestDigest = strings.TrimSpace(i.RequestDigest)+ i.AgentID = strings.TrimSpace(i.AgentID)+ if i.AttemptID == "" || i.ActionID == "" || i.OperationKind == "" || i.AgentID == "" {+ return Identity{}, fmt.Errorf("operation receipt identity fields are required")+ }+ if len(i.AttemptID) > 128 || len(i.ActionID) > 128 || len(i.OperationKind) > 128 || len(i.AgentID) > 128 {+ return Identity{}, fmt.Errorf("operation receipt identity exceeds bounded length")+ }+ if i.OperationVersion <= 0 {+ return Identity{}, fmt.Errorf("operation version must be positive")+ }+ if len(i.RequestDigest) != 71 || !strings.HasPrefix(i.RequestDigest, "sha256:") {+ return Identity{}, fmt.Errorf("request digest must be sha256")+ }+ if _, err := hex.DecodeString(strings.TrimPrefix(i.RequestDigest, "sha256:")); err != nil {+ return Identity{}, fmt.Errorf("request digest must be sha256: %w", err)+ }+ return i, nil+}+func ValidateRecord(r Record) error {+ i, err := NormalizeIdentity(r.Identity)+ if err != nil {+ return err+ }+ if i != r.Identity {+ return fmt.Errorf("operation receipt identity is not normalized")+ }+ if r.AcceptedAt.IsZero() || len(r.Result) > MaxResultBytes {+ return fmt.Errorf("invalid operation receipt bounds")+ }+ if !r.StartedAt.IsZero() && r.StartedAt.Before(r.AcceptedAt) {+ return fmt.Errorf("operation receipt start precedes admission")+ }+ if !r.TerminalAt.IsZero() && (r.StartedAt.IsZero() || r.TerminalAt.Before(r.StartedAt)) {+ return fmt.Errorf("operation receipt terminal time is invalid")+ }+ switch r.State {+ case StateAccepted:+ if !r.StartedAt.IsZero() || !r.TerminalAt.IsZero() || len(r.Result) > 0 || r.ResultKind != "" || r.ResultVersion != 0 {+ return fmt.Errorf("accepted receipt contains later state")+ }+ case StateStarted, StateInterrupted:+ if r.StartedAt.IsZero() || !r.TerminalAt.IsZero() || len(r.Result) > 0 || r.ResultKind != "" || r.ResultVersion != 0 {+ return fmt.Errorf("nonterminal receipt contains terminal state")+ }+ case StateTerminal:+ if r.StartedAt.IsZero() || r.TerminalAt.IsZero() || len(r.Result) == 0 || strings.TrimSpace(r.ResultKind) == "" || r.ResultVersion <= 0 {+ return fmt.Errorf("terminal receipt is incomplete")+ }+ case StateTombstone:+ if r.StartedAt.IsZero() || r.TerminalAt.IsZero() || len(r.Result) != 0 || r.ResultKind != "" || r.ResultVersion != 0 {+ return fmt.Errorf("receipt tombstone contains payload")+ }+ default:+ return fmt.Errorf("unsupported operation receipt state %q", r.State)+ }+ return nil+}+func DecodeQuery(data []byte) (Query, error) {+ var q Query+ if err := decodeStrict(data, &q); err != nil {+ return Query{}, err+ }+ if q.Version != ProtocolVersion {+ return Query{}, fmt.Errorf("unsupported operation query version %d", q.Version)+ }+ i, err := NormalizeIdentity(q.Identity)+ if err != nil {+ return Query{}, err+ }+ q.Identity = i+ return q, nil+}+func DecodeQueryResult(data []byte) (QueryResult, error) {+ var r QueryResult+ if err := decodeStrict(data, &r); err != nil {+ return QueryResult{}, err+ }+ if r.Version != ProtocolVersion {+ return QueryResult{}, fmt.Errorf("unsupported operation query result version %d", r.Version)+ }+ switch r.Status {+ case QueryNotFound:+ if r.Record != nil {+ return QueryResult{}, fmt.Errorf("not-found query result cannot include a record")+ }+ case QueryFoundTerminal:+ if r.Record == nil || r.Record.State != StateTerminal {+ return QueryResult{}, fmt.Errorf("terminal query result requires terminal record")+ }+ case QueryFoundInterrupted:+ if r.Record == nil || (r.Record.State != StateAccepted && r.Record.State != StateStarted && r.Record.State != StateInterrupted && r.Record.State != StateTombstone) {+ return QueryResult{}, fmt.Errorf("interrupted query result requires nonterminal or tombstone record")+ }+ default:+ return QueryResult{}, fmt.Errorf("unsupported operation query status %q", r.Status)+ }+ if r.Record != nil {+ if err := ValidateRecord(*r.Record); err != nil {+ return QueryResult{}, err+ }+ }+ return r, nil+}+func decodeStrict(data []byte, target any) error {+ if len(bytes.TrimSpace(data)) == 0 {+ return fmt.Errorf("operation receipt payload is empty")+ }+ d := json.NewDecoder(bytes.NewReader(data))+ d.DisallowUnknownFields()+ if err := d.Decode(target); err != nil {+ return err+ }+ if err := d.Decode(&struct{}{}); err != io.EOF {+ if err == nil {+ return fmt.Errorf("operation receipt payload contains trailing JSON")+ }+ return fmt.Errorf("operation receipt payload contains trailing data: %w", err)+ }+ return nil+}diff --git a/internal/unifiedresources/action_dispatch.go b/internal/unifiedresources/action_dispatch.goindex 7ad720a113..a1406d11e0 100644--- a/internal/unifiedresources/action_dispatch.go+++ b/internal/unifiedresources/action_dispatch.go@@ -21,14 +21,29 @@ const (// ActionDispatchAttempt is the create-once durable identity for sending one// canonical action to its mutation transport.type ActionDispatchAttempt struct {- ID string `json:"id"`- ActionID string `json:"actionId"`- State ActionDispatchState `json:"state"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`- LeaseOwner string `json:"leaseOwner,omitempty"`- LeaseExpiresAt time.Time `json:"leaseExpiresAt,omitempty"`- DispatchCount int `json:"dispatchCount"`+ ID string `json:"id"`+ ActionID string `json:"actionId"`+ State ActionDispatchState `json:"state"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ LeaseOwner string `json:"leaseOwner,omitempty"`+ LeaseExpiresAt time.Time `json:"leaseExpiresAt,omitempty"`+ DispatchCount int `json:"dispatchCount"`+ OperationKind string `json:"operationKind,omitempty"`+ OperationVersion int `json:"operationVersion,omitempty"`+ RequestDigest string `json:"requestDigest,omitempty"`+ AgentID string `json:"agentId,omitempty"`+}++type ActionDispatchBinding struct {+ OperationKind string+ OperationVersion int+ RequestDigest string+ AgentID string+}++func (a ActionDispatchAttempt) HasOperationBinding() bool {+ return strings.TrimSpace(a.OperationKind) != "" && a.OperationVersion > 0 && strings.TrimSpace(a.RequestDigest) != "" && strings.TrimSpace(a.AgentID) != ""}// ActionDispatchReceipt proves only that the transport answered the committed@@ -71,6 +86,9 @@ func NormalizeActionDispatchAttempt(attempt ActionDispatchAttempt) (ActionDispatattempt.ID = strings.TrimSpace(attempt.ID)attempt.ActionID = strings.TrimSpace(attempt.ActionID)attempt.LeaseOwner = strings.TrimSpace(attempt.LeaseOwner)+ attempt.OperationKind = strings.TrimSpace(attempt.OperationKind)+ attempt.RequestDigest = strings.TrimSpace(attempt.RequestDigest)+ attempt.AgentID = strings.TrimSpace(attempt.AgentID)if attempt.ActionID == "" {return ActionDispatchAttempt{}, fmt.Errorf("action dispatch action id required")}@@ -104,9 +122,21 @@ func NormalizeActionDispatchAttempt(attempt ActionDispatchAttempt) (ActionDispatif attempt.DispatchCount < 0 {return ActionDispatchAttempt{}, fmt.Errorf("action dispatch count cannot be negative")}+ bound := attempt.OperationKind != "" || attempt.OperationVersion != 0 || attempt.RequestDigest != "" || attempt.AgentID != ""+ if bound && (attempt.OperationKind == "" || attempt.OperationVersion <= 0 || attempt.RequestDigest == "" || attempt.AgentID == "") {+ return ActionDispatchAttempt{}, fmt.Errorf("action dispatch operation binding is incomplete")+ }return attempt, nil}+func BindActionDispatchAttempt(attempt ActionDispatchAttempt, binding ActionDispatchBinding) (ActionDispatchAttempt, error) {+ attempt.OperationKind = binding.OperationKind+ attempt.OperationVersion = binding.OperationVersion+ attempt.RequestDigest = binding.RequestDigest+ attempt.AgentID = binding.AgentID+ return NormalizeActionDispatchAttempt(attempt)+}+func NormalizeActionDispatchReceipt(receipt ActionDispatchReceipt) (ActionDispatchReceipt, error) {receipt.AttemptID = strings.TrimSpace(receipt.AttemptID)receipt.ActionID = strings.TrimSpace(receipt.ActionID)diff --git a/internal/unifiedresources/action_dispatch_store.go b/internal/unifiedresources/action_dispatch_store.goindex c7f9cde695..f3a217be5c 100644--- a/internal/unifiedresources/action_dispatch_store.go+++ b/internal/unifiedresources/action_dispatch_store.go@@ -15,9 +15,9 @@ func insertActionDispatchSQL(exec sqlExecutor, attempt ActionDispatchAttempt) er}if _, err := exec.Exec(`INSERT INTO action_dispatch_attempts- (attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count)- VALUES (?, ?, ?, ?, ?, NULL, NULL, ?)- `, attempt.ID, attempt.ActionID, string(attempt.State), attempt.CreatedAt, attempt.UpdatedAt, attempt.DispatchCount); err != nil {+ (attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count, operation_kind, operation_version, request_digest, agent_id)+ VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?)+ `, attempt.ID, attempt.ActionID, string(attempt.State), attempt.CreatedAt, attempt.UpdatedAt, attempt.DispatchCount, attempt.OperationKind, attempt.OperationVersion, attempt.RequestDigest, attempt.AgentID); err != nil {return fmt.Errorf("insert action dispatch attempt: %w", err)}if _, err := exec.Exec(`@@ -34,7 +34,7 @@ func scanActionDispatch(scanner interface{ Scan(...any) error }) (ActionDispatchvar state stringvar owner sql.NullStringvar lease sql.NullTime- if err := scanner.Scan(&attempt.ID, &attempt.ActionID, &state, &attempt.CreatedAt, &attempt.UpdatedAt, &owner, &lease, &attempt.DispatchCount); err != nil {+ if err := scanner.Scan(&attempt.ID, &attempt.ActionID, &state, &attempt.CreatedAt, &attempt.UpdatedAt, &owner, &lease, &attempt.DispatchCount, &attempt.OperationKind, &attempt.OperationVersion, &attempt.RequestDigest, &attempt.AgentID); err != nil {return ActionDispatchAttempt{}, err}attempt.State = ActionDispatchState(state)@@ -47,7 +47,7 @@ func scanActionDispatch(scanner interface{ Scan(...any) error }) (ActionDispatchfunc getActionDispatchFrom(queryer actionAuditQueryRower, actionID string) (ActionDispatchAttempt, bool, error) {row := queryer.QueryRow(`- SELECT attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count+ SELECT attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count, operation_kind, operation_version, request_digest, agent_idFROM action_dispatch_attempts WHERE action_id = ?`, strings.TrimSpace(actionID))attempt, err := scanActionDispatch(row)@@ -59,7 +59,7 @@ func getActionDispatchFrom(queryer actionAuditQueryRower, actionID string) (Actifunc getActionDispatchByAttemptFrom(queryer actionAuditQueryRower, attemptID string) (ActionDispatchAttempt, bool, error) {row := queryer.QueryRow(`- SELECT attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count+ SELECT attempt_id, action_id, state, created_at, updated_at, lease_owner, lease_expires_at, dispatch_count, operation_kind, operation_version, request_digest, agent_idFROM action_dispatch_attempts WHERE attempt_id = ?`, strings.TrimSpace(attemptID))attempt, err := scanActionDispatch(row)diff --git a/internal/unifiedresources/action_dispatch_store_test.go b/internal/unifiedresources/action_dispatch_store_test.goindex 7219574197..f9ec09fc2e 100644--- a/internal/unifiedresources/action_dispatch_store_test.go+++ b/internal/unifiedresources/action_dispatch_store_test.go@@ -1,12 +1,50 @@package unifiedresourcesimport (+ "database/sql""errors"+ _ "modernc.org/sqlite"+ "os"+ "path/filepath""sync""testing""time")+func TestSQLiteActionDispatchBindingMigrationKeepsLegacyReceiptPendingInert(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "resources", "unified_resources.db")+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ t.Fatal(err)+ }+ db, err := sql.Open("sqlite", path)+ if err != nil {+ t.Fatal(err)+ }+ _, err = db.Exec(`CREATE TABLE action_dispatch_attempts(attempt_id TEXT PRIMARY KEY,action_id TEXT NOT NULL UNIQUE,state TEXT NOT NULL,created_at DATETIME NOT NULL,updated_at DATETIME NOT NULL,lease_owner TEXT,lease_expires_at DATETIME,dispatch_count INTEGER NOT NULL DEFAULT 0);INSERT INTO action_dispatch_attempts(attempt_id,action_id,state,created_at,updated_at,dispatch_count)VALUES('legacy.dispatch.1','legacy','receipt_pending',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,1)`)+ if err != nil {+ t.Fatal(err)+ }+ if err := db.Close(); err != nil {+ t.Fatal(err)+ }+ store, err := NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ attempt, found, err := store.GetActionDispatchAttempt("legacy")+ if err != nil || !found {+ t.Fatalf("attempt=%#v found=%v err=%v", attempt, found, err)+ }+ if attempt.State != ActionDispatchReceiptPending || attempt.OperationKind != "" || attempt.OperationVersion != 0 || attempt.RequestDigest != "" || attempt.AgentID != "" {+ t.Fatalf("migrated attempt=%#v", attempt)+ }+ if _, claimed, err := store.ClaimActionDispatch("legacy", "worker", time.Now(), time.Minute); err != nil || claimed {+ t.Fatalf("claimed=%v err=%v", claimed, err)+ }+}+func admitDispatchTestAction(t *testing.T, store ResourceStore, id string, now time.Time) ActionDispatchAttempt {t.Helper()record := atomicLifecycleTestRecord(id, ActionStatePlanned)diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.goindex 9ee4f5cfe6..d31ec669b9 100644--- a/internal/unifiedresources/adapters.go+++ b/internal/unifiedresources/adapters.go@@ -9,6 +9,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rcourtman/pulse-go-rewrite/internal/platformsupport""github.com/rcourtman/pulse-go-rewrite/internal/storagehealth")@@ -153,17 +154,18 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {SwapUsed: host.Memory.SwapUsed,SwapTotal: host.Memory.SwapTotal,},- CommandsEnabled: host.CommandsEnabled,- ReportIP: host.ReportIP,- DiskExclude: append([]string(nil), host.DiskExclude...),- IsLegacy: host.IsLegacy,- NetInRate: host.NetInRate,- NetOutRate: host.NetOutRate,- DiskReadRate: host.DiskReadRate,- DiskWriteRate: host.DiskWriteRate,- LinkedNodeID: host.LinkedNodeID,- LinkedVMID: host.LinkedVMID,- LinkedContainerID: host.LinkedContainerID,+ CommandsEnabled: host.CommandsEnabled,+ OperationReceiptVersion: host.OperationReceiptVersion,+ ReportIP: host.ReportIP,+ DiskExclude: append([]string(nil), host.DiskExclude...),+ IsLegacy: host.IsLegacy,+ NetInRate: host.NetInRate,+ NetOutRate: host.NetOutRate,+ DiskReadRate: host.DiskReadRate,+ DiskWriteRate: host.DiskWriteRate,+ LinkedNodeID: host.LinkedNodeID,+ LinkedVMID: host.LinkedVMID,+ LinkedContainerID: host.LinkedContainerID,}if host.PackageUpdates != nil {packages := make([]AgentPackageUpdate, len(host.PackageUpdates.Packages))@@ -521,7 +523,7 @@ func hostPackageUpdateCapabilities(host models.Host) []ResourceCapability {status := host.PackageUpdatesnow := time.Now().UTC()meta := agentPackageUpdateMetaFromModel(status)- if !host.CommandsEnabled || status == nil || !status.Supported || strings.TrimSpace(status.Manager) != "apt" || strings.TrimSpace(status.InventoryHash) == "" || status.PendingCount <= 0 || strings.TrimSpace(status.Error) != "" || !HostPackageUpdateTelemetryFresh(meta, now) {+ if !host.CommandsEnabled || host.OperationReceiptVersion != operationreceipt.ProtocolVersion || status == nil || !status.Supported || strings.TrimSpace(status.Manager) != "apt" || strings.TrimSpace(status.InventoryHash) == "" || status.PendingCount <= 0 || strings.TrimSpace(status.Error) != "" || !HostPackageUpdateTelemetryFresh(meta, now) {return nil}return []ResourceCapability{{@@ -539,7 +541,7 @@ func hostStorageCleanupCapability(host models.Host) (ResourceCapability, bool) {status := host.StorageCleanupnow := time.Now().UTC()meta := agentStorageCleanupMetaFromModel(status)- if !host.CommandsEnabled || status == nil || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" || strings.TrimSpace(status.Fingerprint) == "" || status.ReclaimableBytes < HostStorageCleanupMinReclaimableBytes || strings.TrimSpace(status.Error) != "" || !HostStorageCleanupTelemetryFresh(meta, now) {+ if !host.CommandsEnabled || host.OperationReceiptVersion != operationreceipt.ProtocolVersion || status == nil || !status.Supported || strings.TrimSpace(status.Provider) != "apt-package-cache" || strings.TrimSpace(status.Fingerprint) == "" || status.ReclaimableBytes < HostStorageCleanupMinReclaimableBytes || strings.TrimSpace(status.Error) != "" || !HostStorageCleanupTelemetryFresh(meta, now) {return ResourceCapability{}, false}if _, ok := HostStorageCleanupPressureDisk(convertDisks(host.Disks)); !ok {diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.goindex fff97801a8..bf75a293e1 100644--- a/internal/unifiedresources/adapters_test.go+++ b/internal/unifiedresources/adapters_test.go@@ -1,6 +1,7 @@package unifiedresourcesimport (+ "encoding/json""reflect""strings""testing"@@ -8,6 +9,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/mockruntime""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rcourtman/pulse-go-rewrite/internal/storagehealth")@@ -70,7 +72,7 @@ func TestResourceFromProxmoxNodeUsesDisplayNameWithoutChangingRawNodeIdentity(tfunc TestResourceFromHostAdvertisesElevatedTypedPackageUpdateCapability(t *testing.T) {now := time.Now().UTC()host := models.Host{- ID: "agent-1", Hostname: "host-1", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true,+ ID: "agent-1", Hostname: "host-1", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion,PackageUpdates: &models.HostPackageUpdateStatus{Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 2, CheckedAt: now.Add(-time.Minute), ObservedAt: now, RebootRequired: true,Packages: []models.HostPackageUpdate{{Name: "openssl", InstalledVersion: "1.0", AvailableVersion: "1.1"}},@@ -100,11 +102,13 @@ func TestResourceFromHostAdvertisesElevatedTypedPackageUpdateCapability(t *testifunc TestResourceFromHostDoesNotAdvertiseUnsupportedOrCommandDisabledPackageUpdates(t *testing.T) {base := models.Host{- ID: "agent-1", Hostname: "host-1", Platform: "linux", Status: "online", LastSeen: time.Now().UTC(), CommandsEnabled: true,+ ID: "agent-1", Hostname: "host-1", Platform: "linux", Status: "online", LastSeen: time.Now().UTC(), CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion,PackageUpdates: &models.HostPackageUpdateStatus{Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 1, CheckedAt: time.Now().UTC()},}for _, mutate := range []func(*models.Host){func(host *models.Host) { host.CommandsEnabled = false },+ func(host *models.Host) { host.OperationReceiptVersion = 0 },+ func(host *models.Host) { host.OperationReceiptVersion = operationreceipt.ProtocolVersion + 1 },func(host *models.Host) { host.PackageUpdates.Supported = false },func(host *models.Host) { host.PackageUpdates.Manager = "dnf" },func(host *models.Host) { host.PackageUpdates = nil },@@ -123,10 +127,10 @@ func TestResourceFromHostDoesNotAdvertiseUnsupportedOrCommandDisabledPackageUpdafunc 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,+ ID: "agent-cleanup", Hostname: "host-cleanup", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion,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,+ Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("c", 64), ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now, ObservedAt: now,},}@@ -149,14 +153,16 @@ func TestResourceFromHostAdvertisesPressureBoundPackageCacheCleanup(t *testing.Tfunc 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,+ ID: "agent-cleanup", Hostname: "host-cleanup", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion,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,+ Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("c", 64), ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now, ObservedAt: now,},}mutations := []func(*models.Host){func(host *models.Host) { host.CommandsEnabled = false },+ func(host *models.Host) { host.OperationReceiptVersion = 0 },+ func(host *models.Host) { host.OperationReceiptVersion = operationreceipt.ProtocolVersion + 1 },func(host *models.Host) { host.StorageCleanup.Supported = false },func(host *models.Host) { host.StorageCleanup.Provider = "arbitrary-path" },func(host *models.Host) { host.StorageCleanup.Fingerprint = "" },@@ -184,6 +190,22 @@ func TestResourceFromHostStorageCleanupUsesActualCacheFilesystemAndFailsClosed(t}}+func TestResourceFromCompatibleHostAdvertisesBothDurableAPTCapabilities(t *testing.T) {+ now := time.Now().UTC()+ host := models.Host{ID: "agent", Hostname: "host", Platform: "linux", Status: "online", LastSeen: now, CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion, Disks: []models.Disk{{Mountpoint: "/", Usage: 95}}, PackageUpdates: &models.HostPackageUpdateStatus{Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 2, CheckedAt: now, ObservedAt: now}, StorageCleanup: &models.HostStorageCleanupStatus{Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 512 * 1024 * 1024, CheckedAt: now, ObservedAt: now}}+ resource, _ := resourceFromHost(host)+ if len(resource.Capabilities) != 2 || resource.Agent.OperationReceiptVersion != operationreceipt.ProtocolVersion {+ t.Fatalf("resource=%#v", resource)+ }+ encoded, err := json.Marshal(resource)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(encoded), "operationReceiptVersion") {+ t.Fatalf("public resource exposed receipt protocol: %s", encoded)+ }+}+func TestResourceFromDockerContainerAdvertisesLifecycleCapabilities(t *testing.T) {now := time.Now().UTC()host := models.DockerHost{diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex c5d89f8630..2e27d3fc85 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -109,6 +109,74 @@ func TestActionTruthTypesStayUnifiedResourceOwned(t *testing.T) {}}+func TestOperationReceiptProtocolRemainsInternalToIngestAndRuntime(t *testing.T) {+ repoRoot := filepath.Join("..", "..")+ for _, path := range []string{+ "internal/models/models_frontend.go",+ "internal/unifiedresources/types.go",+ } {+ source, err := os.ReadFile(filepath.Join(repoRoot, path))+ if err != nil {+ t.Fatal(err)+ }+ if path == "internal/models/models_frontend.go" && strings.Contains(string(source), "OperationReceiptVersion") {+ t.Fatalf("%s exposes the raw receipt protocol in a frontend DTO", path)+ }+ if path == "internal/unifiedresources/types.go" {+ field := regexp.MustCompile(`OperationReceiptVersion\s+int\s+` + "`json:\"-\"`")+ if !field.Match(source) {+ t.Fatalf("%s must keep receipt metadata internal-only", path)+ }+ }+ }++ err := filepath.Walk(filepath.Join(repoRoot, "frontend-modern", "src"), func(path string, info os.FileInfo, err error) error {+ if err != nil {+ return err+ }+ if info.IsDir() || (filepath.Ext(path) != ".ts" && filepath.Ext(path) != ".tsx") {+ return nil+ }+ source, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if strings.Contains(string(source), "OperationReceiptVersion") || strings.Contains(string(source), "operationReceiptVersion") {+ t.Errorf("%s learned the internal receipt protocol", filepath.ToSlash(path))+ }+ return nil+ })+ if err != nil {+ t.Fatal(err)+ }++ for _, path := range []string{"internal/actionlifecycle", "internal/workflow", "internal/workflows"} {+ root := filepath.Join(repoRoot, path)+ if _, err := os.Stat(root); os.IsNotExist(err) {+ continue+ }+ err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {+ if err != nil {+ return err+ }+ if info.IsDir() || filepath.Ext(path) != ".go" || strings.HasSuffix(path, "_test.go") {+ return nil+ }+ source, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if regexp.MustCompile(`(?m)^\s*OperationReceiptVersion\s+`).Match(source) {+ t.Errorf("%s declares workflow-local receipt protocol truth", filepath.ToSlash(path))+ }+ return nil+ })+ if err != nil {+ t.Fatal(err)+ }+ }+}+func TestProductionActionLifecycleDoesNotUseRecordActionAuditAsUpsert(t *testing.T) {paths := []string{"../actionlifecycle/service.go", "../ai/tools/action_audit.go", "../api/patrol_action_broker.go"}for _, path := range paths {diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.goindex f3c9feeb45..4130e12e11 100644--- a/internal/unifiedresources/store.go+++ b/internal/unifiedresources/store.go@@ -487,6 +487,10 @@ func (s *SQLiteResourceStore) initSchema() error {lease_owner TEXT,lease_expires_at DATETIME,dispatch_count INTEGER NOT NULL DEFAULT 0+ , operation_kind TEXT NOT NULL DEFAULT ''+ , operation_version INTEGER NOT NULL DEFAULT 0+ , request_digest TEXT NOT NULL DEFAULT ''+ , agent_id TEXT NOT NULL DEFAULT '');CREATE INDEX IF NOT EXISTS idx_action_dispatch_attempts_state_updated ON action_dispatch_attempts(state, updated_at);CREATE TABLE IF NOT EXISTS action_dispatch_outbox (@@ -581,6 +585,9 @@ func (s *SQLiteResourceStore) initSchema() error {if err := s.migrateActionLifecycleEventsSchema(); err != nil {return err}+ if err := s.migrateActionDispatchSchema(); err != nil {+ return err+ }if err := s.migrateResourceOperatorStateSchema(); err != nil {return err}@@ -590,6 +597,23 @@ func (s *SQLiteResourceStore) initSchema() error {return nil}+func (s *SQLiteResourceStore) migrateActionDispatchSchema() error {+ columns, err := s.tableColumns("action_dispatch_attempts")+ if err != nil {+ return err+ }+ definitions := map[string]string{"operation_kind": "TEXT NOT NULL DEFAULT ''", "operation_version": "INTEGER NOT NULL DEFAULT 0", "request_digest": "TEXT NOT NULL DEFAULT ''", "agent_id": "TEXT NOT NULL DEFAULT ''"}+ for name, definition := range definitions {+ if _, ok := columns[name]; ok {+ continue+ }+ if _, err := s.db.Exec("ALTER TABLE action_dispatch_attempts ADD COLUMN " + name + " " + definition); err != nil {+ return fmt.Errorf("add action_dispatch_attempts.%s column: %w", name, err)+ }+ }+ return nil+}+func (s *SQLiteResourceStore) migrateResourceOperatorStateSchema() error {columns, err := s.tableColumns("resource_operator_state")if err != nil {diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.goindex 845b928121..3da7dec3ad 100644--- a/internal/unifiedresources/store_test.go+++ b/internal/unifiedresources/store_test.go@@ -11,8 +11,61 @@ import ("strings""testing""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt")+func TestSQLiteResourceStoreDoesNotPersistRawOperationReceiptProtocolOrReplayAuthority(t *testing.T) {+ now := time.Now().UTC()+ host := models.Host{+ ID: "agent-receipt", Hostname: "host-receipt", Platform: "linux", Status: "online", LastSeen: now,+ CommandsEnabled: true, OperationReceiptVersion: operationreceipt.ProtocolVersion,+ Disks: []models.Disk{{Mountpoint: "/", Usage: 95}},+ PackageUpdates: &models.HostPackageUpdateStatus{Supported: true, Manager: "apt", InventoryHash: "sha256:" + strings.Repeat("a", 64), PendingCount: 1, CheckedAt: now, ObservedAt: now},+ StorageCleanup: &models.HostStorageCleanupStatus{Supported: true, Provider: "apt-package-cache", Fingerprint: "sha256:" + strings.Repeat("b", 64), ReclaimableBytes: 512 << 20, CheckedAt: now, ObservedAt: now},+ }+ resource := HostIngestRecord(host).Resource+ encoded, err := json.Marshal(resource)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(encoded), "operationReceiptVersion") || strings.Contains(string(encoded), "operation_receipt_version") {+ t.Fatalf("public resource exposed raw receipt protocol: %s", encoded)+ }+ capabilities := map[string]bool{}+ for _, capability := range resource.Capabilities {+ capabilities[capability.Name] = true+ }+ if !capabilities["install_os_updates"] || !capabilities["clean_package_cache"] || len(capabilities) != 2 {+ t.Fatalf("derived capabilities = %#v", capabilities)+ }++ store, err := NewSQLiteResourceStore(t.TempDir(), "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ rows, err := store.db.Query(`SELECT name, sql FROM sqlite_master WHERE type='table' ORDER BY name`)+ if err != nil {+ t.Fatal(err)+ }+ defer rows.Close()+ for rows.Next() {+ var name, schema string+ if err := rows.Scan(&name, &schema); err != nil {+ t.Fatal(err)+ }+ lower := strings.ToLower(schema)+ if strings.Contains(lower, "operation_receipt_version") || name == "operation_receipts" {+ t.Fatalf("resource store acquired raw protocol or agent replay authority: table=%q schema=%q", name, schema)+ }+ }+ if err := rows.Err(); err != nil {+ t.Fatal(err)+ }+}+func atomicLifecycleTestRecord(id string, state ActionState) ActionAuditRecord {now := time.Date(2026, 7, 11, 12, 0, 0, 0, time.UTC)actor := ActionActor{SubjectID: "agent:test", Kind: ActionActorService, CredentialID: "service:test", OrgID: "default"}diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.goindex cf25a6bf81..1d8f800c9e 100644--- a/internal/unifiedresources/types.go+++ b/internal/unifiedresources/types.go@@ -822,49 +822,50 @@ 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"`- 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"`+ 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"`+ OperationReceiptVersion int `json:"-"`+ 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.goindex 04fbcddf36..5469000f95 100644--- a/pkg/agents/host/report.go+++ b/pkg/agents/host/report.go@@ -31,17 +31,18 @@ type ClusterNodeSensors struct {// AgentInfo describes the reporting agent.type AgentInfo struct {- ID string `json:"id"`- Version string `json:"version,omitempty"`- Type string `json:"type,omitempty"` // "unified", "host", or "docker" - empty means legacy- IntervalSeconds int `json:"intervalSeconds,omitempty"`- Hostname string `json:"hostname,omitempty"`- UpdatedFrom string `json:"updatedFrom,omitempty"` // Previous version if recently auto-updated- CommandsEnabled bool `json:"commandsEnabled,omitempty"` // Whether AI command execution is enabled- DiskExclude []string `json:"diskExclude,omitempty"` // Disk exclusion patterns from --disk-exclude flag- AppliedConfig *ConfigFingerprint `json:"appliedConfig,omitempty"`- Update *UpdateStatus `json:"update,omitempty"`- Modules []ModuleStatus `json:"modules,omitempty"`+ ID string `json:"id"`+ Version string `json:"version,omitempty"`+ Type string `json:"type,omitempty"` // "unified", "host", or "docker" - empty means legacy+ IntervalSeconds int `json:"intervalSeconds,omitempty"`+ Hostname string `json:"hostname,omitempty"`+ UpdatedFrom string `json:"updatedFrom,omitempty"` // Previous version if recently auto-updated+ CommandsEnabled bool `json:"commandsEnabled,omitempty"` // Whether AI command execution is enabled+ OperationReceiptVersion int `json:"operationReceiptVersion,omitempty"`+ DiskExclude []string `json:"diskExclude,omitempty"` // Disk exclusion patterns from --disk-exclude flag+ AppliedConfig *ConfigFingerprint `json:"appliedConfig,omitempty"`+ Update *UpdateStatus `json:"update,omitempty"`+ Modules []ModuleStatus `json:"modules,omitempty"`}// ModuleStatus describes whether an enabled Unified Agent module initializeddiff --git a/pkg/agents/host/report_test.go b/pkg/agents/host/report_test.goindex 44c71ee84c..9e48287684 100644--- a/pkg/agents/host/report_test.go+++ b/pkg/agents/host/report_test.go@@ -6,6 +6,16 @@ import ("time")+func TestLegacyReportJSONDefaultsOperationReceiptProtocolUnsupported(t *testing.T) {+ var report Report+ if err := json.Unmarshal([]byte(`{"agent":{"id":"legacy","commandsEnabled":true},"host":{"hostname":"legacy"}}`), &report); err != nil {+ t.Fatal(err)+ }+ if report.Agent.OperationReceiptVersion != 0 {+ t.Fatalf("version=%d", report.Agent.OperationReceiptVersion)+ }+}+func float64Ptr(value float64) *float64 {return &value}