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 canonical policy posture summary

rcourtmanad7388b59175
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 99e63ad462..8fb7ca620c 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -167,6 +167,10 @@ the same change source of truth.
The unified intelligence summary should follow the same rule when it counts
recent activity, so the shared AI summary and the Patrol seed context stay
aligned with the canonical timeline.
+The same unified intelligence summary now also surfaces a canonical policy
+posture snapshot derived from unified resources, so sensitivity, routing, and
+redaction counts stay aligned with the governed resource model that the
+runtime uses for prompt export and context rendering.
The shared AI resource and infrastructure prompt contexts should also surface
the same canonical recent changes section before any patrol-local fallback so
the model sees the same timeline entries that power the resource API and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d5b1c02f76..5cafbe3f7c 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -77,6 +77,7 @@ Own canonical runtime payload shapes between backend and frontend.
6. Route dedicated unified-resource capability, relationship, timeline, and facet-bundle reads through `frontend-modern/src/api/resources.ts`, `internal/api/resources.go`, and `internal/api/contract_test.go` together so the backend facet contract and the frontend client stay aligned on one governed surface, including the backend-provided facet counts needed to distinguish loaded slices from total history
7. Route canonical AI intelligence summary and resource-intelligence reads through `frontend-modern/src/api/ai.ts`, `frontend-modern/src/stores/aiIntelligence.ts`, `frontend-modern/src/pages/AIIntelligence.tsx`, `internal/api/ai_handlers.go`, and `internal/api/contract_test.go` together so the summary card, store state, and backend payload stay aligned on one governed surface, including the canonical recent-changes slice
and the shared `frontend-modern/src/utils/resourceChangePresentation.ts` formatter used by the summary page and resource drawer, so canonical change wording does not drift across surfaces
+ and the canonical policy-posture snapshot derived from unified resources, so sensitivity, routing, and redaction counts stay owned by the same AI summary contract instead of being reconstructed as a page-local governance rollup
8. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`
9. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`
10. Add or change infrastructure operations token generation, lookup, assignment, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 896a7fc583..71de1d4289 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -88,6 +88,10 @@ instead of being reconstructed locally.
The Patrol page also now renders the canonical intelligence summary card
through the governed AI client and store, so the visible page summary and the
resource/timeline sections stay aligned on the same shared backend slice.
+That Patrol summary card now also includes the canonical data-governance
+posture snapshot from the shared AI summary payload, so the visible page can
+show the same sensitivity, routing, and redaction distribution that the
+runtime derives from unified resources.
The Patrol page and resource drawer now also share the canonical
`frontend-modern/src/utils/resourceChangePresentation.ts` formatter so
recent-change kind and headline wording stays aligned wherever the canonical
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 3df18535e6..10c8c69595 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -143,6 +143,10 @@ That same facet bundle now also returns grouped recent-change adapter counts
by source adapter, so the detail drawer can distinguish Docker, Proxmox,
TrueNAS, and ops-helper provenance without re-deriving integration origin
from the loaded slice.
+The same unified resource model now also feeds the canonical AI policy
+posture summary, so sensitivity, routing, and redaction distributions stay
+derived from the shared resource view instead of being rebuilt as a
+page-local governance rollup.
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/pages/AIIntelligence.tsx b/frontend-modern/src/pages/AIIntelligence.tsx
index e4fe8f0cf8..310370b491 100644
--- a/frontend-modern/src/pages/AIIntelligence.tsx
+++ b/frontend-modern/src/pages/AIIntelligence.tsx
@@ -93,14 +93,41 @@ import {
formatResourceChangeHeadline,
formatResourceChangeKind,
} from '@/utils/resourceChangePresentation';
+import {
+ getResourceRedactionHintLabel,
+ getResourceRoutingScopeLabel,
+ getResourceSensitivityLabel,
+} from '@/utils/resourcePolicyPresentation';
import {
getProTrialStartedMessage,
getTrialAlreadyUsedMessage,
getTrialStartErrorMessage,
getTrialTryAgainLaterMessage,
} from '@/utils/upgradePresentation';
+import type {
+ ResourceRedactionHint,
+ ResourceRoutingScope,
+ ResourceSensitivity,
+} from '@/types/resource';
type PatrolTab = 'findings' | 'history';
+const policySensitivityOrder: ResourceSensitivity[] = [
+ 'public',
+ 'internal',
+ 'sensitive',
+ 'restricted',
+];
+
+const policyRoutingOrder: ResourceRoutingScope[] = ['cloud-summary', 'local-first', 'local-only'];
+
+const policyRedactionOrder: ResourceRedactionHint[] = [
+ 'hostname',
+ 'ip-address',
+ 'platform-id',
+ 'alias',
+ 'path',
+];
+
export function AIIntelligence() {
const [activeTab, setActiveTab] = createSignal<PatrolTab>('findings');
const [findingsFilterOverride, setFindingsFilterOverride] = createSignal<
@@ -541,6 +568,7 @@ export function AIIntelligence() {
});
const intelligenceSummary = createMemo(() => aiIntelligenceStore.intelligenceSummary);
+ const policyPosture = createMemo(() => intelligenceSummary()?.policy_posture);
// Live in-progress run entry for history list
const liveRunRecord = createMemo<PatrolRunRecord | null>(() => {
@@ -1334,52 +1362,121 @@ export function AIIntelligence() {
</Show>
</div>
- <div class="rounded-md border border-border-subtle bg-base p-4">
- <div class="flex items-center justify-between gap-2">
- <h3 class="text-sm font-semibold text-base-content">Learning signals</h3>
- <span class="text-xs text-muted">
- {summary().learning.resources_with_baselines} baselined
- </span>
+ <div class="space-y-4">
+ <div class="rounded-md border border-border-subtle bg-base p-4">
+ <div class="flex items-center justify-between gap-2">
+ <h3 class="text-sm font-semibold text-base-content">Learning signals</h3>
+ <span class="text-xs text-muted">
+ {summary().learning.resources_with_baselines} baselined
+ </span>
+ </div>
+
+ <dl class="mt-3 grid grid-cols-2 gap-2 text-sm">
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">Knowledge</dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {summary().learning.resources_with_knowledge}
+ </dd>
+ </div>
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">Notes</dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {summary().learning.total_notes}
+ </dd>
+ </div>
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">Patterns</dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {summary().learning.patterns_detected}
+ </dd>
+ </div>
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">Correlations</dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {summary().learning.correlations_learned}
+ </dd>
+ </div>
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">Incidents</dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {summary().learning.incidents_tracked}
+ </dd>
+ </div>
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">Predictions</dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {summary().predictions_count}
+ </dd>
+ </div>
+ </dl>
</div>
- <dl class="mt-3 grid grid-cols-2 gap-2 text-sm">
- <div class="rounded-md bg-surface px-3 py-2">
- <dt class="text-xs uppercase tracking-wide text-muted">Knowledge</dt>
- <dd class="mt-1 font-semibold text-base-content">
- {summary().learning.resources_with_knowledge}
- </dd>
- </div>
- <div class="rounded-md bg-surface px-3 py-2">
- <dt class="text-xs uppercase tracking-wide text-muted">Notes</dt>
- <dd class="mt-1 font-semibold text-base-content">
- {summary().learning.total_notes}
- </dd>
- </div>
- <div class="rounded-md bg-surface px-3 py-2">
- <dt class="text-xs uppercase tracking-wide text-muted">Patterns</dt>
- <dd class="mt-1 font-semibold text-base-content">
- {summary().learning.patterns_detected}
- </dd>
- </div>
- <div class="rounded-md bg-surface px-3 py-2">
- <dt class="text-xs uppercase tracking-wide text-muted">Correlations</dt>
- <dd class="mt-1 font-semibold text-base-content">
- {summary().learning.correlations_learned}
- </dd>
- </div>
- <div class="rounded-md bg-surface px-3 py-2">
- <dt class="text-xs uppercase tracking-wide text-muted">Incidents</dt>
- <dd class="mt-1 font-semibold text-base-content">
- {summary().learning.incidents_tracked}
- </dd>
- </div>
- <div class="rounded-md bg-surface px-3 py-2">
- <dt class="text-xs uppercase tracking-wide text-muted">Predictions</dt>
- <dd class="mt-1 font-semibold text-base-content">
- {summary().predictions_count}
- </dd>
- </div>
- </dl>
+ <Show when={policyPosture()}>
+ {(posture) => (
+ <div class="rounded-md border border-border-subtle bg-base p-4">
+ <div class="flex flex-wrap items-start justify-between gap-2">
+ <div>
+ <h3 class="text-sm font-semibold text-base-content">Data Governance</h3>
+ <p class="mt-1 text-xs text-muted">
+ {posture().total_resources} governed resources
+ </p>
+ </div>
+ </div>
+
+ <dl class="mt-3 grid grid-cols-2 gap-2 text-sm">
+ <For each={policySensitivityOrder}>
+ {(sensitivity) => {
+ const count = () => posture().sensitivity_counts?.[sensitivity] ?? 0;
+ return (
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">
+ {getResourceSensitivityLabel(sensitivity)}
+ </dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {count()}
+ </dd>
+ </div>
+ );
+ }}
+ </For>
+ </dl>
+
+ <div class="mt-3 grid grid-cols-3 gap-2 text-sm">
+ <For each={policyRoutingOrder}>
+ {(scope) => {
+ const count = () => posture().routing_counts?.[scope] ?? 0;
+ return (
+ <div class="rounded-md bg-surface px-3 py-2">
+ <dt class="text-xs uppercase tracking-wide text-muted">
+ {getResourceRoutingScopeLabel(scope)}
+ </dt>
+ <dd class="mt-1 font-semibold text-base-content">
+ {count()}
+ </dd>
+ </div>
+ );
+ }}
+ </For>
+ </div>
+
+ <Show when={policyRedactionOrder.some((hint) => (posture().redaction_counts?.[hint] ?? 0) > 0)}>
+ <div class="mt-3 flex flex-wrap gap-1.5">
+ <For each={policyRedactionOrder}>
+ {(hint) => {
+ const count = posture().redaction_counts?.[hint] ?? 0;
+ if (!count) return null;
+ return (
+ <span class="rounded-full border border-border-subtle bg-surface px-2 py-0.5 text-[11px] font-medium text-muted">
+ {getResourceRedactionHintLabel(hint)} {count}
+ </span>
+ );
+ }}
+ </For>
+ </div>
+ </Show>
+ </div>
+ )}
+ </Show>
</div>
</div>
</section>
diff --git a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
index f0ab3e7533..900ba4f6c5 100644
--- a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
+++ b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
@@ -47,6 +47,12 @@ const { findingsPanelState, runHistoryState, intelligenceState } = vi.hoisted(()
reason?: string;
relatedResources?: string[];
}>;
+ policy_posture?: {
+ total_resources: number;
+ sensitivity_counts: Record<string, number>;
+ routing_counts: Record<string, number>;
+ redaction_counts?: Record<string, number>;
+ };
learning: {
resources_with_knowledge: number;
total_notes: number;
@@ -389,6 +395,24 @@ describe('AIIntelligence entitlement gating', () => {
relatedResources: ['agent-1'],
},
],
+ policy_posture: {
+ total_resources: 4,
+ sensitivity_counts: {
+ public: 1,
+ internal: 1,
+ sensitive: 1,
+ restricted: 1,
+ },
+ routing_counts: {
+ 'cloud-summary': 2,
+ 'local-first': 1,
+ 'local-only': 1,
+ },
+ redaction_counts: {
+ hostname: 2,
+ 'ip-address': 1,
+ },
+ },
learning: {
resources_with_knowledge: 4,
total_notes: 11,
@@ -412,6 +436,13 @@ describe('AIIntelligence entitlement gating', () => {
expect(screen.getByText('vm-100')).toBeInTheDocument();
expect(screen.getByText('proxmox_adapter')).toBeInTheDocument();
expect(screen.getByText('Learning signals')).toBeInTheDocument();
+ expect(screen.getByText('Data Governance')).toBeInTheDocument();
+ expect(screen.getByText('4 governed resources')).toBeInTheDocument();
+ expect(screen.getByText('Public')).toBeInTheDocument();
+ expect(screen.getByText('Restricted')).toBeInTheDocument();
+ expect(screen.getByText('Cloud Summary')).toBeInTheDocument();
+ expect(screen.getByText('Local Only')).toBeInTheDocument();
+ expect(screen.getByText('Hostname 2')).toBeInTheDocument();
});
it('treats a selected zero-finding run as an empty snapshot and uses effective scope ids', async () => {
diff --git a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
index 2bb29890d1..7dcea5b103 100644
--- a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
@@ -90,6 +90,24 @@ describe('aiIntelligenceStore', () => {
confidence: 'high',
},
],
+ policy_posture: {
+ total_resources: 4,
+ sensitivity_counts: {
+ public: 1,
+ internal: 1,
+ sensitive: 1,
+ restricted: 1,
+ },
+ routing_counts: {
+ 'cloud-summary': 2,
+ 'local-first': 1,
+ 'local-only': 1,
+ },
+ redaction_counts: {
+ hostname: 2,
+ 'ip-address': 1,
+ },
+ },
learning: {
resources_with_knowledge: 4,
total_notes: 11,
@@ -109,6 +127,9 @@ describe('aiIntelligenceStore', () => {
total: 7,
},
recent_changes_count: 1,
+ policy_posture: {
+ total_resources: 4,
+ },
});
expect(aiIntelligenceStore.intelligenceSummary?.recent_changes).toHaveLength(1);
});
diff --git a/frontend-modern/src/types/aiIntelligence.ts b/frontend-modern/src/types/aiIntelligence.ts
index a601836d97..2e6541190b 100644
--- a/frontend-modern/src/types/aiIntelligence.ts
+++ b/frontend-modern/src/types/aiIntelligence.ts
@@ -9,7 +9,12 @@
* Store logic lives in @/stores/aiIntelligence.ts
*/
-import type { ResourceChange } from '@/types/resource';
+import type {
+ ResourceChange,
+ ResourceRedactionHint,
+ ResourceRoutingScope,
+ ResourceSensitivity,
+} from '@/types/resource';
// ============================================
// Anomaly Detection Types
@@ -82,6 +87,13 @@ export interface IntelligenceLearningStats {
incidents_tracked: number;
}
+export interface IntelligencePolicyPostureSummary {
+ total_resources: number;
+ sensitivity_counts: Partial<Record<ResourceSensitivity, number>>;
+ routing_counts: Partial<Record<ResourceRoutingScope, number>>;
+ redaction_counts?: Partial<Record<ResourceRedactionHint, number>>;
+}
+
export interface IntelligenceSummary {
timestamp: string;
overall_health: IntelligenceHealthScore;
@@ -90,6 +102,7 @@ export interface IntelligenceSummary {
recent_changes_count: number;
recent_changes?: ResourceChange[];
recent_remediations?: Array<Record<string, unknown>>;
+ policy_posture?: IntelligencePolicyPostureSummary;
learning: IntelligenceLearningStats;
resources_at_risk?: Array<Record<string, unknown>>;
}
diff --git a/frontend-modern/src/utils/__tests__/resourcePolicyPresentation.test.ts b/frontend-modern/src/utils/__tests__/resourcePolicyPresentation.test.ts
new file mode 100644
index 0000000000..05c43645b1
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourcePolicyPresentation.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getResourcePolicyRedactionLabels,
+ getResourceRedactionHintLabel,
+ getResourceRoutingScopeLabel,
+ getResourceSensitivityLabel,
+} from '@/utils/resourcePolicyPresentation';
+
+describe('resourcePolicyPresentation utils', () => {
+ it('formats canonical policy labels', () => {
+ expect(getResourceSensitivityLabel('restricted')).toBe('Restricted');
+ expect(getResourceRoutingScopeLabel('local-only')).toBe('Local Only');
+ expect(getResourceRedactionHintLabel('platform-id')).toBe('Platform ID');
+ });
+
+ it('formats canonical redaction labels from policy hints', () => {
+ expect(
+ getResourcePolicyRedactionLabels({
+ sensitivity: 'sensitive',
+ routing: {
+ scope: 'local-first',
+ allowCloudSummary: true,
+ allowCloudRawSignals: false,
+ redact: ['hostname', 'ip-address'],
+ },
+ }),
+ ).toEqual(['Hostname', 'IP Address']);
+ });
+});
diff --git a/frontend-modern/src/utils/resourcePolicyPresentation.ts b/frontend-modern/src/utils/resourcePolicyPresentation.ts
index 5e40335c21..1dc09e3b7f 100644
--- a/frontend-modern/src/utils/resourcePolicyPresentation.ts
+++ b/frontend-modern/src/utils/resourcePolicyPresentation.ts
@@ -80,6 +80,8 @@ export const getResourceSensitivityLabel = (sensitivity?: ResourceSensitivity):
export const getResourceRoutingScopeLabel = (scope?: ResourceRoutingScope): string =>
scope ? routingPresentation[scope].label : 'Unrouted';
-export const getResourcePolicyRedactionLabels = (policy?: ResourcePolicy): string[] =>
- (policy?.routing.redact ?? []).map((hint) => redactionLabels[hint] ?? hint);
+export const getResourceRedactionHintLabel = (hint?: ResourceRedactionHint): string =>
+ hint ? redactionLabels[hint] ?? hint : 'Unclassified';
+export const getResourcePolicyRedactionLabels = (policy?: ResourcePolicy): string[] =>
+ (policy?.routing.redact ?? []).map((hint) => getResourceRedactionHintLabel(hint));
diff --git a/internal/ai/intelligence.go b/internal/ai/intelligence.go
index 61552e7849..e82eb44a26 100644
--- a/internal/ai/intelligence.go
+++ b/internal/ai/intelligence.go
@@ -102,6 +102,9 @@ type IntelligenceSummary struct {
RecentChanges []unifiedresources.ResourceChange `json:"recent_changes,omitempty"`
RecentRemediations []memory.RemediationRecord `json:"recent_remediations,omitempty"`
+ // Data governance posture
+ PolicyPosture *PolicyPostureSummary `json:"policy_posture,omitempty"`
+
// Learning progress
Learning LearningStats `json:"learning"`
@@ -152,6 +155,7 @@ type Intelligence struct {
remediations *memory.RemediationLog
resourceTimelineStore unifiedresources.ResourceStore
resourceTimelineStoreOrgID string
+ unifiedResourceProvider UnifiedResourceProvider
// State access
stateProvider StateProvider
@@ -208,6 +212,14 @@ func (i *Intelligence) SetResourceTimelineStore(store unifiedresources.ResourceS
i.resourceTimelineStoreOrgID = strings.TrimSpace(orgID)
}
+// SetUnifiedResourceProvider wires the canonical unified resource provider used
+// for infrastructure-wide posture summaries.
+func (i *Intelligence) SetUnifiedResourceProvider(urp UnifiedResourceProvider) {
+ i.mu.Lock()
+ defer i.mu.Unlock()
+ i.unifiedResourceProvider = urp
+}
+
// SetStateProvider sets the state provider for current metrics
func (i *Intelligence) SetStateProvider(sp StateProvider) {
i.mu.Lock()
@@ -227,6 +239,7 @@ func (i *Intelligence) GetSummary() *IntelligenceSummary {
remediations := i.remediations
changes := i.changes
resourceTimelineStore := i.resourceTimelineStore
+ unifiedResourceProvider := i.unifiedResourceProvider
i.mu.RUnlock()
// Aggregate findings
@@ -271,6 +284,12 @@ func (i *Intelligence) GetSummary() *IntelligenceSummary {
summary.RecentRemediations = recent
}
+ if unifiedResourceProvider != nil {
+ summary.PolicyPosture = summarizePolicyPosture(
+ normalizeUnifiedResourceContextSlice(unifiedResourceProvider.GetAll()),
+ )
+ }
+
// Learning stats
summary.Learning = i.getLearningStats()
diff --git a/internal/ai/intelligence_coverage_test.go b/internal/ai/intelligence_coverage_test.go
index 5e0ff78023..4305647b66 100644
--- a/internal/ai/intelligence_coverage_test.go
+++ b/internal/ai/intelligence_coverage_test.go
@@ -1,6 +1,7 @@
package ai
import (
+ "reflect"
"strings"
"testing"
"time"
@@ -207,6 +208,82 @@ func TestIntelligence_getLearningStats(t *testing.T) {
}
}
+func TestIntelligence_summarizePolicyPosture(t *testing.T) {
+ resources := []ur.Resource{
+ {
+ ID: "public-1",
+ Name: "public-vm",
+ Type: ur.ResourceTypeVM,
+ Tags: []string{"public"},
+ },
+ {
+ ID: "internal-1",
+ Name: "agent-1",
+ Type: ur.ResourceTypeAgent,
+ Agent: &ur.AgentData{Hostname: "agent-1"},
+ Status: ur.StatusOnline,
+ },
+ {
+ ID: "sensitive-1",
+ Name: "db-1",
+ Type: ur.ResourceTypeVM,
+ Status: ur.StatusOnline,
+ Identity: ur.ResourceIdentity{
+ Hostnames: []string{"db.internal"},
+ IPAddresses: []string{"10.0.0.10"},
+ },
+ Canonical: &ur.CanonicalIdentity{
+ PlatformID: "db.internal",
+ Aliases: []string{"db-1"},
+ },
+ },
+ {
+ ID: "restricted-1",
+ Name: "mail-gw",
+ Type: ur.ResourceTypePMG,
+ Status: ur.StatusWarning,
+ PMG: &ur.PMGData{Hostname: "mail.internal"},
+ },
+ }
+
+ summary := summarizePolicyPosture(normalizeUnifiedResourceContextSlice(resources))
+ if summary == nil {
+ t.Fatal("expected posture summary")
+ }
+ if summary.TotalResources != 4 {
+ t.Fatalf("total resources = %d, want 4", summary.TotalResources)
+ }
+ if got := summary.SensitivityCounts[ur.ResourceSensitivityPublic]; got != 1 {
+ t.Fatalf("public sensitivity count = %d, want 1", got)
+ }
+ if got := summary.SensitivityCounts[ur.ResourceSensitivityInternal]; got != 1 {
+ t.Fatalf("internal sensitivity count = %d, want 1", got)
+ }
+ if got := summary.SensitivityCounts[ur.ResourceSensitivitySensitive]; got != 1 {
+ t.Fatalf("sensitive sensitivity count = %d, want 1", got)
+ }
+ if got := summary.SensitivityCounts[ur.ResourceSensitivityRestricted]; got != 1 {
+ t.Fatalf("restricted sensitivity count = %d, want 1", got)
+ }
+ if got := summary.RoutingCounts[ur.ResourceRoutingScopeCloudSummary]; got != 2 {
+ t.Fatalf("cloud summary routing count = %d, want 2", got)
+ }
+ if got := summary.RoutingCounts[ur.ResourceRoutingScopeLocalFirst]; got != 1 {
+ t.Fatalf("local-first routing count = %d, want 1", got)
+ }
+ if got := summary.RoutingCounts[ur.ResourceRoutingScopeLocalOnly]; got != 1 {
+ t.Fatalf("local-only routing count = %d, want 1", got)
+ }
+ if got := summary.RedactionCounts[ur.ResourceRedactionHostname]; got == 0 {
+ t.Fatal("expected hostname redaction count")
+ }
+
+ labels := policyPostureRedactionLabels(summary)
+ if !reflect.DeepEqual(labels, []string{"Alias", "Hostname", "IP Address", "Platform ID"}) {
+ t.Fatalf("redaction labels = %#v, want %#v", labels, []string{"Alias", "Hostname", "IP Address", "Platform ID"})
+ }
+}
+
func TestIntelligence_getResourcesAtRisk(t *testing.T) {
intel := NewIntelligence(IntelligenceConfig{})
findings := NewFindingsStore()
diff --git a/internal/ai/patrol_init.go b/internal/ai/patrol_init.go
index 8d7a9ef124..e49f387c58 100644
--- a/internal/ai/patrol_init.go
+++ b/internal/ai/patrol_init.go
@@ -789,6 +789,7 @@ func (p *PatrolService) GetIntelligence() *Intelligence {
p.aiService.mu.RUnlock()
p.intelligence.SetResourceTimelineStore(store, orgID)
}
+ p.intelligence.SetUnifiedResourceProvider(p.unifiedResourceProvider)
if p.stateProvider != nil {
p.intelligence.SetStateProvider(p.stateProvider)
diff --git a/internal/ai/patrol_test.go b/internal/ai/patrol_test.go
index 0011c55753..a124a48720 100644
--- a/internal/ai/patrol_test.go
+++ b/internal/ai/patrol_test.go
@@ -1003,6 +1003,24 @@ func TestPatrolService_GetIntelligence(t *testing.T) {
ps := NewPatrolService(svc, nil)
ps.stateProvider = &mockStateProvider{}
+ ps.SetUnifiedResourceProvider(&mockUnifiedResourceProvider{
+ getAllFunc: func() []ur.Resource {
+ return []ur.Resource{
+ {
+ ID: "public-1",
+ Name: "public-vm",
+ Type: ur.ResourceTypeVM,
+ Tags: []string{"public"},
+ },
+ {
+ ID: "internal-1",
+ Name: "agent-1",
+ Type: ur.ResourceTypeAgent,
+ Agent: &ur.AgentData{Hostname: "agent-1"},
+ },
+ }
+ },
+ })
intel := ps.GetIntelligence()
if intel == nil {
@@ -1015,6 +1033,15 @@ func TestPatrolService_GetIntelligence(t *testing.T) {
if summary.RecentChangesCount != 1 {
t.Fatalf("expected canonical timeline count, got %d", summary.RecentChangesCount)
}
+ if summary.PolicyPosture == nil {
+ t.Fatal("expected canonical policy posture summary")
+ }
+ if summary.PolicyPosture.TotalResources != 2 {
+ t.Fatalf("expected 2 governed resources, got %d", summary.PolicyPosture.TotalResources)
+ }
+ if got := summary.PolicyPosture.SensitivityCounts[ur.ResourceSensitivityPublic]; got != 1 {
+ t.Fatalf("expected 1 public resource, got %d", got)
+ }
}
func TestPatrolService_Stop(t *testing.T) {
diff --git a/internal/ai/policy_posture.go b/internal/ai/policy_posture.go
new file mode 100644
index 0000000000..04af9eabd4
--- /dev/null
+++ b/internal/ai/policy_posture.go
@@ -0,0 +1,69 @@
+package ai
+
+import (
+ "sort"
+
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// PolicyPostureSummary captures the canonical data-governance posture derived
+// from the unified resource registry.
+type PolicyPostureSummary struct {
+ TotalResources int `json:"total_resources"`
+ SensitivityCounts map[unifiedresources.ResourceSensitivity]int `json:"sensitivity_counts,omitempty"`
+ RoutingCounts map[unifiedresources.ResourceRoutingScope]int `json:"routing_counts,omitempty"`
+ RedactionCounts map[unifiedresources.ResourceRedactionHint]int `json:"redaction_counts,omitempty"`
+}
+
+func summarizePolicyPosture(resources []unifiedresources.Resource) *PolicyPostureSummary {
+ if len(resources) == 0 {
+ return &PolicyPostureSummary{}
+ }
+
+ summary := &PolicyPostureSummary{
+ TotalResources: len(resources),
+ SensitivityCounts: make(map[unifiedresources.ResourceSensitivity]int),
+ RoutingCounts: make(map[unifiedresources.ResourceRoutingScope]int),
+ RedactionCounts: make(map[unifiedresources.ResourceRedactionHint]int),
+ }
+
+ for _, resource := range resources {
+ if resource.Policy == nil {
+ continue
+ }
+ summary.SensitivityCounts[resource.Policy.Sensitivity]++
+ summary.RoutingCounts[resource.Policy.Routing.Scope]++
+ for _, hint := range resource.Policy.Routing.Redact {
+ summary.RedactionCounts[hint]++
+ }
+ }
+
+ if len(summary.SensitivityCounts) == 0 {
+ summary.SensitivityCounts = nil
+ }
+ if len(summary.RoutingCounts) == 0 {
+ summary.RoutingCounts = nil
+ }
+ if len(summary.RedactionCounts) == 0 {
+ summary.RedactionCounts = nil
+ }
+
+ return summary
+}
+
+func policyPostureRedactionLabels(summary *PolicyPostureSummary) []string {
+ if summary == nil || len(summary.RedactionCounts) == 0 {
+ return nil
+ }
+
+ labels := make([]string, 0, len(summary.RedactionCounts))
+ for hint := range summary.RedactionCounts {
+ label := unifiedresources.ResourceRedactionHintLabel(hint)
+ if label == "" {
+ continue
+ }
+ labels = append(labels, label)
+ }
+ sort.Strings(labels)
+ return labels
+}
diff --git a/internal/ai/resource_context.go b/internal/ai/resource_context.go
index d5ae4779e7..daa68a6da1 100644
--- a/internal/ai/resource_context.go
+++ b/internal/ai/resource_context.go
@@ -101,52 +101,43 @@ func (s *Service) buildUnifiedResourceContextForModel(destinationModel string) s
infrastructure := normalizeUnifiedResourceContextSlice(urp.GetInfrastructure())
workloads := normalizeUnifiedResourceContextSlice(urp.GetWorkloads())
allResources := normalizeUnifiedResourceContextSlice(urp.GetAll())
- byResourceID := make(map[string]unifiedresources.Resource, len(allResources))
- for _, resource := range allResources {
- byResourceID[resource.ID] = resource
- }
- sensitivityCounts := make(map[unifiedresources.ResourceSensitivity]int)
- routingCounts := make(map[unifiedresources.ResourceRoutingScope]int)
- localOnlyCount := 0
+ policyPosture := summarizePolicyPosture(allResources)
+ sensitivityCounts := map[unifiedresources.ResourceSensitivity]int{}
+ routingCounts := map[unifiedresources.ResourceRoutingScope]int{}
var redactionHints []unifiedresources.ResourceRedactionHint
- redactionHintSet := make(map[unifiedresources.ResourceRedactionHint]struct{})
- if len(allResources) > 0 {
- for _, resource := range allResources {
- if resource.Policy == nil {
- continue
- }
- sensitivityCounts[resource.Policy.Sensitivity]++
- routingCounts[resource.Policy.Routing.Scope]++
- if resource.Policy.Routing.Scope == unifiedresources.ResourceRoutingScopeLocalOnly {
- localOnlyCount++
- }
- for _, hint := range resource.Policy.Routing.Redact {
- redactionHintSet[hint] = struct{}{}
- }
- }
- if len(redactionHintSet) > 0 {
- redactionHints = make([]unifiedresources.ResourceRedactionHint, 0, len(redactionHintSet))
- for hint := range redactionHintSet {
+ localOnlyCount := 0
+ if policyPosture != nil {
+ sensitivityCounts = policyPosture.SensitivityCounts
+ routingCounts = policyPosture.RoutingCounts
+ localOnlyCount = routingCounts[unifiedresources.ResourceRoutingScopeLocalOnly]
+ if len(policyPosture.RedactionCounts) > 0 {
+ redactionHints = make([]unifiedresources.ResourceRedactionHint, 0, len(policyPosture.RedactionCounts))
+ for hint := range policyPosture.RedactionCounts {
redactionHints = append(redactionHints, hint)
}
- sort.Slice(redactionHints, func(i, j int) bool {
- return redactionHints[i] < redactionHints[j]
- })
}
- if len(sensitivityCounts) > 0 {
- sections = append(sections, "\n### Data Governance")
- sections = append(sections, fmt.Sprintf("- Sensitivity: %d public, %d internal, %d sensitive, %d restricted",
- sensitivityCounts[unifiedresources.ResourceSensitivityPublic],
- sensitivityCounts[unifiedresources.ResourceSensitivityInternal],
- sensitivityCounts[unifiedresources.ResourceSensitivitySensitive],
- sensitivityCounts[unifiedresources.ResourceSensitivityRestricted],
- ))
- sections = append(sections, fmt.Sprintf("- Routing: %d cloud-summary, %d local-first, %d local-only",
- routingCounts[unifiedresources.ResourceRoutingScopeCloudSummary],
- routingCounts[unifiedresources.ResourceRoutingScopeLocalFirst],
- routingCounts[unifiedresources.ResourceRoutingScopeLocalOnly],
- ))
- sections = append(sections, fmt.Sprintf("- Local-only resources: %d", localOnlyCount))
+ }
+ byResourceID := make(map[string]unifiedresources.Resource, len(allResources))
+ for _, resource := range allResources {
+ byResourceID[resource.ID] = resource
+ }
+ if policyPosture != nil && policyPosture.TotalResources > 0 {
+ sections = append(sections, "\n### Data Governance")
+ sections = append(sections, fmt.Sprintf("- Sensitivity: %d public, %d internal, %d sensitive, %d restricted",
+ sensitivityCounts[unifiedresources.ResourceSensitivityPublic],
+ sensitivityCounts[unifiedresources.ResourceSensitivityInternal],
+ sensitivityCounts[unifiedresources.ResourceSensitivitySensitive],
+ sensitivityCounts[unifiedresources.ResourceSensitivityRestricted],
+ ))
+ sections = append(sections, fmt.Sprintf("- Routing: %d cloud-summary, %d local-first, %d local-only",
+ routingCounts[unifiedresources.ResourceRoutingScopeCloudSummary],
+ routingCounts[unifiedresources.ResourceRoutingScopeLocalFirst],
+ routingCounts[unifiedresources.ResourceRoutingScopeLocalOnly],
+ ))
+ sections = append(sections, fmt.Sprintf("- Local-only resources: %d", localOnlyCount))
+ if redactionLabels := policyPostureRedactionLabels(policyPosture); len(redactionLabels) > 0 {
+ sections = append(sections, "\n### Policy Redaction Hints")
+ sections = append(sections, fmt.Sprintf("- Redactions in use: %s", strings.Join(redactionLabels, ", ")))
}
}
diff --git a/internal/api/ai_handlers_more_test.go b/internal/api/ai_handlers_more_test.go
index 99b4df6891..01bf406bb5 100644
--- a/internal/api/ai_handlers_more_test.go
+++ b/internal/api/ai_handlers_more_test.go
@@ -49,27 +49,35 @@ func (stubMetricsHistoryProvider) GetAllStorageMetrics(string, time.Duration) ma
return nil
}
-type stubUnifiedResourceProvider struct{}
+type stubUnifiedResourceProvider struct {
+ resources []unifiedresources.Resource
+}
-func (stubUnifiedResourceProvider) GetAll() []unifiedresources.Resource { return nil }
-func (stubUnifiedResourceProvider) GetInfrastructure() []unifiedresources.Resource { return nil }
-func (stubUnifiedResourceProvider) GetWorkloads() []unifiedresources.Resource { return nil }
-func (stubUnifiedResourceProvider) GetByType(unifiedresources.ResourceType) []unifiedresources.Resource {
+func (s stubUnifiedResourceProvider) GetAll() []unifiedresources.Resource {
+ return s.resources
+}
+func (s stubUnifiedResourceProvider) GetInfrastructure() []unifiedresources.Resource {
+ return nil
+}
+func (s stubUnifiedResourceProvider) GetWorkloads() []unifiedresources.Resource {
+ return nil
+}
+func (s stubUnifiedResourceProvider) GetByType(unifiedresources.ResourceType) []unifiedresources.Resource {
return nil
}
func (stubUnifiedResourceProvider) GetStats() unifiedresources.ResourceStats {
return unifiedresources.ResourceStats{}
}
-func (stubUnifiedResourceProvider) GetTopByCPU(int, []unifiedresources.ResourceType) []unifiedresources.Resource {
+func (s stubUnifiedResourceProvider) GetTopByCPU(int, []unifiedresources.ResourceType) []unifiedresources.Resource {
return nil
}
-func (stubUnifiedResourceProvider) GetTopByMemory(int, []unifiedresources.ResourceType) []unifiedresources.Resource {
+func (s stubUnifiedResourceProvider) GetTopByMemory(int, []unifiedresources.ResourceType) []unifiedresources.Resource {
return nil
}
-func (stubUnifiedResourceProvider) GetTopByDisk(int, []unifiedresources.ResourceType) []unifiedresources.Resource {
+func (s stubUnifiedResourceProvider) GetTopByDisk(int, []unifiedresources.ResourceType) []unifiedresources.Resource {
return nil
}
-func (stubUnifiedResourceProvider) GetRelated(string) map[string][]unifiedresources.Resource {
+func (s stubUnifiedResourceProvider) GetRelated(string) map[string][]unifiedresources.Resource {
return map[string][]unifiedresources.Resource{}
}
func (stubUnifiedResourceProvider) FindContainerHost(string) string { return "" }
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index ad5cda8413..6a8fb60e6a 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -336,6 +336,22 @@ func TestContract_IntelligenceSummaryIncludesRecentChanges(t *testing.T) {
}); err != nil {
t.Fatalf("record canonical change: %v", err)
}
+ svc.SetUnifiedResourceProvider(&stubUnifiedResourceProvider{
+ resources: []unifiedresources.Resource{
+ {
+ ID: "public-1",
+ Name: "public-vm",
+ Type: unifiedresources.ResourceTypeVM,
+ Tags: []string{"public"},
+ },
+ {
+ ID: "restricted-1",
+ Name: "mail-gw",
+ Type: unifiedresources.ResourceTypePMG,
+ PMG: &unifiedresources.PMGData{Hostname: "mail.internal"},
+ },
+ },
+ })
setUnexportedField(t, svc, "resourceExportStore", canonicalStore)
setUnexportedField(t, svc.GetPatrolService(), "aiService", svc)
@@ -360,6 +376,13 @@ func TestContract_IntelligenceSummaryIncludesRecentChanges(t *testing.T) {
if len(recentChanges) != 1 {
t.Fatalf("expected 1 recent change, got %d", len(recentChanges))
}
+ policyPosture, ok := payload["policy_posture"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected policy_posture object in response, got %T", payload["policy_posture"])
+ }
+ if got := int(policyPosture["total_resources"].(float64)); got != 2 {
+ t.Fatalf("expected total_resources=2, got %d", got)
+ }
}
func TestContract_ResolveAuthEnvPathUsesCanonicalRuntimeDataDir(t *testing.T) {