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.

Keep Patrol evidence aligned with live findings

rcourtmane38332de865c
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index a13793458b..ff81787426 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -116,7 +116,11 @@ runtime cost control, and shared AI transport surfaces.
failures must be classified in `internal/ai/` before they reach operators,
surfaced as the synthetic Patrol runtime finding, and preserved on patrol
run records as structured error summary/detail instead of collapsing to
- generic analysis-failed copy.
+ generic analysis-failed copy. Demo-mode Patrol run records must carry
+ explicit source provenance and must not persist as live runtime evidence;
+ outside demo mode, run-history reads, run lookup, and Patrol coverage
+ scoring must filter both source-marked and legacy `demo-run-*` records so
+ live assessment state cannot be contaminated by public demo fixtures.
Unavailable-provider blocked states must direct operators to Assistant &
Patrol provider settings and tool-capable Patrol model selection, not
legacy `Settings > Pulse Assistant` copy.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 95e3c55428..64882f01f1 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -119,6 +119,10 @@ product API routes free of maintainer commercial analytics.
`/api/ai/patrol/run` must use the `patrol_readiness_not_ready` error taxonomy
when it rejects a known-bad Patrol runtime configuration. Bounded `status`,
`cause`, `provider`, and `model` details are the canonical transport shape.
+ `/api/ai/patrol/findings` is the canonical Patrol-page findings source, and
+ `/api/ai/patrol/runs` records may expose bounded `source` provenance so demo
+ evidence can be separated from live runtime assessment state without
+ changing the stable run payload shape.
7. `frontend-modern/src/api/rbac.ts` shared with `organization-settings`: the RBAC frontend client is both an organization settings control surface and a canonical API payload contract boundary.
8. `frontend-modern/src/api/security.ts` shared with `security-privacy`: the security frontend client is both a security/privacy control surface and a canonical API payload contract boundary.
9. `frontend-modern/src/api/updates.ts` shared with `deployment-installability`: the updates frontend client is both a deployment-installability control surface and a canonical API payload contract boundary.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 67c2789a18..0f78059a3e 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -784,7 +784,11 @@ prompt explain the same operator-facing priority.
Assistant drawer is not visually hidden behind feature chrome. When a Patrol
assessment handoff is attached, the shared Assistant drawer empty state must
stay aligned with that source-named briefing and must not render generic
- cluster/system starter prompts below the Patrol-owned context.
+ cluster/system starter prompts below the Patrol-owned context. The Patrol
+ feature shell must also consume the Patrol-owned findings source for its
+ findings tab, run-scoped findings panels, and tab badges so shared feature
+ composition does not rebuild Patrol state by filtering the cross-product
+ unified findings feed.
19. Keep the shared `system-ai` settings shell product-first.
`frontend-modern/src/components/Settings/AISettings.tsx`,
`frontend-modern/src/components/Settings/settingsHeaderMeta.ts`,
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 67d7bfeb40..f6717cb075 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -75,6 +75,11 @@ Patrol-specific presentation helpers.
## Completion Obligations
1. Update Patrol page, state, presentation helpers, and proof files together when Patrol UX semantics change
+ The Patrol route must source its Patrol findings from the direct Patrol
+ findings transport through the shared intelligence store. Unified findings
+ may remain available to cross-product AI surfaces, but the Patrol page,
+ selected-run findings panel, badges, and active-finding summaries must not
+ infer current Patrol evidence by filtering the unified threshold/AI feed.
2. Keep Patrol-specific copy and badge logic inside the governed Patrol presentation helpers instead of page-local branches
3. Update this contract whenever a new Patrol-specific page, store, helper, or presentation component becomes canonical runtime surface area
4. Keep retired hosted-model and trial-like Patrol acquisition copy out of the
diff --git a/frontend-modern/src/api/__tests__/patrol.test.ts b/frontend-modern/src/api/__tests__/patrol.test.ts
index 1212c66cd8..834be760a4 100644
--- a/frontend-modern/src/api/__tests__/patrol.test.ts
+++ b/frontend-modern/src/api/__tests__/patrol.test.ts
@@ -7,6 +7,7 @@ vi.mock('@/utils/apiClient', () => ({
import {
getPatrolStatus,
getPatrolRun,
+ getPatrolFindings,
getPatrolRunHistory,
getPatrolRunHistoryWithToolCalls,
getPatrolRunWithToolCalls,
@@ -189,6 +190,38 @@ describe('patrol api', () => {
});
});
+ it('fetches direct Patrol findings and preserves canonical alert identity', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce([
+ {
+ id: 'finding-1',
+ severity: 'warning',
+ category: 'reliability',
+ resource_id: 'instance:node:100',
+ resource_name: 'vm-100',
+ resource_type: 'vm',
+ title: 'Provider connection issue',
+ description: 'Patrol could not complete provider analysis.',
+ detected_at: '2026-03-01T00:00:00Z',
+ last_seen_at: '2026-03-01T00:05:00Z',
+ auto_resolved: false,
+ times_raised: 1,
+ suppressed: false,
+ investigation_attempts: 0,
+ alert_identifier: 'instance:node:100::patrol/provider',
+ },
+ ] as any);
+
+ const findings = await getPatrolFindings();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/findings');
+ expect(findings).toHaveLength(1);
+ expect(findings[0]).toMatchObject({
+ id: 'finding-1',
+ alertIdentifier: 'instance:node:100::patrol/provider',
+ title: 'Provider connection issue',
+ });
+ });
+
it('normalizes single patrol run payloads', async () => {
apiFetchJSONMock.mockResolvedValueOnce({
id: 'run-2',
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index 6ed2827054..fa2664fb44 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -48,6 +48,17 @@ export interface Finding {
last_investigated_at?: string;
investigation_attempts: number;
investigation_record?: InvestigationRecord;
+ loop_state?: string;
+ lifecycle?: Array<{
+ at: string;
+ type: string;
+ message?: string;
+ from?: string;
+ to?: string;
+ metadata?: Record<string, string>;
+ }>;
+ regression_count?: number;
+ last_regression_at?: string;
}
export type InvestigationStatus =
@@ -204,6 +215,13 @@ export async function getPatrolStatus(): Promise<PatrolStatus> {
return apiFetchJSON<PatrolStatus>('/api/ai/patrol/status');
}
+export async function getPatrolFindings(): Promise<Finding[]> {
+ const findings = await apiFetchJSON<Finding[]>('/api/ai/patrol/findings');
+ return arrayOrEmpty<Finding>(findings).map((finding) =>
+ promoteLegacyAlertIdentifier(finding as Finding & { alert_identifier?: string }),
+ );
+}
+
/**
* Acknowledge a finding (marks as seen but keeps visible, like alert acknowledgement)
* Finding will auto-resolve when the underlying condition clears.
@@ -421,6 +439,7 @@ export interface ToolCallRecord {
export interface PatrolRunRecord {
id: string;
+ source?: 'demo' | string;
started_at: string;
completed_at: string;
duration_ms: number;
diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsx
index e9b76f131e..ee40c9dc5c 100644
--- a/frontend-modern/src/components/AI/FindingsPanel.tsx
+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx
@@ -83,6 +83,7 @@ interface FindingsPanelProps {
runtimeState?: PatrolRuntimeState;
blockedReason?: string;
overallHealth?: IntelligenceHealthScore;
+ findingsSource?: 'unified' | 'patrol';
runSnapshot?: Pick<
PatrolRunRecord,
| 'resources_checked'
@@ -113,6 +114,20 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
const [dismissNote, setDismissNote] = createSignal('');
const [dismissedPlanIds, setDismissedPlanIds] = createSignal<string[]>([]);
+ const isPatrolFindingsSource = createMemo(() => props.findingsSource === 'patrol');
+ const sourceFindings = createMemo(() =>
+ isPatrolFindingsSource() ? aiIntelligenceStore.patrolFindings : aiIntelligenceStore.findings,
+ );
+ const sourceFindingsNeedingAttention = createMemo(() =>
+ isPatrolFindingsSource()
+ ? aiIntelligenceStore.patrolFindingsNeedingAttention
+ : aiIntelligenceStore.findingsNeedingAttention,
+ );
+ const sourceFindingsWithPendingApprovals = createMemo(() =>
+ isPatrolFindingsSource()
+ ? aiIntelligenceStore.patrolFindingsWithPendingApprovals
+ : aiIntelligenceStore.findingsWithPendingApprovals,
+ );
const handleDismissPlan = async (plan: RemediationPlan, e: Event) => {
e.stopPropagation();
@@ -142,7 +157,11 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
// Load findings and remediation plans on mount
createEffect(() => {
- aiIntelligenceStore.loadFindings();
+ if (isPatrolFindingsSource()) {
+ aiIntelligenceStore.loadPatrolFindings();
+ } else {
+ aiIntelligenceStore.loadFindings();
+ }
aiIntelligenceStore.loadRemediationPlans();
});
@@ -161,7 +180,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
return [];
}
- let findings = [...aiIntelligenceStore.findings];
+ let findings = [...sourceFindings()];
// Filter by resource if specified
if (props.resourceId) {
@@ -176,12 +195,10 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
(f) => f.status === 'resolved' || f.status === 'dismissed' || f.status === 'snoozed',
);
} else if (filter() === 'attention') {
- const attentionIds = new Set(aiIntelligenceStore.findingsNeedingAttention.map((f) => f.id));
+ const attentionIds = new Set(sourceFindingsNeedingAttention().map((f) => f.id));
findings = findings.filter((f) => attentionIds.has(f.id));
} else if (filter() === 'approvals') {
- const approvalFindingIds = new Set(
- aiIntelligenceStore.findingsWithPendingApprovals.map((f) => f.id),
- );
+ const approvalFindingIds = new Set(sourceFindingsWithPendingApprovals().map((f) => f.id));
findings = findings.filter((f) => approvalFindingIds.has(f.id));
}
@@ -233,11 +250,14 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
});
// Filter to only show Patrol findings (exclude threshold alerts)
- const allPatrolFindings = createMemo(() =>
- aiIntelligenceStore.findings.filter(
+ const allPatrolFindings = createMemo(() => {
+ if (isPatrolFindingsSource()) {
+ return sourceFindings();
+ }
+ return sourceFindings().filter(
(f) => f.source !== 'threshold' && !f.isThreshold && !hasTriggeringAlert(f),
- ),
- );
+ );
+ });
const runSnapshotScopedPatrolFindings = createMemo(() => {
if (hasUnknownRunSnapshot()) {
return [];
@@ -250,30 +270,31 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
});
const useRunSnapshotScopedControls = createMemo(() => props.runSnapshot !== undefined);
const scopedNeedsAttentionCount = createMemo(() => {
- const attentionIds = new Set(aiIntelligenceStore.findingsNeedingAttention.map((f) => f.id));
+ const attentionIds = new Set(sourceFindingsNeedingAttention().map((f) => f.id));
return runSnapshotScopedPatrolFindings().filter((finding) => attentionIds.has(finding.id))
.length;
});
const scopedPendingApprovalCount = createMemo(() => {
- const approvalIds = new Set(
- aiIntelligenceStore.findingsWithPendingApprovals.map((finding) => finding.id),
- );
+ const approvalIds = new Set(sourceFindingsWithPendingApprovals().map((finding) => finding.id));
return runSnapshotScopedPatrolFindings().filter((finding) => approvalIds.has(finding.id))
.length;
});
const filterCounts = createMemo(() => ({
needsAttentionCount: useRunSnapshotScopedControls()
? scopedNeedsAttentionCount()
- : aiIntelligenceStore.needsAttentionCount,
+ : sourceFindingsNeedingAttention().length,
pendingApprovalCount: useRunSnapshotScopedControls()
? scopedPendingApprovalCount()
- : aiIntelligenceStore.patrolPendingApprovalCount,
+ : sourceFindingsWithPendingApprovals().length,
}));
- const patrolFindings = createMemo(() =>
- filteredFindings().filter(
+ const patrolFindings = createMemo(() => {
+ if (isPatrolFindingsSource()) {
+ return filteredFindings();
+ }
+ return filteredFindings().filter(
(f) => f.source !== 'threshold' && !f.isThreshold && !hasTriggeringAlert(f),
- ),
- );
+ );
+ });
const filterOptions = createMemo(() => buildFindingFilterOptions(filterCounts()));
const emptyStateCopy = createMemo(() =>
getPatrolFindingsEmptyState({
@@ -341,7 +362,11 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
createEffect(() => {
location.hash;
- aiIntelligenceStore.findingsSignal();
+ if (isPatrolFindingsSource()) {
+ aiIntelligenceStore.patrolFindingsSignal();
+ } else {
+ aiIntelligenceStore.findingsSignal();
+ }
requestAnimationFrame(scrollToFindingHash);
});
diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx b/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
index 09e257b6dd..4ab0c900f0 100644
--- a/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
@@ -6,6 +6,7 @@ import { FindingsPanel } from '../FindingsPanel';
const mockState = vi.hoisted(() => {
const loadFindings = vi.fn();
+ const loadPatrolFindings = vi.fn();
const getRemediationPlans = vi.fn().mockResolvedValue({ plans: [] });
const getResource = vi.fn((resourceId: string) =>
resourceId === 'app-container:truenas-main:nextcloud'
@@ -44,12 +45,31 @@ const mockState = vi.hoisted(() => {
status: 'active',
},
];
+ const patrolFindings = [
+ {
+ id: 'finding-provider-issue',
+ source: 'ai-patrol',
+ resourceId: 'instance:node:100',
+ resourceName: 'vm-100',
+ resourceType: 'vm',
+ alertIdentifier: 'instance:node:100::patrol/provider',
+ category: 'reliability',
+ severity: 'warning',
+ title: 'Provider connection issue',
+ description: 'Pulse Patrol could not complete provider analysis.',
+ detectedAt: '2026-03-30T11:00:00Z',
+ lastSeenAt: '2026-03-30T11:05:00Z',
+ status: 'active',
+ },
+ ];
return {
findings,
+ patrolFindings,
getResource,
getRemediationPlans,
loadFindings,
+ loadPatrolFindings,
};
});
@@ -107,15 +127,33 @@ vi.mock('@/stores/aiIntelligence', () => ({
get findingsError() {
return null;
},
+ get patrolFindings() {
+ return mockState.patrolFindings;
+ },
+ get patrolFindingsLoading() {
+ return false;
+ },
+ get patrolFindingsError() {
+ return null;
+ },
get findingsNeedingAttention() {
return [];
},
+ get patrolFindingsNeedingAttention() {
+ return [];
+ },
get findingsWithPendingApprovals() {
return [];
},
+ get patrolFindingsWithPendingApprovals() {
+ return [];
+ },
get needsAttentionCount() {
return 0;
},
+ get patrolNeedsAttentionCount() {
+ return 0;
+ },
get pendingApprovalCount() {
return 0;
},
@@ -126,7 +164,9 @@ vi.mock('@/stores/aiIntelligence', () => ({
return [];
},
findingsSignal: () => mockState.findings,
+ patrolFindingsSignal: () => mockState.patrolFindings,
loadFindings: mockState.loadFindings,
+ loadPatrolFindings: mockState.loadPatrolFindings,
loadRemediationPlans: vi.fn(),
},
}));
@@ -134,6 +174,7 @@ vi.mock('@/stores/aiIntelligence', () => ({
describe('FindingsPanel resource links', () => {
beforeEach(() => {
mockState.loadFindings.mockClear();
+ mockState.loadPatrolFindings.mockClear();
mockState.getRemediationPlans.mockClear();
mockState.getResource.mockClear();
@@ -163,4 +204,13 @@ describe('FindingsPanel resource links', () => {
'/workloads?type=app-container&platform=truenas&agent=truenas-main&resource=app-container%3Atruenas-main%3Anextcloud',
);
});
+
+ it('can render Patrol findings from the direct Patrol source', async () => {
+ render(() => <FindingsPanel findingsSource="patrol" />);
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ expect(mockState.loadFindings).not.toHaveBeenCalled();
+ expect(screen.getByText('Provider connection issue')).toBeInTheDocument();
+ });
});
diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
index 52b6a269cf..33435fc6b6 100644
--- a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
@@ -502,6 +502,18 @@ describe('aiFindingPresentation', () => {
expect(findingsPanelSource).not.toContain('AIAPI.getRemediationPlans()');
});
+ it('can source Patrol findings from the direct Patrol store boundary', () => {
+ expect(findingsPanelSource).toContain("findingsSource?: 'unified' | 'patrol'");
+ expect(findingsPanelSource).toContain('aiIntelligenceStore.loadPatrolFindings()');
+ expect(findingsPanelSource).toContain('aiIntelligenceStore.patrolFindings');
+ expect(findingsPanelSource).toContain('aiIntelligenceStore.patrolFindingsSignal()');
+ expect(findingsPanelSource).toContain('aiIntelligenceStore.patrolFindingsNeedingAttention');
+ expect(findingsPanelSource).toContain(
+ 'aiIntelligenceStore.patrolFindingsWithPendingApprovals',
+ );
+ expect(patrolWorkspaceSource).toContain('findingsSource="patrol"');
+ });
+
it('routes same-severity ordering through the shared patrol runtime sort helper', () => {
expect(findingsPanelSource).toContain('getFindingActiveRuntimeSortOrder(a)');
expect(findingsPanelSource).toContain('getFindingActiveRuntimeSortOrder(b)');
diff --git a/frontend-modern/src/components/patrol/RunHistoryEntry.tsx b/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
index 9d8e518d88..3b749030c8 100644
--- a/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
+++ b/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
@@ -523,6 +523,7 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
scopeResourceTypes={run.scope_resource_types}
showScopeWarnings={true}
showControls={false}
+ findingsSource="patrol"
runSnapshot={run}
/>
</div>
diff --git a/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx b/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
index fbdc25622e..1a0ae381f4 100644
--- a/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
@@ -23,6 +23,7 @@ vi.mock('@/components/AI/FindingsPanel', () => ({
scopeResourceTypes: Array.isArray(props.scopeResourceTypes)
? [...(props.scopeResourceTypes as string[])]
: props.scopeResourceTypes,
+ findingsSource: props.findingsSource,
showControls: props.showControls,
showScopeWarnings: props.showScopeWarnings,
runSnapshot: props.runSnapshot,
@@ -119,6 +120,7 @@ describe('RunHistoryEntry', () => {
filterOverride: 'all',
scopeResourceIds: [],
scopeResourceTypes: ['vm'],
+ findingsSource: 'patrol',
showControls: false,
showScopeWarnings: true,
runSnapshot: run,
@@ -148,6 +150,7 @@ describe('RunHistoryEntry', () => {
filterOverride: 'all',
scopeResourceIds: [],
scopeResourceTypes: ['vm'],
+ findingsSource: 'patrol',
showControls: false,
showScopeWarnings: true,
runSnapshot: {
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
index ca83627825..6a3514ce1c 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
@@ -119,6 +119,7 @@ export function PatrolIntelligenceWorkspace(props: { state: PatrolIntelligenceSt
runtimeState={state.runtimeState()}
blockedReason={state.blockedReason()}
overallHealth={state.intelligenceSummary()?.overall_health}
+ findingsSource="patrol"
runSnapshot={state.selectedRun() ?? undefined}
/>
</Show>
@@ -140,9 +141,7 @@ export function PatrolIntelligenceWorkspace(props: { state: PatrolIntelligenceSt
<p class="text-xs font-semibold uppercase tracking-[0.16em] text-muted">
{PATROL_SUPPORTING_CONTEXT_TITLE}
</p>
- <p class="mt-1 text-sm text-muted">
- {PATROL_SUPPORTING_CONTEXT_DESCRIPTION}
- </p>
+ <p class="mt-1 text-sm text-muted">{PATROL_SUPPORTING_CONTEXT_DESCRIPTION}</p>
<Show when={state.investigationContextSummary()}>
<p class="mt-1 text-xs text-base-content">{state.investigationContextSummary()}</p>
</Show>
diff --git a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
index be40594f36..8f162223e3 100644
--- a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
+++ b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
@@ -21,7 +21,6 @@ import {
} from '@/stores/aiRuntimeState';
import { aiChatStore } from '@/stores/aiChat';
import { notificationStore } from '@/stores/notifications';
-import { hasTriggeringAlert } from '@/utils/findingAlertIdentity';
import { usePatrolStream } from '@/hooks/usePatrolStream';
import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
import { hasFeature, loadRuntimeCapabilities } from '@/stores/license';
@@ -548,12 +547,7 @@ export function usePatrolIntelligenceState() {
});
const selectedRunScopeResourceIds = createMemo(() => getCanonicalScopeResourceIds(selectedRun()));
- const allPatrolFindings = createMemo(() =>
- aiIntelligenceStore.findings.filter(
- (finding) =>
- finding.source !== 'threshold' && !finding.isThreshold && !hasTriggeringAlert(finding),
- ),
- );
+ const allPatrolFindings = createMemo(() => aiIntelligenceStore.patrolFindings);
const selectedRunPatrolFindings = createMemo(() => {
const run = selectedRun();
if (!run) return null;
diff --git a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
index a461174d9c..5e4b61bd68 100644
--- a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
@@ -11,6 +11,7 @@ vi.mock('@/api/ai', () => ({
}));
vi.mock('@/api/patrol', () => ({
+ getPatrolFindings: vi.fn(),
acknowledgeFinding: vi.fn(),
snoozeFinding: vi.fn(),
dismissFinding: vi.fn(),
@@ -31,6 +32,7 @@ vi.mock('@/stores/sessionPresentationPolicy', () => ({
}));
import { AIAPI } from '@/api/ai';
+import { getPatrolFindings } from '@/api/patrol';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import { presentationPolicyIsDemoMode } from '@/stores/sessionPresentationPolicy';
@@ -43,6 +45,7 @@ describe('aiIntelligenceStore', () => {
vi.clearAllMocks();
vi.useRealTimers();
vi.mocked(presentationPolicyIsDemoMode).mockReturnValue(false);
+ vi.mocked(getPatrolFindings).mockResolvedValue([]);
});
it('loads unified findings with canonical alert identity first', async () => {
@@ -101,6 +104,41 @@ describe('aiIntelligenceStore', () => {
});
});
+ it('loads direct Patrol findings for Patrol surfaces', async () => {
+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([
+ {
+ id: 'patrol-finding-1',
+ severity: 'warning',
+ category: 'reliability',
+ resource_id: 'instance:node:100',
+ resource_name: 'vm-100',
+ resource_type: 'vm',
+ title: 'Provider connection issue',
+ description: 'Patrol could not complete provider analysis.',
+ detected_at: '2026-03-01T00:00:00Z',
+ last_seen_at: '2026-03-01T00:05:00Z',
+ auto_resolved: false,
+ alertIdentifier: 'instance:node:100::patrol/provider',
+ times_raised: 1,
+ suppressed: false,
+ investigation_attempts: 0,
+ },
+ ]);
+
+ await aiIntelligenceStore.loadPatrolFindings();
+
+ expect(getPatrolFindings).toHaveBeenCalledTimes(1);
+ expect(aiIntelligenceStore.patrolFindings).toHaveLength(1);
+ expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({
+ id: 'patrol-finding-1',
+ source: 'ai-patrol',
+ isThreshold: false,
+ status: 'active',
+ alertIdentifier: 'instance:node:100::patrol/provider',
+ lastSeenAt: '2026-03-01T00:05:00Z',
+ });
+ });
+
it('loads the canonical intelligence summary', async () => {
vi.mocked(AIAPI.getIntelligenceSummary).mockResolvedValueOnce({
timestamp: '2026-03-01T00:00:00Z',
diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.ts
index 7f7fcc46b9..5e599002e8 100644
--- a/frontend-modern/src/stores/aiIntelligence.ts
+++ b/frontend-modern/src/stores/aiIntelligence.ts
@@ -10,7 +10,14 @@
import { createSignal } from 'solid-js';
import { AIAPI } from '@/api/ai';
-import { acknowledgeFinding, snoozeFinding, dismissFinding, setFindingNote } from '@/api/patrol';
+import {
+ acknowledgeFinding,
+ snoozeFinding,
+ dismissFinding,
+ setFindingNote,
+ getPatrolFindings,
+ type Finding as PatrolFinding,
+} from '@/api/patrol';
import type {
RemediationPlan,
CircuitBreakerStatus,
@@ -94,6 +101,29 @@ function validateSource(value: string | undefined): UnifiedFinding['source'] {
return 'ai-patrol';
}
+type FindingStatusInput = {
+ status?: string;
+ resolved_at?: string;
+ snoozed_until?: string;
+ dismissed_reason?: string;
+ suppressed?: boolean;
+};
+
+function normalizeFindingStatus(item: FindingStatusInput, now: number): UnifiedFinding['status'] {
+ if (
+ item.status === 'active' ||
+ item.status === 'resolved' ||
+ item.status === 'dismissed' ||
+ item.status === 'snoozed'
+ ) {
+ return item.status;
+ }
+ if (item.resolved_at) return 'resolved';
+ if (item.snoozed_until && new Date(item.snoozed_until).getTime() > now) return 'snoozed';
+ if (item.dismissed_reason || item.suppressed) return 'dismissed';
+ return 'active';
+}
+
// ============================================
// Unified Findings
// ============================================
@@ -156,6 +186,84 @@ export interface UnifiedFinding {
const [unifiedFindings, setUnifiedFindings] = createSignal<UnifiedFinding[]>([]);
const [findingsLoading, setFindingsLoading] = createSignal(false);
const [findingsError, setFindingsError] = createSignal<string | null>(null);
+const [patrolFindings, setPatrolFindings] = createSignal<UnifiedFinding[]>([]);
+const [patrolFindingsLoading, setPatrolFindingsLoading] = createSignal(false);
+const [patrolFindingsError, setPatrolFindingsError] = createSignal<string | null>(null);
+
+function normalizeUnifiedFindingRecord(item: UnifiedFindingRecord, now: number): UnifiedFinding {
+ const alertIdentifier = item.alertIdentifier;
+ return {
+ id: item.id,
+ source: validateSource(item.source),
+ resourceId: item.resource_id,
+ resourceName: item.resource_name || item.resource_id,
+ resourceType: item.resource_type || 'unknown',
+ alertIdentifier,
+ isThreshold: Boolean(item.is_threshold || item.source === 'threshold'),
+ category: item.category || 'general',
+ severity: validateSeverity(item.severity),
+ title: item.title,
+ description: item.description,
+ recommendation: item.recommendation,
+ detectedAt: item.detected_at,
+ lastSeenAt: item.last_seen_at || item.detected_at,
+ resolvedAt: item.resolved_at,
+ acknowledgedAt: item.acknowledged_at,
+ snoozedUntil: item.snoozed_until,
+ dismissedReason: item.dismissed_reason,
+ userNote: item.user_note,
+ status: normalizeFindingStatus(item, now),
+ correlatedFindingIds: item.correlated_ids,
+ remediationPlanId: item.remediation_id,
+ investigationSessionId: item.investigation_session_id || '',
+ investigationStatus: validateInvestigationStatus(item.investigation_status),
+ investigationOutcome: validateInvestigationOutcome(item.investigation_outcome),
+ lastInvestigatedAt: item.last_investigated_at || undefined,
+ investigationAttempts: item.investigation_attempts || 0,
+ investigationRecord: item.investigation_record,
+ loopState: item.loop_state || undefined,
+ lifecycle: item.lifecycle || [],
+ timesRaised: item.times_raised || 0,
+ regressionCount: item.regression_count || 0,
+ lastRegressionAt: item.last_regression_at || undefined,
+ };
+}
+
+function normalizePatrolFindingRecord(item: PatrolFinding, now: number): UnifiedFinding {
+ return {
+ id: item.id,
+ source: 'ai-patrol',
+ resourceId: item.resource_id,
+ resourceName: item.resource_name || item.resource_id,
+ resourceType: item.resource_type || 'unknown',
+ alertIdentifier: item.alertIdentifier,
+ isThreshold: false,
+ category: item.category || 'general',
+ severity: validateSeverity(item.severity),
+ title: item.title,
+ description: item.description,
+ recommendation: item.recommendation,
+ detectedAt: item.detected_at,
+ lastSeenAt: item.last_seen_at || item.detected_at,
+ resolvedAt: item.resolved_at,
+ acknowledgedAt: item.acknowledged_at,
+ snoozedUntil: item.snoozed_until,
+ dismissedReason: item.dismissed_reason,
+ userNote: item.user_note,
+ status: normalizeFindingStatus(item, now),
+ investigationSessionId: item.investigation_session_id || '',
+ investigationStatus: validateInvestigationStatus(item.investigation_status),
+ investigationOutcome: validateInvestigationOutcome(item.investigation_outcome),
+ lastInvestigatedAt: item.last_investigated_at || undefined,
+ investigationAttempts: item.investigation_attempts || 0,
+ investigationRecord: item.investigation_record,
+ loopState: item.loop_state || undefined,
+ lifecycle: item.lifecycle || [],
+ timesRaised: item.times_raised || 0,
+ regressionCount: item.regression_count || 0,
+ lastRegressionAt: item.last_regression_at || undefined,
+ };
+}
// ============================================
// Remediation Plans
@@ -226,6 +334,27 @@ function getLivePatrolPendingApprovals() {
return getLivePendingApprovals().filter(isPatrolInvestigationFixApproval);
}
+function getFindingsWithPendingApprovalsFor(findings: UnifiedFinding[]) {
+ const approvals = getLivePatrolPendingApprovals();
+ const approvalOrder = new Map(
+ sortPendingApprovalsByUrgency(approvals).map((approval, index) => [approval.targetId, index]),
+ );
+ return findings
+ .filter((finding) => hasPendingInvestigationFixApproval(finding.id, approvals))
+ .sort(
+ (a, b) =>
+ (approvalOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER) -
+ (approvalOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER),
+ );
+}
+
+function getFindingsNeedingAttentionFor(findings: UnifiedFinding[]) {
+ const approvals = getLivePatrolPendingApprovals();
+ return sortFindingsForAttentionQueue(
+ findings.filter((finding) => doesFindingNeedAttention(finding, approvals)),
+ );
+}
+
// ============================================
// Circuit Breaker
// ============================================
@@ -264,6 +393,16 @@ export const aiIntelligenceStore = {
return findingsError();
},
findingsSignal: unifiedFindings,
+ get patrolFindings() {
+ return patrolFindings();
+ },
+ get patrolFindingsLoading() {
+ return patrolFindingsLoading();
+ },
+ get patrolFindingsError() {
+ return patrolFindingsError();
+ },
+ patrolFindingsSignal: patrolFindings,
async loadFindings() {
setFindingsLoading(true);
@@ -273,59 +412,9 @@ export const aiIntelligenceStore = {
if (!resp) return;
const now = Date.now();
- const findings = (resp.findings || []).map((item: UnifiedFindingRecord): UnifiedFinding => {
- const alertIdentifier = item.alertIdentifier;
- let status = item.status as UnifiedFinding['status'] | undefined;
- if (!status) {
- if (item.resolved_at) {
- status = 'resolved';
- } else if (item.snoozed_until && new Date(item.snoozed_until).getTime() > now) {
- status = 'snoozed';
- } else if (item.dismissed_reason || item.suppressed) {
- status = 'dismissed';
- } else {
- status = 'active';
- }
- }
-
- return {
- id: item.id,
- source: validateSource(item.source),
- resourceId: item.resource_id,
- resourceName: item.resource_name || item.resource_id,
- resourceType: item.resource_type || 'unknown',
- alertIdentifier,
- isThreshold: Boolean(item.is_threshold || item.source === 'threshold'),
- category: item.category || 'general',
- severity: validateSeverity(item.severity),
- title: item.title,
- description: item.description,
- recommendation: item.recommendation,
- detectedAt: item.detected_at,
- lastSeenAt: item.last_seen_at || item.detected_at,
- resolvedAt: item.resolved_at,
- acknowledgedAt: item.acknowledged_at,
- snoozedUntil: item.snoozed_until,
- dismissedReason: item.dismissed_reason,
- userNote: item.user_note,
- status,
- correlatedFindingIds: item.correlated_ids,
- remediationPlanId: item.remediation_id,
- investigationSessionId: item.investigation_session_id || '',
- investigationStatus: validateInvestigationStatus(item.investigation_status),
- investigationOutcome: validateInvestigationOutcome(item.investigation_outcome),
- lastInvestigatedAt: item.last_investigated_at || undefined,
- investigationAttempts: item.investigation_attempts || 0,
- investigationRecord: item.investigation_record,
- loopState: item.loop_state || undefined,
- lifecycle: item.lifecycle || [],
- timesRaised: item.times_raised || 0,
- regressionCount: item.regression_count || 0,
- lastRegressionAt: item.last_regression_at || undefined,
- };
- });
-
- setUnifiedFindings(findings);
+ setUnifiedFindings(
+ (resp.findings || []).map((item) => normalizeUnifiedFindingRecord(item, now)),
+ );
} catch (e) {
logger.error('Failed to load unified findings:', e);
setFindingsError(e instanceof Error ? e.message : 'Failed to load findings');
@@ -334,6 +423,21 @@ export const aiIntelligenceStore = {
}
},
+ async loadPatrolFindings() {
+ setPatrolFindingsLoading(true);
+ setPatrolFindingsError(null);
+ try {
+ const findings = await getPatrolFindings();
+ const now = Date.now();
+ setPatrolFindings(findings.map((item) => normalizePatrolFindingRecord(item, now)));
+ } catch (e) {
+ logger.error('Failed to load Patrol findings:', e);
+ setPatrolFindingsError(e instanceof Error ? e.message : 'Failed to load Patrol findings');
+ } finally {
+ setPatrolFindingsLoading(false);
+ }
+ },
+
// Remediation Plans
get remediationPlans() {
return remediationPlans();
@@ -401,7 +505,7 @@ export const aiIntelligenceStore = {
async acknowledgeFinding(findingId: string) {
try {
await acknowledgeFinding(findingId);
- await this.loadFindings();
+ await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
return true;
} catch (e) {
logger.error('Failed to acknowledge finding:', e);
@@ -412,7 +516,7 @@ export const aiIntelligenceStore = {
async snoozeFinding(findingId: string, durationHours: number) {
try {
await snoozeFinding(findingId, durationHours);
- await this.loadFindings();
+ await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
return true;
} catch (e) {
logger.error('Failed to snooze finding:', e);
@@ -427,7 +531,7 @@ export const aiIntelligenceStore = {
) {
try {
await dismissFinding(findingId, reason, note);
- await this.loadFindings();
+ await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
return true;
} catch (e) {
logger.error('Failed to dismiss finding:', e);
@@ -442,6 +546,9 @@ export const aiIntelligenceStore = {
setUnifiedFindings((prev) =>
prev.map((f) => (f.id === findingId ? { ...f, userNote: note } : f)),
);
+ setPatrolFindings((prev) =>
+ prev.map((f) => (f.id === findingId ? { ...f, userNote: note } : f)),
+ );
return true;
} catch (e) {
logger.error('Failed to set finding note:', e);
@@ -469,29 +576,25 @@ export const aiIntelligenceStore = {
},
get findingsWithPendingApprovals() {
- const approvals = getLivePatrolPendingApprovals();
- const approvalOrder = new Map(
- sortPendingApprovalsByUrgency(approvals).map((approval, index) => [approval.targetId, index]),
- );
- return unifiedFindings()
- .filter((finding) => hasPendingInvestigationFixApproval(finding.id, approvals))
- .sort(
- (a, b) =>
- (approvalOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER) -
- (approvalOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER),
- );
+ return getFindingsWithPendingApprovalsFor(unifiedFindings());
+ },
+ get patrolFindingsWithPendingApprovals() {
+ return getFindingsWithPendingApprovalsFor(patrolFindings());
},
get findingsNeedingAttention() {
- const approvals = getLivePatrolPendingApprovals();
- return sortFindingsForAttentionQueue(
- unifiedFindings().filter((finding) => doesFindingNeedAttention(finding, approvals)),
- );
+ return getFindingsNeedingAttentionFor(unifiedFindings());
+ },
+ get patrolFindingsNeedingAttention() {
+ return getFindingsNeedingAttentionFor(patrolFindings());
},
get needsAttentionCount() {
return this.findingsNeedingAttention.length;
},
+ get patrolNeedsAttentionCount() {
+ return this.patrolFindingsNeedingAttention.length;
+ },
async loadPendingApprovals() {
setApprovalsError(null);
@@ -517,7 +620,7 @@ export const aiIntelligenceStore = {
try {
const result = await AIAPI.approvePendingApproval(approvalId);
await this.loadPendingApprovals();
- await this.loadFindings();
+ await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
return result;
} catch (e) {
logger.error('Failed to approve fix:', e);
@@ -533,7 +636,7 @@ export const aiIntelligenceStore = {
try {
await AIAPI.denyPendingApproval(approvalId, reason);
await this.loadPendingApprovals();
- await this.loadFindings();
+ await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
return true;
} catch (e) {
logger.error('Failed to deny fix:', e);
@@ -575,6 +678,7 @@ export const aiIntelligenceStore = {
await Promise.all([
this.loadIntelligenceSummary(),
this.loadFindings(),
+ this.loadPatrolFindings(),
this.loadCircuitBreakerStatus(),
this.loadPendingApprovals(),
this.loadCorrelations(),
diff --git a/internal/ai/demo.go b/internal/ai/demo.go
index 49aba7bcf6..b425a1e447 100644
--- a/internal/ai/demo.go
+++ b/internal/ai/demo.go
@@ -172,6 +172,7 @@ func (p *PatrolService) injectDemoRunHistory() {
// 1. Most recent run (just happened)
demoRuns = append(demoRuns, PatrolRunRecord{
ID: fmt.Sprintf("demo-run-%d", now.Unix()),
+ Source: PatrolRunSourceDemo,
StartedAt: now.Add(-15 * time.Minute),
CompletedAt: now.Add(-14*time.Minute + 15*time.Second),
Duration: 75 * time.Second,
@@ -229,6 +230,7 @@ func (p *PatrolService) injectDemoRunHistory() {
demoRuns = append(demoRuns, PatrolRunRecord{
ID: fmt.Sprintf("demo-run-%d", startTime.Unix()),
+ Source: PatrolRunSourceDemo,
StartedAt: startTime,
CompletedAt: startTime.Add(duration),
Duration: duration,
diff --git a/internal/ai/demo_test.go b/internal/ai/demo_test.go
index 0a6d960535..a229e223c5 100644
--- a/internal/ai/demo_test.go
+++ b/internal/ai/demo_test.go
@@ -3,6 +3,7 @@ package ai
import (
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/mockruntime"
)
@@ -49,6 +50,113 @@ func TestPatrolService_InjectDemoRunHistory_NoStore(t *testing.T) {
service.injectDemoRunHistory()
}
+func TestPatrolRunHistoryFiltersDemoEvidenceOutsideDemoMode(t *testing.T) {
+ original := mockruntime.IsEnabled()
+ t.Cleanup(func() { mockruntime.SetEnabled(original) })
+ mockruntime.SetEnabled(false)
+
+ service := NewPatrolService(nil, nil)
+ now := time.Date(2026, 5, 8, 10, 0, 0, 0, time.UTC)
+ service.runHistoryStore.Add(PatrolRunRecord{
+ ID: "live-run-1",
+ StartedAt: now.Add(-15 * time.Minute),
+ CompletedAt: now.Add(-14 * time.Minute),
+ Type: "patrol",
+ ResourcesChecked: 12,
+ FindingsSummary: "No issues found",
+ FindingIDs: []string{},
+ Status: "healthy",
+ })
+ service.runHistoryStore.Add(PatrolRunRecord{
+ ID: "demo-run-legacy",
+ StartedAt: now.Add(-5 * time.Minute),
+ CompletedAt: now.Add(-4 * time.Minute),
+ Type: "patrol",
+ ResourcesChecked: 47,
+ ExistingFindings: 5,
+ FindingsSummary: "2 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical"},
+ Status: "issues_found",
+ })
+
+ runs := service.GetRunHistory(1)
+ if len(runs) != 1 {
+ t.Fatalf("expected one live run after filtering demo evidence, got %d", len(runs))
+ }
+ if runs[0].ID != "live-run-1" {
+ t.Fatalf("expected live-run-1 after filtering demo evidence, got %q", runs[0].ID)
+ }
+ if _, ok := service.GetRunByID("demo-run-legacy"); ok {
+ t.Fatal("expected legacy demo run lookup to be hidden outside demo mode")
+ }
+}
+
+func TestPatrolRunHistoryKeepsDemoEvidenceInDemoMode(t *testing.T) {
+ original := mockruntime.IsEnabled()
+ t.Cleanup(func() { mockruntime.SetEnabled(original) })
+ mockruntime.SetEnabled(true)
+
+ service := NewPatrolService(nil, nil)
+ now := time.Date(2026, 5, 8, 10, 0, 0, 0, time.UTC)
+ service.runHistoryStore.Add(PatrolRunRecord{
+ ID: "live-run-1",
+ StartedAt: now.Add(-15 * time.Minute),
+ CompletedAt: now.Add(-14 * time.Minute),
+ Type: "patrol",
+ ResourcesChecked: 12,
+ FindingsSummary: "No issues found",
+ FindingIDs: []string{},
+ Status: "healthy",
+ })
+ service.runHistoryStore.Add(PatrolRunRecord{
+ ID: "demo-run-1",
+ Source: PatrolRunSourceDemo,
+ StartedAt: now.Add(-5 * time.Minute),
+ CompletedAt: now.Add(-4 * time.Minute),
+ Type: "patrol",
+ ResourcesChecked: 47,
+ ExistingFindings: 5,
+ FindingsSummary: "2 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical"},
+ Status: "issues_found",
+ })
+
+ runs := service.GetRunHistory(1)
+ if len(runs) != 1 {
+ t.Fatalf("expected one run, got %d", len(runs))
+ }
+ if runs[0].ID != "demo-run-1" || runs[0].Source != PatrolRunSourceDemo {
+ t.Fatalf("expected current demo run in demo mode, got %+v", runs[0])
+ }
+ if _, ok := service.GetRunByID("demo-run-1"); !ok {
+ t.Fatal("expected demo run lookup to be available in demo mode")
+ }
+}
+
+func TestPatrolCoverageIgnoresPersistedDemoRunsOutsideDemoMode(t *testing.T) {
+ original := mockruntime.IsEnabled()
+ t.Cleanup(func() { mockruntime.SetEnabled(original) })
+ mockruntime.SetEnabled(false)
+
+ now := time.Date(2026, 5, 8, 10, 0, 0, 0, time.UTC)
+ store := NewPatrolRunHistoryStore(10)
+ store.Add(PatrolRunRecord{
+ ID: "demo-run-legacy",
+ StartedAt: now.Add(-5 * time.Minute),
+ CompletedAt: now.Add(-4 * time.Minute),
+ Type: "patrol",
+ ResourcesChecked: 47,
+ ErrorCount: 1,
+ Status: "error",
+ FindingsSummary: "2 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical"},
+ })
+
+ if factor, ok := summarizeRecentPatrolCoverage(store, now); ok {
+ t.Fatalf("expected persisted demo run to be excluded from coverage scoring, got %+v", factor)
+ }
+}
+
func TestGenerateDemoAIResponse(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/ai/intelligence.go b/internal/ai/intelligence.go
index 210fad680d..830c745328 100644
--- a/internal/ai/intelligence.go
+++ b/internal/ai/intelligence.go
@@ -1054,7 +1054,10 @@ func summarizeRecentPatrolCoverage(
return patrolCoverageFactor{}, false
}
- recentRuns := runHistoryStore.GetRecent(intelligenceRecentRunLimit)
+ recentRuns := limitPatrolRunRecords(
+ filterPatrolRunRecordsForRuntimeEvidence(runHistoryStore.GetAll()),
+ intelligenceRecentRunLimit,
+ )
if len(recentRuns) == 0 {
return patrolCoverageFactor{}, false
}
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index 2a017ee5d2..f08502ceea 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -110,6 +110,7 @@ type PatrolStatus struct {
// PatrolRunRecord represents a single patrol check run
type PatrolRunRecord struct {
ID string `json:"id"`
+ Source string `json:"source,omitempty"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
Duration time.Duration `json:"-"`
@@ -159,6 +160,7 @@ type PatrolRunRecord struct {
type patrolRunRecordJSON struct {
ID string `json:"id"`
+ Source string `json:"source,omitempty"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
DurationMs int64 `json:"duration_ms"`
@@ -227,6 +229,7 @@ func canonicalPatrolFindingIDs(ids []string) []string {
}
func normalizePatrolRunRecord(record PatrolRunRecord) PatrolRunRecord {
+ record.Source = normalizePatrolRunSource(record.Source)
record.AlertIdentifier = canonicalPatrolAlertIdentifier(record.AlertIdentifier)
record.FindingIDs = canonicalPatrolFindingIDs(record.FindingIDs)
record.ErrorSummary = strings.TrimSpace(redactPatrolRuntimeFailureDetail(record.ErrorSummary))
@@ -236,10 +239,52 @@ func normalizePatrolRunRecord(record PatrolRunRecord) PatrolRunRecord {
return record
}
+const PatrolRunSourceDemo = "demo"
+
+func normalizePatrolRunSource(source string) string {
+ return strings.ToLower(strings.TrimSpace(source))
+}
+
+func isDemoPatrolRunRecord(record PatrolRunRecord) bool {
+ if normalizePatrolRunSource(record.Source) == PatrolRunSourceDemo {
+ return true
+ }
+ return strings.HasPrefix(strings.ToLower(strings.TrimSpace(record.ID)), "demo-run-")
+}
+
+func filterPatrolRunRecordsForRuntimeEvidence(records []PatrolRunRecord) []PatrolRunRecord {
+ if IsDemoMode() || len(records) == 0 {
+ return records
+ }
+
+ filtered := make([]PatrolRunRecord, 0, len(records))
+ for _, record := range records {
+ if isDemoPatrolRunRecord(record) {
+ continue
+ }
+ filtered = append(filtered, record)
+ }
+ return filtered
+}
+
+func limitPatrolRunRecords(records []PatrolRunRecord, limit int) []PatrolRunRecord {
+ if limit <= 0 || len(records) == 0 {
+ return records
+ }
+ if limit > MaxPatrolRunHistory {
+ limit = MaxPatrolRunHistory
+ }
+ if limit > len(records) {
+ limit = len(records)
+ }
+ return records[:limit]
+}
+
func (r PatrolRunRecord) MarshalJSON() ([]byte, error) {
normalized := normalizePatrolRunRecord(r)
return json.Marshal(patrolRunRecordJSON{
ID: normalized.ID,
+ Source: normalized.Source,
StartedAt: normalized.StartedAt,
CompletedAt: normalized.CompletedAt,
DurationMs: normalized.DurationMs,
@@ -290,6 +335,7 @@ func (r *PatrolRunRecord) UnmarshalJSON(data []byte) error {
*r = normalizePatrolRunRecord(PatrolRunRecord{
ID: payload.ID,
+ Source: payload.Source,
StartedAt: payload.StartedAt,
CompletedAt: payload.CompletedAt,
Duration: time.Duration(payload.DurationMs) * time.Millisecond,
diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.go
index a672d5f221..ea54bca762 100644
--- a/internal/ai/patrol_findings.go
+++ b/internal/ai/patrol_findings.go
@@ -609,10 +609,8 @@ func (p *PatrolService) DismissFinding(findingID string, reason string, note str
// GetRunHistory returns the history of patrol runs
// If limit is > 0, returns at most that many records
func (p *PatrolService) GetRunHistory(limit int) []PatrolRunRecord {
- if limit <= 0 {
- return p.runHistoryStore.GetAll()
- }
- return p.runHistoryStore.GetRecent(limit)
+ runs := filterPatrolRunRecordsForRuntimeEvidence(p.runHistoryStore.GetAll())
+ return limitPatrolRunRecords(runs, limit)
}
// GetRunByID returns a single patrol run from history.
@@ -620,7 +618,14 @@ func (p *PatrolService) GetRunByID(id string) (PatrolRunRecord, bool) {
if strings.TrimSpace(id) == "" {
return PatrolRunRecord{}, false
}
- return p.runHistoryStore.GetByID(id)
+ run, ok := p.runHistoryStore.GetByID(id)
+ if !ok {
+ return PatrolRunRecord{}, false
+ }
+ if !IsDemoMode() && isDemoPatrolRunRecord(run) {
+ return PatrolRunRecord{}, false
+ }
+ return run, true
}
// GetAllFindings returns all active findings sorted by severity
diff --git a/internal/ai/patrol_history_persistence.go b/internal/ai/patrol_history_persistence.go
index b4d2e1b078..842ca59175 100644
--- a/internal/ai/patrol_history_persistence.go
+++ b/internal/ai/patrol_history_persistence.go
@@ -28,15 +28,19 @@ func NewPatrolHistoryPersistenceAdapter(cfg *config.ConfigPersistence) *PatrolHi
// SavePatrolRunHistory saves patrol run history to disk via ConfigPersistence
func (a *PatrolHistoryPersistenceAdapter) SavePatrolRunHistory(runs []PatrolRunRecord) error {
// Convert from ai.PatrolRunRecord to config.PatrolRunRecord
- records := make([]config.PatrolRunRecord, len(runs))
- for i, r := range runs {
+ records := make([]config.PatrolRunRecord, 0, len(runs))
+ for _, r := range runs {
normalized := normalizePatrolRunRecord(r)
+ if isDemoPatrolRunRecord(normalized) {
+ continue
+ }
durationMs := normalized.DurationMs
if durationMs == 0 && normalized.Duration > 0 {
durationMs = int64(normalized.Duration / time.Millisecond)
}
- records[i] = config.PatrolRunRecord{
+ records = append(records, config.PatrolRunRecord{
ID: normalized.ID,
+ Source: normalized.Source,
StartedAt: normalized.StartedAt,
CompletedAt: normalized.CompletedAt,
DurationMs: durationMs,
@@ -76,7 +80,7 @@ func (a *PatrolHistoryPersistenceAdapter) SavePatrolRunHistory(runs []PatrolRunR
OutputTokens: normalized.OutputTokens,
ToolCalls: convertAIToolCallsToConfig(normalized.ToolCalls),
ToolCallCount: normalized.ToolCallCount,
- }
+ })
}
return a.config.SavePatrolRunHistory(records)
}
@@ -90,10 +94,11 @@ func (a *PatrolHistoryPersistenceAdapter) LoadPatrolRunHistory() ([]PatrolRunRec
// Convert from config.PatrolRunRecord to ai.PatrolRunRecord
runCount := clampHistoryCount(len(data.Runs), 0, MaxPatrolRunHistory)
- runs := make([]PatrolRunRecord, runCount)
- for i, r := range data.Runs[:runCount] {
- runs[i] = normalizePatrolRunRecord(PatrolRunRecord{
+ runs := make([]PatrolRunRecord, 0, runCount)
+ for _, r := range data.Runs[:runCount] {
+ run := normalizePatrolRunRecord(PatrolRunRecord{
ID: r.ID,
+ Source: r.Source,
StartedAt: r.StartedAt,
CompletedAt: r.CompletedAt,
Duration: time.Duration(r.DurationMs) * time.Millisecond, // Convert milliseconds to nanoseconds
@@ -135,6 +140,10 @@ func (a *PatrolHistoryPersistenceAdapter) LoadPatrolRunHistory() ([]PatrolRunRec
ToolCalls: convertConfigToolCallsToAI(r.ToolCalls),
ToolCallCount: r.ToolCallCount,
})
+ if !IsDemoMode() && isDemoPatrolRunRecord(run) {
+ continue
+ }
+ runs = append(runs, run)
}
return runs, nil
}
diff --git a/internal/ai/patrol_history_persistence_test.go b/internal/ai/patrol_history_persistence_test.go
index fafd6381ae..b0c5a49529 100644
--- a/internal/ai/patrol_history_persistence_test.go
+++ b/internal/ai/patrol_history_persistence_test.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mockruntime"
)
// mockPatrolHistoryPersistence implements PatrolHistoryPersistence for testing
@@ -267,6 +268,119 @@ func TestPatrolHistoryPersistenceAdapter_NormalizesAlertIdentity(t *testing.T) {
}
}
+func TestPatrolHistoryPersistenceAdapter_DoesNotPersistDemoRuns(t *testing.T) {
+ tmp := t.TempDir()
+ persistence := config.NewConfigPersistence(tmp)
+ adapter := NewPatrolHistoryPersistenceAdapter(persistence)
+ now := time.Date(2026, 5, 8, 10, 0, 0, 0, time.UTC)
+
+ runs := []PatrolRunRecord{
+ {
+ ID: "live-run-1",
+ StartedAt: now.Add(-10 * time.Minute),
+ CompletedAt: now.Add(-9 * time.Minute),
+ Type: "patrol",
+ FindingsSummary: "No issues found",
+ FindingIDs: []string{},
+ Status: "healthy",
+ ResourcesChecked: 4,
+ },
+ {
+ ID: "demo-run-current",
+ Source: PatrolRunSourceDemo,
+ StartedAt: now.Add(-5 * time.Minute),
+ CompletedAt: now.Add(-4 * time.Minute),
+ Type: "patrol",
+ FindingsSummary: "2 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical"},
+ Status: "issues_found",
+ ResourcesChecked: 47,
+ },
+ {
+ ID: "demo-run-legacy",
+ StartedAt: now.Add(-3 * time.Minute),
+ CompletedAt: now.Add(-2 * time.Minute),
+ Type: "patrol",
+ FindingsSummary: "2 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical"},
+ Status: "issues_found",
+ ResourcesChecked: 47,
+ },
+ }
+
+ if err := adapter.SavePatrolRunHistory(runs); err != nil {
+ t.Fatalf("save patrol run history: %v", err)
+ }
+
+ persisted, err := persistence.LoadPatrolRunHistory()
+ if err != nil {
+ t.Fatalf("load raw patrol run history: %v", err)
+ }
+ if len(persisted.Runs) != 1 {
+ t.Fatalf("expected one persisted live run, got %d", len(persisted.Runs))
+ }
+ if persisted.Runs[0].ID != "live-run-1" {
+ t.Fatalf("expected persisted live run, got %q", persisted.Runs[0].ID)
+ }
+}
+
+func TestPatrolHistoryPersistenceAdapter_PrunesDemoRunsOnLoadOutsideDemoMode(t *testing.T) {
+ original := mockruntime.IsEnabled()
+ t.Cleanup(func() { mockruntime.SetEnabled(original) })
+ mockruntime.SetEnabled(false)
+
+ tmp := t.TempDir()
+ persistence := config.NewConfigPersistence(tmp)
+ now := time.Date(2026, 5, 8, 10, 0, 0, 0, time.UTC)
+ if err := persistence.SavePatrolRunHistory([]config.PatrolRunRecord{
+ {
+ ID: "live-run-1",
+ StartedAt: now.Add(-10 * time.Minute),
+ CompletedAt: now.Add(-9 * time.Minute),
+ Type: "patrol",
+ FindingsSummary: "No issues found",
+ FindingIDs: []string{},
+ Status: "healthy",
+ ResourcesChecked: 4,
+ },
+ {
+ ID: "demo-run-source",
+ Source: PatrolRunSourceDemo,
+ StartedAt: now.Add(-5 * time.Minute),
+ CompletedAt: now.Add(-4 * time.Minute),
+ Type: "patrol",
+ FindingsSummary: "2 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical"},
+ Status: "issues_found",
+ ResourcesChecked: 47,
+ },
+ {
+ ID: "demo-run-legacy",
+ StartedAt: now.Add(-3 * time.Minute),
+ CompletedAt: now.Add(-2 * time.Minute),
+ Type: "patrol",
+ FindingsSummary: "2 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical"},
+ Status: "issues_found",
+ ResourcesChecked: 47,
+ },
+ }); err != nil {
+ t.Fatalf("save raw patrol run history: %v", err)
+ }
+
+ adapter := NewPatrolHistoryPersistenceAdapter(persistence)
+ loaded, err := adapter.LoadPatrolRunHistory()
+ if err != nil {
+ t.Fatalf("load patrol run history: %v", err)
+ }
+ if len(loaded) != 1 {
+ t.Fatalf("expected one live run after pruning demo runs, got %d", len(loaded))
+ }
+ if loaded[0].ID != "live-run-1" {
+ t.Fatalf("expected live-run-1 after pruning demo runs, got %q", loaded[0].ID)
+ }
+}
+
func TestPatrolHistoryPersistenceAdapter_LoadPatrolRunHistoryCapsRuns(t *testing.T) {
records := make([]config.PatrolRunRecord, MaxPatrolRunHistory+10)
for i := range records {
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 50ae1e1b9d..47fe76bbc8 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -2473,6 +2473,7 @@ type PatrolRunHistoryData struct {
// PatrolRunRecord represents a single patrol check run
type PatrolRunRecord struct {
ID string `json:"id"`
+ Source string `json:"source,omitempty"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
DurationMs int64 `json:"duration_ms"`
@@ -2521,6 +2522,7 @@ type PatrolRunRecord struct {
type patrolRunRecordJSON struct {
ID string `json:"id"`
+ Source string `json:"source,omitempty"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
DurationMs int64 `json:"duration_ms"`
@@ -2589,6 +2591,7 @@ func canonicalPatrolFindingIDs(ids []string) []string {
}
func normalizePatrolRunRecord(record PatrolRunRecord) PatrolRunRecord {
+ record.Source = strings.ToLower(strings.TrimSpace(record.Source))
alertIdentifier := canonicalPatrolAlertIdentifier(record.AlertIdentifier)
record.AlertIdentifier = alertIdentifier
record.FindingIDs = canonicalPatrolFindingIDs(record.FindingIDs)
@@ -2600,6 +2603,7 @@ func (r PatrolRunRecord) MarshalJSON() ([]byte, error) {
alertIdentifier := strings.TrimSpace(normalized.AlertIdentifier)
return json.Marshal(patrolRunRecordJSON{
ID: normalized.ID,
+ Source: normalized.Source,
StartedAt: normalized.StartedAt,
CompletedAt: normalized.CompletedAt,
DurationMs: normalized.DurationMs,
@@ -2651,6 +2655,7 @@ func (r *PatrolRunRecord) UnmarshalJSON(data []byte) error {
alertIdentifier := canonicalPatrolAlertIdentifier(payload.AlertIdentifier)
*r = PatrolRunRecord{
ID: payload.ID,
+ Source: strings.ToLower(strings.TrimSpace(payload.Source)),
StartedAt: payload.StartedAt,
CompletedAt: payload.CompletedAt,
DurationMs: payload.DurationMs,
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index ab92d15bad..96b688f182 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3627,7 +3627,7 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Shared Boundaries",
"path": "internal/api/access_control_handlers.go",
- "line": 191,
+ "line": 195,
"heading_line": 106,
}
],