Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Expose grouped timeline kind counts

rcourtman72fcfd01be0e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index ab48f8d5e4..f47800a766 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -139,6 +139,10 @@ That same boundary now also assumes canonical resource payloads preserve
shared facet totals through `facetCounts`, so the resource list and detail
surfaces can keep row summaries aligned without re-inferring totals from
consumer-local slices.
+That same shared facet bundle now also carries grouped `recentChangeKinds`
+counts by canonical change kind, so the lifecycle-adjacent detail surfaces can
+report restart, anomaly, relationship, and capability distribution without
+rebuilding timeline math in the browser.
That same shared `internal/api/` boundary now also assumes tenant AI services
stay on canonical Patrol runtime wiring: adjacent fleet and install surfaces
must not revive tenant snapshot-provider bridges through shared AI handler
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 96077c5b14..dbd4fb36c8 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -127,6 +127,10 @@ Those history reads now also accept governed `kind`, `sourceType`, and
`sourceAdapter` query filters, and the backend store owns the corresponding
filtered counts, so the timeline contract can narrow by change class and
adapter provenance without inventing a frontend-only slice of the graph.
+The same facet bundle contract now also returns grouped `recentChangeKinds`
+counts by canonical `ChangeKind`, so the shared drawer and summary chips can
+show the distribution of restarts, anomalies, state transitions, and other
+timeline classes without guessing from the loaded slice.
Relationship-change timeline entries also preserve the affected graph endpoints
in `relatedResources`, so the canonical history keeps enough context for the
detail drawer and audit views to explain which neighboring resources moved with
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 4b7d0a77cb..42134b28b8 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -115,6 +115,11 @@ as adjacent governed API ownership rather than timeline-store ownership. The
storage and recovery lanes still own their own persistence and query
contracts, while the control-plane execution trail remains governed by the
unified-resource and audit contracts.
+The shared unified-resource facet bundle that storage-adjacent detail views
+consume now also carries grouped `recentChangeKinds` counts by canonical change
+kind, so storage and recovery surfaces can show the distribution of restarts,
+anomalies, relationships, and capability changes without re-deriving their own
+timeline breakdowns.
Those unified audit list endpoints also clamp oversized `limit` requests to
the governed maximum, so adjacent recovery and storage workflows do not turn
bounded history reads into unbounded collection scans.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 06fc0db73b..79d26fbefd 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -116,6 +116,10 @@ The frontend now also consumes those facet reads through
`frontend-modern/src/api/resources.ts` and the dedicated resource detail
drawer, which keeps the presentation surface aligned with the governed API
contract instead of rebuilding the graph and timeline inline.
+The same facet bundle now also returns grouped recent-change counts by
+canonical change kind, so the detail drawer can surface the distribution of
+state transitions, restarts, config updates, anomalies, relationships, and
+capabilities without recomputing timeline history in the browser.
That same shared store now also persists append-only action lifecycle, action
audit, and export audit records, giving the control-plane verbs a durable home
diff --git a/frontend-modern/src/api/__tests__/resources.test.ts b/frontend-modern/src/api/__tests__/resources.test.ts
index 8d2fc7a478..118c7905a6 100644
--- a/frontend-modern/src/api/__tests__/resources.test.ts
+++ b/frontend-modern/src/api/__tests__/resources.test.ts
@@ -40,6 +40,10 @@ describe('ResourceAPI', () => {
capabilities: 1,
relationships: 1,
recentChanges: 3,
+ recentChangeKinds: {
+ metric_anomaly: 2,
+ restart: 1,
+ },
},
} as any);
@@ -66,12 +70,20 @@ describe('ResourceAPI', () => {
capabilities: 1,
relationships: 1,
recentChanges: 3,
+ recentChangeKinds: {
+ metric_anomaly: 2,
+ restart: 1,
+ },
},
});
expect(result.counts).toStrictEqual({
capabilities: 1,
relationships: 1,
recentChanges: 3,
+ recentChangeKinds: {
+ metric_anomaly: 2,
+ restart: 1,
+ },
});
});
diff --git a/frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx b/frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx
index 14bf4687b2..99d2740117 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx
@@ -2,6 +2,7 @@ import { For, Show, createMemo, type Component } from 'solid-js';
import type {
ResourceCapability,
ResourceChange,
+ ResourceChangeKind,
ResourceFacetCounts,
ResourceRelationship,
} from '@/types/resource';
@@ -27,6 +28,51 @@ const badgeBase =
const countLabel = (count: number, singular: string, plural = `${singular}s`) =>
`${count} ${count === 1 ? singular : plural}`;
+const recentChangeKindOrder: ResourceChangeKind[] = [
+ 'state_transition',
+ 'restart',
+ 'config_update',
+ 'metric_anomaly',
+ 'relationship_change',
+ 'capability_change',
+];
+
+const recentChangeKindLabels: Record<
+ ResourceChangeKind,
+ { label: string; plural: string; className: string }
+> = {
+ state_transition: {
+ label: 'State transition',
+ plural: 'State transitions',
+ className: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300',
+ },
+ restart: {
+ label: 'Restart',
+ plural: 'Restarts',
+ className: 'bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300',
+ },
+ config_update: {
+ label: 'Config update',
+ plural: 'Config updates',
+ className: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300',
+ },
+ metric_anomaly: {
+ label: 'Anomaly',
+ plural: 'Anomalies',
+ className: 'bg-rose-100 text-rose-700 dark:bg-rose-900 dark:text-rose-300',
+ },
+ relationship_change: {
+ label: 'Relationship change',
+ plural: 'Relationship changes',
+ className: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300',
+ },
+ capability_change: {
+ label: 'Capability change',
+ plural: 'Capability changes',
+ className: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300',
+ },
+};
+
const buildFacetBadges = (
capabilities?: readonly ResourceCapability[] | null,
relationships?: readonly ResourceRelationship[] | null,
@@ -62,6 +108,20 @@ const buildFacetBadges = (
});
}
+ const kindCounts = counts?.recentChangeKinds;
+ if (kindCounts) {
+ for (const kind of recentChangeKindOrder) {
+ const count = kindCounts[kind];
+ if (!count || count <= 0) continue;
+ const kindLabel = recentChangeKindLabels[kind];
+ badges.push({
+ label: `${kindLabel.label} ${count}`,
+ title: countLabel(count, kindLabel.label.toLowerCase(), kindLabel.plural.toLowerCase()),
+ className: `${badgeBase} ${kindLabel.className}`,
+ });
+ }
+ }
+
return badges;
};
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
index 966bc11cad..84efc8bb88 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
@@ -106,6 +106,10 @@ describe('ResourceDetailDrawer history tab', () => {
capabilities: 1,
relationships: 1,
recentChanges: 3,
+ recentChangeKinds: {
+ restart: 2,
+ metric_anomaly: 1,
+ },
},
});
@@ -124,6 +128,8 @@ describe('ResourceDetailDrawer history tab', () => {
expect(await screen.findByText('Capabilities 1')).toBeInTheDocument();
expect(screen.getByText('Relationships 1')).toBeInTheDocument();
expect(screen.getByText('Timeline 3')).toBeInTheDocument();
+ expect(screen.getByText('Restart 2')).toBeInTheDocument();
+ expect(screen.getByText('Anomaly 1')).toBeInTheDocument();
});
it('renders resource capability, relationship, and timeline facets', async () => {
@@ -187,6 +193,10 @@ describe('ResourceDetailDrawer history tab', () => {
capabilities: 1,
relationships: 1,
recentChanges: 3,
+ recentChangeKinds: {
+ restart: 2,
+ metric_anomaly: 1,
+ },
},
});
@@ -286,6 +296,10 @@ describe('ResourceDetailDrawer history tab', () => {
capabilities: 1,
relationships: 1,
recentChanges: 2,
+ recentChangeKinds: {
+ restart: 1,
+ metric_anomaly: 1,
+ },
},
};
const filteredFacetBundle = {
@@ -418,6 +432,10 @@ describe('ResourceDetailDrawer history tab', () => {
capabilities: 1,
relationships: 1,
recentChanges: 2,
+ recentChangeKinds: {
+ restart: 1,
+ metric_anomaly: 1,
+ },
},
})
.mockResolvedValueOnce({
@@ -461,6 +479,9 @@ describe('ResourceDetailDrawer history tab', () => {
capabilities: 1,
relationships: 1,
recentChanges: 1,
+ recentChangeKinds: {
+ metric_anomaly: 1,
+ },
},
});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx
index 4b73b14e2b..082f9722cf 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx
@@ -152,6 +152,10 @@ describe('UnifiedResourceTable performance contract', () => {
capabilities: 1,
relationships: 1,
recentChanges: 3,
+ recentChangeKinds: {
+ restart: 2,
+ metric_anomaly: 1,
+ },
}}
recentChanges={[]}
/>
@@ -160,6 +164,8 @@ describe('UnifiedResourceTable performance contract', () => {
expect(getByText('Capabilities 1')).toBeInTheDocument();
expect(getByText('Relationships 1')).toBeInTheDocument();
expect(getByText('Timeline 3')).toBeInTheDocument();
+ expect(getByText('Restart 2')).toBeInTheDocument();
+ expect(getByText('Anomaly 1')).toBeInTheDocument();
});
it('renders facet summary badges without changing the Profile S row budget', async () => {
@@ -190,6 +196,10 @@ describe('UnifiedResourceTable performance contract', () => {
capabilities: 1,
relationships: 1,
recentChanges: 3,
+ recentChangeKinds: {
+ restart: 2,
+ metric_anomaly: 1,
+ },
},
recentChanges: [],
}
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index 73e404db74..2b13eef56b 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -124,12 +124,7 @@ export type ResourceSensitivity = 'public' | 'internal' | 'sensitive' | 'restric
export type ResourceRoutingScope = 'cloud-summary' | 'local-first' | 'local-only';
-export type ResourceRedactionHint =
- | 'hostname'
- | 'ip-address'
- | 'platform-id'
- | 'alias'
- | 'path';
+export type ResourceRedactionHint = 'hostname' | 'ip-address' | 'platform-id' | 'alias' | 'path';
export interface ResourceRoutingPolicy {
scope: ResourceRoutingScope;
@@ -196,6 +191,7 @@ export interface ResourceFacetCounts {
capabilities: number;
relationships: number;
recentChanges: number;
+ recentChangeKinds?: Partial<Record<ResourceChangeKind, number>>;
}
export interface ResourceRelationship {
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 6943020c1d..20fd35572c 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -3932,9 +3932,10 @@ func TestContract_ResourceFacetsJSONSnapshot(t *testing.T) {
Relationships []unifiedresources.ResourceRelationship `json:"relationships"`
RecentChanges []unifiedresources.ResourceChange `json:"recentChanges"`
Counts struct {
- Capabilities int `json:"capabilities"`
- Relationships int `json:"relationships"`
- RecentChanges int `json:"recentChanges"`
+ Capabilities int `json:"capabilities"`
+ Relationships int `json:"relationships"`
+ RecentChanges int `json:"recentChanges"`
+ RecentChangeKinds map[unifiedresources.ChangeKind]int `json:"recentChangeKinds"`
} `json:"counts"`
}{
ResourceID: "vm:42",
@@ -3981,13 +3982,15 @@ func TestContract_ResourceFacetsJSONSnapshot(t *testing.T) {
},
},
Counts: struct {
- Capabilities int `json:"capabilities"`
- Relationships int `json:"relationships"`
- RecentChanges int `json:"recentChanges"`
+ Capabilities int `json:"capabilities"`
+ Relationships int `json:"relationships"`
+ RecentChanges int `json:"recentChanges"`
+ RecentChangeKinds map[unifiedresources.ChangeKind]int `json:"recentChangeKinds"`
}{
- Capabilities: 1,
- Relationships: 1,
- RecentChanges: 3,
+ Capabilities: 1,
+ Relationships: 1,
+ RecentChanges: 3,
+ RecentChangeKinds: map[unifiedresources.ChangeKind]int{unifiedresources.ChangeRestart: 1, unifiedresources.ChangeAnomaly: 2},
},
}
@@ -4037,7 +4040,11 @@ func TestContract_ResourceFacetsJSONSnapshot(t *testing.T) {
"counts":{
"capabilities":1,
"relationships":1,
- "recentChanges":3
+ "recentChanges":3,
+ "recentChangeKinds":{
+ "metric_anomaly":2,
+ "restart":1
+ }
}
}`
diff --git a/internal/api/resources.go b/internal/api/resources.go
index a54ca18007..db0b7b7a44 100644
--- a/internal/api/resources.go
+++ b/internal/api/resources.go
@@ -495,6 +495,11 @@ func (h *ResourceHandlers) HandleGetResourceFacets(w http.ResponseWriter, r *htt
http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
return
}
+ changeKindCounts, err := store.CountRecentChangesByKindFiltered(resourceID, since, filters)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
capabilities := resource.Capabilities
if capabilities == nil {
@@ -512,9 +517,10 @@ func (h *ResourceHandlers) HandleGetResourceFacets(w http.ResponseWriter, r *htt
Relationships: relationships,
RecentChanges: recentChanges,
Counts: resourceFacetCountsResponse{
- Capabilities: resource.FacetCounts.Capabilities,
- Relationships: resource.FacetCounts.Relationships,
- RecentChanges: changeCount,
+ Capabilities: resource.FacetCounts.Capabilities,
+ Relationships: resource.FacetCounts.Relationships,
+ RecentChanges: changeCount,
+ RecentChangeKinds: changeKindCounts,
},
})
}
diff --git a/internal/api/resources_test.go b/internal/api/resources_test.go
index 47b177fa0e..3950366f91 100644
--- a/internal/api/resources_test.go
+++ b/internal/api/resources_test.go
@@ -985,9 +985,10 @@ func TestResourceGetFacetsAndTimeline(t *testing.T) {
Relationships []unified.ResourceRelationship `json:"relationships"`
RecentChanges []unified.ResourceChange `json:"recentChanges"`
Counts struct {
- Capabilities int `json:"capabilities"`
- Relationships int `json:"relationships"`
- RecentChanges int `json:"recentChanges"`
+ Capabilities int `json:"capabilities"`
+ Relationships int `json:"relationships"`
+ RecentChanges int `json:"recentChanges"`
+ RecentChangeKinds map[unified.ChangeKind]int `json:"recentChangeKinds"`
} `json:"counts"`
}
if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {
@@ -999,6 +1000,9 @@ func TestResourceGetFacetsAndTimeline(t *testing.T) {
if payload.Counts.Capabilities != 1 || payload.Counts.Relationships != 1 {
t.Fatalf("unexpected facet counts: %#v", payload.Counts)
}
+ if got := payload.Counts.RecentChangeKinds; len(got) != 2 || got[unified.ChangeRestart] != 1 || got[unified.ChangeAnomaly] != 2 {
+ t.Fatalf("unexpected recent change kind counts: %#v", got)
+ }
if got := payload.Relationships[0].Metadata["cluster"]; got != "pve-prod" {
t.Fatalf("unexpected relationship metadata: %#v", payload.Relationships[0].Metadata)
}
@@ -1134,9 +1138,10 @@ func TestResourceGetFacetsAndTimeline(t *testing.T) {
RecentChanges []unified.ResourceChange `json:"recentChanges"`
Relationships []unified.ResourceRelationship `json:"relationships"`
Counts struct {
- Capabilities int `json:"capabilities"`
- Relationships int `json:"relationships"`
- RecentChanges int `json:"recentChanges"`
+ Capabilities int `json:"capabilities"`
+ Relationships int `json:"relationships"`
+ RecentChanges int `json:"recentChanges"`
+ RecentChangeKinds map[unified.ChangeKind]int `json:"recentChangeKinds"`
} `json:"counts"`
}
if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {
@@ -1145,6 +1150,9 @@ func TestResourceGetFacetsAndTimeline(t *testing.T) {
if payload.ResourceID != "vm:42" || payload.Counts.RecentChanges != 1 || len(payload.RecentChanges) != 1 {
t.Fatalf("unexpected filtered facets payload: %#v", payload)
}
+ if got := payload.Counts.RecentChangeKinds; len(got) != 1 || got[unified.ChangeRestart] != 1 {
+ t.Fatalf("unexpected filtered facet kind counts: %#v", got)
+ }
if payload.RecentChanges[0].ID != "chg-42" {
t.Fatalf("unexpected filtered facets change: %#v", payload.RecentChanges[0])
}
@@ -1162,9 +1170,10 @@ func TestResourceGetFacetsAndTimeline(t *testing.T) {
RecentChanges []unified.ResourceChange `json:"recentChanges"`
Relationships []unified.ResourceRelationship `json:"relationships"`
Counts struct {
- Capabilities int `json:"capabilities"`
- Relationships int `json:"relationships"`
- RecentChanges int `json:"recentChanges"`
+ Capabilities int `json:"capabilities"`
+ Relationships int `json:"relationships"`
+ RecentChanges int `json:"recentChanges"`
+ RecentChangeKinds map[unified.ChangeKind]int `json:"recentChangeKinds"`
} `json:"counts"`
}
if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {
@@ -1173,6 +1182,9 @@ func TestResourceGetFacetsAndTimeline(t *testing.T) {
if payload.ResourceID != "vm:42" || payload.Counts.RecentChanges != 1 || len(payload.RecentChanges) != 1 {
t.Fatalf("unexpected filtered facets adapter payload: %#v", payload)
}
+ if got := payload.Counts.RecentChangeKinds; len(got) != 1 || got[unified.ChangeAnomaly] != 1 {
+ t.Fatalf("unexpected adapter-filtered facet kind counts: %#v", got)
+ }
if payload.RecentChanges[0].ID != "chg-42-extra-2" {
t.Fatalf("unexpected adapter-filtered facets change: %#v", payload.RecentChanges[0])
}
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index d14abac34c..fce49ccd69 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -248,6 +248,7 @@ func TestResourceAPIExposesDedicatedFacetReads(t *testing.T) {
"parseResourceChangeFilters(r.URL.Query())",
"GetRecentChangesFiltered(resourceID, since, limit, filters)",
"CountRecentChangesFiltered(resourceID, since, filters)",
+ "CountRecentChangesByKindFiltered(resourceID, since, filters)",
"sourceAdapter",
"invalid sourceAdapter value",
"strings.HasSuffix(r.URL.Path, \"/facets\")",
@@ -324,6 +325,9 @@ func TestResourceFacetCountsAreCanonicalResourceFields(t *testing.T) {
if !strings.Contains(typesSource, "json:\"facetCounts,omitempty\"") {
t.Fatalf("internal/unifiedresources/types.go must keep the facetCounts JSON contract")
}
+ if !strings.Contains(typesSource, "RecentChangeKinds map[ChangeKind]int") {
+ t.Fatalf("internal/unifiedresources/types.go must expose grouped timeline counts on the canonical facet model")
+ }
cloneData, err := os.ReadFile(filepath.Join("clone.go"))
if err != nil {
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index db3f41576e..e5b6f85f1d 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -29,6 +29,8 @@ type ResourceStore interface {
GetRecentChangesFiltered(canonicalID string, since time.Time, limit int, filters ResourceChangeFilters) ([]ResourceChange, error)
CountRecentChanges(canonicalID string, since time.Time) (int, error)
CountRecentChangesFiltered(canonicalID string, since time.Time, filters ResourceChangeFilters) (int, error)
+ CountRecentChangesByKind(canonicalID string, since time.Time) (map[ChangeKind]int, error)
+ CountRecentChangesByKindFiltered(canonicalID string, since time.Time, filters ResourceChangeFilters) (map[ChangeKind]int, error)
RecordActionAudit(record ActionAuditRecord) error
GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error)
RecordActionLifecycleEvent(event ActionLifecycleEvent) error
@@ -777,40 +779,7 @@ func (s *SQLiteResourceStore) CountRecentChanges(canonicalID string, since time.
}
func (s *SQLiteResourceStore) CountRecentChangesFiltered(canonicalID string, since time.Time, filters ResourceChangeFilters) (int, error) {
- query := `SELECT COUNT(*) FROM resource_changes`
- args := []any{}
- conditions := []string{"observed_at >= ?"}
- args = append(args, since)
- canonicalID = CanonicalResourceID(canonicalID)
- if canonicalID != "" {
- conditions = append(conditions, "canonical_id = ?")
- args = append(args, canonicalID)
- }
- if len(filters.Kinds) > 0 {
- placeholders := make([]string, 0, len(filters.Kinds))
- for _, kind := range filters.Kinds {
- placeholders = append(placeholders, "?")
- args = append(args, string(kind))
- }
- conditions = append(conditions, "kind IN ("+strings.Join(placeholders, ", ")+")")
- }
- if len(filters.SourceTypes) > 0 {
- placeholders := make([]string, 0, len(filters.SourceTypes))
- for _, sourceType := range filters.SourceTypes {
- placeholders = append(placeholders, "?")
- args = append(args, string(sourceType))
- }
- conditions = append(conditions, "source_type IN ("+strings.Join(placeholders, ", ")+")")
- }
- if len(filters.SourceAdapters) > 0 {
- placeholders := make([]string, 0, len(filters.SourceAdapters))
- for _, sourceAdapter := range filters.SourceAdapters {
- placeholders = append(placeholders, "?")
- args = append(args, string(sourceAdapter))
- }
- conditions = append(conditions, "source_adapter IN ("+strings.Join(placeholders, ", ")+")")
- }
- query += ` WHERE ` + strings.Join(conditions, " AND ")
+ query, args := buildRecentChangeCountQuery(canonicalID, since, filters, "SELECT COUNT(*) FROM resource_changes")
s.mu.Lock()
defer s.mu.Unlock()
@@ -822,6 +791,41 @@ func (s *SQLiteResourceStore) CountRecentChangesFiltered(canonicalID string, sin
return count, nil
}
+func (s *SQLiteResourceStore) CountRecentChangesByKind(canonicalID string, since time.Time) (map[ChangeKind]int, error) {
+ return s.CountRecentChangesByKindFiltered(canonicalID, since, ResourceChangeFilters{})
+}
+
+func (s *SQLiteResourceStore) CountRecentChangesByKindFiltered(canonicalID string, since time.Time, filters ResourceChangeFilters) (map[ChangeKind]int, error) {
+ query, args := buildRecentChangeCountQuery(canonicalID, since, filters, "SELECT COALESCE(kind, ''), COUNT(*) FROM resource_changes")
+ query += ` GROUP BY kind`
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ rows, err := s.db.Query(query, args...)
+ if err != nil {
+ return nil, fmt.Errorf("query resource change counts by kind: %w", err)
+ }
+ defer rows.Close()
+
+ counts := make(map[ChangeKind]int)
+ for rows.Next() {
+ var kind string
+ var count int
+ if err := rows.Scan(&kind, &count); err != nil {
+ return nil, fmt.Errorf("scan resource change kind count row: %w", err)
+ }
+ if kind == "" {
+ continue
+ }
+ counts[ChangeKind(kind)] = count
+ }
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("iterate resource change kind count rows: %w", err)
+ }
+ return counts, nil
+}
+
func (s *SQLiteResourceStore) RecordActionAudit(record ActionAuditRecord) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -1176,6 +1180,71 @@ func (m *MemoryStore) CountRecentChangesFiltered(canonicalID string, since time.
return count, nil
}
+func (m *MemoryStore) CountRecentChangesByKind(canonicalID string, since time.Time) (map[ChangeKind]int, error) {
+ return m.CountRecentChangesByKindFiltered(canonicalID, since, ResourceChangeFilters{})
+}
+
+func (m *MemoryStore) CountRecentChangesByKindFiltered(canonicalID string, since time.Time, filters ResourceChangeFilters) (map[ChangeKind]int, error) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ canonicalID = CanonicalResourceID(canonicalID)
+ counts := make(map[ChangeKind]int)
+ for _, change := range m.changes {
+ if canonicalID != "" && CanonicalResourceID(change.ResourceID) != canonicalID {
+ continue
+ }
+ if !since.IsZero() && change.ObservedAt.Before(since) {
+ continue
+ }
+ if !filters.matches(change) {
+ continue
+ }
+ counts[change.Kind]++
+ }
+ if len(counts) == 0 {
+ return nil, nil
+ }
+ return counts, nil
+}
+
+func buildRecentChangeCountQuery(canonicalID string, since time.Time, filters ResourceChangeFilters, selectClause string) (string, []any) {
+ query := selectClause
+ args := []any{}
+ conditions := []string{"observed_at >= ?"}
+ args = append(args, since)
+ canonicalID = CanonicalResourceID(canonicalID)
+ if canonicalID != "" {
+ conditions = append(conditions, "canonical_id = ?")
+ args = append(args, canonicalID)
+ }
+ if len(filters.Kinds) > 0 {
+ placeholders := make([]string, 0, len(filters.Kinds))
+ for _, kind := range filters.Kinds {
+ placeholders = append(placeholders, "?")
+ args = append(args, string(kind))
+ }
+ conditions = append(conditions, "kind IN ("+strings.Join(placeholders, ", ")+")")
+ }
+ if len(filters.SourceTypes) > 0 {
+ placeholders := make([]string, 0, len(filters.SourceTypes))
+ for _, sourceType := range filters.SourceTypes {
+ placeholders = append(placeholders, "?")
+ args = append(args, string(sourceType))
+ }
+ conditions = append(conditions, "source_type IN ("+strings.Join(placeholders, ", ")+")")
+ }
+ if len(filters.SourceAdapters) > 0 {
+ placeholders := make([]string, 0, len(filters.SourceAdapters))
+ for _, sourceAdapter := range filters.SourceAdapters {
+ placeholders = append(placeholders, "?")
+ args = append(args, string(sourceAdapter))
+ }
+ conditions = append(conditions, "source_adapter IN ("+strings.Join(placeholders, ", ")+")")
+ }
+ query += ` WHERE ` + strings.Join(conditions, " AND ")
+ return query, args
+}
+
func (m *MemoryStore) RecordActionAudit(record ActionAuditRecord) error {
m.mu.Lock()
defer m.mu.Unlock()
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index 3af059680a..2d433cfa9c 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "reflect"
"strings"
"testing"
"time"
@@ -651,6 +652,86 @@ func TestCountRecentChanges_RespectsFilters(t *testing.T) {
}
}
+func TestCountRecentChangesByKind_RespectsFilters(t *testing.T) {
+ store := newTestStore(t)
+ base := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)
+ changes := []ResourceChange{
+ {
+ ID: "chg-kind-1",
+ ResourceID: "vm:1",
+ ObservedAt: base.Add(-30 * time.Minute),
+ Kind: ChangeStateTransition,
+ SourceType: SourcePlatformEvent,
+ SourceAdapter: AdapterProxmox,
+ Confidence: ConfidenceHigh,
+ },
+ {
+ ID: "chg-kind-2",
+ ResourceID: "vm:1",
+ ObservedAt: base.Add(-20 * time.Minute),
+ Kind: ChangeAnomaly,
+ SourceType: SourcePulseDiff,
+ SourceAdapter: AdapterDocker,
+ Confidence: ConfidenceMedium,
+ },
+ {
+ ID: "chg-kind-3",
+ ResourceID: "vm:1",
+ ObservedAt: base.Add(-10 * time.Minute),
+ Kind: ChangeAnomaly,
+ SourceType: SourcePulseDiff,
+ SourceAdapter: AdapterProxmox,
+ Confidence: ConfidenceLow,
+ },
+ {
+ ID: "chg-kind-4",
+ ResourceID: "vm:2",
+ ObservedAt: base.Add(-5 * time.Minute),
+ Kind: ChangeCapability,
+ SourceType: SourcePulseDiff,
+ SourceAdapter: AdapterDocker,
+ Confidence: ConfidenceLow,
+ },
+ }
+ for _, change := range changes {
+ if err := store.RecordChange(change); err != nil {
+ t.Fatalf("RecordChange(%s): %v", change.ID, err)
+ }
+ }
+
+ counts, err := store.CountRecentChangesByKind("vm:1", base.Add(-35*time.Minute))
+ if err != nil {
+ t.Fatalf("CountRecentChangesByKind vm:1: %v", err)
+ }
+ wantCounts := map[ChangeKind]int{
+ ChangeStateTransition: 1,
+ ChangeAnomaly: 2,
+ }
+ if !reflect.DeepEqual(counts, wantCounts) {
+ t.Fatalf("CountRecentChangesByKind vm:1 = %#v, want %#v", counts, wantCounts)
+ }
+
+ filteredCounts, err := store.CountRecentChangesByKindFiltered("vm:1", base.Add(-35*time.Minute), ResourceChangeFilters{
+ SourceTypes: []ChangeSourceType{SourcePulseDiff},
+ })
+ if err != nil {
+ t.Fatalf("CountRecentChangesByKindFiltered source types: %v", err)
+ }
+ if !reflect.DeepEqual(filteredCounts, map[ChangeKind]int{ChangeAnomaly: 2}) {
+ t.Fatalf("CountRecentChangesByKindFiltered source types = %#v, want %#v", filteredCounts, map[ChangeKind]int{ChangeAnomaly: 2})
+ }
+
+ adapterCounts, err := store.CountRecentChangesByKindFiltered("vm:1", base.Add(-35*time.Minute), ResourceChangeFilters{
+ SourceAdapters: []ChangeSourceAdapter{AdapterProxmox},
+ })
+ if err != nil {
+ t.Fatalf("CountRecentChangesByKindFiltered source adapters: %v", err)
+ }
+ if !reflect.DeepEqual(adapterCounts, map[ChangeKind]int{ChangeStateTransition: 1, ChangeAnomaly: 1}) {
+ t.Fatalf("CountRecentChangesByKindFiltered source adapters = %#v, want %#v", adapterCounts, map[ChangeKind]int{ChangeStateTransition: 1, ChangeAnomaly: 1})
+ }
+}
+
func TestGetRecentChanges_RespectsFilters(t *testing.T) {
store := newTestStore(t)
base := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)
diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.go
index 745cc9a750..c044324ced 100644
--- a/internal/unifiedresources/types.go
+++ b/internal/unifiedresources/types.go
@@ -69,9 +69,10 @@ type Resource struct {
// ResourceFacetCounts captures the total count of each resource facet that
// may be surfaced in row summaries or detail drawers.
type ResourceFacetCounts struct {
- Capabilities int `json:"capabilities"`
- Relationships int `json:"relationships"`
- RecentChanges int `json:"recentChanges"`
+ Capabilities int `json:"capabilities"`
+ Relationships int `json:"relationships"`
+ RecentChanges int `json:"recentChanges"`
+ RecentChangeKinds map[ChangeKind]int `json:"recentChangeKinds,omitempty"`
}
// DiscoveryTarget describes the canonical discovery request coordinates