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
Replace the two non-discriminating audit telemetry fields and guard the class
rcourtman72eaab444f14
diff --git a/docs/PRIVACY.md b/docs/PRIVACY.mdindex d73ab858d0..f953af622e 100644--- a/docs/PRIVACY.md+++ b/docs/PRIVACY.md@@ -111,8 +111,7 @@ Every field is listed below with the reason it exists. Nothing else is included| Has API tokens | `true`/`false` | See whether token-based automation/integration is being used without sending token counts || RBAC custom roles | `3` | Count roles created by the operator, excluding the roles that ship built in, without sending role names, permissions, or scopes || RBAC user assignments | `7` | Count user-to-role assignments without sending usernames, role names, or permissions |-| Audit logging persistent | `true`/`false` | See whether a persistent audit store is active rather than console-only logging, without sending any audit event |-| Audit events 30d | `41` | Count audit events retained in the current 30-day telemetry window without sending event types, actors, targets, outcomes, or event detail |+| Audit reads 30d | `41` | Count how many times an entitled operator opened or exported the audit log in the current 30-day telemetry window, without sending query filters, actors, ranges, or any audit event || Report schedules | `5` | Count configured scheduled reports without sending schedule names, report scope, formats, or delivery recipients || Report schedules enabled | `4` | Count scheduled reports that are switched on, without sending schedule names, scope, or recipients || Report schedules run 30d | `2` | Count scheduled reports that last ran inside the current 30-day telemetry window, without sending run times, report contents, or delivery results |diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex a705fb7ee2..d1866f66c8 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -5801,3 +5801,13 @@ The read happens in `applyLicensedFeatureConfigSnapshot``TestApplyLicensedFeatureConfigSnapshot_CountsScheduledReportingAndProfiles`,which also asserts an unconfigured install reports zero rather than omittingthe field.+### Licence-gated audit read surfaces record a content-free usage marker++The eight audit read and export routes registered in+`internal/api/router_routes_licensing.go` wrap their handlers with+`Router.withAuditReadActivity` inside `RequireLicenseFeature`, so only requests+that cleared the licence gate record a marker. The marker is a timestamp plus a+coarse activity class (`list`, `export`, `verify`, `summary`); the handler runs+unchanged whether or not recording succeeds, and a router without persistence+serves the request rather than failing it+(`TestWithAuditReadActivity_NilPersistenceIsSafe`).diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 2f4d1757ac..03306997bb 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -8865,3 +8865,15 @@ scrubbed columns. Schema v6 adds nine licensed-feature adoption fields andremoves `pulse_intelligence_patrol_autofixes_30d`. The frontend interface isnot decorative: the Settings telemetry preview renders the payload verbatim, soa field missing there is a field the user is not shown before it is sent.+### Telemetry payload parity spans three surfaces at schema v7++The outbound telemetry contract stays defined in exactly three places that move+together: `type Ping struct` in `internal/telemetry/telemetry.go`, the+`var ping struct` receiver in the private license server, and+`export interface TelemetryPingPreview` in+`frontend-modern/src/api/settings.ts`, all checked by+`scripts/check_telemetry_schema_parity.py`. Schema v7 removes+`audit_logging_persistent` and `audit_events_30d` and adds `audit_reads_30d`.+Retired columns stay in the live receiver database rather than being dropped:+migrations only add, the columns hold real rows from the schema-v6 window, and+nothing writes them once the receiver struct loses the fields.diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex ba5ea96dfe..4077f322f4 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -1903,3 +1903,38 @@ adoption. `TestTenantRBACProvider_PeekManagerDoesNotProvision` and`internal/api/rbac_tenant_provider_test.go` pin both properties, and`TestApplyLicensedFeatureTelemetrySnapshot_DoesNotCreateRBACStores` pins itthrough the router boundary.+### Audit adoption telemetry counts gated reads, never store presence++Schema v7 replaced `audit_logging_persistent` and `audit_events_30d` with+`audit_reads_30d`. The first two did not discriminate: `pkg/server` installs the+SQLite audit logger on every install for defense in depth and gates only the+read and export endpoints, so the boolean was true on every install that+reported it and the event count measured background write volume, saturating+the receiver clamp on unlicensed community installs. `audit_reads_30d` counts+requests that cleared `RequireLicenseFeature(featureAuditLoggingValue, ...)` on+an audit read or export surface, which requires a human action and so cannot+settle into a constant. The recorder in+`internal/api/telemetry_audit_reads.go` is wrapped inside the licence gate, and+`AuditReadActivityRecord` (`internal/config/audit_read_activity.go`) carries+only a timestamp and an activity class drawn from a fixed allowlist; unknown+classes are dropped rather than stored. Query filters, requested ranges, the+actor, and every audit row read stay on the install.+`TestWithAuditReadActivity_RecordIsContentFree` and+`TestRecordAuditReadActivity_RejectsUnknownActivity` pin both properties.++### Licensed-feature adoption fields must discriminate++`telemetry.LicensedFeatureAdoptionFields` registers every telemetry field whose+purpose is to measure adoption of a licensed feature, and+`TestLicensedFeatureAdoptionFieldsDiscriminate`+(`pkg/server/telemetry_licensed_features_guard_test.go`) fails if any registered+field is non-zero on an install that uses none of them. The guard builds that+install through the real production snapshot paths and installs a real SQLite+audit logger exactly as `pkg/server` does, because pinning a console logger+would let the guard pass while the outbound payload lied. A field that reads the+same on a used and an unused install measures nothing and is worse than no field+because it looks like data in the fleet aggregate.+`TestRetiredNonDiscriminatingFieldsStayRemoved` additionally pins+`audit_logging_persistent`, `audit_events_30d`, and+`pulse_intelligence_patrol_autofixes_30d` so they cannot return under their old+names.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex dc24359e5b..66c44ae96b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -4973,3 +4973,14 @@ reporting actually produced output, not whether it is currently armed. The readis in `applyLicensedFeatureConfigSnapshot`(`pkg/server/telemetry_licensed_features.go`), pinned by`TestApplyLicensedFeatureConfigSnapshot_CountsScheduledReportingAndProfiles`.+### Audit-read activity is a bounded, content-free local history++`audit_read_activity.json` follows the same shape as the existing external-agent+and workflow-prompt activity histories: bounded to 500 records, pruned to a+90-day retention on every append, written through the shared+`recordActivityHistoryLocked` cycle, and encrypted at rest when crypto is+configured. Records carry a timestamp and an activity class only. Reads outside+the 30-day telemetry window are excluded at count time by+`CountAuditReadActivitySince`, so the derived signal stays "is using" rather+than drifting into "has ever used"+(`TestAuditReadsOutsideWindowAreNotCounted`).diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.jsonindex 36ba60631c..a3b92070e5 100644--- a/frontend-modern/browser-verification.json+++ b/frontend-modern/browser-verification.json@@ -1,13 +1,13 @@{"version": 1,- "base_sha": "f271313b3d8d69bb303129f7310f2696d164f40c",- "verified_at": "2026-08-05T13:34:22Z",+ "base_sha": "518a5e22942cfac4304ab13a5de6dd73f6a8a048",+ "verified_at": "2026-08-05T16:33:39Z","result": "passed","changed_paths": ["frontend-modern/src/api/settings.ts"],"content_sha256": {- "frontend-modern/src/api/settings.ts": "ab0bf34f16a18a2d6a4cb0ce7341480ee4d9e961201b2f5290c366fef9c4c26b"+ "frontend-modern/src/api/settings.ts": "29b7e4dadf5bea59b21ecad808eaa3ad0b75d9f40b3851fb60b88206e7887d67"},"routes": ["/settings"@@ -23,17 +23,16 @@}],"states": [- "Settings > General > Usage data and privacy with no telemetry payload loaded yet",- "Heartbeat payload rendered on a fresh install: schema_version 6, all nine new licensed-feature fields present, pulse_intelligence_patrol_autofixes_30d absent",- "Heartbeat payload after seeding three report schedules (two enabled, one last run inside the window) and two agent profiles: report_schedules 3, report_schedules_enabled 2, report_schedules_run_30d 1, agent_profiles 2",- "Audit adoption reported live from the running install: audit_logging_persistent true and audit_events_30d 1 after the sign-in event",- "Payload block at the 375px narrow viewport scrolling inside its own overflow-x container with no horizontal page scroll",- "Re-verified on parent f271313b3 after that commit reworked CollapsibleSection expansion: payload block renders its full 2949px height at the 375px viewport with no clipping and no horizontal page scroll"+ "Settings > General > Usage data and privacy before a payload is loaded",+ "Heartbeat payload on an unlicensed install: schema_version 7, audit_reads_30d 0, and audit_logging_persistent / audit_events_30d / pulse_intelligence_patrol_autofixes_30d all absent. On this same unlicensed install schema v6 reported audit_logging_persistent true and a five-figure audit_events_30d, which is the defect this release corrects",+ "Heartbeat payload after seeding four audit-read markers (two valid inside the window, one outside it, one with an unrecognized activity class): audit_reads_30d reads 2, so the window filter and the activity-class allowlist both hold on the real read path",+ "Payload block at the 375px narrow viewport rendering its full 2930px height inside its own overflow-x container with no horizontal page scroll",+ "Re-verified on parent 518a5e229 after that commit changed mock snapshot caching: schema_version 7 and audit_reads_30d 2 unchanged, retired fields still absent"],"interactions": [- "Signed in at /settings with the admin credentials",- "Opened Settings > General and clicked Preview payload",- "Clicked Refresh payload after seeding report_schedules.json and agent_profiles.json to confirm the counts track real configuration",- "Resized to the 375px narrow viewport and scrolled the payload block to confirm it contains its own horizontal overflow"+ "Signed in and opened Settings > General",+ "Clicked Preview payload and read the rendered heartbeat payload",+ "Seeded audit_read_activity.json with in-window, out-of-window, and invalid-class records, then re-read the payload to confirm only the two valid in-window reads counted",+ "Resized to the 375px narrow viewport and scrolled the payload block to confirm it owns its horizontal overflow"]}diff --git a/frontend-modern/public/docs/PRIVACY.md b/frontend-modern/public/docs/PRIVACY.mdindex d73ab858d0..f953af622e 100644--- a/frontend-modern/public/docs/PRIVACY.md+++ b/frontend-modern/public/docs/PRIVACY.md@@ -111,8 +111,7 @@ Every field is listed below with the reason it exists. Nothing else is included| Has API tokens | `true`/`false` | See whether token-based automation/integration is being used without sending token counts || RBAC custom roles | `3` | Count roles created by the operator, excluding the roles that ship built in, without sending role names, permissions, or scopes || RBAC user assignments | `7` | Count user-to-role assignments without sending usernames, role names, or permissions |-| Audit logging persistent | `true`/`false` | See whether a persistent audit store is active rather than console-only logging, without sending any audit event |-| Audit events 30d | `41` | Count audit events retained in the current 30-day telemetry window without sending event types, actors, targets, outcomes, or event detail |+| Audit reads 30d | `41` | Count how many times an entitled operator opened or exported the audit log in the current 30-day telemetry window, without sending query filters, actors, ranges, or any audit event || Report schedules | `5` | Count configured scheduled reports without sending schedule names, report scope, formats, or delivery recipients || Report schedules enabled | `4` | Count scheduled reports that are switched on, without sending schedule names, scope, or recipients || Report schedules run 30d | `2` | Count scheduled reports that last ran inside the current 30-day telemetry window, without sending run times, report contents, or delivery results |diff --git a/frontend-modern/src/api/__tests__/settings.test.ts b/frontend-modern/src/api/__tests__/settings.test.tsindex 8851d0b80c..8206b83726 100644--- a/frontend-modern/src/api/__tests__/settings.test.ts+++ b/frontend-modern/src/api/__tests__/settings.test.ts@@ -66,8 +66,7 @@ const mockTelemetryPreviewPayload = {has_api_tokens: true,rbac_custom_roles: 0,rbac_user_assignments: 0,- audit_logging_persistent: false,- audit_events_30d: 0,+ audit_reads_30d: 0,report_schedules: 0,report_schedules_enabled: 0,report_schedules_run_30d: 0,diff --git a/frontend-modern/src/api/settings.ts b/frontend-modern/src/api/settings.tsindex 49be29848c..3454c059d3 100644--- a/frontend-modern/src/api/settings.ts+++ b/frontend-modern/src/api/settings.ts@@ -67,8 +67,7 @@ export interface TelemetryPingPreview {has_api_tokens: boolean;rbac_custom_roles: number;rbac_user_assignments: number;- audit_logging_persistent: boolean;- audit_events_30d: number;+ audit_reads_30d: number;report_schedules: number;report_schedules_enabled: number;report_schedules_run_30d: number;diff --git a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.tsindex 7c505ea751..0db2ebeb30 100644--- a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts@@ -72,8 +72,7 @@ const buildTelemetryPreviewPayload = (has_api_tokens: true,rbac_custom_roles: 0,rbac_user_assignments: 0,- audit_logging_persistent: false,- audit_events_30d: 0,+ audit_reads_30d: 0,report_schedules: 0,report_schedules_enabled: 0,report_schedules_run_30d: 0,diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.goindex ddfa57a16f..37254e61c6 100644--- a/internal/api/router_routes_licensing.go+++ b/internal/api/router_routes_licensing.go@@ -53,49 +53,49 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHanif !ensureAdminSession(r.config, w, req) {return}- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditAdminEndpoints.HandleListEvents))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivityList, auditAdminEndpoints.HandleListEvents)))(w, req)}))r.mux.HandleFunc("GET /api/audit/", 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.ScopeAuditRead, auditAdminEndpoints.HandleListEvents))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivityList, auditAdminEndpoints.HandleListEvents)))(w, req)}))r.mux.HandleFunc("GET /api/audit/{id}/verify", 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.ScopeAuditRead, auditAdminEndpoints.HandleVerifyEvent))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivityVerify, auditAdminEndpoints.HandleVerifyEvent)))(w, req)}))r.mux.HandleFunc("GET /api/audit/export", 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.ScopeAuditRead, auditAdminEndpoints.HandleExportEvents))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivityExport, auditAdminEndpoints.HandleExportEvents)))(w, req)}))r.mux.HandleFunc("GET /api/audit/summary", 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.ScopeAuditRead, auditAdminEndpoints.HandleSummary))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivitySummary, 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.ScopeAuditRead, auditHandlers.HandleListUnifiedActionAudits))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivityList, 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.ScopeAuditRead, auditHandlers.HandleListUnifiedActionLifecycleEvents))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivityList, 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.ScopeAuditRead, auditHandlers.HandleListUnifiedExportAudits))(w, req)+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, r.withAuditReadActivity(config.AuditReadActivityExport, auditHandlers.HandleListUnifiedExportAudits)))(w, req)}))// RBAC routes (Phase 2 - Enterprise feature)diff --git a/internal/api/telemetry_audit_reads.go b/internal/api/telemetry_audit_reads.gonew file mode 100644index 0000000000..91e4f3e756--- /dev/null+++ b/internal/api/telemetry_audit_reads.go@@ -0,0 +1,43 @@+package api++import (+ "net/http"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rs/zerolog/log"+)++// withAuditReadActivity records that an entitled operator reached a+// license-gated audit read or export surface, then runs the handler.+//+// This wrapper belongs INSIDE RequireLicenseFeature so it only fires for+// requests that cleared the licence gate. Recording the read, rather than the+// presence of an audit store, is the point: the SQLite audit logger is+// installed unconditionally for defense in depth, so store presence is true on+// every install and distinguishes nothing.+//+// The record carries a timestamp and a coarse activity class. Query filters,+// the actor, the requested range, and every audit row read stay on the install.+func (r *Router) withAuditReadActivity(activity string, handler http.HandlerFunc) http.HandlerFunc {+ return func(w http.ResponseWriter, req *http.Request) {+ r.recordAuditReadActivity(req, activity)+ handler(w, req)+ }+}++func (r *Router) recordAuditReadActivity(req *http.Request, activity string) {+ if r == nil || req == nil {+ return+ }+ persistence := r.persistenceForOrg(req.Context())+ if persistence == nil {+ return+ }+ if err := persistence.RecordAuditReadActivity(config.AuditReadActivityRecord{+ Timestamp: time.Now().UTC(),+ Activity: activity,+ }); err != nil {+ log.Debug().Err(err).Str("activity", activity).Msg("Failed to record audit read activity")+ }+}diff --git a/internal/api/telemetry_audit_reads_test.go b/internal/api/telemetry_audit_reads_test.gonew file mode 100644index 0000000000..a4020e83e6--- /dev/null+++ b/internal/api/telemetry_audit_reads_test.go@@ -0,0 +1,112 @@+package api++import (+ "net/http"+ "net/http/httptest"+ "reflect"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++func newAuditReadActivityRouter(t *testing.T) (*Router, *config.ConfigPersistence) {+ t.Helper()+ persistence := config.NewConfigPersistence(t.TempDir())+ return &Router{persistence: persistence}, persistence+}++func countRecordedAuditReads(t *testing.T, persistence *config.ConfigPersistence) int {+ t.Helper()+ history, err := persistence.LoadAuditReadActivityHistory()+ if err != nil {+ t.Fatalf("LoadAuditReadActivityHistory: %v", err)+ }+ if history == nil {+ return 0+ }+ return len(history.Events)+}++func TestWithAuditReadActivity_RecordsAndStillServes(t *testing.T) {+ router, persistence := newAuditReadActivityRouter(t)++ served := false+ handler := router.withAuditReadActivity(config.AuditReadActivityExport, func(w http.ResponseWriter, req *http.Request) {+ served = true+ w.WriteHeader(http.StatusOK)+ })++ rec := httptest.NewRecorder()+ handler(rec, httptest.NewRequest(http.MethodGet, "/api/audit/export", nil))++ if !served {+ t.Fatal("wrapped handler was not invoked")+ }+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", rec.Code)+ }+ if got := countRecordedAuditReads(t, persistence); got != 1 {+ t.Fatalf("recorded audit reads = %d, want 1", got)+ }+}++// The recorded marker must carry the activity class and nothing that could+// describe what was read.+func TestWithAuditReadActivity_RecordIsContentFree(t *testing.T) {+ router, persistence := newAuditReadActivityRouter(t)++ handler := router.withAuditReadActivity(config.AuditReadActivityList, func(w http.ResponseWriter, req *http.Request) {})+ req := httptest.NewRequest(http.MethodGet, "/api/audit?user=alice&event=login&start=2026-01-01", nil)+ handler(httptest.NewRecorder(), req)++ history, err := persistence.LoadAuditReadActivityHistory()+ if err != nil {+ t.Fatalf("LoadAuditReadActivityHistory: %v", err)+ }+ if len(history.Events) != 1 {+ t.Fatalf("events = %d, want 1", len(history.Events))+ }+ record := history.Events[0]+ if record.Activity != config.AuditReadActivityList {+ t.Fatalf("activity = %q, want %q", record.Activity, config.AuditReadActivityList)+ }+ if record.Timestamp.IsZero() {+ t.Fatal("record must carry a timestamp")+ }+ // The record type has exactly two fields; a future field carrying query+ // filters or actors would have to be added deliberately and would fail the+ // privacy disclosure guard.+ if got := recordFieldCount(record); got != 2 {+ t.Fatalf("AuditReadActivityRecord has %d fields, want 2 (timestamp, activity)", got)+ }+}++// Unknown activity classes are dropped rather than stored, so a future caller+// cannot widen what this history means by passing a new string.+func TestRecordAuditReadActivity_RejectsUnknownActivity(t *testing.T) {+ router, persistence := newAuditReadActivityRouter(t)++ handler := router.withAuditReadActivity("peeked-at-everything", func(w http.ResponseWriter, req *http.Request) {})+ handler(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/audit", nil))++ if got := countRecordedAuditReads(t, persistence); got != 0 {+ t.Fatalf("recorded audit reads = %d for an unknown activity class, want 0", got)+ }+}++// A router with no persistence must not panic: the audit routes are reachable+// before every dependency is guaranteed to be wired.+func TestWithAuditReadActivity_NilPersistenceIsSafe(t *testing.T) {+ served := false+ handler := (&Router{}).withAuditReadActivity(config.AuditReadActivityList, func(w http.ResponseWriter, req *http.Request) {+ served = true+ })+ handler(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/audit", nil))+ if !served {+ t.Fatal("handler must still run when activity cannot be recorded")+ }+}++func recordFieldCount(record config.AuditReadActivityRecord) int {+ return reflect.TypeOf(record).NumField()+}diff --git a/internal/api/telemetry_licensed_features.go b/internal/api/telemetry_licensed_features.goindex 0cf821db7d..22da4f1ebb 100644--- a/internal/api/telemetry_licensed_features.go+++ b/internal/api/telemetry_licensed_features.go@@ -4,7 +4,6 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/telemetry"- "github.com/rcourtman/pulse-go-rewrite/pkg/audit""github.com/rs/zerolog/log")@@ -12,18 +11,16 @@ import (// adoption counts for licensed features whose state lives behind the router// rather than in persisted config files.//-// Everything here is a count or a coarse boolean. Role names, permission sets,-// usernames, audit event types, actors, and audit event detail all stay on the-// install; only "how many" and "is a persistent store active" leave it.+// Counts only. Role names, permission sets, and usernames stay on the install;+// only "how many" leaves it. The `now` parameter is retained for symmetry with+// the other router telemetry boundaries.func (r *Router) ApplyLicensedFeatureTelemetrySnapshot(s *telemetry.Snapshot, now time.Time) {if r == nil || s == nil {return}- since := now.Add(-telemetry.PulseIntelligenceTelemetryWindow)for _, orgID := range r.pulseIntelligenceTelemetryOrgIDs() {applyRBACAdoption(s, r, orgID)- applyAuditAdoption(s, orgID, since)}}@@ -49,20 +46,3 @@ func applyRBACAdoption(s *telemetry.Snapshot, r *Router, orgID string) {}s.RBACUserAssignments += len(manager.GetUserAssignments())}--// applyAuditAdoption records whether a persistent audit store is active and how-// many events it retained inside the telemetry window.-func applyAuditAdoption(s *telemetry.Snapshot, orgID string, since time.Time) {- logger := getLoggerForOrg(orgID)- if logger == nil || !isPersistentLogger(logger) {- return- }- s.AuditLoggingPersistent = true-- count, err := logger.Count(audit.QueryFilter{StartTime: &since})- if err != nil {- log.Debug().Err(err).Str("org_id", orgID).Msg("Unable to count audit events for telemetry summary")- return- }- s.AuditEvents30d += count-}diff --git a/internal/api/telemetry_licensed_features_test.go b/internal/api/telemetry_licensed_features_test.goindex 7ba992fd90..80f5111339 100644--- a/internal/api/telemetry_licensed_features_test.go+++ b/internal/api/telemetry_licensed_features_test.go@@ -5,7 +5,6 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/telemetry"- "github.com/rcourtman/pulse-go-rewrite/pkg/audit""github.com/rcourtman/pulse-go-rewrite/pkg/auth")@@ -52,34 +51,6 @@ func TestApplyLicensedFeatureTelemetrySnapshot_CountsOnlyOperatorAuthoredRBAC(t}}-// The OSS console audit logger is not a persistent store; reporting it as one-// would overstate audit-logging adoption across the fleet.-func TestApplyLicensedFeatureTelemetrySnapshot_ConsoleAuditLoggerIsNotAdoption(t *testing.T) {- provider := NewTenantRBACProvider(t.TempDir())- t.Cleanup(func() {- if err := provider.Close(); err != nil {- t.Errorf("provider close failed: %v", err)- }- })-- // The audit logger is process-global, so pin it rather than inheriting- // whatever a sibling test in this package installed.- previous := audit.GetLogger()- audit.SetLogger(audit.NewConsoleLogger())- t.Cleanup(func() { audit.SetLogger(previous) })-- router := &Router{rbacProvider: provider}- var snap telemetry.Snapshot- router.ApplyLicensedFeatureTelemetrySnapshot(&snap, time.Now().UTC())-- if snap.AuditLoggingPersistent {- t.Fatal("console audit logger must not report persistent audit logging")- }- if snap.AuditEvents30d != 0 {- t.Fatalf("audit events = %d, want 0 without a persistent store", snap.AuditEvents30d)- }-}-func TestApplyLicensedFeatureTelemetrySnapshot_ToleratesNilInputs(t *testing.T) {var router *Routervar snap telemetry.Snapshotdiff --git a/internal/config/audit_read_activity.go b/internal/config/audit_read_activity.gonew file mode 100644index 0000000000..b1fa8148f2--- /dev/null+++ b/internal/config/audit_read_activity.go@@ -0,0 +1,155 @@+package config++import (+ "encoding/json"+ "fmt"+ "strings"+ "time"+)++// normalizeAuditReadActivityRecord drops records that carry no recognized+// activity class. Unknown classes are rejected rather than coerced so a future+// caller cannot silently widen what this history means.+func normalizeAuditReadActivityRecord(record AuditReadActivityRecord) (AuditReadActivityRecord, bool) {+ if record.Timestamp.IsZero() {+ return AuditReadActivityRecord{}, false+ }+ record.Timestamp = record.Timestamp.UTC()+ switch strings.TrimSpace(record.Activity) {+ case AuditReadActivityList, AuditReadActivityExport, AuditReadActivityVerify, AuditReadActivitySummary:+ record.Activity = strings.TrimSpace(record.Activity)+ default:+ return AuditReadActivityRecord{}, false+ }+ return record, true+}++func normalizeAuditReadActivityRecords(records []AuditReadActivityRecord) []AuditReadActivityRecord {+ if records == nil {+ return make([]AuditReadActivityRecord, 0)+ }+ normalized := make([]AuditReadActivityRecord, 0, len(records))+ for _, record := range records {+ record, ok := normalizeAuditReadActivityRecord(record)+ if !ok {+ continue+ }+ normalized = append(normalized, record)+ }+ return normalized+}++func pruneAuditReadActivityRecords(records []AuditReadActivityRecord, cutoff time.Time, maxRecords int) []AuditReadActivityRecord {+ normalized := normalizeAuditReadActivityRecords(records)+ if !cutoff.IsZero() {+ kept := normalized[:0]+ for _, record := range normalized {+ if record.Timestamp.Before(cutoff) {+ continue+ }+ kept = append(kept, record)+ }+ normalized = kept+ }+ if maxRecords > 0 && len(normalized) > maxRecords {+ normalized = normalized[len(normalized)-maxRecords:]+ }+ return normalized+}++func newEmptyAuditReadActivityHistoryData() *AuditReadActivityHistoryData {+ return &AuditReadActivityHistoryData{+ Version: 1,+ Events: make([]AuditReadActivityRecord, 0),+ }+}++// RecordAuditReadActivity appends a content-free marker that an entitled+// operator reached one of the license-gated audit read or export surfaces.+func (c *ConfigPersistence) RecordAuditReadActivity(record AuditReadActivityRecord) error {+ if c == nil {+ return nil+ }+ now := time.Now().UTC()+ if record.Timestamp.IsZero() {+ record.Timestamp = now+ }+ record, ok := normalizeAuditReadActivityRecord(record)+ if !ok {+ return nil+ }+ return recordActivityHistoryLocked(c, c.auditReadActivityFile,+ "audit read activity history", "Resetting unreadable audit read activity history",+ newEmptyAuditReadActivityHistoryData,+ func(history *AuditReadActivityHistoryData) {+ history.Events = append(history.Events, record)+ history.Events = pruneAuditReadActivityRecords(+ history.Events,+ record.Timestamp.Add(-auditReadActivityHistoryRetention),+ maxAuditReadActivityHistoryRecords,+ )+ history.Version = 1+ history.LastSaved = now+ })+}++// SaveAuditReadActivityHistory replaces the persisted audit-read history.+func (c *ConfigPersistence) SaveAuditReadActivityHistory(events []AuditReadActivityRecord) error {+ normalized := normalizeAuditReadActivityRecords(events)+ data := AuditReadActivityHistoryData{+ Version: 1,+ LastSaved: time.Now().UTC(),+ Events: normalized,+ }+ return saveHistoryData(c, c.auditReadActivityFile, data, len(normalized),+ "audit read activity history", "Audit read activity history")+}++// LoadAuditReadActivityHistory reads the persisted audit-read history.+func (c *ConfigPersistence) LoadAuditReadActivityHistory() (*AuditReadActivityHistoryData, error) {+ return loadHistoryData(+ c.fs,+ &c.mu,+ c.auditReadActivityFile,+ c.crypto,+ newEmptyAuditReadActivityHistoryData,+ func(data *AuditReadActivityHistoryData) {+ data.Events = normalizeAuditReadActivityRecords(data.Events)+ },+ func(data *AuditReadActivityHistoryData) error {+ jsonData, err := json.Marshal(data)+ if err != nil {+ return fmt.Errorf("marshal audit read activity history migration rewrite: %w", err)+ }+ return rewriteEncryptedJSONLocked(c, c.auditReadActivityFile, jsonData, "audit read activity history migration rewrite")+ },+ func(data *AuditReadActivityHistoryData) int {+ return len(data.Events)+ },+ func(data *AuditReadActivityHistoryData) time.Time {+ return data.LastSaved+ },+ "Audit read activity history",+ )+}++// CountAuditReadActivitySince returns how many audit reads happened at or after+// the cutoff. Count only: the activity classes are not broken out, so the+// telemetry payload cannot describe what an operator looked at.+func (c *ConfigPersistence) CountAuditReadActivitySince(since time.Time) int {+ if c == nil {+ return 0+ }+ history, err := c.LoadAuditReadActivityHistory()+ if err != nil || history == nil {+ return 0+ }+ count := 0+ for _, record := range history.Events {+ if record.Timestamp.Before(since) {+ continue+ }+ count+++ }+ return count+}diff --git a/internal/config/persistence.go b/internal/config/persistence.goindex 345d370966..a712a1e45e 100644--- a/internal/config/persistence.go+++ b/internal/config/persistence.go@@ -48,6 +48,7 @@ type ConfigPersistence struct {aiUsageHistoryFile stringexternalAgentActivityFile stringworkflowPromptActivityFile string+ auditReadActivityFile stringagentProfilesFile stringagentAssignmentsFile stringaiChatSessionsFile string@@ -128,6 +129,7 @@ type resolvedConfigPersistencePaths struct {aiUsageHistoryFile stringexternalAgentActivityFile stringworkflowPromptActivityFile string+ auditReadActivityFile stringagentProfilesFile stringagentAssignmentsFile stringaiChatSessionsFile string@@ -225,6 +227,10 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPersif err != nil {return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve workflow_prompt_activity.json: %w", err)}+ auditReadActivityFile, err := resolveLeaf("audit_read_activity.json")+ if err != nil {+ return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve audit_read_activity.json: %w", err)+ }agentProfilesFile, err := resolveLeaf("agent_profiles.json")if err != nil {return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve agent_profiles.json: %w", err)@@ -267,6 +273,7 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPersaiUsageHistoryFile: aiUsageHistoryFile,externalAgentActivityFile: externalAgentActivityFile,workflowPromptActivityFile: workflowPromptActivityFile,+ auditReadActivityFile: auditReadActivityFile,agentProfilesFile: agentProfilesFile,agentAssignmentsFile: agentAssignmentsFile,aiChatSessionsFile: aiChatSessionsFile,@@ -323,6 +330,7 @@ func newConfigPersistence(configDir string) (*ConfigPersistence, error) {aiUsageHistoryFile: resolvedPaths.aiUsageHistoryFile,externalAgentActivityFile: resolvedPaths.externalAgentActivityFile,workflowPromptActivityFile: resolvedPaths.workflowPromptActivityFile,+ auditReadActivityFile: resolvedPaths.auditReadActivityFile,agentProfilesFile: resolvedPaths.agentProfilesFile,agentAssignmentsFile: resolvedPaths.agentAssignmentsFile,aiChatSessionsFile: resolvedPaths.aiChatSessionsFile,@@ -2934,6 +2942,17 @@ const (maxWorkflowPromptActivityHistoryRecords = 500workflowPromptActivityHistoryRetention = 90 * 24 * time.Hour++ // Audit-read activity classes. These mark that an operator reached one of+ // the license-gated audit read/export surfaces; the audit events they read+ // never enter this history.+ AuditReadActivityList = "list"+ AuditReadActivityExport = "export"+ AuditReadActivityVerify = "verify"+ AuditReadActivitySummary = "summary"++ maxAuditReadActivityHistoryRecords = 500+ auditReadActivityHistoryRetention = 90 * 24 * time.Hour)// ExternalAgentActivityHistoryData represents persisted external-agent surface@@ -2973,6 +2992,26 @@ type WorkflowPromptActivityRecord struct {PromptName string `json:"prompt_name"`}+// AuditReadActivityHistoryData represents persisted audit-read activity with+// metadata. Events carry only a coarse activity class and a timestamp: the+// audit events that were read, the query filters, the actor, and the exported+// rows never belong in this telemetry source.+type AuditReadActivityHistoryData struct {+ Version int `json:"version"`+ LastSaved time.Time `json:"last_saved"`+ Events []AuditReadActivityRecord `json:"events"`+}++// AuditReadActivityRecord is a content-free marker that an entitled operator+// read or exported the audit log. Recording the read rather than the presence+// of an audit store is deliberate: the SQLite audit logger is installed on+// every install for defense in depth, so only a read distinguishes an install+// that uses audit logging from one that merely has it.+type AuditReadActivityRecord struct {+ Timestamp time.Time `json:"timestamp"`+ Activity string `json:"activity"`+}+func normalizeExternalAgentActivityRecord(record ExternalAgentActivityRecord) (ExternalAgentActivityRecord, bool) {if record.Timestamp.IsZero() {return ExternalAgentActivityRecord{}, falsediff --git a/internal/telemetry/licensed_feature_fields.go b/internal/telemetry/licensed_feature_fields.gonew file mode 100644index 0000000000..78871d4a0a--- /dev/null+++ b/internal/telemetry/licensed_feature_fields.go@@ -0,0 +1,31 @@+package telemetry++// LicensedFeatureAdoptionFields lists every telemetry field whose only purpose+// is to measure adoption of a licensed feature.+//+// Membership carries an obligation, enforced by the guard in+// pkg/server/telemetry_licensed_features_guard_test.go: an install that uses+// none of these features must report the zero value for every field here. A+// field that reads the same on a used and an unused install measures nothing,+// and is worse than no field at all because it looks like data.+//+// This registry exists because that exact defect shipped twice. Schema v6 added+// audit_logging_persistent and audit_events_30d, both sourced from an audit+// store that is installed unconditionally for defense in depth, so both+// reported identically on free and paid installs. The same schema removed+// pulse_intelligence_patrol_autofixes_30d, which had been hardcoded to zero+// with no increment site anywhere. Three instances of one bug class is a guard,+// not a habit.+//+// Adding a field here without teaching the guard how to exercise it fails the+// guard, which is the intended friction.+var LicensedFeatureAdoptionFields = []string{+ "alert_ai_enabled",+ "rbac_custom_roles",+ "rbac_user_assignments",+ "audit_reads_30d",+ "report_schedules",+ "report_schedules_enabled",+ "report_schedules_run_30d",+ "agent_profiles",+}diff --git a/internal/telemetry/licensed_feature_fields_test.go b/internal/telemetry/licensed_feature_fields_test.gonew file mode 100644index 0000000000..e655ff42da--- /dev/null+++ b/internal/telemetry/licensed_feature_fields_test.go@@ -0,0 +1,58 @@+package telemetry++import (+ "reflect"+ "strings"+ "testing"+)++// Every registered name must be a real Ping field, so a rename or removal+// cannot leave the registry pointing at nothing while still looking enforced.+func TestLicensedFeatureAdoptionFieldsExistOnPing(t *testing.T) {+ pingType := reflect.TypeOf(Ping{})+ present := make(map[string]struct{}, pingType.NumField())+ for i := 0; i < pingType.NumField(); i++ {+ jsonName := strings.Split(pingType.Field(i).Tag.Get("json"), ",")[0]+ if jsonName == "" || jsonName == "-" {+ continue+ }+ present[jsonName] = struct{}{}+ }++ if len(LicensedFeatureAdoptionFields) == 0 {+ t.Fatal("licensed-feature adoption registry must not be empty")+ }+ for _, name := range LicensedFeatureAdoptionFields {+ if _, ok := present[name]; !ok {+ t.Errorf("registered licensed-feature field %q is not a Ping field", name)+ }+ }+}++func TestLicensedFeatureAdoptionFieldsHaveNoDuplicates(t *testing.T) {+ seen := make(map[string]struct{}, len(LicensedFeatureAdoptionFields))+ for _, name := range LicensedFeatureAdoptionFields {+ if _, ok := seen[name]; ok {+ t.Errorf("duplicate licensed-feature field %q", name)+ }+ seen[name] = struct{}{}+ }+}++// The removed v6 fields must not come back under their old names. Both were+// sourced from an unconditionally-installed audit store, so both read+// identically on every install regardless of entitlement.+func TestRetiredNonDiscriminatingFieldsStayRemoved(t *testing.T) {+ pingType := reflect.TypeOf(Ping{})+ retired := map[string]string{+ "audit_logging_persistent": "the SQLite audit logger is installed on every install, so this was always true",+ "audit_events_30d": "counted defense-in-depth write volume, not audit-log use, and saturated the receiver clamp",+ "pulse_intelligence_patrol_autofixes_30d": "AutoFixCount was hardcoded to zero with no increment site",+ }+ for i := 0; i < pingType.NumField(); i++ {+ jsonName := strings.Split(pingType.Field(i).Tag.Get("json"), ",")[0]+ if reason, ok := retired[jsonName]; ok {+ t.Errorf("retired telemetry field %q reintroduced: %s", jsonName, reason)+ }+ }+}diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.goindex 8c6570d875..e993ec79a9 100644--- a/internal/telemetry/telemetry.go+++ b/internal/telemetry/telemetry.go@@ -141,7 +141,13 @@ const (// scheduled reporting, agent profiles, alert-triggered AI) and drops// pulse_intelligence_patrol_autofixes_30d, which no code path could ever// set to a non-zero value.- TelemetrySchemaVersion = 6+ // Schema v7 replaces audit_logging_persistent and audit_events_30d with+ // audit_reads_30d. The SQLite audit logger is installed on every install+ // for defense in depth, so the boolean was true everywhere and the event+ // count measured background write volume; neither discriminated an install+ // that uses audit logging from one that merely has it. Reaching a+ // license-gated audit read does.+ TelemetrySchemaVersion = 7)type installIDRecord struct {@@ -231,17 +237,16 @@ type Ping struct {// Licensed-feature adoption. Counts only: no role names, schedule names,// profile names, recipients, report contents, or audit event detail.- RBACCustomRoles int `json:"rbac_custom_roles"`- RBACUserAssignments int `json:"rbac_user_assignments"`- AuditLoggingPersistent bool `json:"audit_logging_persistent"`- AuditEvents30d int `json:"audit_events_30d"`- ReportSchedules int `json:"report_schedules"`- ReportSchedulesEnabled int `json:"report_schedules_enabled"`- ReportSchedulesRun30d int `json:"report_schedules_run_30d"`- AgentProfiles int `json:"agent_profiles"`- UpdateAttempts30d int `json:"update_attempts_30d"`- UpdateSuccesses30d int `json:"update_successes_30d"`- UpdateFailures30d int `json:"update_failures_30d"`+ RBACCustomRoles int `json:"rbac_custom_roles"`+ RBACUserAssignments int `json:"rbac_user_assignments"`+ AuditReads30d int `json:"audit_reads_30d"`+ ReportSchedules int `json:"report_schedules"`+ ReportSchedulesEnabled int `json:"report_schedules_enabled"`+ ReportSchedulesRun30d int `json:"report_schedules_run_30d"`+ AgentProfiles int `json:"agent_profiles"`+ UpdateAttempts30d int `json:"update_attempts_30d"`+ UpdateSuccesses30d int `json:"update_successes_30d"`+ UpdateFailures30d int `json:"update_failures_30d"`// Last coarse update failure category; never raw error text.UpdateLastFailureCategory string `json:"update_last_failure_category,omitempty"`@@ -380,8 +385,7 @@ type Snapshot struct {HasAPITokens boolRBACCustomRoles intRBACUserAssignments int- AuditLoggingPersistent bool- AuditEvents30d int+ AuditReads30d intReportSchedules intReportSchedulesEnabled intReportSchedulesRun30d int@@ -913,6 +917,18 @@ func platformName(isDocker bool) string {return "binary"}+// BuildPingForSnapshot projects a Snapshot onto an otherwise-zero Ping using+// the same merge the outbound path uses.+//+// It exists so the licensed-feature adoption guard can assert against the real+// serialized payload instead of a hand-built stand-in. Asserting on a+// hand-built ping is what lets a field look correct in a test while shipping+// something else, which is how audit_logging_persistent reached production+// reading true on every install.+func BuildPingForSnapshot(s Snapshot) Ping {+ return applySnapshot(Ping{}, func() Snapshot { return s })+}+// applySnapshot merges dynamic state into the base ping.func applySnapshot(base Ping, fn SnapshotFunc) Ping {ping := base@@ -959,8 +975,7 @@ func applySnapshot(base Ping, fn SnapshotFunc) Ping {ping.HasAPITokens = s.HasAPITokensping.RBACCustomRoles = s.RBACCustomRolesping.RBACUserAssignments = s.RBACUserAssignments- ping.AuditLoggingPersistent = s.AuditLoggingPersistent- ping.AuditEvents30d = s.AuditEvents30d+ ping.AuditReads30d = s.AuditReads30dping.ReportSchedules = s.ReportSchedulesping.ReportSchedulesEnabled = s.ReportSchedulesEnabledping.ReportSchedulesRun30d = s.ReportSchedulesRun30ddiff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.goindex 8a47849422..7186c5d9c1 100644--- a/internal/telemetry/telemetry_test.go+++ b/internal/telemetry/telemetry_test.go@@ -358,8 +358,7 @@ func TestApplySnapshot(t *testing.T) {HasAPITokens: true,RBACCustomRoles: 3,RBACUserAssignments: 7,- AuditLoggingPersistent: true,- AuditEvents30d: 41,+ AuditReads30d: 41,ReportSchedules: 5,ReportSchedulesEnabled: 4,ReportSchedulesRun30d: 2,@@ -471,8 +470,8 @@ func TestApplySnapshot(t *testing.T) {if ping.RBACCustomRoles != 3 || ping.RBACUserAssignments != 7 {t.Fatalf("RBAC adoption counts not applied: %#v", ping)}- if !ping.AuditLoggingPersistent || ping.AuditEvents30d != 41 {- t.Fatalf("audit adoption signals not applied: %#v", ping)+ if ping.AuditReads30d != 41 {+ t.Fatalf("audit read count not applied: %#v", ping)}if ping.ReportSchedules != 5 || ping.ReportSchedulesEnabled != 4 || ping.ReportSchedulesRun30d != 2 {t.Fatalf("report schedule adoption counts not applied: %#v", ping)diff --git a/pkg/server/telemetry_licensed_features.go b/pkg/server/telemetry_licensed_features.goindex 3315a2af78..c7eedfd36b 100644--- a/pkg/server/telemetry_licensed_features.go+++ b/pkg/server/telemetry_licensed_features.go@@ -34,4 +34,10 @@ func applyLicensedFeatureConfigSnapshot(snap *telemetry.Snapshot, persistence *cif profiles, err := persistence.LoadAgentProfiles(); err == nil {snap.AgentProfiles = len(profiles)}++ // Audit adoption is a read count, not store presence: the SQLite audit+ // logger is installed on every install for defense in depth, so only an+ // operator reaching a license-gated read surface distinguishes an install+ // that uses audit logging from one that merely has it.+ snap.AuditReads30d = persistence.CountAuditReadActivitySince(now.Add(-telemetry.PulseIntelligenceTelemetryWindow))}diff --git a/pkg/server/telemetry_licensed_features_guard_test.go b/pkg/server/telemetry_licensed_features_guard_test.gonew file mode 100644index 0000000000..f713a493bf--- /dev/null+++ b/pkg/server/telemetry_licensed_features_guard_test.go@@ -0,0 +1,157 @@+package server++import (+ "encoding/json"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/api"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/telemetry"+ "github.com/rcourtman/pulse-go-rewrite/pkg/audit"+)++// buildUnusedInstallPing produces the outbound payload for an install that has+// configured none of the licensed features, running every production snapshot+// path the real server runs.+//+// It deliberately installs a real SQLite audit logger, because that is what+// pkg/server does unconditionally on every install. Pinning a console logger+// here would make the guard pass while the shipped payload lied.+func buildUnusedInstallPing(t *testing.T) map[string]any {+ t.Helper()++ dataDir := t.TempDir()++ sqliteLogger, err := audit.NewSQLiteLogger(audit.SQLiteLoggerConfig{DataDir: dataDir})+ if err != nil {+ t.Fatalf("NewSQLiteLogger: %v", err)+ }+ previous := audit.GetLogger()+ audit.SetLogger(sqliteLogger)+ t.Cleanup(func() {+ audit.SetLogger(previous)+ if err := sqliteLogger.Close(); err != nil {+ t.Logf("close audit logger: %v", err)+ }+ })++ // An unused install still records audit events for defense in depth, so+ // write one. A field that counts these rather than counting operator reads+ // will be caught here.+ if err := audit.GetLogger().Record(audit.Event{+ Timestamp: time.Now().UTC(),+ EventType: "login",+ Success: true,+ }); err != nil {+ t.Fatalf("record baseline audit event: %v", err)+ }++ now := time.Now().UTC()+ var snap telemetry.Snapshot+ applyLicensedFeatureConfigSnapshot(&snap, config.NewConfigPersistence(dataDir), now)+ (&api.Router{}).ApplyLicensedFeatureTelemetrySnapshot(&snap, now)++ ping := telemetry.BuildPingForSnapshot(snap)+ raw, err := json.Marshal(ping)+ if err != nil {+ t.Fatalf("marshal ping: %v", err)+ }+ var decoded map[string]any+ if err := json.Unmarshal(raw, &decoded); err != nil {+ t.Fatalf("unmarshal ping: %v", err)+ }+ return decoded+}++// TestLicensedFeatureAdoptionFieldsDiscriminate is the guard that schema v6+// needed and did not have.+//+// Every field that exists to measure licensed-feature adoption must read its+// zero value on an install that uses none of those features. A field that reads+// the same whether or not the feature is used measures nothing, and is worse+// than no field because it looks like data in the fleet aggregate.+//+// audit_logging_persistent and audit_events_30d both failed this property in+// production before anyone noticed: the audit store is installed on every+// install, so the boolean was true and the count was in the tens of thousands+// on unlicensed community installs.+func TestLicensedFeatureAdoptionFieldsDiscriminate(t *testing.T) {+ payload := buildUnusedInstallPing(t)++ for _, field := range telemetry.LicensedFeatureAdoptionFields {+ value, ok := payload[field]+ if !ok {+ t.Errorf("licensed-feature field %q is missing from the outbound payload", field)+ continue+ }+ switch v := value.(type) {+ case bool:+ if v {+ t.Errorf("licensed-feature field %q is true on an install that uses no licensed feature; it cannot discriminate adoption", field)+ }+ case float64:+ if v != 0 {+ t.Errorf("licensed-feature field %q is %v on an install that uses no licensed feature; it cannot discriminate adoption", field, v)+ }+ default:+ t.Errorf("licensed-feature field %q has unsupported type %T; adoption fields must be counts or coarse booleans", field, value)+ }+ }+}++// The complement: once a feature is actually used, its field must move off+// zero. A field that is always zero is as useless as one that is always set,+// which is what pulse_intelligence_patrol_autofixes_30d was for its whole life.+func TestLicensedFeatureAdoptionFieldsMoveWhenFeaturesAreUsed(t *testing.T) {+ dataDir := t.TempDir()+ persistence := config.NewConfigPersistence(dataDir)+ now := time.Now().UTC()+ recent := now.Add(-24 * time.Hour)++ if err := persistence.SaveReportScheduleStore(config.ReportScheduleStore{+ Schedules: []config.ReportSchedule{+ {ID: "s1", Name: "weekly", Enabled: true, LastRunAt: &recent},+ },+ }); err != nil {+ t.Fatalf("SaveReportScheduleStore: %v", err)+ }+ if err := persistence.RecordAuditReadActivity(config.AuditReadActivityRecord{+ Timestamp: recent,+ Activity: config.AuditReadActivityList,+ }); err != nil {+ t.Fatalf("RecordAuditReadActivity: %v", err)+ }++ var snap telemetry.Snapshot+ applyLicensedFeatureConfigSnapshot(&snap, persistence, now)++ if snap.AuditReads30d != 1 {+ t.Errorf("audit_reads_30d = %d after one gated read, want 1", snap.AuditReads30d)+ }+ if snap.ReportSchedules != 1 || snap.ReportSchedulesEnabled != 1 || snap.ReportSchedulesRun30d != 1 {+ t.Errorf("report schedule fields did not move: %#v", snap)+ }+}++// An audit read that fell outside the telemetry window must not be counted, or+// the field would drift into "has ever used" rather than "is using".+func TestAuditReadsOutsideWindowAreNotCounted(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ now := time.Now().UTC()+ stale := now.Add(-(telemetry.PulseIntelligenceTelemetryWindow + 48*time.Hour))++ if err := persistence.RecordAuditReadActivity(config.AuditReadActivityRecord{+ Timestamp: stale,+ Activity: config.AuditReadActivityExport,+ }); err != nil {+ t.Fatalf("RecordAuditReadActivity: %v", err)+ }++ var snap telemetry.Snapshot+ applyLicensedFeatureConfigSnapshot(&snap, persistence, now)++ if snap.AuditReads30d != 0 {+ t.Errorf("audit_reads_30d = %d for a read outside the window, want 0", snap.AuditReads30d)+ }+}