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
Expose unified audit history
rcourtmanfae55976a513
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 6caec5e197..a94370bb0f 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -87,6 +87,11 @@ does not own unified-resource history or control-plane timeline persistence.Those runtime changes now travel through the shared API and unified-resourcecontracts, which keeps fleet bootstrap and identity continuity separate fromresource-change recording and historical inspection.+The shared API runtime now also exposes unified-resource action, lifecycle,+and export audit reads alongside the enterprise audit surface. That read path+belongs to the API and unified-resource contracts, not to lifecycle ownership,+so the agent-install and registration lane stays focused on fleet continuity+instead of adopting execution-history persistence as a side effect.The owned backend API surfaces must preserve the exact-release installerfallback, canonical /api/auto-register behavior, and hosted org install-commanddiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex e661f5eb94..ee117922fe 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -138,3 +138,6 @@ The same runtime boundary now also owns durable action execution auditing.startup, and the write-action tool paths under `internal/ai/tools/` persistappend-only action lifecycle and action audit records through that sharedstore instead of leaving command execution state in memory-only tool helpers.+Those unified-resource action and export audit records are now also exposed+through the enterprise audit read surface so operators can inspect the+execution trail without reaching into storage internals.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 23c2fc0c90..5169a290e4 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -22,16 +22,17 @@ Own canonical runtime payload shapes between backend and frontend.1. `internal/api/contract_test.go`2. `internal/api/resources.go`3. `internal/api/alerts.go`-4. `frontend-modern/src/types/api.ts`-5. `frontend-modern/src/api/responseUtils.ts`-6. `frontend-modern/src/components/Settings/APITokenManager.tsx`-7. `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`-8. `frontend-modern/src/components/Settings/UnifiedAgents.tsx`-9. `frontend-modern/src/utils/agentInstallCommand.ts`-10. `frontend-modern/src/api/nodes.ts`-11. `frontend-modern/src/api/license.ts`-12. `frontend-modern/src/api/monitoredSystemLedger.ts`-13. `internal/api/monitored_system_ledger.go`+4. `internal/api/activity_audit_handlers.go`+5. `frontend-modern/src/types/api.ts`+6. `frontend-modern/src/api/responseUtils.ts`+7. `frontend-modern/src/components/Settings/APITokenManager.tsx`+8. `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`+9. `frontend-modern/src/components/Settings/UnifiedAgents.tsx`+10. `frontend-modern/src/utils/agentInstallCommand.ts`+11. `frontend-modern/src/api/nodes.ts`+12. `frontend-modern/src/api/license.ts`+13. `frontend-modern/src/api/monitoredSystemLedger.ts`+14. `internal/api/monitored_system_ledger.go`## Shared Boundaries@@ -69,11 +70,12 @@ Own canonical runtime payload shapes between backend and frontend.2. Update frontend API types in lockstep with backend contract changes3. Add dedicated contract tests for new stable payloads4. Route unified resource sensitivity, routing, and `aiSafeSummary` payload changes through `internal/api/resources.go`, `internal/api/contract_test.go`, and the canonical frontend resource consumer proofs together; resource governance metadata must not ship as an API-only or frontend-only heuristic-5. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`-6. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`-7. Add or change infrastructure operations token generation, lookup, assignment, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`-8. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.-9. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.+5. Route unified-resource action, lifecycle, and export audit reads through `internal/api/activity_audit_handlers.go`, `internal/api/router_routes_licensing.go`, and `internal/api/contract_test.go` together so the control-plane execution trail stays on a governed API contract instead of a store-only shape+6. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`+7. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`+8. Add or change infrastructure operations token generation, lookup, assignment, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`+9. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.+10. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.## Forbidden Paths@@ -114,6 +116,12 @@ through the owned backend response: resource objects can expose canonical`capabilities`, `relationships`, and `recentChanges` in addition to policy andidentity metadata, so the backend payload contract stays aligned with thetimeline and control-plane model instead of flattening those fields away.+The same API contract now also exposes the unified-resource control-plane+history through dedicated enterprise audit reads. The action, lifecycle, and+export history endpoints live in `internal/api/activity_audit_handlers.go` and+`internal/api/router_routes_licensing.go`, and the contract tests now pin their+response shapes so the execution trail remains queryable through the governed+API surface rather than only through the underlying store.The tenant-scoped unified resource API now also stays on canonicalunified-resource seeds end to end: `internal/api/resources.go`,`internal/api/router_helpers.go`, and `internal/api/state_provider.go` nodiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 7e6b4e4cf5..ffbd23f5e1 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -109,6 +109,12 @@ handlers stay on canonical Patrol runtime wiring: recovery- andstorage-adjacent API helpers must not revive tenant snapshot-provider bridgesthrough `internal/api/ai_handlers.go` once Patrol can initialize from tenant`ReadState` and unified-resource providers directly.+The same shared API runtime also exposes unified-resource action, lifecycle,+and export audit reads, but storage and recovery must continue to treat that+as adjacent governed API ownership rather than timeline-store ownership. The+storage and recovery lanes still own their own persistence and query+contracts, while the control-plane execution trail remains governed by the+unified-resource and audit contracts.The frontend storage and recovery surfaces are also first-class runtime entrypoints. `frontend-modern/src/components/Storage/` plusdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 824199cbdf..d412ab1808 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -92,6 +92,9 @@ memory-only models.The in-memory store mirrors the durable audit contract by upserting actionaudits on action ID, so tests and runtime callers observe the same currentrecord state that SQLite persists for the control-plane execution trail.+The enterprise audit API now reads those same unified-resource action and+export records back out, so the durable store is not just a write sink but the+canonical history surface for the control-plane verbs.The unified resource core is strong and canonical, but monitoring and somefrontend/API consumers are still being tightened around it.diff --git a/internal/api/activity_audit_handlers.go b/internal/api/activity_audit_handlers.goindex d422158996..12f29edacf 100644--- a/internal/api/activity_audit_handlers.go+++ b/internal/api/activity_audit_handlers.go@@ -12,6 +12,7 @@ import ("strings""time"+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/pkg/audit")@@ -21,13 +22,30 @@ var validAuditEventID = regexp.MustCompile(`^[a-zA-Z0-9\-]+$`)var resolveWebhookIPs = net.DefaultResolver.LookupIPAddr// AuditHandlers provides HTTP handlers for audit log endpoints.-type AuditHandlers struct{}+type AuditHandlers struct {+ resourceStoreProvider func(orgID string) (unifiedresources.ResourceStore, error)+}// NewAuditHandlers creates a new AuditHandlers instance.func NewAuditHandlers() *AuditHandlers {return &AuditHandlers{}}+// SetResourceStoreProvider configures the store used for unified-resource audit history.+func (h *AuditHandlers) SetResourceStoreProvider(provider func(orgID string) (unifiedresources.ResourceStore, error)) {+ if h == nil {+ return+ }+ h.resourceStoreProvider = provider+}++func (h *AuditHandlers) getResourceStore(orgID string) (unifiedresources.ResourceStore, error) {+ if h == nil || h.resourceStoreProvider == nil {+ return nil, fmt.Errorf("resource audit store unavailable")+ }+ return h.resourceStoreProvider(orgID)+}+// HandleListAuditEvents handles GET /api/auditfunc (h *AuditHandlers) HandleListAuditEvents(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {@@ -473,6 +491,142 @@ func (h *AuditHandlers) HandleAuditSummary(w http.ResponseWriter, r *http.Requesjson.NewEncoder(w).Encode(summary)}+// HandleListUnifiedActionAudits handles GET /api/audit/actions.+func (h *AuditHandlers) HandleListUnifiedActionAudits(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ orgID := GetOrgID(r.Context())+ store, err := h.getResourceStore(orgID)+ if err != nil {+ writeErrorResponse(w, http.StatusServiceUnavailable, "audit_unavailable", "Unified resource audit history is not available", nil)+ return+ }++ query := r.URL.Query()+ resourceID := unifiedresources.CanonicalResourceID(query.Get("resourceId"))+ since := parseAuditSince(query)+ limit := parseAuditLimit(query.Get("limit"), 100)++ audits, err := store.GetActionAudits(resourceID, since, limit)+ if err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "query_failed", "Failed to query action audits", nil)+ return+ }++ response := map[string]any{+ "audits": audits,+ "count": len(audits),+ }+ if resourceID != "" {+ response["resourceId"] = resourceID+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(response)+}++// HandleListUnifiedActionLifecycleEvents handles GET /api/audit/actions/{id}/events.+func (h *AuditHandlers) HandleListUnifiedActionLifecycleEvents(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ actionID := strings.TrimSpace(r.PathValue("id"))+ if actionID == "" {+ writeErrorResponse(w, http.StatusBadRequest, "missing_id", "Missing action ID", nil)+ return+ }+ if !validAuditEventID.MatchString(actionID) || len(actionID) > 64 {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format", nil)+ return+ }++ orgID := GetOrgID(r.Context())+ store, err := h.getResourceStore(orgID)+ if err != nil {+ writeErrorResponse(w, http.StatusServiceUnavailable, "audit_unavailable", "Unified resource audit history is not available", nil)+ return+ }++ query := r.URL.Query()+ since := parseAuditSince(query)+ limit := parseAuditLimit(query.Get("limit"), 100)++ events, err := store.GetActionLifecycleEvents(actionID, since, limit)+ if err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "query_failed", "Failed to query action lifecycle events", nil)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "actionId": actionID,+ "events": events,+ "count": len(events),+ })+}++// HandleListUnifiedExportAudits handles GET /api/audit/exports.+func (h *AuditHandlers) HandleListUnifiedExportAudits(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ orgID := GetOrgID(r.Context())+ store, err := h.getResourceStore(orgID)+ if err != nil {+ writeErrorResponse(w, http.StatusServiceUnavailable, "audit_unavailable", "Unified resource audit history is not available", nil)+ return+ }++ query := r.URL.Query()+ since := parseAuditSince(query)+ limit := parseAuditLimit(query.Get("limit"), 100)++ records, err := store.GetExportAudits(since, limit)+ if err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "query_failed", "Failed to query export audits", nil)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "audits": records,+ "count": len(records),+ })+}++func parseAuditSince(query url.Values) time.Time {+ for _, key := range []string{"since", "startTime"} {+ raw := strings.TrimSpace(query.Get(key))+ if raw == "" {+ continue+ }+ if t, err := time.Parse(time.RFC3339, raw); err == nil {+ return t.UTC()+ }+ }+ return time.Time{}+}++func parseAuditLimit(raw string, defaultLimit int) int {+ limit := defaultLimit+ if trimmed := strings.TrimSpace(raw); trimmed != "" {+ if parsed, err := strconv.Atoi(trimmed); err == nil && parsed > 0 {+ limit = parsed+ }+ }+ if limit <= 0 {+ return defaultLimit+ }+ return limit+}+func getLoggerForOrg(orgID string) audit.Logger {if mgr := GetTenantAuditManager(); mgr != nil {return mgr.GetLogger(orgID)diff --git a/internal/api/audit_handlers_test.go b/internal/api/audit_handlers_test.goindex 29875cfcbe..590896efd9 100644--- a/internal/api/audit_handlers_test.go+++ b/internal/api/audit_handlers_test.go@@ -11,6 +11,7 @@ import ("testing""time"+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/pkg/audit""github.com/stretchr/testify/assert")@@ -664,3 +665,158 @@ func TestHandleAuditSummary(t *testing.T) {assert.Equal(t, http.StatusInternalServerError, w.Code)})}++func TestHandleListUnifiedActionAudits(t *testing.T) {+ store := unifiedresources.NewMemoryStore()+ now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)+ records := []unifiedresources.ActionAuditRecord{+ {+ ID: "action-1",+ CreatedAt: now.Add(-2 * time.Minute),+ UpdatedAt: now.Add(-2 * time.Minute),+ State: unifiedresources.ActionStateCompleted,+ Request: unifiedresources.ActionRequest{+ RequestID: "req-1",+ ResourceID: "vm:100",+ CapabilityName: "restart",+ RequestedBy: "agent:ops",+ },+ },+ {+ ID: "action-2",+ CreatedAt: now.Add(-time.Minute),+ UpdatedAt: now.Add(-time.Minute),+ State: unifiedresources.ActionStateFailed,+ Request: unifiedresources.ActionRequest{+ RequestID: "req-2",+ ResourceID: "vm:101",+ CapabilityName: "restart",+ RequestedBy: "agent:ops",+ },+ },+ }+ for _, record := range records {+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }+ }++ handler := NewAuditHandlers()+ handler.SetResourceStoreProvider(func(string) (unifiedresources.ResourceStore, error) {+ return store, nil+ })++ req := httptest.NewRequest(http.MethodGet, "/api/audit/actions?limit=10", nil)+ rec := httptest.NewRecorder()+ handler.HandleListUnifiedActionAudits(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ var payload struct {+ Audits []unifiedresources.ActionAuditRecord `json:"audits"`+ Count int `json:"count"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatalf("unmarshal action audits: %v", err)+ }+ if payload.Count != 2 {+ t.Fatalf("expected count 2, got %d", payload.Count)+ }+ if len(payload.Audits) != 2 {+ t.Fatalf("expected 2 action audits, got %d", len(payload.Audits))+ }+ if payload.Audits[0].ID != "action-2" || payload.Audits[1].ID != "action-1" {+ t.Fatalf("unexpected action audit order: %#v", payload.Audits)+ }+}++func TestHandleListUnifiedActionLifecycleEvents(t *testing.T) {+ store := unifiedresources.NewMemoryStore()+ now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)+ events := []unifiedresources.ActionLifecycleEvent{+ {ActionID: "action-1", Timestamp: now.Add(-2 * time.Minute), State: unifiedresources.ActionStatePlanned},+ {ActionID: "action-1", Timestamp: now.Add(-time.Minute), State: unifiedresources.ActionStateCompleted},+ }+ for _, event := range events {+ if err := store.RecordActionLifecycleEvent(event); err != nil {+ t.Fatalf("RecordActionLifecycleEvent: %v", err)+ }+ }++ handler := NewAuditHandlers()+ handler.SetResourceStoreProvider(func(string) (unifiedresources.ResourceStore, error) {+ return store, nil+ })++ req := httptest.NewRequest(http.MethodGet, "/api/audit/actions/action-1/events?limit=10", nil)+ req.SetPathValue("id", "action-1")+ rec := httptest.NewRecorder()+ handler.HandleListUnifiedActionLifecycleEvents(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ var payload struct {+ ActionID string `json:"actionId"`+ Events []unifiedresources.ActionLifecycleEvent `json:"events"`+ Count int `json:"count"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatalf("unmarshal action lifecycle events: %v", err)+ }+ if payload.ActionID != "action-1" {+ t.Fatalf("expected action-1, got %q", payload.ActionID)+ }+ if payload.Count != 2 || len(payload.Events) != 2 {+ t.Fatalf("unexpected lifecycle event payload: %#v", payload)+ }+ if payload.Events[0].State != unifiedresources.ActionStateCompleted || payload.Events[1].State != unifiedresources.ActionStatePlanned {+ t.Fatalf("unexpected lifecycle order: %#v", payload.Events)+ }+}++func TestHandleListUnifiedExportAudits(t *testing.T) {+ store := unifiedresources.NewMemoryStore()+ now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)+ if err := store.RecordExportAudit(unifiedresources.ExportAuditRecord{+ ID: "export-1",+ Timestamp: now.Add(-time.Minute),+ Actor: "agent:ops",+ EnvelopeHash: "hash-1",+ Decision: unifiedresources.ExportAllowed,+ Destination: "gpt-4o",+ Redactions: []string{"metadata.hostname"},+ }); err != nil {+ t.Fatalf("RecordExportAudit: %v", err)+ }++ handler := NewAuditHandlers()+ handler.SetResourceStoreProvider(func(string) (unifiedresources.ResourceStore, error) {+ return store, nil+ })++ req := httptest.NewRequest(http.MethodGet, "/api/audit/exports?limit=10", nil)+ rec := httptest.NewRecorder()+ handler.HandleListUnifiedExportAudits(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ var payload struct {+ Audits []unifiedresources.ExportAuditRecord `json:"audits"`+ Count int `json:"count"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatalf("unmarshal export audits: %v", err)+ }+ if payload.Count != 1 || len(payload.Audits) != 1 {+ t.Fatalf("unexpected export payload: %#v", payload)+ }+ if payload.Audits[0].ID != "export-1" {+ t.Fatalf("unexpected export audit id: %q", payload.Audits[0].ID)+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 85e32ab250..462203ad82 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -3567,6 +3567,199 @@ func TestContract_ResourceListCarriesTimelineAndCapabilityContracts(t *testing.TassertJSONSnapshot(t, got, want)}+func TestContract_UnifiedActionAuditsJSONSnapshot(t *testing.T) {+ now := time.Date(2026, 3, 18, 16, 0, 0, 0, time.UTC)+ payload := struct {+ Audits []unifiedresources.ActionAuditRecord `json:"audits"`+ Count int `json:"count"`+ ResourceID string `json:"resourceId,omitempty"`+ }{+ Audits: []unifiedresources.ActionAuditRecord{+ {+ ID: "action-1",+ CreatedAt: now,+ UpdatedAt: now,+ State: unifiedresources.ActionStateCompleted,+ Request: unifiedresources.ActionRequest{+ RequestID: "req-1",+ ResourceID: "vm:42",+ CapabilityName: "restart",+ Reason: "maintenance",+ RequestedBy: "agent:ops",+ },+ Plan: unifiedresources.ActionPlan{+ ActionID: "action-1",+ RequestID: "req-1",+ Allowed: true,+ RequiresApproval: false,+ ApprovalPolicy: unifiedresources.ApprovalNone,+ RollbackAvailable: false,+ PlannedAt: now,+ ExpiresAt: now.Add(5 * time.Minute),+ ResourceVersion: "rv-1",+ PolicyVersion: "pv-1",+ GraphVersion: "gv-1",+ PlanHash: "hash-1",+ },+ Approvals: []unifiedresources.ActionApprovalRecord{+ {+ Actor: "[email protected]",+ Method: unifiedresources.MethodUI,+ Timestamp: now.Add(time.Minute),+ Outcome: unifiedresources.OutcomeApproved,+ Reason: "approved",+ },+ },+ Result: &unifiedresources.ExecutionResult{+ Success: true,+ Output: "done",+ },+ },+ },+ Count: 1,+ ResourceID: "vm:42",+ }++ got, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal action audits response: %v", err)+ }++ const want = `{+ "audits":[+ {+ "id":"action-1",+ "createdAt":"2026-03-18T16:00:00Z",+ "updatedAt":"2026-03-18T16:00:00Z",+ "state":"completed",+ "request":{+ "requestId":"req-1",+ "resourceId":"vm:42",+ "capabilityName":"restart",+ "reason":"maintenance",+ "requestedBy":"agent:ops"+ },+ "plan":{+ "actionId":"action-1",+ "requestId":"req-1",+ "allowed":true,+ "requiresApproval":false,+ "approvalPolicy":"none",+ "rollbackAvailable":false,+ "plannedAt":"2026-03-18T16:00:00Z",+ "expiresAt":"2026-03-18T16:05:00Z",+ "resourceVersion":"rv-1",+ "policyVersion":"pv-1",+ "graphVersion":"gv-1",+ "planHash":"hash-1"+ },+ "approvals":[+ {+ "actor":"[email protected]",+ "method":"ui",+ "timestamp":"2026-03-18T16:01:00Z",+ "outcome":"approved",+ "reason":"approved"+ }+ ],+ "result":{+ "success":true,+ "output":"done"+ }+ }+ ],+ "count":1,+ "resourceId":"vm:42"+ }`++ assertJSONSnapshot(t, got, want)+}++func TestContract_UnifiedActionLifecycleEventsJSONSnapshot(t *testing.T) {+ now := time.Date(2026, 3, 18, 16, 0, 0, 0, time.UTC)+ payload := struct {+ ActionID string `json:"actionId"`+ Events []unifiedresources.ActionLifecycleEvent `json:"events"`+ Count int `json:"count"`+ }{+ ActionID: "action-1",+ Events: []unifiedresources.ActionLifecycleEvent{+ {+ ActionID: "action-1",+ Timestamp: now,+ State: unifiedresources.ActionStatePlanned,+ Actor: "system",+ Message: "planned",+ },+ },+ Count: 1,+ }++ got, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal action lifecycle response: %v", err)+ }++ const want = `{+ "actionId":"action-1",+ "events":[+ {+ "actionId":"action-1",+ "timestamp":"2026-03-18T16:00:00Z",+ "state":"planned",+ "actor":"system",+ "message":"planned"+ }+ ],+ "count":1+ }`++ assertJSONSnapshot(t, got, want)+}++func TestContract_UnifiedExportAuditsJSONSnapshot(t *testing.T) {+ now := time.Date(2026, 3, 18, 16, 0, 0, 0, time.UTC)+ payload := struct {+ Audits []unifiedresources.ExportAuditRecord `json:"audits"`+ Count int `json:"count"`+ }{+ Audits: []unifiedresources.ExportAuditRecord{+ {+ ID: "export-1",+ Timestamp: now,+ Actor: "agent:ops",+ EnvelopeHash: "hash-1",+ Decision: unifiedresources.ExportRedacted,+ Destination: "local-llama",+ Redactions: []string{"metadata.hostname"},+ },+ },+ Count: 1,+ }++ got, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal export audits response: %v", err)+ }++ const want = `{+ "audits":[+ {+ "id":"export-1",+ "timestamp":"2026-03-18T16:00:00Z",+ "actor":"agent:ops",+ "envelopeHash":"hash-1",+ "decision":"redacted",+ "destination":"local-llama",+ "redactions":["metadata.hostname"]+ }+ ],+ "count":1+ }`++ assertJSONSnapshot(t, got, want)+}+func mustStreamEvent(t *testing.T, eventType string, data interface{}) chat.StreamEvent {t.Helper()diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex a859a656c7..284e8cff83 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -421,6 +421,9 @@ var allRouteAllowlist = []string{"GET /api/audit/{id}/verify","GET /api/audit/export","GET /api/audit/summary",+ "GET /api/audit/actions",+ "GET /api/audit/actions/{id}/events",+ "GET /api/audit/exports","GET /api/admin/orgs/{id}/billing-state","PUT /api/admin/orgs/{id}/billing-state","POST /api/admin/orgs/{id}/suspend",diff --git a/internal/api/router.go b/internal/api/router.goindex 65faca41a0..b49f9cbf00 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -422,6 +422,7 @@ func (r *Router) setupRoutes() {stripeWebhookHandlers := r.stripeWebhookHandlersinfraUpdateHandlers := NewUpdateDetectionHandlers(r.monitor, r.defaultReadState())auditHandlers := NewAuditHandlers()+ auditHandlers.SetResourceStoreProvider(r.resourceHandlers.getStore)// System settings and API token managementr.systemSettingsHandler = NewSystemSettingsHandler(r.config, r.persistence, r.wsHub, r.mtMonitor, r.monitor, r.reloadSystemSettings, r.reloadFunc)diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.goindex e97836ad84..6849f0367c 100644--- a/internal/api/router_routes_licensing.go+++ b/internal/api/router_routes_licensing.go@@ -110,6 +110,24 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHan}RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditAdminEndpoints.HandleSummary))(w, req)}))+ r.mux.HandleFunc("GET /api/audit/actions", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {+ if !ensureAdminSession(r.config, w, req) {+ return+ }+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListUnifiedActionAudits))(w, req)+ }))+ r.mux.HandleFunc("GET /api/audit/actions/{id}/events", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {+ if !ensureAdminSession(r.config, w, req) {+ return+ }+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListUnifiedActionLifecycleEvents))(w, req)+ }))+ r.mux.HandleFunc("GET /api/audit/exports", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {+ if !ensureAdminSession(r.config, w, req) {+ return+ }+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListUnifiedExportAudits))(w, req)+ }))// RBAC routes (Phase 2 - Enterprise feature)r.mux.HandleFunc("/api/admin/roles", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.goindex 96cab21bfd..074ab68832 100644--- a/internal/unifiedresources/store.go+++ b/internal/unifiedresources/store.go@@ -496,12 +496,22 @@ func (s *SQLiteResourceStore) RecordChange(change ResourceChange) error {func (s *SQLiteResourceStore) GetRecentChanges(canonicalID string, since time.Time, limit int) ([]ResourceChange, error) {query := `- SELECT id, observed_at, occurred_at, kind, from_state, to_state, source_type, source_adapter, actor, confidence, reason, related_resources, metadata_json- FROM resource_changes- WHERE canonical_id = ? AND observed_at >= ?- ORDER BY observed_at DESC`+ SELECT id, canonical_id, observed_at, occurred_at, kind, from_state, to_state, source_type, source_adapter, actor, confidence, reason, related_resources, metadata_json+ FROM resource_changes`- args := []any{CanonicalResourceID(canonicalID), since}+ args := []any{}+ canonicalID = CanonicalResourceID(canonicalID)+ if canonicalID != "" {+ query += `+ WHERE canonical_id = ? AND observed_at >= ?`+ args = append(args, canonicalID, since)+ } else {+ query += `+ WHERE observed_at >= ?`+ args = append(args, since)+ }+ query += `+ ORDER BY observed_at DESC`if limit > 0 {query += ` LIMIT ?`args = append(args, limit)@@ -518,11 +528,11 @@ func (s *SQLiteResourceStore) GetRecentChanges(canonicalID string, since time.Tivar c ResourceChangevar conf, kindStr stringvar relText, metaText sql.NullString- c.ResourceID = canonicalID- if err := rows.Scan(&c.ID, &c.ObservedAt, &c.OccurredAt, &kindStr, &c.From, &c.To, &c.SourceType, &c.SourceAdapter, &c.Actor, &conf, &c.Reason, &relText, &metaText); err != nil {+ if err := rows.Scan(&c.ID, &c.ResourceID, &c.ObservedAt, &c.OccurredAt, &kindStr, &c.From, &c.To, &c.SourceType, &c.SourceAdapter, &c.Actor, &conf, &c.Reason, &relText, &metaText); err != nil {return nil, fmt.Errorf("scan resource change row: %w", err)}+ c.ResourceID = CanonicalResourceID(c.ResourceID)c.Kind = ChangeKind(kindStr)c.Confidence = ChangeConfidence(conf)@@ -587,11 +597,21 @@ func (s *SQLiteResourceStore) RecordActionAudit(record ActionAuditRecord) errorfunc (s *SQLiteResourceStore) GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error) {query := `SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json- FROM action_audits- WHERE canonical_id = ? AND created_at >= ?- ORDER BY created_at DESC`+ FROM action_audits`- args := []any{CanonicalResourceID(canonicalID), since}+ args := []any{}+ canonicalID = CanonicalResourceID(canonicalID)+ if canonicalID != "" {+ query += `+ WHERE canonical_id = ? AND created_at >= ?`+ args = append(args, canonicalID, since)+ } else {+ query += `+ WHERE created_at >= ?`+ args = append(args, since)+ }+ query += `+ ORDER BY created_at DESC`if limit > 0 {query += ` LIMIT ?`args = append(args, limit)@@ -664,11 +684,21 @@ func (s *SQLiteResourceStore) RecordActionLifecycleEvent(event ActionLifecycleEvfunc (s *SQLiteResourceStore) GetActionLifecycleEvents(actionID string, since time.Time, limit int) ([]ActionLifecycleEvent, error) {query := `SELECT action_id, timestamp, state, actor, message- FROM action_lifecycle_events- WHERE action_id = ? AND timestamp >= ?+ FROM action_lifecycle_events`++ args := []any{}+ actionID = strings.TrimSpace(actionID)+ if actionID != "" {+ query += `+ WHERE action_id = ? AND timestamp >= ?`+ args = append(args, actionID, since)+ } else {+ query += `+ WHERE timestamp >= ?`+ args = append(args, since)+ }+ query += `ORDER BY timestamp DESC`-- args := []any{actionID, since}if limit > 0 {query += ` LIMIT ?`args = append(args, limit)diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.goindex 1ceb55185f..3d98c70811 100644--- a/internal/unifiedresources/store_test.go+++ b/internal/unifiedresources/store_test.go@@ -393,6 +393,103 @@ func TestMemoryStore_RecordActionAudit_UpsertsByID(t *testing.T) {}}+func TestSQLiteStore_GetActionAudits_AllWhenResourceIDBlank(t *testing.T) {+ store := newTestStore(t)+ now := time.Date(2026, 3, 18, 13, 45, 0, 0, time.UTC)++ records := []ActionAuditRecord{+ {+ ID: "action-3",+ CreatedAt: now.Add(-2 * time.Minute),+ UpdatedAt: now.Add(-2 * time.Minute),+ State: ActionStatePlanned,+ Request: ActionRequest{+ RequestID: "req-3",+ ResourceID: "vm:400",+ CapabilityName: "restart",+ RequestedBy: "agent:test",+ },+ },+ {+ ID: "action-4",+ CreatedAt: now.Add(-time.Minute),+ UpdatedAt: now.Add(-time.Minute),+ State: ActionStateCompleted,+ Request: ActionRequest{+ RequestID: "req-4",+ ResourceID: "vm:401",+ CapabilityName: "restart",+ RequestedBy: "agent:test",+ },+ },+ }++ for _, record := range records {+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatalf("RecordActionAudit(%s): %v", record.ID, err)+ }+ }++ results, err := store.GetActionAudits("", now.Add(-time.Hour), 10)+ if err != nil {+ t.Fatalf("GetActionAudits: %v", err)+ }+ if len(results) != 2 {+ t.Fatalf("expected 2 action audits without resource filter, got %d", len(results))+ }+ if results[0].ID != "action-4" || results[1].ID != "action-3" {+ t.Fatalf("unexpected action audit order: %+v", results)+ }+}++func TestSQLiteStore_GetRecentChanges_AllWhenResourceIDBlank(t *testing.T) {+ store := newTestStore(t)+ now := time.Date(2026, 3, 18, 13, 50, 0, 0, time.UTC)++ changes := []ResourceChange{+ {+ ID: "change-1",+ ResourceID: "vm:500",+ ObservedAt: now.Add(-2 * time.Minute),+ Kind: ChangeRestart,+ SourceType: SourcePlatformEvent,+ SourceAdapter: AdapterDocker,+ Confidence: ConfidenceHigh,+ Reason: "restart detected",+ },+ {+ ID: "change-2",+ ResourceID: "vm:501",+ ObservedAt: now.Add(-time.Minute),+ Kind: ChangeConfigUpdate,+ SourceType: SourcePulseDiff,+ SourceAdapter: AdapterProxmox,+ Confidence: ConfidenceMedium,+ Reason: "configuration drift",+ },+ }++ for _, change := range changes {+ if err := store.RecordChange(change); err != nil {+ t.Fatalf("RecordChange(%s): %v", change.ID, err)+ }+ }++ results, err := store.GetRecentChanges("", now.Add(-time.Hour), 10)+ if err != nil {+ t.Fatalf("GetRecentChanges: %v", err)+ }+ if len(results) != 2 {+ t.Fatalf("expected 2 recent changes without resource filter, got %d", len(results))+ }+ if results[0].ID != "change-2" || results[1].ID != "change-1" {+ t.Fatalf("unexpected recent change order: %+v", results)+ }+ if results[0].ResourceID != "vm:501" || results[1].ResourceID != "vm:500" {+ t.Fatalf("expected canonical resource IDs to round-trip, got %+v", results)+ }+}+func TestActionLifecycleEvent_RoundTrip(t *testing.T) {store := newTestStore(t)now := time.Date(2026, 3, 18, 14, 0, 0, 0, time.UTC)