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
Gate grandfather floor capture on settled supplemental inventory
rcourtman4524baa1b0db
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 24595a9b35..c45740bb30 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -206,14 +206,6 @@ management, and fleet control surfaces.entitlements payloads, but they must not cache their own pre-activationhost counts, synthesize a second grandfather floor, or treat install-timefleet inventory as the authority for commercial continuity.-14. Keep dormant assistant availability on the shared auth/bootstrap contract.- When `internal/api/ai_handlers.go`,- `internal/api/router_routes_auth_security.go`, or- `internal/api/security_status_capabilities.go` change, first-session,- setup, and install routes that do not own assistant or Patrol UI must- consume `/api/security/status.sessionCapabilities.assistantEnabled`- instead of probing `/api/settings/ai` or `/api/ai/*` during ordinary route- bootstrap.## Forbidden Paths@@ -1030,6 +1022,13 @@ lifecycle-local counter, drift on source priority, or treat missing monitored-system usage as zero; when an active cap is present and usage cannot beresolved, the route must fail closed with retryable unavailable guidanceinstead of silently admitting a net-new monitored system.+That same commercial readiness boundary now also assumes settled canonical+usage, not the first non-nil monitor view. Lifecycle-owned setup or first-host+surfaces may not seal migrated-v5 continuity, display counted-system totals as+final, or retry admission against a provider-owned supplemental platform such+as TrueNAS or VMware until the monitor has both seen an initial baseline for+every active connection and rebuilt the canonical store at or after that+provider watermark.That same validation contract must stay coherent across the public`/api/auto-register` route and the direct canonical handler path used by thesame runtime surface, so Unified Agent/setup entry points do not inherit divergentdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 75094f0d4e..60dfb9bf7f 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -411,6 +411,11 @@ before persistence, and `/api/license/entitlements` must expose`current_available` when an active monitored-system cap cannot resolve currentusage so callers can fail closed without misreading unavailable usage as areal zero.+That same `current_available` truth now includes supplemental-provider startup+readiness. API contracts must not serialize a live monitored-system count from+the first store-backed read-state when provider-owned inventories such as+TrueNAS or VMware have not yet completed an initial baseline and been rebuilt+into the canonical monitor store.The shared metrics-history contract now also owns physical-disk live I/Owindows. `/api/metrics-store/history` must accept `resourceType=disk`, keep`30m` as a valid compact live range, and resolve `disk`, `diskread`,@@ -477,12 +482,6 @@ as the canonical runtime contract for `demoMode`, `readOnly`,must therefore defer their first read until that policy has resolved, sopublic demos fail closed without probing hidden commercial routes duringbootstrap.-That same `/api/security/status` contract now also owns closed-shell-assistant availability. The response must expose-`sessionCapabilities.assistantEnabled` as the only general-route bootstrap-fact for dormant assistant chrome, so non-AI routes do not probe-`/api/settings/ai` or `/api/ai/*` merely to decide whether the assistant-affordance may be opened.That same contract split also makes the licensing boundary explicit:`/api/license/runtime-capabilities` is the public runtime feature contract,`/api/license/commercial-posture` is the non-billing upgrade/trial posture@@ -1199,6 +1198,11 @@ greater of the exchanged plan limit and the one-time deduped monitored-systemfloor captured from canonical runtime usage, and restored grant activationsmust backfill that floor once canonical usage becomes available instead offalling back to the raw exchanged grant limit after restart.+That migration capture must wait for settled canonical usage, not merely the+first non-nil read-state. If provider-owned supplemental inventories are still+between initial wiring and the first canonical store rebuild, the API must+keep the grandfather floor uncaptured and expose usage as unavailable rather+than sealing continuity against a partial startup graph.That same configured-path contract now also has an explicit shared owner formanual auth env files: `internal/api/auth_env_path.go` must remain the onlyplace that derives `.env` from configured runtime paths, and neighboringdiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 011dbb9459..c2ed9b18db 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -135,14 +135,6 @@ agreement, and cloud-specific enforcement rules.`/settings/system/billing/usage?details=counting-rules` for explanation and`/settings/system/billing/plan?intent=max_monitored_systems` for upgradeintent.-24. Keep dormant assistant availability on the shared browser bootstrap- contract. When `frontend-modern/src/App.tsx`,- `frontend-modern/src/useAppRuntimeState.ts`,- `internal/api/router_routes_auth_security.go`, or- `internal/api/security_status_capabilities.go` change, cloud-paid routes- that do not own assistant or Patrol interaction must consume- `/api/security/status.sessionCapabilities.assistantEnabled` instead of- probing `/api/settings/ai` or `/api/ai/*` during ordinary route bootstrap.## Forbidden Paths@@ -791,6 +783,12 @@ installation Pulse must persist a one-time grandfather floor so status,runtime entitlement evaluation, and later restore/refresh flows keep theexisting estate admissible without silently grandfathering post-migrationgrowth.+That first resolved usage snapshot must be a settled canonical monitor view,+not the first store-backed read-state seen during startup. When provider-owned+supplemental inventories such as TrueNAS or VMware are still between initial+provider wiring and the first canonical store rebuild after their baseline+poll, cloud-paid continuity must keep usage unavailable and delay floor+capture rather than sealing a lower count forever.That continuity rule cannot depend on webhook metadata being perfect. Thecanonical Stripe price-to-plan lookup in `pkg/licensing/features.go` and`pkg/licensing/stripe_subscription.go` must recognize the still-renewingdiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex c4da403e79..69b776fba9 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -94,6 +94,13 @@ This subsystem now sits under the dedicated core monitoring runtime lane sodiscovery, metrics-history correctness, and platform-specific runtime coveragecan be governed as first-class product work instead of staying diluted insidearchitecture coherence.+That same monitoring owner now also governs monitored-system usage readiness+for commercial boundaries. A non-nil unified read-state is not sufficient when+provider-owned supplemental inventories such as TrueNAS or VMware are still+settling: monitoring must fail closed until every active connection in that+provider has reached an initial baseline and the canonical monitor store has+rebuilt at or after that provider watermark, otherwise billing and upgrade+continuity can freeze against a transient startup undercount.VMware vSphere now also has a locked phase-1 ingestion boundary under thislane. The admitted direction is vCenter-only in phase 1, and monitoring muststay API-first through thediff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 8c7f306f38..816feedceb 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -227,6 +227,12 @@ the unified-resource projection helpers must reuse one current monitored-system snapshot plus prospective candidate/preview projection for add andupdate checks instead of rescanning platform inventories per handler orfalling back to zero when monitor state is unavailable.+That protected path now also includes supplemental-inventory settlement.+Performance work may not shortcut monitored-system usage readiness to "store+exists" once provider-owned platforms such as TrueNAS or VMware suppress+snapshot-owned sources; the hot path must fail closed until the monitor has+both observed an initial baseline for every active connection and rebuilt the+canonical store at or after the latest provider watermark.The dashboard workload selector path and the dashboard runtime that consumes itare now part of the protected performance surface rather than proof-onlydiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 59ba25ef0b..058e4c8e37 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -176,14 +176,6 @@ querying, and the operator-facing storage health presentation layer.backup counts, or recovery-point presence when commercial continuity isalready defined by the canonical monitored-system resolver and activationpersistence.-37. Keep dormant assistant availability on the shared auth/bootstrap contract.- When `frontend-modern/src/App.tsx`, `internal/api/ai_handlers.go`,- `internal/api/router_routes_auth_security.go`, or- `internal/api/security_status_capabilities.go` change, storage and- recovery routes that do not own assistant or Patrol interaction must- consume `/api/security/status.sessionCapabilities.assistantEnabled`- instead of probing `/api/settings/ai` or `/api/ai/*` during ordinary route- bootstrap.## Forbidden Paths@@ -1446,6 +1438,13 @@ an already-counted host, the API helper must strip only that source from theprospective grouped system and preserve any remaining top-level evidence suchas agent or sibling API ownership, rather than briefly freeing a slot ordouble-counting the same monitored system.+That same shared boundary now also assumes settled monitored-system usage+readiness. Storage- or recovery-adjacent transport flows may not interpret the+first store-backed monitor view as commercial truth when provider-owned+supplemental platforms such as TrueNAS or VMware are still between initial+connection wiring and the first rebuilt canonical store; until that baseline+settles, adjacent surfaces must preserve `current_available=false` and avoid+sealing any migration or admission decision against a transient undercount.That same shared `internal/api/` dependency also assumes session-carried OIDCrefresh tokens stay fail-closed at rest: `session_store.go` may only persistor recover those tokens through encrypted-at-rest session payloads, and anydiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 5e76ed7b04..10fea4c72d 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -48,6 +48,53 @@ type contractCapturingStreamingProvider struct {lastRequest providers.ChatRequest}+type contractSupplementalUsageProvider struct {+ settled bool+ readyAt time.Time+ records []unifiedresources.IngestRecord+}++func (p *contractSupplementalUsageProvider) SupplementalRecords(*monitoring.Monitor, string) []unifiedresources.IngestRecord {+ out := make([]unifiedresources.IngestRecord, len(p.records))+ copy(out, p.records)+ return out+}++func (p *contractSupplementalUsageProvider) SnapshotOwnedSources() []unifiedresources.DataSource {+ return []unifiedresources.DataSource{unifiedresources.SourceTrueNAS}+}++func (p *contractSupplementalUsageProvider) SupplementalInventoryReadyAt(*monitoring.Monitor, string) (time.Time, bool) {+ return p.readyAt, p.settled+}++func (p *contractSupplementalUsageProvider) settle(count int) {+ now := time.Now().UTC()+ p.readyAt = now+ p.settled = true+ p.records = make([]unifiedresources.IngestRecord, 0, count)+ for i := 0; i < count; i++ {+ host := fmt.Sprintf("contract-truenas-%02d.lab.local", i+1)+ p.records = append(p.records, unifiedresources.IngestRecord{+ SourceID: fmt.Sprintf("system:contract-truenas-%02d", i+1),+ Resource: unifiedresources.Resource{+ ID: fmt.Sprintf("contract-truenas-%02d", i+1),+ Type: unifiedresources.ResourceTypeAgent,+ Name: host,+ Status: unifiedresources.StatusOnline,+ LastSeen: now,+ UpdatedAt: now,+ Identity: unifiedresources.ResourceIdentity{+ Hostnames: []string{host},+ },+ TrueNAS: &unifiedresources.TrueNASData{+ Hostname: host,+ },+ },+ })+ }+}+func (p *contractCapturingStreamingProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {p.lastRequest = reqreturn &providers.ChatResponse{Content: "ok", Model: req.Model}, nil@@ -4803,6 +4850,35 @@ func TestContract_EntitlementPayloadMonitoredSystemUsageUnavailableJSONSnapshot(assertJSONSnapshot(t, got, want)}+func TestContract_EntitlementUsageSnapshotWaitsForSettledSupplementalInventory(t *testing.T) {+ provider := &contractSupplementalUsageProvider{}+ monitor := &monitoring.Monitor{}+ monitor.SetResourceStore(unifiedresources.NewMonitorAdapter(nil))+ monitor.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, provider)++ handlers := &LicenseHandlers{monitor: monitor}++ usage := handlers.entitlementUsageSnapshot(context.Background())+ if usage.MonitoredSystemsAvailable {+ t.Fatalf("expected unsettled supplemental inventory to keep usage unavailable, got %+v", usage)+ }++ provider.settle(1)+ usage = handlers.entitlementUsageSnapshot(context.Background())+ if usage.MonitoredSystemsAvailable {+ t.Fatalf("expected stale store freshness to keep usage unavailable, got %+v", usage)+ }++ monitor.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, provider)+ usage = handlers.entitlementUsageSnapshot(context.Background())+ if !usage.MonitoredSystemsAvailable {+ t.Fatalf("expected usage to become available after canonical store rebuild, got %+v", usage)+ }+ if usage.MonitoredSystems != 1 {+ t.Fatalf("MonitoredSystems=%d, want 1", usage.MonitoredSystems)+ }+}+func TestContract_LegacyMigrationGrandfatherFloorJSONSnapshot(t *testing.T) {t.Setenv("PULSE_LICENSE_DEV_MODE", "false")diff --git a/internal/api/licensing_handlers_auto_migrate_test.go b/internal/api/licensing_handlers_auto_migrate_test.goindex 8ad6e57b6b..f030f47892 100644--- a/internal/api/licensing_handlers_auto_migrate_test.go+++ b/internal/api/licensing_handlers_auto_migrate_test.go@@ -16,6 +16,33 @@ import (pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")+type grandfatherFloorSupplementalProvider struct {+ settled bool+ readyAt time.Time+ records []unifiedresources.IngestRecord+}++func (p *grandfatherFloorSupplementalProvider) SupplementalRecords(*monitoring.Monitor, string) []unifiedresources.IngestRecord {+ out := make([]unifiedresources.IngestRecord, len(p.records))+ copy(out, p.records)+ return out+}++func (p *grandfatherFloorSupplementalProvider) SnapshotOwnedSources() []unifiedresources.DataSource {+ return []unifiedresources.DataSource{unifiedresources.SourceTrueNAS}+}++func (p *grandfatherFloorSupplementalProvider) SupplementalInventoryReadyAt(*monitoring.Monitor, string) (time.Time, bool) {+ return p.readyAt, p.settled+}++func (p *grandfatherFloorSupplementalProvider) settle(count int) {+ now := time.Now().UTC()+ p.readyAt = now+ p.settled = true+ p.records = buildSupplementalGrandfatherFloorRecords(count, now)+}+func TestGetTenantComponents_AutoExchangesPersistedLegacyJWT(t *testing.T) {t.Setenv("PULSE_LICENSE_DEV_MODE", "false")@@ -553,6 +580,128 @@ func TestActivateLicenseKey_GrandfathersObservedMonitoredSystemsForLegacyMigrati}}+func TestGetTenantComponents_DelaysGrandfatherFloorUntilSupplementalInventorySettles(t *testing.T) {+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")++ grantJWT, grantPublicKey, err := pkglicensing.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{+ LicenseID: "lic_floor_supplemental",+ Tier: "pro",+ PlanKey: "v5_pro_monthly_grandfathered",+ State: "active",+ Features: []string{"relay"},+ MaxMonitoredSystems: 10,+ IssuedAt: time.Now().Unix(),+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),+ Email: "[email protected]",+ })+ if err != nil {+ t.Fatalf("generate grant jwt: %v", err)+ }+ pkglicensing.SetPublicKey(grantPublicKey)+ t.Cleanup(func() { pkglicensing.SetPublicKey(nil) })++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/licenses/exchange" {+ t.Fatalf("path = %q, want /v1/licenses/exchange", r.URL.Path)+ }+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(pkglicensing.ActivateInstallationResponse{+ License: pkglicensing.ActivateResponseLicense{+ LicenseID: "lic_floor_supplemental",+ State: "active",+ Tier: "pro",+ Features: []string{"relay"},+ MaxMonitoredSystems: 10,+ },+ Installation: pkglicensing.ActivateResponseInstallation{+ InstallationID: "inst_floor_supplemental",+ InstallationToken: "pit_live_floor_supplemental",+ Status: "active",+ },+ Grant: pkglicensing.GrantEnvelope{+ JWT: grantJWT,+ JTI: "grant_floor_supplemental",+ ExpiresAt: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),+ },+ })+ }))+ defer server.Close()+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)++ baseDir := t.TempDir()+ mtp := config.NewMultiTenantPersistence(baseDir)+ cp, err := mtp.GetPersistence("default")+ if err != nil {+ t.Fatalf("init default persistence: %v", err)+ }++ legacyJWT, err := pkglicensing.GenerateLicenseForTesting("[email protected]", pkglicensing.TierPro, 24*time.Hour)+ if err != nil {+ t.Fatalf("generate test license: %v", err)+ }+ persistence, err := pkglicensing.NewPersistence(cp.GetConfigDir())+ if err != nil {+ t.Fatalf("new persistence: %v", err)+ }+ if err := persistence.Save(legacyJWT); err != nil {+ t.Fatalf("save legacy jwt: %v", err)+ }++ provider := &grandfatherFloorSupplementalProvider{}+ monitor := buildSupplementalGrandfatherFloorMonitor(provider)++ handlers := NewLicenseHandlers(mtp, false)+ handlers.SetMonitors(monitor, nil)+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")++ svc := handlers.Service(ctx)+ if svc == nil {+ t.Fatal("expected non-nil service")+ }+ if got := svc.Status().MaxMonitoredSystems; got != 10 {+ t.Fatalf("initial status.MaxMonitoredSystems=%d, want 10 while supplemental inventory is unsettled", got)+ }++ activationState, err := persistence.LoadActivationState()+ if err != nil {+ t.Fatalf("load activation state: %v", err)+ }+ if activationState == nil {+ t.Fatal("expected activation state after legacy exchange")+ }+ if activationState.Continuity.GrandfatheredMonitoredSystemsCapturedAt != 0 {+ t.Fatalf("GrandfatheredMonitoredSystemsCapturedAt=%d, want 0 before supplemental baseline settles", activationState.Continuity.GrandfatheredMonitoredSystemsCapturedAt)+ }++ provider.settle(23)+ svc = handlers.Service(ctx)+ if got := svc.Status().MaxMonitoredSystems; got != 10 {+ t.Fatalf("stale supplemental store should not capture grandfather floor yet, got %d", got)+ }++ monitor.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, provider)+ svc = handlers.Service(ctx)+ if got := svc.Status().MaxMonitoredSystems; got != 23 {+ t.Fatalf("status.MaxMonitoredSystems=%d, want 23 after supplemental store rebuild", got)+ }++ activationState, err = persistence.LoadActivationState()+ if err != nil {+ t.Fatalf("reload activation state: %v", err)+ }+ if activationState == nil {+ t.Fatal("expected activation state after grandfather capture")+ }+ if activationState.Continuity.GrandfatheredMaxMonitoredSystems != 23 {+ t.Fatalf("GrandfatheredMaxMonitoredSystems=%d, want 23", activationState.Continuity.GrandfatheredMaxMonitoredSystems)+ }+ if activationState.Continuity.GrandfatheredMonitoredSystemsCapturedAt == 0 {+ t.Fatal("expected grandfather capture timestamp after supplemental store rebuild")+ }++ handlers.StopAllBackgroundLoops()+}+func buildGrandfatherFloorMonitor(count int) *monitoring.Monitor {now := time.Now().UTC()registry := unifiedresources.NewRegistry(nil)@@ -589,6 +738,42 @@ func buildGrandfatherFloorMonitor(count int) *monitoring.Monitor {return monitor}+func buildSupplementalGrandfatherFloorMonitor(provider *grandfatherFloorSupplementalProvider) *monitoring.Monitor {+ monitor := &monitoring.Monitor{}+ monitor.SetResourceStore(unifiedresources.NewMonitorAdapter(nil))+ monitor.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, provider)+ return monitor+}++func buildSupplementalGrandfatherFloorRecords(+ count int,+ now time.Time,+) []unifiedresources.IngestRecord {+ records := make([]unifiedresources.IngestRecord, 0, count)+ for i := 0; i < count; i++ {+ id := fmt.Sprintf("truenas-%02d", i+1)+ hostname := fmt.Sprintf("truenas-%02d.lab.local", i+1)+ records = append(records, unifiedresources.IngestRecord{+ SourceID: "system:" + id,+ Resource: unifiedresources.Resource{+ ID: id,+ Type: unifiedresources.ResourceTypeAgent,+ Name: hostname,+ Status: unifiedresources.StatusOnline,+ LastSeen: now,+ UpdatedAt: now,+ Identity: unifiedresources.ResourceIdentity{+ Hostnames: []string{hostname},+ },+ TrueNAS: &unifiedresources.TrueNASData{+ Hostname: hostname,+ },+ },+ })+ }+ return records+}+// base64RawURLEncode is a helper for tests.func base64RawURLEncode(data []byte) string {// Use the same encoding as JWT: base64 URL-safe without padding.diff --git a/internal/api/monitored_system_limit_enforcement.go b/internal/api/monitored_system_limit_enforcement.goindex 1f226c9b91..ed5778f5d8 100644--- a/internal/api/monitored_system_limit_enforcement.go+++ b/internal/api/monitored_system_limit_enforcement.go@@ -130,19 +130,11 @@ type monitoredSystemUsageSnapshot struct {}func monitoredSystemUsage(monitor *monitoring.Monitor) monitoredSystemUsageSnapshot {- if monitor == nil {- return monitoredSystemUsageSnapshot{}- }-- readState := monitor.GetUnifiedReadStateOrSnapshot()- if readState == nil {- return monitoredSystemUsageSnapshot{}- }-+ usage := monitor.MonitoredSystemUsage()return monitoredSystemUsageSnapshot{- count: unifiedresources.MonitoredSystemCount(readState),- readState: readState,- available: true,+ count: usage.Count,+ readState: usage.ReadState,+ available: usage.Available,}}diff --git a/internal/api/router.go b/internal/api/router.goindex 558d057048..b4b2028366 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -9610,4 +9610,8 @@ func (a mockSupplementalRecordsAdapter) SnapshotOwnedSourcesForOrg(string) []unireturn a.SnapshotOwnedSources()}+func (a mockSupplementalRecordsAdapter) SupplementalInventoryReadyAt(*monitoring.Monitor, string) (time.Time, bool) {+ return time.Time{}, true+}+// trigger rebuild Fri Jan 16 10:52:41 UTC 2026diff --git a/internal/api/subscription_entitlements.go b/internal/api/subscription_entitlements.goindex 6d97cfc06b..7fca7c833e 100644--- a/internal/api/subscription_entitlements.go+++ b/internal/api/subscription_entitlements.go@@ -168,21 +168,21 @@ func (h *LicenseHandlers) entitlementUsageSnapshot(ctx context.Context) entitlemvar monitorResolved boolif h.mtMonitor != nil {if monitor, err := h.mtMonitor.GetMonitor(orgID); err == nil && monitor != nil {- state := monitoredSystemUsage(monitor)- if state.available {- usage.MonitoredSystems = int64(state.count)+ state := monitor.MonitoredSystemUsage()+ if state.Available {+ usage.MonitoredSystems = int64(state.Count)usage.MonitoredSystemsAvailable = true- usage.LegacyConnections = legacyConnectionCounts(monitor)+ usage.LegacyConnections = legacyConnectionCountsFromReadState(state.ReadState)monitorResolved = true}}}if !monitorResolved && orgID == "default" && h.monitor != nil {- state := monitoredSystemUsage(h.monitor)- if state.available {- usage.MonitoredSystems = int64(state.count)+ state := h.monitor.MonitoredSystemUsage()+ if state.Available {+ usage.MonitoredSystems = int64(state.Count)usage.MonitoredSystemsAvailable = true- usage.LegacyConnections = legacyConnectionCounts(h.monitor)+ usage.LegacyConnections = legacyConnectionCountsFromReadState(state.ReadState)}}diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex aa28766c31..40ae70af3b 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -91,6 +91,45 @@ func TestGetStateRefreshesLiveAlertSnapshots(t *testing.T) {}}+func TestMonitoredSystemUsageReadinessGuardrailsRemainCanonical(t *testing.T) {+ requiredSnippets := map[string][]string{+ "monitor.go": {+ "type MonitorSupplementalInventoryReadinessProvider interface {",+ "SupplementalInventoryReadyAt(m *Monitor, orgID string) (time.Time, bool)",+ },+ "monitored_system_usage.go": {+ "func (m *Monitor) MonitoredSystemUsage() MonitoredSystemUsageSnapshot {",+ "readyAt, settled := m.supplementalInventoryReadyAt(orgID)",+ "if !settled {",+ "if freshness.IsZero() || freshness.Before(readyAt) {",+ "return MonitoredSystemUsageSnapshot{ReadState: readState}",+ },+ "truenas_poller.go": {+ "func (p *TrueNASPoller) SupplementalInventoryReadyAt(_ *Monitor, orgID string) (time.Time, bool) {",+ "configs := p.activeConnectionConfigsForOrg(orgID)",+ "if status == nil || status.lastAttemptAt.IsZero() {",+ },+ "vmware_poller.go": {+ "func (p *VMwarePoller) SupplementalInventoryReadyAt(_ *Monitor, orgID string) (time.Time, bool) {",+ "configs := p.activeConnectionConfigsForOrg(orgID)",+ "if status == nil || status.lastAttemptAt.IsZero() {",+ },+ }++ for file, snippets := range requiredSnippets {+ data, err := os.ReadFile(file)+ if err != nil {+ t.Fatalf("failed to read %s: %v", file, err)+ }+ source := string(data)+ for _, snippet := range snippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("%s must contain %q", file, snippet)+ }+ }+ }+}+func TestGuestMemoryFallbackUsesCanonicalLowTrustSelector(t *testing.T) {data, err := os.ReadFile("guest_memory_sources.go")if err != nil {diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 5909ebe8b7..243d339d61 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -148,6 +148,17 @@ type MonitorSupplementalChangesProvider interface {SupplementalChanges(m *Monitor, orgID string) []unifiedresources.ResourceChange}+// MonitorSupplementalInventoryReadinessProvider optionally reports when a+// supplemental provider's current org-scoped inventory is settled enough to be+// consumed by billing and monitored-system admission boundaries.+//+// Providers that suppress snapshot-owned sources must implement this contract+// so the monitor can fail closed until the canonical store has been rebuilt+// from a settled provider baseline.+type MonitorSupplementalInventoryReadinessProvider interface {+ SupplementalInventoryReadyAt(m *Monitor, orgID string) (time.Time, bool)+}+// MonitorPhysicalDiskTemperatureHistoryProvider optionally exposes source-native// physical-disk temperature history through the canonical monitoring chart// boundary when Pulse's own stored history is shallow.diff --git a/internal/monitoring/monitor_unified_state_test.go b/internal/monitoring/monitor_unified_state_test.goindex f5da9d5233..35a53f99d3 100644--- a/internal/monitoring/monitor_unified_state_test.go+++ b/internal/monitoring/monitor_unified_state_test.go@@ -35,6 +35,30 @@ func (s *freshnessResourceStore) UnifiedResourceFreshness() time.Time {return s.freshness}+type testSupplementalInventoryReadinessProvider struct {+ source unifiedresources.DataSource+ records []unifiedresources.IngestRecord+ settled bool+ readyAt time.Time+}++func (p *testSupplementalInventoryReadinessProvider) SupplementalRecords(_ *Monitor, _ string) []unifiedresources.IngestRecord {+ out := make([]unifiedresources.IngestRecord, len(p.records))+ copy(out, p.records)+ return out+}++func (p *testSupplementalInventoryReadinessProvider) SnapshotOwnedSources() []unifiedresources.DataSource {+ if p.source == "" {+ return nil+ }+ return []unifiedresources.DataSource{p.source}+}++func (p *testSupplementalInventoryReadinessProvider) SupplementalInventoryReadyAt(*Monitor, string) (time.Time, bool) {+ return p.readyAt, p.settled+}+type unifiedResourceGetter interface {GetAll() []unifiedresources.Resource}@@ -232,3 +256,51 @@ func TestMonitorGetUnifiedReadStateOrSnapshotUsesCanonicalMockUnifiedResources(tt.Fatalf("expected mock-mode read-state to include legacy mock resource %q, got %#v", legacyName, resources)}}++func TestMonitorMonitoredSystemUsageWaitsForSupplementalReadinessAndStoreFreshness(t *testing.T) {+ monitor := &Monitor{}+ monitor.SetResourceStore(unifiedresources.NewMonitorAdapter(nil))++ provider := &testSupplementalInventoryReadinessProvider{+ source: unifiedresources.SourceTrueNAS,+ }+ monitor.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, provider)++ if usage := monitor.MonitoredSystemUsage(); usage.Available {+ t.Fatalf("expected unsettled supplemental inventory to be unavailable, got %+v", usage)+ }++ readyAt := time.Now().UTC()+ provider.records = []unifiedresources.IngestRecord{{+ SourceID: "system:tn-main",+ Resource: unifiedresources.Resource{+ ID: "tn-main",+ Type: unifiedresources.ResourceTypeAgent,+ Name: "tn-main",+ Status: unifiedresources.StatusOnline,+ LastSeen: readyAt,+ Identity: unifiedresources.ResourceIdentity{+ Hostnames: []string{"tn-main"},+ },+ TrueNAS: &unifiedresources.TrueNASData{+ Hostname: "tn-main",+ },+ },+ }}+ provider.readyAt = readyAt+ provider.settled = true++ if usage := monitor.MonitoredSystemUsage(); usage.Available {+ t.Fatalf("expected stale store freshness to keep usage unavailable, got %+v", usage)+ }++ monitor.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, provider)++ usage := monitor.MonitoredSystemUsage()+ if !usage.Available {+ t.Fatalf("expected usage to become available after rebuild, got %+v", usage)+ }+ if usage.Count != 1 {+ t.Fatalf("MonitoredSystemUsage().Count = %d, want 1", usage.Count)+ }+}diff --git a/internal/monitoring/monitored_system_usage.go b/internal/monitoring/monitored_system_usage.gonew file mode 100644index 0000000000..730515fcfb--- /dev/null+++ b/internal/monitoring/monitored_system_usage.go@@ -0,0 +1,127 @@+package monitoring++import (+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++// MonitoredSystemUsageSnapshot describes whether the monitor can currently+// supply a canonical monitored-system count that is safe for billing and+// admission enforcement to consume.+type MonitoredSystemUsageSnapshot struct {+ Count int+ ReadState unifiedresources.ReadState+ Available bool+}++// MonitoredSystemUsage returns the canonical monitored-system count only when+// the current unified view is settled enough for billing boundaries. When+// supplemental provider-owned sources are still settling, the result fails+// closed with Available=false.+func (m *Monitor) MonitoredSystemUsage() MonitoredSystemUsageSnapshot {+ if m == nil {+ return MonitoredSystemUsageSnapshot{}+ }++ readState := m.GetUnifiedReadStateOrSnapshot()+ if readState == nil {+ return MonitoredSystemUsageSnapshot{}+ }++ orgID := normalizedMonitorUsageOrgID(m)+ readyAt, settled := m.supplementalInventoryReadyAt(orgID)+ if !settled {+ return MonitoredSystemUsageSnapshot{ReadState: readState}+ }+ if !readyAt.IsZero() {+ freshness := m.currentUnifiedResourceFreshness()+ if freshness.IsZero() || freshness.Before(readyAt) {+ return MonitoredSystemUsageSnapshot{ReadState: readState}+ }+ }++ return MonitoredSystemUsageSnapshot{+ Count: unifiedresources.MonitoredSystemCount(readState),+ ReadState: readState,+ Available: true,+ }+}++func normalizedMonitorUsageOrgID(m *Monitor) string {+ if m == nil {+ return "default"+ }+ orgID := strings.TrimSpace(m.GetOrgID())+ if orgID == "" {+ return "default"+ }+ return orgID+}++func (m *Monitor) supplementalInventoryReadyAt(orgID string) (time.Time, bool) {+ providers := m.supplementalProviderSnapshot()+ if len(providers) == 0 {+ return time.Time{}, true+ }++ var watermark time.Time+ for _, provider := range providers {+ if provider == nil {+ continue+ }++ readinessProvider, hasReadiness := provider.(MonitorSupplementalInventoryReadinessProvider)+ if !hasReadiness {+ if len(supplementalProviderOwnedSourcesForOrg(provider, orgID)) > 0 {+ return time.Time{}, false+ }+ continue+ }++ readyAt, settled := readinessProvider.SupplementalInventoryReadyAt(m, orgID)+ if !settled {+ return time.Time{}, false+ }+ if readyAt.After(watermark) {+ watermark = readyAt+ }+ }++ return watermark, true+}++func supplementalProviderOwnedSourcesForOrg(+ provider MonitorSupplementalRecordsProvider,+ orgID string,+) []unifiedresources.DataSource {+ if provider == nil {+ return nil+ }++ var sources []unifiedresources.DataSource+ if tenantOwner, ok := provider.(interface {+ SnapshotOwnedSourcesForOrg(string) []unifiedresources.DataSource+ }); ok {+ sources = tenantOwner.SnapshotOwnedSourcesForOrg(orgID)+ } else if owner, ok := provider.(interface {+ SnapshotOwnedSources() []unifiedresources.DataSource+ }); ok {+ sources = owner.SnapshotOwnedSources()+ }++ if len(sources) == 0 {+ return nil+ }++ out := make([]unifiedresources.DataSource, 0, len(sources))+ for _, source := range sources {+ normalized := unifiedresources.DataSource(strings.ToLower(strings.TrimSpace(string(source))))+ if normalized == "" {+ continue+ }+ out = append(out, normalized)+ }+ return out+}diff --git a/internal/monitoring/truenas_poller.go b/internal/monitoring/truenas_poller.goindex d5aa3b4397..4974beb061 100644--- a/internal/monitoring/truenas_poller.go+++ b/internal/monitoring/truenas_poller.go@@ -1019,6 +1019,39 @@ func (p *TrueNASPoller) SnapshotOwnedSourcesForOrg(string) []unifiedresources.Dareturn []unifiedresources.DataSource{unifiedresources.SourceTrueNAS}}+// SupplementalInventoryReadyAt reports when the current org-scoped TrueNAS+// inventory has reached a settled initial baseline that has to be reflected in+// the canonical monitor store before billing can consume monitored-system+// counts.+func (p *TrueNASPoller) SupplementalInventoryReadyAt(_ *Monitor, orgID string) (time.Time, bool) {+ if p == nil {+ return time.Time{}, true+ }++ orgID = normalizeTrueNASOrgID(orgID)+ configs := p.activeConnectionConfigsForOrg(orgID)+ if len(configs) == 0 {+ return time.Time{}, true+ }++ p.mu.Lock()+ defer p.mu.Unlock()++ var watermark time.Time+ statusByConn := p.statusByOrg[orgID]+ for connID := range configs {+ status := statusByConn[connID]+ if status == nil || status.lastAttemptAt.IsZero() {+ return time.Time{}, false+ }+ if status.lastAttemptAt.After(watermark) {+ watermark = status.lastAttemptAt+ }+ }++ return watermark, true+}+// GetCurrentRecordsForOrg returns the latest known TrueNAS records for the specified org.func (p *TrueNASPoller) GetCurrentRecordsForOrg(orgID string) []unifiedresources.IngestRecord {if p == nil {@@ -1059,6 +1092,57 @@ func (p *TrueNASPoller) GetCurrentRecordsForOrg(orgID string) []unifiedresourcesreturn records}+func (p *TrueNASPoller) activeConnectionConfigsForOrg(orgID string) map[string]config.TrueNASInstance {+ orgID = normalizeTrueNASOrgID(orgID)+ if p == nil {+ return nil+ }++ p.mu.Lock()+ cached := cloneTrueNASConnectionConfigMap(p.configsByOrg[orgID])+ p.mu.Unlock()+ if len(cached) > 0 || p.multiTenant == nil {+ return cached+ }++ persistence, err := p.multiTenant.GetPersistence(orgID)+ if err != nil || persistence == nil {+ return cached+ }+ instances, err := persistence.LoadTrueNASConfig()+ if err != nil {+ return cached+ }++ active := make(map[string]config.TrueNASInstance)+ for i := range instances {+ instance := instances[i]+ instance.ApplyDefaults()+ if !instance.Enabled {+ continue+ }+ connID := strings.TrimSpace(instance.ID)+ if connID == "" {+ continue+ }+ active[connID] = instance+ }+ return active+}++func cloneTrueNASConnectionConfigMap(+ in map[string]config.TrueNASInstance,+) map[string]config.TrueNASInstance {+ if len(in) == 0 {+ return nil+ }+ out := make(map[string]config.TrueNASInstance, len(in))+ for connID, instance := range in {+ out[connID] = instance+ }+ return out+}+// ControlApp executes a canonical TrueNAS app action for one tenant-scoped// API-backed app-container resource and refreshes the cached records afterward.func (p *TrueNASPoller) ControlApp(ctx context.Context, orgID, host, appID, action string) (*truenas.App, error) {diff --git a/internal/monitoring/truenas_poller_test.go b/internal/monitoring/truenas_poller_test.goindex d824aa09fb..90f3444497 100644--- a/internal/monitoring/truenas_poller_test.go+++ b/internal/monitoring/truenas_poller_test.go@@ -1279,6 +1279,35 @@ func TestTrueNASPollerSnapshotOwnedSources(t *testing.T) {}}+func TestTrueNASPollerSupplementalInventoryReadyAtUsesPersistedActiveConnections(t *testing.T) {+ mtp, persistence := newTestTenantPersistence(t)++ connection := config.NewTrueNASInstance()+ connection.ID = "conn-ready"+ connection.Host = "nas-ready.lab.local"+ connection.APIKey = "api-key"+ if err := persistence.SaveTrueNASConfig([]config.TrueNASInstance{connection}); err != nil {+ t.Fatalf("SaveTrueNASConfig() error = %v", err)+ }++ poller := NewTrueNASPoller(mtp, time.Second, nil)++ if readyAt, settled := poller.SupplementalInventoryReadyAt(nil, "default"); settled || !readyAt.IsZero() {+ t.Fatalf("SupplementalInventoryReadyAt() before any attempt = (%v, %t), want (zero, false)", readyAt, settled)+ }++ attemptedAt := time.Now().UTC()+ poller.RecordConnectionTestSuccess("default", connection.ID, connection, attemptedAt)++ readyAt, settled := poller.SupplementalInventoryReadyAt(nil, "default")+ if !settled {+ t.Fatal("expected readiness to settle after the first recorded attempt")+ }+ if !readyAt.Equal(attemptedAt) {+ t.Fatalf("SupplementalInventoryReadyAt() = %v, want %v", readyAt, attemptedAt)+ }+}+func TestTrueNASPollerSyncConnectionsLogsStructuredContextWhenPersistenceNil(t *testing.T) {logOutput := captureTrueNASPollerLogs(t)diff --git a/internal/monitoring/vmware_poller.go b/internal/monitoring/vmware_poller.goindex ef61cd62c6..adad3e17cd 100644--- a/internal/monitoring/vmware_poller.go+++ b/internal/monitoring/vmware_poller.go@@ -581,6 +581,39 @@ func (p *VMwarePoller) SnapshotOwnedSourcesForOrg(string) []unifiedresources.Datreturn []unifiedresources.DataSource{unifiedresources.SourceVMware}}+// SupplementalInventoryReadyAt reports when the current org-scoped VMware+// inventory has reached a settled initial baseline that has to be reflected in+// the canonical monitor store before billing can consume monitored-system+// counts.+func (p *VMwarePoller) SupplementalInventoryReadyAt(_ *Monitor, orgID string) (time.Time, bool) {+ if p == nil {+ return time.Time{}, true+ }++ orgID = normalizeVMwareOrgID(orgID)+ configs := p.activeConnectionConfigsForOrg(orgID)+ if len(configs) == 0 {+ return time.Time{}, true+ }++ p.mu.Lock()+ defer p.mu.Unlock()++ var watermark time.Time+ statusByConn := p.statusByOrg[orgID]+ for connID := range configs {+ status := statusByConn[connID]+ if status == nil || status.lastAttemptAt.IsZero() {+ return time.Time{}, false+ }+ if status.lastAttemptAt.After(watermark) {+ watermark = status.lastAttemptAt+ }+ }++ return watermark, true+}+// GetCurrentRecordsForOrg returns the latest known VMware records for the specified org.func (p *VMwarePoller) GetCurrentRecordsForOrg(orgID string) []unifiedresources.IngestRecord {if p == nil {@@ -621,6 +654,57 @@ func (p *VMwarePoller) GetCurrentRecordsForOrg(orgID string) []unifiedresources.return records}+func (p *VMwarePoller) activeConnectionConfigsForOrg(orgID string) map[string]config.VMwareVCenterInstance {+ orgID = normalizeVMwareOrgID(orgID)+ if p == nil {+ return nil+ }++ p.mu.Lock()+ cached := cloneVMwareConnectionConfigMap(p.configsByOrg[orgID])+ p.mu.Unlock()+ if len(cached) > 0 || p.multiTenant == nil {+ return cached+ }++ persistence, err := p.multiTenant.GetPersistence(orgID)+ if err != nil || persistence == nil {+ return cached+ }+ instances, err := persistence.LoadVMwareConfig()+ if err != nil {+ return cached+ }++ active := make(map[string]config.VMwareVCenterInstance)+ for i := range instances {+ instance := instances[i]+ instance.ApplyDefaults()+ if !instance.Enabled {+ continue+ }+ connID := strings.TrimSpace(instance.ID)+ if connID == "" {+ continue+ }+ active[connID] = instance+ }+ return active+}++func cloneVMwareConnectionConfigMap(+ in map[string]config.VMwareVCenterInstance,+) map[string]config.VMwareVCenterInstance {+ if len(in) == 0 {+ return nil+ }+ out := make(map[string]config.VMwareVCenterInstance, len(in))+ for connID, instance := range in {+ out[connID] = instance+ }+ return out+}+// GetCurrentChangesForOrg returns the latest known VMware timeline changes for the specified org.func (p *VMwarePoller) GetCurrentChangesForOrg(orgID string) []unifiedresources.ResourceChange {if p == nil {diff --git a/internal/monitoring/vmware_poller_test.go b/internal/monitoring/vmware_poller_test.goindex 17927310e5..ad4fc25de3 100644--- a/internal/monitoring/vmware_poller_test.go+++ b/internal/monitoring/vmware_poller_test.go@@ -134,6 +134,36 @@ func TestVMwarePollerPollsConfiguredConnections(t *testing.T) {}}+func TestVMwarePollerSupplementalInventoryReadyAtUsesPersistedActiveConnections(t *testing.T) {+ mtp, persistence := newTestTenantPersistence(t)++ connection := config.NewVMwareVCenterInstance()+ connection.ID = "vc-ready"+ connection.Host = "vc-ready.lab.local"+ connection.Username = "[email protected]"+ connection.Password = "secret"+ if err := persistence.SaveVMwareConfig([]config.VMwareVCenterInstance{connection}); err != nil {+ t.Fatalf("SaveVMwareConfig() error = %v", err)+ }++ poller := NewVMwarePoller(mtp, time.Second)++ if readyAt, settled := poller.SupplementalInventoryReadyAt(nil, "default"); settled || !readyAt.IsZero() {+ t.Fatalf("SupplementalInventoryReadyAt() before any attempt = (%v, %t), want (zero, false)", readyAt, settled)+ }++ attemptedAt := time.Now().UTC()+ poller.RecordConnectionTestSuccess("default", connection.ID, &vmware.InventorySummary{}, attemptedAt)++ readyAt, settled := poller.SupplementalInventoryReadyAt(nil, "default")+ if !settled {+ t.Fatal("expected readiness to settle after the first recorded attempt")+ }+ if !readyAt.Equal(attemptedAt) {+ t.Fatalf("SupplementalInventoryReadyAt() = %v, want %v", readyAt, attemptedAt)+ }+}+func TestVMwarePollerFeatureFlagGate(t *testing.T) {previous := vmware.IsFeatureEnabled()vmware.SetFeatureEnabled(false)