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
Explain monitored-system grouping decisions
rcourtmanf036663439d6
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex a6258838d5..e77aa5634c 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -218,6 +218,12 @@ That same shared `internal/api/` lifecycle boundary also assumes tenant-scopedresource helpers stay on canonical unified-resource seeds: adjacent fleet andinstall surfaces may not revive raw tenant `StateSnapshot` fallback throughshared API resource wiring once `UnifiedResourceSnapshotForTenant` exists.+That same shared `internal/api/` dependency now also includes the monitored-system+ledger support read: lifecycle-adjacent inventory and billing surfaces may+show the counted monitored systems coming from agent-backed infrastructure, but+the shared API helper must expose the canonical unified-resource grouping+explanation instead of rebuilding count reasons from install or registration+state.That same boundary now also assumes canonical resource payloads preserveshared facet totals through `facetCounts`, so the resource list and detailsurfaces can keep row summaries aligned without re-inferring totals fromdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 9ae28fd4a4..2bd3f39655 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -224,6 +224,12 @@ export history endpoints live in `internal/api/activity_audit_handlers.go` and`internal/api/router_routes_licensing.go`, and the contract tests now pin theirresponse shapes so the execution trail remains queryable through the governedAPI surface rather than only through the underlying store.+The monitored-system ledger contract now also carries a canonical grouping+explanation payload. `/api/license/monitored-system-ledger` must expose the+shared monitored-system explanation summary, sanitized grouping reasons, and+included top-level surfaces exactly as the unified-resource resolver computed+them, while the frontend client stays in lockstep with that nested payload+shape.Action-plan stale-plan protection on those audit records now uses the canonical`resourceVersion`, `policyVersion`, and `planHash` fields only, so theresponse contract stays deterministic without extra version baggage.diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex a28511dd8d..89e45f490e 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -196,6 +196,11 @@ decode-only compatibility inputs at the storage or grant boundary. Runtimeenforcement, entitlement payload `current` usage, checkout/activation flows,and upgrade messaging must all treat the cap as deduped top-level monitoredsystems across agent, API, and Kubernetes views.+The monitored-system ledger settings surface now also has to explain those+count decisions. Commercial usage UI may show grouped monitored systems, but+it must render the canonical backend explanation for why one or more+top-level views counted as a single monitored system instead of inventing+support copy or merge heuristics in the frontend.Frontend billing/admin surfaces must not synthesize `plan_version` fromsubscription lifecycle state. When a hosted billing record lacks a plan label,the UI must preserve that absence instead of fabricating values like `active`diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex cd5802255f..ea3b27e70c 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -142,6 +142,11 @@ as adjacent governed API ownership rather than timeline-store ownership. Thestorage and recovery lanes still own their own persistence and querycontracts, while the control-plane execution trail remains governed by theunified-resource and audit contracts.+That same shared `internal/api/` dependency now also includes monitored-system+ledger explanation reads: storage- and recovery-adjacent surfaces may coexist+with counted monitored-system inventory, but any support-facing count+reasoning must come from the canonical unified-resource grouping explanation+payload rather than from storage or recovery heuristics.The same API resource serializer also refreshes canonical identity and policymetadata through the shared unified-resource helper before it writes resourcepayloads, so storage and recovery links inherit the same canonical metadatadiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex f68c354c21..a24dd03361 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -164,6 +164,13 @@ underlying host's monitored-system identity. The canonical resolver coverageis pinned by an explicit top-level source matrix and mixed-environmentcharacterization tests so new top-level sources cannot quietly bypass thecounting contract.+That same resolver now also owns monitored-system grouping explanations. When+one counted system includes multiple top-level collection paths, the resolver+must record the actual canonical merge evidence it used, expose sanitized+grouping reasons plus included top-level surfaces, and fall back to an+explicit standalone explanation when no cross-source merge occurred. Support+and billing surfaces must consume that shared explanation contract instead of+reconstructing count reasons from API-local heuristics.The unified-resource runtime now also owns the durable change timeline for thecanonical resource view. `internal/unifiedresources/monitor_adapter.go` feedsdiff --git a/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.ts b/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.tsindex f271064767..ba2e52856f 100644--- a/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.ts+++ b/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.ts@@ -28,4 +28,38 @@ describe('MonitoredSystemLedgerAPI', () => {limit: 5,});});++ it('preserves grouping explanation payloads from the API contract', async () => {+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ systems: [+ {+ name: 'server-1',+ type: 'host',+ status: 'online',+ last_seen: '2026-01-01T00:00:00Z',+ source: 'agent',+ explanation: {+ summary:+ 'Counts as one monitored system because Pulse sees one top-level host view from agent.',+ reasons: [+ {+ kind: 'standalone',+ signal: 'single-top-level-view',+ summary: 'No overlapping top-level source matched this system.',+ },+ ],+ surfaces: [{ name: 'server-1', type: 'host', source: 'agent' }],+ },+ },+ ],+ total: 1,+ limit: 5,+ });++ const result = await MonitoredSystemLedgerAPI.getLedger();++ expect(result.systems[0]?.explanation.summary).toContain('Counts as one monitored system');+ expect(result.systems[0]?.explanation.reasons).toHaveLength(1);+ expect(result.systems[0]?.explanation.surfaces).toHaveLength(1);+ });});diff --git a/frontend-modern/src/api/monitoredSystemLedger.ts b/frontend-modern/src/api/monitoredSystemLedger.tsindex f3a3ec21e0..be6ec58bd1 100644--- a/frontend-modern/src/api/monitoredSystemLedger.ts+++ b/frontend-modern/src/api/monitoredSystemLedger.ts@@ -1,11 +1,30 @@import { apiFetchJSON } from '@/utils/apiClient';+export interface MonitoredSystemLedgerExplanationReason {+ kind: string;+ signal: string;+ summary: string;+}++export interface MonitoredSystemLedgerExplanationSurface {+ name: string;+ type: string;+ source: string;+}++export interface MonitoredSystemLedgerExplanation {+ summary: string;+ reasons: MonitoredSystemLedgerExplanationReason[];+ surfaces: MonitoredSystemLedgerExplanationSurface[];+}+export interface MonitoredSystemLedgerEntry {name: string;type: string;status: string; // "online" | "offline" | "unknown"last_seen: string; // RFC3339 or emptysource: string;+ explanation: MonitoredSystemLedgerExplanation;}export interface MonitoredSystemLedgerResponse {diff --git a/frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx b/frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsxindex 7885a22801..d799363258 100644--- a/frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx+++ b/frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx@@ -1,4 +1,4 @@-import { createResource, For, Show } from 'solid-js';+import { createResource, createSignal, For, Show } from 'solid-js';import SettingsPanel from '@/components/shared/SettingsPanel';import { StatusDot } from '@/components/shared/StatusDot';import {@@ -34,6 +34,7 @@ function usagePercent(total: number, limit: number): number {export function MonitoredSystemLedgerPanel(props: MonitoredSystemLedgerPanelProps = {}) {const [ledger, { refetch }] = createResource(() => MonitoredSystemLedgerAPI.getLedger());+ const [expandedSystemKey, setExpandedSystemKey] = createSignal<string | null>(null);const total = () => ledger()?.total ?? 0;const limit = () => ledger()?.limit ?? 0;@@ -41,6 +42,11 @@ export function MonitoredSystemLedgerPanel(props: MonitoredSystemLedgerPanelPropconst hasLimit = () => limit() > 0;const overLimit = () => hasLimit() && total() > limit();const pct = () => usagePercent(total(), limit());+ const systemKey = (system: MonitoredSystemLedgerEntry, index: number) =>+ `${system.name}:${system.type}:${index}`;+ const toggleSystemExplanation = (key: string) => {+ setExpandedSystemKey((current) => (current === key ? null : key));+ };const content = (<>@@ -120,12 +126,57 @@ export function MonitoredSystemLedgerPanel(props: MonitoredSystemLedgerPanelProp</TableHeader><TableBody><For each={systems()}>- {(system: MonitoredSystemLedgerEntry) => {+ {(system: MonitoredSystemLedgerEntry, index) => {const indicator = getSimpleStatusIndicator(system.status);+ const key = systemKey(system, index());+ const explanationID = `monitored-system-explanation-${index()}`;+ const expanded = () => expandedSystemKey() === key;return (<TableRow><TableCell>- <span class="text-sm font-medium text-base-content">{system.name}</span>+ <div class="space-y-1 whitespace-normal">+ <span class="text-sm font-medium text-base-content">{system.name}</span>+ <button+ type="button"+ class="block text-[11px] font-medium text-muted underline-offset-2 transition-colors hover:text-base-content hover:underline"+ aria-expanded={expanded()}+ aria-controls={explanationID}+ onClick={() => toggleSystemExplanation(key)}+ >+ {expanded() ? 'Hide count details' : 'Why this counts'}+ </button>+ <Show when={expanded()}>+ <div+ id={explanationID}+ class="space-y-2 rounded-md border border-border bg-surface px-3 py-2 text-xs text-muted"+ >+ <p class="whitespace-normal text-base-content">+ {system.explanation.summary}+ </p>+ <Show when={system.explanation.reasons.length > 0}>+ <ul class="space-y-1 whitespace-normal">+ <For each={system.explanation.reasons}>+ {(reason) => <li>{reason.summary}</li>}+ </For>+ </ul>+ </Show>+ <Show when={system.explanation.surfaces.length > 0}>+ <div class="space-y-1">+ <p class="font-medium text-base-content">Included views</p>+ <ul class="space-y-1 whitespace-normal">+ <For each={system.explanation.surfaces}>+ {(surface) => (+ <li>+ {surface.name} ({surface.type}, {surface.source})+ </li>+ )}+ </For>+ </ul>+ </div>+ </Show>+ </div>+ </Show>+ </div></TableCell><TableCell><span class="inline-flex items-center gap-1.5">diff --git a/frontend-modern/src/components/Settings/__tests__/MonitoredSystemLedgerPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/MonitoredSystemLedgerPanel.test.tsxindex 18f37ca85a..ec847b4bf8 100644--- a/frontend-modern/src/components/Settings/__tests__/MonitoredSystemLedgerPanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/MonitoredSystemLedgerPanel.test.tsx@@ -77,6 +77,18 @@ describe('MonitoredSystemLedgerPanel', () => {status: 'online',last_seen: '2026-01-01T00:00:00Z',source: 'agent',+ explanation: {+ summary:+ 'Counts as one monitored system because Pulse sees one top-level host view from agent.',+ reasons: [+ {+ kind: 'standalone',+ signal: 'single-top-level-view',+ summary: 'No overlapping top-level source matched this system.',+ },+ ],+ surfaces: [{ name: 'host-1', type: 'host', source: 'agent' }],+ },},],total: 1,@@ -122,6 +134,18 @@ describe('MonitoredSystemLedgerPanel', () => {status: 'online',last_seen: '2026-01-01T00:00:00Z',source: 'agent',+ explanation: {+ summary:+ 'Counts as one monitored system because Pulse sees one top-level host view from agent.',+ reasons: [+ {+ kind: 'standalone',+ signal: 'single-top-level-view',+ summary: 'No overlapping top-level source matched this system.',+ },+ ],+ surfaces: [{ name: 'server-a', type: 'host', source: 'agent' }],+ },},{name: 'server-b',@@ -129,6 +153,21 @@ describe('MonitoredSystemLedgerPanel', () => {status: 'offline',last_seen: '2026-01-02T00:00:00Z',source: 'pbs',+ explanation: {+ summary:+ 'Counts as one monitored system because Pulse merged 2 top-level views into one canonical system using shared machine identity.',+ reasons: [+ {+ kind: 'shared-identity',+ signal: 'machine-id',+ summary: 'Merged host and PBS server views using shared machine identity.',+ },+ ],+ surfaces: [+ { name: 'server-b', type: 'pbs-server', source: 'pbs' },+ { name: 'server-b host', type: 'host', source: 'agent' },+ ],+ },},],total: 2,@@ -159,6 +198,15 @@ describe('MonitoredSystemLedgerPanel', () => {).toBeInTheDocument();expect(screen.getByText('server-b')).toBeInTheDocument();expect(screen.getByText('2 / 10')).toBeInTheDocument();+ expect(screen.getAllByRole('button', { name: 'Why this counts' })).toHaveLength(2);+ fireEvent.click(screen.getAllByRole('button', { name: 'Why this counts' })[1]!);+ expect(+ screen.getByText(+ 'Counts as one monitored system because Pulse merged 2 top-level views into one canonical system using shared machine identity.',+ ),+ ).toBeInTheDocument();+ expect(screen.getByText('Included views')).toBeInTheDocument();+ expect(screen.getByText('server-b host (host, agent)')).toBeInTheDocument();expect(screen.queryByText('Failed to load monitored system ledger.')).not.toBeInTheDocument();});});diff --git a/internal/api/monitored_system_ledger.go b/internal/api/monitored_system_ledger.goindex 455dc7d8e4..f80cad8ca9 100644--- a/internal/api/monitored_system_ledger.go+++ b/internal/api/monitored_system_ledger.go@@ -13,11 +13,30 @@ import (// MonitoredSystemLedgerEntry represents a single counted top-level monitored// system.type MonitoredSystemLedgerEntry struct {- Name string `json:"name"`- Type string `json:"type"`- Status string `json:"status"` // "online", "offline", "unknown"- LastSeen string `json:"last_seen"` // RFC3339 or empty- Source string `json:"source"`+ Name string `json:"name"`+ Type string `json:"type"`+ Status string `json:"status"` // "online", "offline", "unknown"+ LastSeen string `json:"last_seen"` // RFC3339 or empty+ Source string `json:"source"`+ Explanation MonitoredSystemLedgerExplanation `json:"explanation"`+}++type MonitoredSystemLedgerExplanation struct {+ Summary string `json:"summary"`+ Reasons []MonitoredSystemLedgerExplanationReason `json:"reasons"`+ Surfaces []MonitoredSystemLedgerExplanationSurface `json:"surfaces"`+}++type MonitoredSystemLedgerExplanationReason struct {+ Kind string `json:"kind"`+ Signal string `json:"signal"`+ Summary string `json:"summary"`+}++type MonitoredSystemLedgerExplanationSurface struct {+ Name string `json:"name"`+ Type string `json:"type"`+ Source string `json:"source"`}// MonitoredSystemLedgerResponse is the response for GET /api/license/monitored-system-ledger.@@ -35,9 +54,22 @@ func (r MonitoredSystemLedgerResponse) NormalizeCollections() MonitoredSystemLedif r.Systems == nil {r.Systems = []MonitoredSystemLedgerEntry{}}+ for i := range r.Systems {+ r.Systems[i] = r.Systems[i].NormalizeCollections()+ }return r}+func (e MonitoredSystemLedgerEntry) NormalizeCollections() MonitoredSystemLedgerEntry {+ if e.Explanation.Reasons == nil {+ e.Explanation.Reasons = []MonitoredSystemLedgerExplanationReason{}+ }+ if e.Explanation.Surfaces == nil {+ e.Explanation.Surfaces = []MonitoredSystemLedgerExplanationSurface{}+ }+ return e+}+func (r *Router) handleMonitoredSystemLedger(w http.ResponseWriter, req *http.Request) {orgID := GetOrgID(req.Context())@@ -66,11 +98,12 @@ func (r *Router) handleMonitoredSystemLedger(w http.ResponseWriter, req *http.Reentries := make([]MonitoredSystemLedgerEntry, 0, len(systems))for _, system := range systems {entries = append(entries, MonitoredSystemLedgerEntry{- Name: system.Name,- Type: system.Type,- Status: normalizeStatus(string(system.Status)),- LastSeen: formatLastSeen(system.LastSeen),- Source: system.Source,+ Name: system.Name,+ Type: system.Type,+ Status: normalizeStatus(string(system.Status)),+ LastSeen: formatLastSeen(system.LastSeen),+ Source: system.Source,+ Explanation: monitoredSystemLedgerExplanation(system.Explanation),})}@@ -104,3 +137,31 @@ func formatLastSeen(t time.Time) string {}return t.UTC().Format(time.RFC3339)}++func monitoredSystemLedgerExplanation(+ explanation unifiedresources.MonitoredSystemGroupingExplanation,+) MonitoredSystemLedgerExplanation {+ reasons := make([]MonitoredSystemLedgerExplanationReason, 0, len(explanation.Reasons))+ for _, reason := range explanation.Reasons {+ reasons = append(reasons, MonitoredSystemLedgerExplanationReason{+ Kind: reason.Kind,+ Signal: reason.Signal,+ Summary: reason.Summary,+ })+ }++ surfaces := make([]MonitoredSystemLedgerExplanationSurface, 0, len(explanation.Surfaces))+ for _, surface := range explanation.Surfaces {+ surfaces = append(surfaces, MonitoredSystemLedgerExplanationSurface{+ Name: surface.Name,+ Type: surface.Type,+ Source: surface.Source,+ })+ }++ return MonitoredSystemLedgerExplanation{+ Summary: explanation.Summary,+ Reasons: reasons,+ Surfaces: surfaces,+ }+}diff --git a/internal/api/monitored_system_ledger_test.go b/internal/api/monitored_system_ledger_test.goindex 3a42405490..876d46f32e 100644--- a/internal/api/monitored_system_ledger_test.go+++ b/internal/api/monitored_system_ledger_test.go@@ -15,6 +15,15 @@ func TestMonitoredSystemLedgerEntryTypes(t *testing.T) {Status: "online",LastSeen: "2025-01-01T00:00:00Z",Source: "agent",+ Explanation: MonitoredSystemLedgerExplanation{+ Summary: "Counts as one monitored system because Pulse sees one top-level host view from agent.",+ Reasons: []MonitoredSystemLedgerExplanationReason{+ {Kind: "standalone", Signal: "single-top-level-view", Summary: "No overlapping top-level source matched this system."},+ },+ Surfaces: []MonitoredSystemLedgerExplanationSurface{+ {Name: "server-1", Type: "host", Source: "agent"},+ },+ },}data, err := json.Marshal(entry)if err != nil {@@ -30,6 +39,9 @@ func TestMonitoredSystemLedgerEntryTypes(t *testing.T) {if decoded.Source != "agent" {t.Errorf("source mismatch: got %q", decoded.Source)}+ if decoded.Explanation.Summary == "" || len(decoded.Explanation.Reasons) != 1 || len(decoded.Explanation.Surfaces) != 1 {+ t.Errorf("explanation mismatch: %+v", decoded.Explanation)+ }}func TestNormalizeStatus(t *testing.T) {@@ -99,13 +111,44 @@ func TestMonitoredSystemLedgerNilSystemsBecomesEmptyArray(t *testing.T) {}}+func TestMonitoredSystemLedgerEntryNormalizeCollections(t *testing.T) {+ entry := MonitoredSystemLedgerEntry{+ Name: "server-1",+ Explanation: MonitoredSystemLedgerExplanation{+ Summary: "Counts as one monitored system because Pulse sees one top-level host view from agent.",+ },+ }.NormalizeCollections()++ if entry.Explanation.Reasons == nil {+ t.Fatal("expected explanation reasons to normalize to an empty slice")+ }+ if entry.Explanation.Surfaces == nil {+ t.Fatal("expected explanation surfaces to normalize to an empty slice")+ }+}+func TestHandleMonitoredSystemLedgerHTTP(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/api/license/monitored-system-ledger", nil)rec := httptest.NewRecorder()resp := MonitoredSystemLedgerResponse{Systems: []MonitoredSystemLedgerEntry{- {Name: "test-host", Type: "host", Status: "online", LastSeen: "2025-01-01T00:00:00Z", Source: "agent"},+ {+ Name: "test-host",+ Type: "host",+ Status: "online",+ LastSeen: "2025-01-01T00:00:00Z",+ Source: "agent",+ Explanation: MonitoredSystemLedgerExplanation{+ Summary: "Counts as one monitored system because Pulse sees one top-level host view from agent.",+ Reasons: []MonitoredSystemLedgerExplanationReason{+ {Kind: "standalone", Signal: "single-top-level-view", Summary: "No overlapping top-level source matched this system."},+ },+ Surfaces: []MonitoredSystemLedgerExplanationSurface{+ {Name: "test-host", Type: "host", Source: "agent"},+ },+ },+ },},Total: 1,Limit: 5,@@ -130,4 +173,7 @@ func TestHandleMonitoredSystemLedgerHTTP(t *testing.T) {if decoded.Systems[0].Name != "test-host" || decoded.Systems[0].Type != "host" {t.Errorf("unexpected system: %+v", decoded.Systems[0])}+ if decoded.Systems[0].Explanation.Summary == "" {+ t.Errorf("expected explanation summary, got %+v", decoded.Systems[0].Explanation)+ }}diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex 54969bc386..cfbad1db19 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -598,6 +598,7 @@ func TestTopLevelSystemResolverPinsCanonicalInfrastructureCounting(t *testing.T)filepath.Join(".", "top_level_systems.go"): {"ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver","match.Confidence < HighConfidenceThreshold",+ "topLevelSystemGroupingExplanation(","monitoredSystemCandidateAllowsHostAttachment(candidate)","When adding a new top-level monitored-system source, update:",},diff --git a/internal/unifiedresources/monitored_systems.go b/internal/unifiedresources/monitored_systems.goindex 673a9f536b..ade72dc6f4 100644--- a/internal/unifiedresources/monitored_systems.go+++ b/internal/unifiedresources/monitored_systems.go@@ -18,14 +18,39 @@ type MonitoredSystemCandidate struct {ResourceID string}+// MonitoredSystemGroupingExplanation explains why Pulse counted one or more+// top-level collection paths as a single monitored system.+type MonitoredSystemGroupingExplanation struct {+ Summary string+ Reasons []MonitoredSystemGroupingReason+ Surfaces []MonitoredSystemGroupingSurface+}++// MonitoredSystemGroupingReason captures one canonical signal that contributed+// to a top-level monitored-system grouping decision.+type MonitoredSystemGroupingReason struct {+ Kind string+ Signal string+ Summary string+}++// MonitoredSystemGroupingSurface describes one counted top-level collection+// path included in a monitored-system group.+type MonitoredSystemGroupingSurface struct {+ Name string+ Type string+ Source string+}+// MonitoredSystemRecord describes a counted top-level monitored system after// canonical cross-view deduplication.type MonitoredSystemRecord struct {- Name string- Type string- Status ResourceStatus- LastSeen time.Time- Source string+ Name string+ Type string+ Status ResourceStatus+ LastSeen time.Time+ Source string+ Explanation MonitoredSystemGroupingExplanation}// MonitoredSystemCount returns the number of top-level monitored systems after@@ -61,8 +86,9 @@ func HasMatchingMonitoredSystem(rs ReadState, candidate MonitoredSystemCandidate}type monitoredSystemGroup struct {- keys map[string]struct{}- resources []*Resource+ keys map[string]struct{}+ resources []*Resource+ explanation MonitoredSystemGroupingExplanation}func monitoredSystemGroups(rs ReadState) []monitoredSystemGroup {@@ -70,8 +96,9 @@ func monitoredSystemGroups(rs ReadState) []monitoredSystemGroup {groups := make([]monitoredSystemGroup, 0, len(resolver.groups))for _, group := range resolver.groups {groups = append(groups, monitoredSystemGroup{- keys: cloneStringSet(group.strongIDs),- resources: group.resources,+ keys: cloneStringSet(group.strongIDs),+ resources: group.resources,+ explanation: group.explanation,})}return groups@@ -126,11 +153,12 @@ func resolveMonitoredSystemTopLevelSystems(rs ReadState) TopLevelSystemResolverfunc monitoredSystemRecord(group monitoredSystemGroup) MonitoredSystemRecord {resource := preferredMonitoredSystemResource(group.resources)record := MonitoredSystemRecord{- Name: monitoredSystemDisplayName(group.resources, resource),- Type: monitoredSystemType(resource),- Status: monitoredSystemStatus(group.resources),- LastSeen: monitoredSystemLastSeen(group.resources),- Source: monitoredSystemSource(group.resources),+ Name: monitoredSystemDisplayName(group.resources, resource),+ Type: monitoredSystemType(resource),+ Status: monitoredSystemStatus(group.resources),+ LastSeen: monitoredSystemLastSeen(group.resources),+ Source: monitoredSystemSource(group.resources),+ Explanation: normalizeMonitoredSystemGroupingExplanation(group.explanation),}if record.Name == "" {record.Name = "Unnamed system"@@ -144,9 +172,129 @@ func monitoredSystemRecord(group monitoredSystemGroup) MonitoredSystemRecord {if record.Source == "" {record.Source = "unknown"}+ if record.Explanation.Summary == "" {+ record.Explanation = monitoredSystemStandaloneExplanation(group.resources)+ }return record}+func normalizeMonitoredSystemGroupingExplanation(+ explanation MonitoredSystemGroupingExplanation,+) MonitoredSystemGroupingExplanation {+ if explanation.Reasons == nil {+ explanation.Reasons = []MonitoredSystemGroupingReason{}+ }+ if explanation.Surfaces == nil {+ explanation.Surfaces = []MonitoredSystemGroupingSurface{}+ }+ return explanation+}++func monitoredSystemStandaloneExplanation(resources []*Resource) MonitoredSystemGroupingExplanation {+ surfaces := monitoredSystemGroupingSurfaces(resources)+ resource := preferredMonitoredSystemResource(resources)+ source := monitoredSystemPrimarySource(resource)+ if source == "" {+ source = "unknown"+ }++ return normalizeMonitoredSystemGroupingExplanation(MonitoredSystemGroupingExplanation{+ Summary: "Counts as one monitored system because Pulse sees one top-level " ++ monitoredSystemGroupingTypeLabel(monitoredSystemType(resource)) ++ " view from " + monitoredSystemGroupingSourceLabel(source) + ".",+ Reasons: []MonitoredSystemGroupingReason{+ {+ Kind: "standalone",+ Signal: "single-top-level-view",+ Summary: "No overlapping top-level source matched this system.",+ },+ },+ Surfaces: surfaces,+ })+}++func monitoredSystemGroupingSurfaces(resources []*Resource) []MonitoredSystemGroupingSurface {+ surfaces := make([]MonitoredSystemGroupingSurface, 0, len(resources))+ for _, resource := range resources {+ if resource == nil {+ continue+ }++ name := monitoredSystemResourceDisplayName(resource)+ if name == "" {+ name = strings.TrimSpace(resource.ID)+ }+ if name == "" {+ name = "Unnamed source"+ }++ resourceType := monitoredSystemType(resource)+ if resourceType == "" {+ resourceType = "system"+ }++ source := monitoredSystemPrimarySource(resource)+ if source == "" {+ source = "unknown"+ }++ surfaces = append(surfaces, MonitoredSystemGroupingSurface{+ Name: name,+ Type: resourceType,+ Source: source,+ })+ }++ sort.Slice(surfaces, func(i, j int) bool {+ if surfaces[i].Name != surfaces[j].Name {+ return surfaces[i].Name < surfaces[j].Name+ }+ if surfaces[i].Type != surfaces[j].Type {+ return surfaces[i].Type < surfaces[j].Type+ }+ return surfaces[i].Source < surfaces[j].Source+ })++ if surfaces == nil {+ return []MonitoredSystemGroupingSurface{}+ }+ return surfaces+}++func monitoredSystemGroupingTypeLabel(value string) string {+ switch strings.TrimSpace(value) {+ case "docker-host":+ return "Docker host"+ case "host":+ return "host"+ case "kubernetes-cluster":+ return "Kubernetes cluster"+ case "pbs-server":+ return "PBS server"+ case "pmg-server":+ return "PMG server"+ case "proxmox-node":+ return "Proxmox node"+ case "truenas-system":+ return "TrueNAS system"+ }+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ return strings.ReplaceAll(trimmed, "-", " ")+ }+ return "system"+}++func monitoredSystemGroupingSourceLabel(value string) string {+ switch strings.TrimSpace(value) {+ case "":+ return "an unknown source"+ case "multiple":+ return "multiple sources"+ default:+ return strings.TrimSpace(value)+ }+}+func preferredMonitoredSystemResource(resources []*Resource) *Resource {var preferred *ResourcebestPriority := 1 << 30diff --git a/internal/unifiedresources/top_level_systems.go b/internal/unifiedresources/top_level_systems.goindex 88c840fbd1..fcdff1766a 100644--- a/internal/unifiedresources/top_level_systems.go+++ b/internal/unifiedresources/top_level_systems.go@@ -1,6 +1,7 @@package unifiedresourcesimport (+ "fmt""sort""strconv""strings"@@ -21,6 +22,7 @@ type topLevelSystemResolvedGroup struct {strongIDs map[string]struct{}priority intattachByHost bool+ explanation MonitoredSystemGroupingExplanation}type topLevelSystemNode struct {@@ -33,6 +35,19 @@ type topLevelSystemNode struct {attachByHost bool}+type topLevelSystemGroupingEvidence struct {+ kind string+ signal string+ value string+ fromType string+ toType string+}++type topLevelSystemFallbackTarget struct {+ root int+ evidence topLevelSystemGroupingEvidence+}+// ResolveTopLevelSystems builds the shared top-level system grouping used by// monitored-system counting and connected-infrastructure inventory surfaces.func ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver {@@ -62,6 +77,7 @@ func ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver {for i := range parent {parent[i] = i}+ groupEvidence := make(map[int][]topLevelSystemGroupingEvidence, len(nodes))find := func(id int) int {for parent[id] != id {@@ -71,20 +87,27 @@ func ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver {return id}- union := func(left, right int) {+ union := func(left, right int, evidence topLevelSystemGroupingEvidence) {leftRoot := find(left)rightRoot := find(right)if leftRoot == rightRoot {return}+ if existing := groupEvidence[leftRoot]; len(existing) > 0 {+ groupEvidence[rightRoot] = append(groupEvidence[rightRoot], existing...)+ delete(groupEvidence, leftRoot)+ }parent[leftRoot] = rightRoot+ if evidence.kind != "" {+ groupEvidence[rightRoot] = append(groupEvidence[rightRoot], evidence)+ }}strongIDOwners := make(map[string]int)for i := range nodes {- for strongID := range nodes[i].strongIDs {+ for _, strongID := range topLevelSystemOrderedStrongIDs(nodes[i].strongIDs) {if existing, ok := strongIDOwners[strongID]; ok {- union(i, existing)+ union(i, existing, topLevelSystemStrongIDEvidence(nodes[i].resource, nodes[existing].resource, strongID))continue}strongIDOwners[strongID] = i@@ -108,12 +131,12 @@ func ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver {if !ok || existingIndex == i {continue}- union(i, existingIndex)+ union(i, existingIndex, topLevelSystemIdentityMatchEvidence(nodes[i].resource, nodes[existingIndex].resource, match.Reason))}}for {- initialGroups := buildTopLevelSystemResolvedGroups(nodes, parent)+ initialGroups := buildTopLevelSystemResolvedGroups(nodes, parent, groupEvidence)hostOwners, ipOwners := buildTopLevelSystemFallbackOwners(initialGroups)attached := false@@ -121,16 +144,16 @@ func ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver {if !group.attachByHost {continue}- targetRoot, ok := uniqueBetterTopLevelSystemTarget(groupRoot, group, hostOwners, ipOwners, initialGroups)+ target, ok := uniqueBetterTopLevelSystemTarget(groupRoot, group, hostOwners, ipOwners, initialGroups)if !ok {continue}- union(groupRoot, targetRoot)+ union(groupRoot, target.root, target.evidence)attached = true}if !attached {- finalGroups := buildTopLevelSystemResolvedGroups(nodes, parent)+ finalGroups := buildTopLevelSystemResolvedGroups(nodes, parent, groupEvidence)orderedGroups := make([]topLevelSystemResolvedGroup, 0, len(finalGroups))for _, group := range finalGroups {orderedGroups = append(orderedGroups, group)@@ -183,8 +206,9 @@ func (r TopLevelSystemResolver) records() []MonitoredSystemRecord {records := make([]MonitoredSystemRecord, 0, len(r.groups))for _, group := range r.groups {records = append(records, monitoredSystemRecord(monitoredSystemGroup{- keys: cloneStringSet(group.strongIDs),- resources: group.resources,+ keys: cloneStringSet(group.strongIDs),+ resources: group.resources,+ explanation: group.explanation,}))}return records@@ -222,6 +246,7 @@ func (r TopLevelSystemResolver) HasMatchingCandidate(candidate MonitoredSystemCafunc buildTopLevelSystemResolvedGroups(nodes []topLevelSystemNode,parent []int,+ groupEvidence map[int][]topLevelSystemGroupingEvidence,) map[int]topLevelSystemResolvedGroup {find := func(id int) int {for parent[id] != id {@@ -265,6 +290,7 @@ func buildTopLevelSystemResolvedGroups(groups := make(map[int]topLevelSystemResolvedGroup, len(groupIndex))for root, group := range groupIndex {group.id = topLevelSystemGroupID(*group)+ group.explanation = topLevelSystemGroupingExplanation(*group, groupEvidence[root])groups[root] = *group}@@ -429,39 +455,58 @@ func uniqueBetterTopLevelSystemTarget(hostOwners map[string]map[int]struct{},ipOwners map[string]map[int]struct{},groups map[int]topLevelSystemResolvedGroup,-) (int, bool) {- targets := make(map[int]struct{})+) (topLevelSystemFallbackTarget, bool) {+ targets := make(map[int]topLevelSystemGroupingEvidence)- for host := range group.exactHosts {- for targetRoot := range hostOwners[host] {+ for _, host := range topLevelSystemSortedSet(group.exactHosts) {+ for _, targetRoot := range topLevelSystemSortedRoots(hostOwners[host]) {if targetRoot == groupRoot {continue}if groups[targetRoot].priority >= group.priority {continue}- targets[targetRoot] = struct{}{}+ if _, ok := targets[targetRoot]; !ok {+ targets[targetRoot] = topLevelSystemAttachmentEvidence(+ group,+ groups[targetRoot],+ "exact-host-attachment",+ "exact-host",+ host,+ )+ }}}- for ip := range group.exactIPs {- for targetRoot := range ipOwners[ip] {+ for _, ip := range topLevelSystemSortedSet(group.exactIPs) {+ for _, targetRoot := range topLevelSystemSortedRoots(ipOwners[ip]) {if targetRoot == groupRoot {continue}if groups[targetRoot].priority >= group.priority {continue}- targets[targetRoot] = struct{}{}+ if _, ok := targets[targetRoot]; !ok {+ targets[targetRoot] = topLevelSystemAttachmentEvidence(+ group,+ groups[targetRoot],+ "exact-ip-attachment",+ "exact-ip",+ ip,+ )+ }}}if len(targets) != 1 {- return 0, false+ return topLevelSystemFallbackTarget{}, false}- for targetRoot := range targets {- return targetRoot, true+ for targetRoot, evidence := range targets {+ return topLevelSystemFallbackTarget{+ root: targetRoot,+ evidence: evidence,+ }, true}- return 0, false+ return topLevelSystemFallbackTarget{}, false}func candidateExactTargetGroups(@@ -555,15 +600,7 @@ func monitoredSystemResourceAllowsHostAttachment(resource *Resource) bool {}func topLevelSystemGroupID(group topLevelSystemResolvedGroup) string {- orderedStrongIDs := topLevelSystemSortedSet(group.strongIDs)- sort.SliceStable(orderedStrongIDs, func(i, j int) bool {- leftPrefix, leftValue := topLevelSystemSplitStrongID(orderedStrongIDs[i])- rightPrefix, rightValue := topLevelSystemSplitStrongID(orderedStrongIDs[j])- if topLevelSystemStrongIDPriority(leftPrefix) != topLevelSystemStrongIDPriority(rightPrefix) {- return topLevelSystemStrongIDPriority(leftPrefix) < topLevelSystemStrongIDPriority(rightPrefix)- }- return leftValue < rightValue- })+ orderedStrongIDs := topLevelSystemOrderedStrongIDs(group.strongIDs)if len(orderedStrongIDs) > 0 {return orderedStrongIDs[0]}@@ -586,6 +623,19 @@ func topLevelSystemGroupID(group topLevelSystemResolvedGroup) string {return "resource:unknown"}+func topLevelSystemOrderedStrongIDs(values map[string]struct{}) []string {+ ordered := topLevelSystemSortedSet(values)+ sort.SliceStable(ordered, func(i, j int) bool {+ leftPrefix, leftValue := topLevelSystemSplitStrongID(ordered[i])+ rightPrefix, rightValue := topLevelSystemSplitStrongID(ordered[j])+ if topLevelSystemStrongIDPriority(leftPrefix) != topLevelSystemStrongIDPriority(rightPrefix) {+ return topLevelSystemStrongIDPriority(leftPrefix) < topLevelSystemStrongIDPriority(rightPrefix)+ }+ return leftValue < rightValue+ })+ return ordered+}+func topLevelSystemStrongIDPriority(prefix string) int {switch prefix {case "machine":@@ -619,6 +669,293 @@ func topLevelSystemSplitStrongID(value string) (string, string) {return parts[0], parts[1]}+func topLevelSystemGroupingExplanation(+ group topLevelSystemResolvedGroup,+ evidence []topLevelSystemGroupingEvidence,+) MonitoredSystemGroupingExplanation {+ reasons := topLevelSystemGroupingReasons(evidence)+ if len(reasons) == 0 {+ return monitoredSystemStandaloneExplanation(group.resources)+ }++ return normalizeMonitoredSystemGroupingExplanation(MonitoredSystemGroupingExplanation{+ Summary: topLevelSystemGroupingSummary(group.resources, reasons),+ Reasons: reasons,+ Surfaces: monitoredSystemGroupingSurfaces(group.resources),+ })+}++func topLevelSystemGroupingReasons(+ evidence []topLevelSystemGroupingEvidence,+) []MonitoredSystemGroupingReason {+ reasons := make([]MonitoredSystemGroupingReason, 0, len(evidence))+ seen := make(map[string]struct{}, len(evidence))+ for _, item := range evidence {+ reason := topLevelSystemReasonFromEvidence(item)+ if reason.Summary == "" {+ continue+ }+ key := reason.Kind + "\x00" + reason.Signal + "\x00" + reason.Summary+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ reasons = append(reasons, reason)+ }+ if reasons == nil {+ return []MonitoredSystemGroupingReason{}+ }+ return reasons+}++func topLevelSystemReasonFromEvidence(+ evidence topLevelSystemGroupingEvidence,+) MonitoredSystemGroupingReason {+ switch evidence.kind {+ case "shared-identity":+ return MonitoredSystemGroupingReason{+ Kind: evidence.kind,+ Signal: evidence.signal,+ Summary: topLevelSystemMergedViewSummary(evidence.fromType, evidence.toType, topLevelSystemStrongIDBasis(evidence.signal)),+ }+ case "identity-match":+ return MonitoredSystemGroupingReason{+ Kind: evidence.kind,+ Signal: evidence.signal,+ Summary: topLevelSystemMergedViewSummary(evidence.fromType, evidence.toType, topLevelSystemIdentityMatchBasis(evidence.signal)),+ }+ case "exact-host-attachment":+ return MonitoredSystemGroupingReason{+ Kind: evidence.kind,+ Signal: evidence.signal,+ Summary: topLevelSystemAttachmentSummary(evidence.fromType, evidence.toType, "a unique exact hostname match", evidence.value),+ }+ case "exact-ip-attachment":+ return MonitoredSystemGroupingReason{+ Kind: evidence.kind,+ Signal: evidence.signal,+ Summary: topLevelSystemAttachmentSummary(evidence.fromType, evidence.toType, "a unique exact IP match", evidence.value),+ }+ default:+ return MonitoredSystemGroupingReason{}+ }+}++func topLevelSystemGroupingSummary(+ resources []*Resource,+ reasons []MonitoredSystemGroupingReason,+) string {+ bases := make([]string, 0, len(reasons))+ seen := make(map[string]struct{}, len(reasons))+ for _, reason := range reasons {+ basis := topLevelSystemReasonBasis(reason)+ if basis == "" {+ continue+ }+ if _, ok := seen[basis]; ok {+ continue+ }+ seen[basis] = struct{}{}+ bases = append(bases, basis)+ }+ if len(bases) > 3 {+ bases = append(bases[:2], "other canonical identity signals")+ }+ return fmt.Sprintf(+ "Counts as one monitored system because Pulse merged %d top-level views into one canonical system using %s.",+ topLevelSystemMaxInt(2, len(monitoredSystemGroupingSurfaces(resources))),+ topLevelSystemHumanList(bases),+ )+}++func topLevelSystemReasonBasis(reason MonitoredSystemGroupingReason) string {+ switch reason.Kind {+ case "shared-identity":+ return topLevelSystemStrongIDBasis(reason.Signal)+ case "identity-match":+ return topLevelSystemIdentityMatchBasis(reason.Signal)+ case "exact-host-attachment":+ return "a unique exact hostname attachment"+ case "exact-ip-attachment":+ return "a unique exact IP attachment"+ default:+ return ""+ }+}++func topLevelSystemStrongIDEvidence(+ left *Resource,+ right *Resource,+ strongID string,+) topLevelSystemGroupingEvidence {+ prefix, _ := topLevelSystemSplitStrongID(strongID)+ return topLevelSystemGroupingEvidence{+ kind: "shared-identity",+ signal: topLevelSystemStrongIDSignal(prefix),+ value: strongID,+ fromType: monitoredSystemType(left),+ toType: monitoredSystemType(right),+ }+}++func topLevelSystemIdentityMatchEvidence(+ left *Resource,+ right *Resource,+ reason string,+) topLevelSystemGroupingEvidence {+ return topLevelSystemGroupingEvidence{+ kind: "identity-match",+ signal: strings.TrimSpace(reason),+ value: strings.TrimSpace(reason),+ fromType: monitoredSystemType(left),+ toType: monitoredSystemType(right),+ }+}++func topLevelSystemAttachmentEvidence(+ fromGroup topLevelSystemResolvedGroup,+ toGroup topLevelSystemResolvedGroup,+ kind string,+ signal string,+ value string,+) topLevelSystemGroupingEvidence {+ return topLevelSystemGroupingEvidence{+ kind: kind,+ signal: signal,+ value: strings.TrimSpace(value),+ fromType: topLevelSystemPreferredGroupType(fromGroup),+ toType: topLevelSystemPreferredGroupType(toGroup),+ }+}++func topLevelSystemPreferredGroupType(group topLevelSystemResolvedGroup) string {+ return monitoredSystemType(preferredMonitoredSystemResource(group.resources))+}++func topLevelSystemStrongIDSignal(prefix string) string {+ switch prefix {+ case "machine":+ return "machine-id"+ case "agent":+ return "agent-id"+ case "primary":+ return "canonical-primary-id"+ case "proxmox":+ return "proxmox-source-id"+ case "docker":+ return "docker-host-id"+ case "pbs":+ return "pbs-instance-id"+ case "pmg":+ return "pmg-instance-id"+ case "k8s":+ return "kubernetes-cluster-id"+ case "resource":+ return "resource-id"+ default:+ return strings.TrimSpace(prefix)+ }+}++func topLevelSystemStrongIDBasis(signal string) string {+ switch signal {+ case "machine-id":+ return "shared machine identity"+ case "agent-id":+ return "shared agent identity"+ case "canonical-primary-id":+ return "shared canonical primary identity"+ case "proxmox-source-id":+ return "shared Proxmox source identity"+ case "docker-host-id":+ return "shared Docker host identity"+ case "pbs-instance-id":+ return "shared PBS instance identity"+ case "pmg-instance-id":+ return "shared PMG instance identity"+ case "kubernetes-cluster-id":+ return "shared Kubernetes cluster identity"+ case "resource-id":+ return "shared canonical resource identity"+ default:+ return "shared canonical identity"+ }+}++func topLevelSystemIdentityMatchBasis(signal string) string {+ switch signal {+ case "dmi_uuid":+ return "high-confidence DMI identity"+ case "hostname+mac":+ return "shared hostname and MAC identity"+ default:+ return "high-confidence canonical identity"+ }+}++func topLevelSystemMergedViewSummary(leftType, rightType, basis string) string {+ leftLabel := monitoredSystemGroupingTypeLabel(leftType)+ rightLabel := monitoredSystemGroupingTypeLabel(rightType)+ if leftLabel == "" || rightLabel == "" || leftLabel == rightLabel {+ return "Merged top-level views using " + basis + "."+ }+ labels := []string{leftLabel, rightLabel}+ sort.Slice(labels, func(i, j int) bool {+ return strings.ToLower(labels[i]) < strings.ToLower(labels[j])+ })+ return fmt.Sprintf("Merged %s and %s views using %s.", labels[0], labels[1], basis)+}++func topLevelSystemAttachmentSummary(fromType, toType, basis, value string) string {+ fromLabel := monitoredSystemGroupingTypeLabel(fromType)+ if fromLabel == "" {+ fromLabel = "top-level view"+ }+ toLabel := monitoredSystemGroupingTypeLabel(toType)+ if toLabel == "" {+ toLabel = "canonical system"+ }+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ return fmt.Sprintf("Attached %s to %s using %s on %s.", fromLabel, toLabel, basis, trimmed)+ }+ return fmt.Sprintf("Attached %s to %s using %s.", fromLabel, toLabel, basis)+}++func topLevelSystemHumanList(values []string) string {+ filtered := make([]string, 0, len(values))+ for _, value := range values {+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ filtered = append(filtered, trimmed)+ }+ }+ switch len(filtered) {+ case 0:+ return "canonical identity signals"+ case 1:+ return filtered[0]+ case 2:+ return filtered[0] + " and " + filtered[1]+ default:+ return strings.Join(filtered[:len(filtered)-1], ", ") + ", and " + filtered[len(filtered)-1]+ }+}++func topLevelSystemSortedRoots(values map[int]struct{}) []int {+ out := make([]int, 0, len(values))+ for value := range values {+ out = append(out, value)+ }+ sort.Ints(out)+ return out+}++func topLevelSystemMaxInt(left, right int) int {+ if left > right {+ return left+ }+ return right+}+func topLevelSystemSortedSet(values map[string]struct{}) []string {out := make([]string, 0, len(values))for value := range values {diff --git a/internal/unifiedresources/top_level_systems_test.go b/internal/unifiedresources/top_level_systems_test.goindex 353556a6d0..39d733f6d1 100644--- a/internal/unifiedresources/top_level_systems_test.go+++ b/internal/unifiedresources/top_level_systems_test.go@@ -129,6 +129,56 @@ func TestResolveTopLevelSystemsMixedEnvironmentCharacterization(t *testing.T) {)}+func TestResolveTopLevelSystemsExplainsStandaloneSystem(t *testing.T) {+ resolver := ResolveTopLevelSystems([]Resource{+ topLevelTestAgent("agent-host", "tower.local", "machine-1", "agent-1"),+ })++ records := resolver.records()+ if len(records) != 1 {+ t.Fatalf("expected one monitored-system record, got %d", len(records))+ }++ explanation := records[0].Explanation+ if explanation.Summary == "" {+ t.Fatal("expected standalone monitored system to carry an explanation summary")+ }+ if len(explanation.Reasons) != 1 || explanation.Reasons[0].Kind != "standalone" {+ t.Fatalf("expected standalone explanation reason, got %+v", explanation.Reasons)+ }+ if len(explanation.Surfaces) != 1 || explanation.Surfaces[0].Source != "agent" {+ t.Fatalf("expected one agent surface, got %+v", explanation.Surfaces)+ }+}++func TestResolveTopLevelSystemsExplainsStrongIdentityAndHostnameAttachment(t *testing.T) {+ resolver := ResolveTopLevelSystems([]Resource{+ topLevelTestAgent("agent-host", "tower.local", "machine-1", "agent-1"),+ topLevelTestDockerHost("docker-host", "tower.local", "docker-runtime-1", "agent-1"),+ topLevelTestPBS("pbs-system", "tower.local", "pbs-1"),+ })++ records := resolver.records()+ if len(records) != 1 {+ t.Fatalf("expected one monitored-system record, got %d", len(records))+ }++ reasons := records[0].Explanation.Reasons+ if len(reasons) < 2 {+ t.Fatalf("expected multiple grouping reasons, got %+v", reasons)+ }++ if !hasGroupingReason(reasons, "shared-identity", "agent-id") {+ t.Fatalf("expected shared agent identity reason, got %+v", reasons)+ }+ if !hasGroupingReason(reasons, "exact-host-attachment", "exact-host") {+ t.Fatalf("expected exact hostname attachment reason, got %+v", reasons)+ }+ if len(records[0].Explanation.Surfaces) != 3 {+ t.Fatalf("expected three grouped surfaces, got %+v", records[0].Explanation.Surfaces)+ }+}+func TestHasMatchingMonitoredSystemDoesNotMergeKubernetesCandidateBySharedAgentID(t *testing.T) {registry := NewRegistry(nil)registry.IngestRecords(SourceAgent, []IngestRecord{@@ -172,6 +222,19 @@ func assertTopLevelSystemGroupPairs(t *testing.T, resolver TopLevelSystemResolve}}+func hasGroupingReason(+ reasons []MonitoredSystemGroupingReason,+ kind string,+ signal string,+) bool {+ for _, reason := range reasons {+ if reason.Kind == kind && reason.Signal == signal {+ return true+ }+ }+ return false+}+func topLevelTestAgent(id, hostname, machineID, agentID string) Resource {resource := topLevelTestAgentWithoutMachineID(id, hostname, agentID)resource.Identity.MachineID = machineID