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.

Add resource priority to Patrol queue

rcourtman229867636d54
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 87a141ea98..c8d2f23026 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -3989,9 +3989,13 @@ wires the adapter at startup, projecting
`unified.ResourceOperatorState` into the
`ResourceOperatorStateProjection` shape the findings runtime
consumes. The projection carries every operator-set signal in one
-call (active maintenance window plus the `IntentionallyOffline`
-flag) so adding new signals later does not multiply round-trips per
-finding.
+call (active maintenance window, `IntentionallyOffline`,
+`NeverAutoRemediate`, and `Criticality`) so adding new signals later does
+not multiply round-trips per finding. `FindingsStore.Add` stamps
+`Finding.ResourceCriticality` from that projection on new and re-detected
+findings. The field persists as `resource_criticality` and may affect
+same-severity Patrol attention ordering only; it must not mutate
+`Finding.Severity` or bypass severity escalation/resolution rules.
The approval store exposes `SetOnApprovalCreated(cb)` so the API
layer can install a fire-and-forget callback that runs after every
@@ -4039,13 +4043,13 @@ the situated picture, and it can avoid proposing fixes the
operator has locked the resource against.
`ResourceOperatorStateProjection` carries `NeverAutoRemediate`
-alongside `IntentionallyOffline` and `MaintenanceWindow` so the
+and `Criticality` alongside `IntentionallyOffline` and `MaintenanceWindow` so the
investigation read path and the suppression read path share a
single projection. The findings store exposes the projection via
`OperatorStateProjectionFor`; the suppression hot path keeps its
existing internal access. Both paths see the same operator-state
-facts so investigation reasoning and suppression behavior cannot
-drift against each other.
+facts so investigation reasoning, suppression behavior, and Patrol
+priority stamping cannot drift against each other.
A cross-slice consequence worth pinning: operator-state-suppressed
findings (auto-dismissed with `DismissedReason="expected_behavior"`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 33006709fd..d66287f06e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -838,6 +838,12 @@ payload shape change when the portal presents compact client rows.
`/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.
+ The Patrol findings payload carries optional `resource_criticality`
+ (`high`, `medium`, `low`, or omitted/empty default) stamped from
+ `/api/resources/{id}/operator-state`. It is a resource priority
+ tie-breaker for same-severity Patrol work, not a severity override; the
+ frontend client mirrors it on both `Finding` and `UnifiedFindingRecord`
+ and normalizes it to `UnifiedFinding.resourceCriticality`.
The Patrol findings payload carries `capacity_forecast` as a structured
deterministic field (`current_pct`, `daily_change`, `days_to_full`) on
capacity-relevant findings whose resource has enough utilization history to
@@ -3606,7 +3612,12 @@ at startup: `internal/api/router.go` calls
`ResourceOperatorStateProviderFunc` closure that reads the unified
store and returns a `ResourceOperatorStateProjection` carrying every
operator-set signal in one call (maintenance window via
-`state.IsInMaintenanceAt` plus the `IntentionallyOffline` flag).
+`state.IsInMaintenanceAt`, the `IntentionallyOffline` flag, and the
+`Criticality` hint). The same router setup also calls
+`SetResourceStoreProvider(r.resourceHandlers.getStore)` on the AI settings
+handler so `/api/ai/patrol/findings` can refresh `resource_criticality` at
+read time after an operator changes priority, without waiting for the next
+Patrol detection to re-stamp stored findings.
This keeps `internal/ai` free of an `internal/unifiedresources`
import while giving the findings runtime full per-resource
suppression without each org needing a separate adapter declaration
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 2972479b34..1f1c03c6e2 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -786,6 +786,16 @@ fix`, or `Explain` based on current finding state), while secondary
subsequent Patrol finding loads continue to request include-resolved history
with the 200-item history limit instead of unbounded historical payloads or
a transient active-only refresh.
+ Resource operator priority is a Patrol attention-queue tie-breaker, not a
+ second queue model and not a severity rewrite. `resource_criticality` from
+ the Patrol findings API normalizes to `UnifiedFinding.resourceCriticality`;
+ `sortFindingsForAttentionQueue` may order same-severity findings by
+ high/medium/default/low before runtime and recency, but severity,
+ investigation outcome, approval state, and the direct Patrol findings source
+ remain the canonical current-work model. The operator edits that priority
+ and the associated note from `ResourceOperatorStateSection` on the resource
+ detail drawer, alongside maintenance/offline/remediation-lock state, so the
+ drawer stays the single resource-level Patrol intent surface.
The TS API client mirrors (`UnifiedFindingRecord.impact`,
`Finding.impact`) and the store normalizers
(`normalizeUnifiedFindingRecord`, `normalizePatrolFindingRecord`) must
diff --git a/frontend-modern/src/api/ai.ts b/frontend-modern/src/api/ai.ts
index f0661b3c81..b10ae6f4cf 100644
--- a/frontend-modern/src/api/ai.ts
+++ b/frontend-modern/src/api/ai.ts
@@ -419,6 +419,7 @@ export interface UnifiedFindingRecord {
resource_id: string;
resource_name: string;
resource_type: string;
+ resource_criticality?: 'high' | 'medium' | 'low' | '';
node?: string;
title: string;
description: string;
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index 28f7d12616..e5b1287178 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -6,6 +6,7 @@
import { apiFetchJSON } from '@/utils/apiClient';
import { arrayOrEmpty, promoteLegacyAlertIdentifier } from './responseUtils';
import type { InvestigationRecord } from './ai';
+import type { ResourceCriticality } from './resourceOperatorState';
export type FindingSeverity = 'info' | 'watch' | 'warning' | 'critical';
export type FindingCategory =
@@ -24,6 +25,7 @@ export interface Finding {
resource_id: string;
resource_name: string;
resource_type: string; // node, vm, system-container, app-container, storage, pbs, host_raid
+ resource_criticality?: ResourceCriticality;
node?: string;
title: string;
description: string;
@@ -774,8 +776,7 @@ export async function triggerPatrolRun(
scope?: PatrolRunScope,
): Promise<{ success: boolean; message: string }> {
const hasScope =
- !!scope &&
- ((scope.resource_ids?.length ?? 0) > 0 || (scope.resource_types?.length ?? 0) > 0);
+ !!scope && ((scope.resource_ids?.length ?? 0) > 0 || (scope.resource_types?.length ?? 0) > 0);
return apiFetchJSON('/api/ai/patrol/run', {
method: 'POST',
...(hasScope
diff --git a/frontend-modern/src/api/resourceOperatorState.ts b/frontend-modern/src/api/resourceOperatorState.ts
index 3afcb4a357..460eac440c 100644
--- a/frontend-modern/src/api/resourceOperatorState.ts
+++ b/frontend-modern/src/api/resourceOperatorState.ts
@@ -7,6 +7,8 @@ import { apiFetchJSON } from '@/utils/apiClient';
* evolution. See the patrol-intelligence and ai-runtime subsystem contracts
* for the suppression / refusal semantics each field drives.
*/
+export type ResourceCriticality = 'high' | 'medium' | 'low' | '';
+
export interface ResourceOperatorState {
canonicalId: string;
/**
@@ -37,7 +39,7 @@ export interface ResourceOperatorState {
* Optional operator hint that affects finding sort order. One of
* `'high' | 'medium' | 'low' | ''` (empty = default).
*/
- criticality?: 'high' | 'medium' | 'low' | '';
+ criticality?: ResourceCriticality;
note?: string;
setAt: string;
setBy?: string;
@@ -70,7 +72,12 @@ export async function getResourceOperatorState(
// The 404 response shape is `{ error: 'operator_state_not_set', ... }`.
// Translating into null lets the caller treat "no state" as a clean
// default rather than a thrown error.
- if (err && typeof err === 'object' && 'status' in err && (err as { status: number }).status === 404) {
+ if (
+ err &&
+ typeof err === 'object' &&
+ 'status' in err &&
+ (err as { status: number }).status === 404
+ ) {
return null;
}
throw err;
@@ -102,8 +109,7 @@ export async function setResourceOperatorState(
* cleanly whether or not an entry was present.
*/
export async function clearResourceOperatorState(resourceId: string): Promise<void> {
- await apiFetchJSON(
- `/api/resources/${encodeURIComponent(resourceId)}/operator-state`,
- { method: 'DELETE' },
- );
+ await apiFetchJSON(`/api/resources/${encodeURIComponent(resourceId)}/operator-state`, {
+ method: 'DELETE',
+ });
}
diff --git a/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx b/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx
index 8c011dafab..355c26219e 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx
@@ -2,6 +2,7 @@ import { Component, Show, createEffect, createMemo, createSignal } from 'solid-j
import { Toggle } from '@/components/shared/Toggle';
import { notificationStore } from '@/stores/notifications';
import {
+ type ResourceCriticality,
type ResourceOperatorState,
type ResourceOperatorStateInput,
clearResourceOperatorState,
@@ -60,6 +61,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
// or Discard.
const [intentionallyOffline, setIntentionallyOffline] = createSignal(false);
const [neverAutoRemediate, setNeverAutoRemediate] = createSignal(false);
+ const [criticality, setCriticality] = createSignal<ResourceCriticality>('');
+ const [note, setNote] = createSignal('');
const [saving, setSaving] = createSignal(false);
const [confirmingLock, setConfirmingLock] = createSignal(false);
@@ -80,6 +83,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
if (current === undefined) return;
setIntentionallyOffline(current?.intentionallyOffline ?? false);
setNeverAutoRemediate(current?.neverAutoRemediate ?? false);
+ setCriticality(current?.criticality ?? '');
+ setNote(current?.note ?? '');
setConfirmingLock(false);
});
@@ -87,12 +92,18 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
const current = persisted();
const persistedOffline = current?.intentionallyOffline ?? false;
const persistedLocked = current?.neverAutoRemediate ?? false;
+ const persistedCriticality = current?.criticality ?? '';
+ const persistedNote = current?.note ?? '';
return (
intentionallyOffline() !== persistedOffline ||
- neverAutoRemediate() !== persistedLocked
+ neverAutoRemediate() !== persistedLocked ||
+ criticality() !== persistedCriticality ||
+ note().trim() !== persistedNote
);
});
+ const noteForSave = () => note().trim() || undefined;
+
// The lock toggle is a safety override — confirm before flipping to
// true. Flipping back to false from true is just a release and does
// not need confirmation.
@@ -121,14 +132,13 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
intentionallyOffline: intentionallyOffline(),
neverAutoRemediate: neverAutoRemediate(),
// Preserve any maintenance-window data the API currently holds
- // — this slice owns toggles only; window scheduling is a
- // separate slice and clobbering it on save would surprise the
- // operator.
+ // — window scheduling is a separate action and clobbering it
+ // on save would surprise the operator.
maintenanceStartAt: current?.maintenanceStartAt,
maintenanceEndAt: current?.maintenanceEndAt,
maintenanceReason: current?.maintenanceReason,
- criticality: current?.criticality,
- note: current?.note,
+ criticality: criticality(),
+ note: noteForSave(),
};
await setResourceOperatorState(props.resourceId, input);
// Refresh from server so the section displays the persisted
@@ -148,6 +158,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
const current = persisted();
setIntentionallyOffline(current?.intentionallyOffline ?? false);
setNeverAutoRemediate(current?.neverAutoRemediate ?? false);
+ setCriticality(current?.criticality ?? '');
+ setNote(current?.note ?? '');
setConfirmingLock(false);
};
@@ -161,6 +173,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
await query.refetch();
setIntentionallyOffline(false);
setNeverAutoRemediate(false);
+ setCriticality('');
+ setNote('');
notificationStore.success('Operator overrides cleared');
} catch (err) {
notificationStore.error(
@@ -198,8 +212,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
return current;
});
- const hasAnyMaintenanceWindow = createMemo(
- () => Boolean(activeMaintenanceWindow() || scheduledMaintenanceWindow()),
+ const hasAnyMaintenanceWindow = createMemo(() =>
+ Boolean(activeMaintenanceWindow() || scheduledMaintenanceWindow()),
);
// Datetime-local input format is "YYYY-MM-DDTHH:mm" in the browser's
@@ -264,7 +278,6 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
}
setSaving(true);
try {
- const current = persisted();
const input: ResourceOperatorStateInput = {
// Keep the toggle state intact when scheduling — operator
// editing one facet must not lose work on the other.
@@ -273,8 +286,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
maintenanceStartAt: start.toISOString(),
maintenanceEndAt: end.toISOString(),
maintenanceReason: scheduleReason().trim() || undefined,
- criticality: current?.criticality,
- note: current?.note,
+ criticality: criticality(),
+ note: noteForSave(),
};
await setResourceOperatorState(props.resourceId, input);
await query.refetch();
@@ -292,15 +305,14 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
const handleClearMaintenanceWindow = async () => {
setSaving(true);
try {
- const current = persisted();
const input: ResourceOperatorStateInput = {
intentionallyOffline: intentionallyOffline(),
neverAutoRemediate: neverAutoRemediate(),
maintenanceStartAt: undefined,
maintenanceEndAt: undefined,
maintenanceReason: undefined,
- criticality: current?.criticality,
- note: current?.note,
+ criticality: criticality(),
+ note: noteForSave(),
};
await setResourceOperatorState(props.resourceId, input);
await query.refetch();
@@ -316,13 +328,16 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
};
return (
- <section class="rounded-md border border-border bg-surface p-4 space-y-3" aria-label="Operator overrides">
+ <section
+ class="rounded-md border border-border bg-surface p-4 space-y-3"
+ aria-label="Operator overrides"
+ >
<header class="flex items-center justify-between">
<div>
<h3 class="text-sm font-semibold text-base-content">Operator overrides</h3>
<p class="text-xs text-muted">
- Tell Pulse how to treat this resource — suppress expected noise, or lock it against
- automated remediation.
+ Tell Pulse how Patrol should treat this resource — suppress expected noise, prioritize
+ its findings, or lock it against automated remediation.
</p>
</div>
<Show when={persisted()?.setBy || persisted()?.setAt}>
@@ -339,8 +354,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
<Show when={activeMaintenanceWindow()}>
<div class="rounded border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-800 dark:bg-amber-900 dark:text-amber-200">
- <span class="font-semibold">Maintenance window active.</span>{' '}
- Findings raised on this resource are auto-acknowledged until{' '}
+ <span class="font-semibold">Maintenance window active.</span> Findings raised on this
+ resource are auto-acknowledged until{' '}
{formatRelativeTime(activeMaintenanceWindow()!.maintenanceEndAt!, { compact: true })}.
<Show when={activeMaintenanceWindow()!.maintenanceReason}>
<span class="block mt-0.5">Reason: {activeMaintenanceWindow()!.maintenanceReason}</span>
@@ -350,17 +365,51 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
<Show when={scheduledMaintenanceWindow() && !activeMaintenanceWindow()}>
<div class="rounded border border-blue-200 bg-blue-50 px-3 py-2 text-xs text-blue-800 dark:border-blue-800 dark:bg-blue-900 dark:text-blue-200">
- <span class="font-semibold">Maintenance window scheduled.</span>{' '}
- Auto-acknowledgement will start{' '}
+ <span class="font-semibold">Maintenance window scheduled.</span> Auto-acknowledgement will
+ start{' '}
{formatRelativeTime(scheduledMaintenanceWindow()!.maintenanceStartAt!, { compact: true })}{' '}
and end{' '}
{formatRelativeTime(scheduledMaintenanceWindow()!.maintenanceEndAt!, { compact: true })}.
<Show when={scheduledMaintenanceWindow()!.maintenanceReason}>
- <span class="block mt-0.5">Reason: {scheduledMaintenanceWindow()!.maintenanceReason}</span>
+ <span class="block mt-0.5">
+ Reason: {scheduledMaintenanceWindow()!.maintenanceReason}
+ </span>
</Show>
</div>
</Show>
+ <div class="grid grid-cols-1 gap-3 pt-2 border-t border-border-subtle sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)]">
+ <label class="block">
+ <span class="text-sm font-medium text-base-content">Patrol priority</span>
+ <select
+ value={criticality()}
+ onChange={(e) => setCriticality(e.currentTarget.value as ResourceCriticality)}
+ disabled={saving()}
+ class="mt-1 w-full text-xs rounded border border-border bg-surface px-2 py-1.5 text-base-content focus:outline-none focus:ring-1 focus:ring-blue-400 disabled:opacity-50"
+ >
+ <option value="">Default</option>
+ <option value="high">High</option>
+ <option value="medium">Medium</option>
+ <option value="low">Low</option>
+ </select>
+ <span class="mt-1 block text-[11px] text-muted leading-tight">
+ Orders this resource among same-severity Patrol findings.
+ </span>
+ </label>
+
+ <label class="block">
+ <span class="text-sm font-medium text-base-content">Operator note</span>
+ <textarea
+ value={note()}
+ onInput={(e) => setNote(e.currentTarget.value)}
+ placeholder="e.g. Production database; page before rebooting"
+ class="mt-1 min-h-16 w-full resize-y text-xs rounded border border-border bg-surface px-2 py-1.5 text-base-content focus:outline-none focus:ring-1 focus:ring-blue-400 disabled:opacity-50"
+ disabled={saving()}
+ maxLength={500}
+ />
+ </label>
+ </div>
+
{/* Maintenance window scheduler. The form is closed by default;
opening it pre-fills with sensible defaults (start = now, end
= +1h) or with the persisted window when one exists. */}
@@ -369,9 +418,8 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
<div class="flex-1">
<label class="text-sm font-medium text-base-content">Maintenance window</label>
<p class="text-[11px] text-muted mt-0.5 leading-tight">
- Suspend findings on this resource for a defined window. Useful for scheduled
- upgrades, planned downtime, or reboots where Pulse should stay quiet until the
- window closes.
+ Suspend findings on this resource for a defined window. Useful for scheduled upgrades,
+ planned downtime, or reboots where Pulse should stay quiet until the window closes.
</p>
</div>
<Show
@@ -590,7 +638,6 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
</button>
</Show>
</div>
-
</section>
);
};
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts
index 1c457b6481..f234e3a10f 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts
@@ -13,10 +13,10 @@ const overviewTabSource = readFileSync(
);
describe('ResourceOperatorStateSection', () => {
- it('exposes the two operator-set toggles bound to the canonical API client', () => {
+ it('exposes operator-set controls bound to the canonical API client', () => {
// The section is the operator's window into the per-resource state
- // feature. It must offer both toggles (intentionally offline + never
- // auto-remediate) and route them through the canonical
+ // feature. It must offer the suppress/remediation toggles plus
+ // Patrol priority and note fields, all routed through the canonical
// resourceOperatorState client — no parallel fetch path that could
// drift from the API contract.
expect(sectionSource).toContain("from '@/api/resourceOperatorState'");
@@ -25,6 +25,10 @@ describe('ResourceOperatorStateSection', () => {
expect(sectionSource).toContain('clearResourceOperatorState');
expect(sectionSource).toContain('Intentionally offline');
expect(sectionSource).toContain('Never auto-remediate');
+ expect(sectionSource).toContain('Patrol priority');
+ expect(sectionSource).toContain('Operator note');
+ expect(sectionSource).toContain('setCriticality');
+ expect(sectionSource).toContain('setNote');
});
it('keeps the section out of the parent Suspense fallback by using createNonSuspendingQuery', () => {
@@ -49,16 +53,45 @@ describe('ResourceOperatorStateSection', () => {
expect(sectionSource).toContain('if (next && !neverAutoRemediate())');
});
- it('preserves persisted maintenance-window data on toggle save so the two facets stay decoupled', () => {
- // Toggling intentionallyOffline or neverAutoRemediate must not
- // clobber a persisted maintenance window. The toggle save path
- // reads the current persisted window fields and forwards them
- // through the PUT body (which replaces the whole record).
+ it('preserves persisted maintenance-window data on override save so window scheduling stays decoupled', () => {
+ // Saving non-window overrides must not clobber a persisted
+ // maintenance window. The save path reads the current persisted
+ // window fields and forwards them through the PUT body (which
+ // replaces the whole record), while priority/note come from the
+ // local edit state.
expect(sectionSource).toContain('maintenanceStartAt: current?.maintenanceStartAt');
expect(sectionSource).toContain('maintenanceEndAt: current?.maintenanceEndAt');
expect(sectionSource).toContain('maintenanceReason: current?.maintenanceReason');
- expect(sectionSource).toContain('criticality: current?.criticality');
- expect(sectionSource).toContain('note: current?.note');
+ expect(sectionSource).toContain('criticality: criticality()');
+ expect(sectionSource).toContain('note: noteForSave()');
+ });
+
+ it('offers the canonical Patrol priority options and dirty-tracks priority plus note edits', () => {
+ // Criticality is constrained by the API contract. The drawer must
+ // expose exactly the canonical values and compare both priority and
+ // trimmed note against persisted state so Save/Discard appear for
+ // those edits too.
+ expect(sectionSource).toContain('<option value="">Default</option>');
+ expect(sectionSource).toContain('<option value="high">High</option>');
+ expect(sectionSource).toContain('<option value="medium">Medium</option>');
+ expect(sectionSource).toContain('<option value="low">Low</option>');
+ expect(sectionSource).toContain('const persistedCriticality = current?.criticality ??');
+ expect(sectionSource).toContain('const persistedNote = current?.note ??');
+ expect(sectionSource).toContain('criticality() !== persistedCriticality');
+ expect(sectionSource).toContain('note().trim() !== persistedNote');
+ });
+
+ it('keeps priority and note edit-state when scheduling or clearing maintenance windows', () => {
+ // PUT replaces the whole record, so the maintenance-window actions
+ // must forward the local priority/note signals rather than the last
+ // persisted values. Otherwise editing a note and then scheduling a
+ // window would silently lose the note.
+ expect(sectionSource).toContain('maintenanceStartAt: start.toISOString()');
+ expect(sectionSource).toContain('maintenanceEndAt: end.toISOString()');
+ expect(sectionSource).toContain('criticality: criticality()');
+ expect(sectionSource).toContain('note: noteForSave()');
+ expect(sectionSource).not.toContain('criticality: current?.criticality');
+ expect(sectionSource).not.toContain('note: current?.note');
});
it('exposes a maintenance-window scheduler with HTML5 datetime-local inputs and quick presets', () => {
@@ -98,7 +131,8 @@ describe('ResourceOperatorStateSection', () => {
// nothing once it ends.
expect(sectionSource).toContain('scheduledMaintenanceWindow');
expect(sectionSource).toContain('Maintenance window scheduled.');
- expect(sectionSource).toContain('Auto-acknowledgement will start');
+ expect(sectionSource).toContain('Auto-acknowledgement will');
+ expect(sectionSource).toContain("start{' '}");
});
it('exposes Edit window and Cancel window controls when a window exists', () => {
@@ -144,7 +178,9 @@ describe('ResourceDetailDrawerOverviewTab integration', () => {
// what Pulse actually did. They belong on the same drawer surface
// so the operator can read both stories together.
expect(overviewTabSource).toContain("from './ResourceOperatorStateSection'");
- expect(overviewTabSource).toContain('<ResourceOperatorStateSection resourceId={resource.id} />');
+ expect(overviewTabSource).toContain(
+ '<ResourceOperatorStateSection resourceId={resource.id} />',
+ );
// Section must precede the action-history block so the override
// explains the actions that follow, not vice versa.
const operatorIndex = overviewTabSource.indexOf('<ResourceOperatorStateSection');
diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.ts
index 033f1d4bfd..6d7b3f7cef 100644
--- a/frontend-modern/src/stores/aiIntelligence.ts
+++ b/frontend-modern/src/stores/aiIntelligence.ts
@@ -20,6 +20,7 @@ import {
type Finding as PatrolFinding,
type CapacityForecast,
} from '@/api/patrol';
+import type { ResourceCriticality } from '@/api/resourceOperatorState';
import type {
RemediationPlan,
CircuitBreakerStatus,
@@ -68,6 +69,7 @@ const VALID_INVESTIGATION_OUTCOMES = new Set<string>([
'fix_verification_unknown',
]);
const VALID_SEVERITIES = new Set<string>(['critical', 'warning', 'info', 'watch']);
+const VALID_RESOURCE_CRITICALITIES = new Set<string>(['high', 'medium', 'low', '']);
const VALID_SOURCES = new Set<string>([
'threshold',
'ai-patrol',
@@ -100,6 +102,13 @@ function validateSeverity(value: string | undefined): UnifiedFinding['severity']
return 'info';
}
+function validateResourceCriticality(value: string | undefined): ResourceCriticality | undefined {
+ if (value === undefined) return undefined;
+ const normalized = String(value).trim().toLowerCase();
+ if (VALID_RESOURCE_CRITICALITIES.has(normalized)) return normalized as ResourceCriticality;
+ return undefined;
+}
+
function validateSource(value: string | undefined): UnifiedFinding['source'] {
if (value && VALID_SOURCES.has(value)) return value as UnifiedFinding['source'];
return 'ai-patrol';
@@ -138,6 +147,7 @@ export interface UnifiedFinding {
resourceId: string;
resourceName: string;
resourceType: string;
+ resourceCriticality?: ResourceCriticality;
alertIdentifier?: string;
alertType?: string;
isThreshold?: boolean;
@@ -229,6 +239,7 @@ function normalizeUnifiedFindingRecord(item: UnifiedFindingRecord, now: number):
resourceId: item.resource_id,
resourceName: item.resource_name || item.resource_id,
resourceType: item.resource_type || 'unknown',
+ resourceCriticality: validateResourceCriticality(item.resource_criticality),
alertIdentifier,
isThreshold: Boolean(item.is_threshold || item.source === 'threshold'),
category: item.category || 'general',
@@ -273,6 +284,7 @@ function normalizePatrolFindingRecord(item: PatrolFinding, now: number): Unified
resourceId: item.resource_id,
resourceName: item.resource_name || item.resource_id,
resourceType: item.resource_type || 'unknown',
+ resourceCriticality: validateResourceCriticality(item.resource_criticality),
alertIdentifier: item.alertIdentifier,
isThreshold: false,
category: item.category || 'general',
diff --git a/frontend-modern/src/utils/__tests__/aiFindingPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiFindingPresentation.test.ts
new file mode 100644
index 0000000000..45ce144c4a
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/aiFindingPresentation.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+
+import type { UnifiedFinding } from '@/stores/aiIntelligence';
+import {
+ getFindingResourceCriticalitySortOrder,
+ sortFindingsForAttentionQueue,
+} from '@/utils/aiFindingPresentation';
+
+function makeFinding(overrides: Partial<UnifiedFinding>): UnifiedFinding {
+ return {
+ id: overrides.id ?? 'finding',
+ source: 'ai-patrol',
+ resourceId: overrides.resourceId ?? 'vm:101',
+ resourceName: overrides.resourceName ?? 'db-primary',
+ resourceType: overrides.resourceType ?? 'vm',
+ category: 'performance',
+ severity: overrides.severity ?? 'warning',
+ title: overrides.title ?? 'CPU saturated',
+ description: overrides.description ?? 'CPU is high',
+ detectedAt: overrides.detectedAt ?? '2026-06-30T08:00:00Z',
+ lastSeenAt: overrides.lastSeenAt ?? overrides.detectedAt ?? '2026-06-30T08:00:00Z',
+ status: overrides.status ?? 'active',
+ investigationOutcome: overrides.investigationOutcome ?? 'fix_failed',
+ ...overrides,
+ };
+}
+
+describe('getFindingResourceCriticalitySortOrder', () => {
+ it('orders explicit resource priority around the default posture', () => {
+ expect(getFindingResourceCriticalitySortOrder('high')).toBeLessThan(
+ getFindingResourceCriticalitySortOrder('medium'),
+ );
+ expect(getFindingResourceCriticalitySortOrder('medium')).toBeLessThan(
+ getFindingResourceCriticalitySortOrder(undefined),
+ );
+ expect(getFindingResourceCriticalitySortOrder(undefined)).toBeLessThan(
+ getFindingResourceCriticalitySortOrder('low'),
+ );
+ });
+});
+
+describe('sortFindingsForAttentionQueue', () => {
+ it('uses resource criticality before recency for same-severity findings', () => {
+ const sorted = sortFindingsForAttentionQueue([
+ makeFinding({
+ id: 'low-newest',
+ resourceCriticality: 'low',
+ lastSeenAt: '2026-06-30T08:30:00Z',
+ }),
+ makeFinding({
+ id: 'default-middle',
+ lastSeenAt: '2026-06-30T08:20:00Z',
+ }),
+ makeFinding({
+ id: 'high-oldest',
+ resourceCriticality: 'high',
+ lastSeenAt: '2026-06-30T08:10:00Z',
+ }),
+ ]);
+
+ expect(sorted.map((finding) => finding.id)).toEqual([
+ 'high-oldest',
+ 'default-middle',
+ 'low-newest',
+ ]);
+ });
+
+ it('does not allow resource criticality to outrank severity', () => {
+ const sorted = sortFindingsForAttentionQueue([
+ makeFinding({
+ id: 'warning-high',
+ severity: 'warning',
+ resourceCriticality: 'high',
+ }),
+ makeFinding({
+ id: 'critical-low',
+ severity: 'critical',
+ resourceCriticality: 'low',
+ }),
+ ]);
+
+ expect(sorted.map((finding) => finding.id)).toEqual(['critical-low', 'warning-high']);
+ });
+});
diff --git a/frontend-modern/src/utils/aiFindingPresentation.ts b/frontend-modern/src/utils/aiFindingPresentation.ts
index 3dbb815cd0..3569054fb4 100644
--- a/frontend-modern/src/utils/aiFindingPresentation.ts
+++ b/frontend-modern/src/utils/aiFindingPresentation.ts
@@ -230,6 +230,13 @@ const FINDING_SEVERITY_SORT_ORDER: Record<string, number> = {
info: 3,
};
+const FINDING_RESOURCE_CRITICALITY_SORT_ORDER: Record<string, number> = {
+ high: 0,
+ medium: 1,
+ '': 2,
+ low: 3,
+};
+
const FINDING_SEVERITY_COMPACT_LABELS: Record<string, string> = {
critical: 'CRIT',
warning: 'WARN',
@@ -398,6 +405,15 @@ export const getFindingSeveritySortOrder = (
severity: UnifiedFinding['severity'] | string,
): number => FINDING_SEVERITY_SORT_ORDER[severity] ?? 4;
+export const getFindingResourceCriticalitySortOrder = (
+ criticality: UnifiedFinding['resourceCriticality'] | string | undefined,
+): number => {
+ const normalized = String(criticality || '')
+ .trim()
+ .toLowerCase();
+ return FINDING_RESOURCE_CRITICALITY_SORT_ORDER[normalized] ?? 2;
+};
+
export const getFindingActiveRuntimeSortOrder = (
finding: Pick<UnifiedFinding, 'status' | 'resourceId' | 'resourceName' | 'title'>,
): number => (finding.status === 'active' && isPatrolRuntimeFinding(finding) ? 0 : 1);
@@ -638,9 +654,7 @@ export function getPatrolWorkTypeComposition<
return composition;
}
-export function getPatrolWorkTypeCompositionClause(
- composition: PatrolWorkTypeComposition,
-): string {
+export function getPatrolWorkTypeCompositionClause(composition: PatrolWorkTypeComposition): string {
const parts: string[] = [];
if (composition.approval > 0) {
parts.push(`${composition.approval} need${composition.approval === 1 ? 's' : ''} approval`);
@@ -750,6 +764,12 @@ export const sortFindingsForAttentionQueue = (findings: UnifiedFinding[]): Unifi
const bSeverity = getFindingSeveritySortOrder(b.severity);
if (aSeverity !== bSeverity) return aSeverity - bSeverity;
+ const aResourceCriticality = getFindingResourceCriticalitySortOrder(a.resourceCriticality);
+ const bResourceCriticality = getFindingResourceCriticalitySortOrder(b.resourceCriticality);
+ if (aResourceCriticality !== bResourceCriticality) {
+ return aResourceCriticality - bResourceCriticality;
+ }
+
const aRuntime = getFindingActiveRuntimeSortOrder(a);
const bRuntime = getFindingActiveRuntimeSortOrder(b);
if (aRuntime !== bRuntime) return aRuntime - bRuntime;
@@ -840,9 +860,9 @@ export const hasFindingInvestigationDetails = (
): boolean =>
Boolean(
finding.investigationSessionId?.trim() ||
- finding.investigationStatus ||
- finding.investigationOutcome ||
- (finding.investigationAttempts ?? 0) > 0,
+ finding.investigationStatus ||
+ finding.investigationOutcome ||
+ (finding.investigationAttempts ?? 0) > 0,
);
// hasFindingInvestigationHandoffPointer is the narrower check used by the
diff --git a/internal/ai/findings.go b/internal/ai/findings.go
index 0e3580eae4..6e07909629 100644
--- a/internal/ai/findings.go
+++ b/internal/ai/findings.go
@@ -180,10 +180,14 @@ type Finding struct {
ResourceID string `json:"resource_id"`
ResourceName string `json:"resource_name"`
ResourceType string `json:"resource_type"` // node, vm, container, docker, storage, agent, pbs, agent_raid
- Node string `json:"node,omitempty"`
- Title string `json:"title"`
- Description string `json:"description"`
- Impact string `json:"impact,omitempty"` // Operator-facing consequence-if-ignored statement
+ // ResourceCriticality is the operator-set resource priority stamped
+ // from ResourceOperatorState. It affects Patrol attention ordering
+ // among same-severity findings but does not alter severity.
+ ResourceCriticality string `json:"resource_criticality,omitempty"`
+ Node string `json:"node,omitempty"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Impact string `json:"impact,omitempty"` // Operator-facing consequence-if-ignored statement
// PreviousResolvedFixSummary preserves the description of the fix that
// resolved this finding the last time it was active. Captured at
// regression time before InvestigationRecord is cleared, so the next
@@ -255,6 +259,7 @@ type findingJSON struct {
ResourceID string `json:"resource_id"`
ResourceName string `json:"resource_name"`
ResourceType string `json:"resource_type"`
+ ResourceCriticality string `json:"resource_criticality,omitempty"`
Node string `json:"node,omitempty"`
Title string `json:"title"`
Description string `json:"description"`
@@ -301,6 +306,7 @@ func (f Finding) MarshalJSON() ([]byte, error) {
ResourceID: f.ResourceID,
ResourceName: f.ResourceName,
ResourceType: f.ResourceType,
+ ResourceCriticality: normalizeResourceCriticality(f.ResourceCriticality),
Node: f.Node,
Title: f.Title,
Description: f.Description,
@@ -352,6 +358,7 @@ func (f *Finding) UnmarshalJSON(data []byte) error {
ResourceID: payload.ResourceID,
ResourceName: payload.ResourceName,
ResourceType: payload.ResourceType,
+ ResourceCriticality: normalizeResourceCriticality(payload.ResourceCriticality),
Node: payload.Node,
Title: payload.Title,
Description: payload.Description,
@@ -467,6 +474,15 @@ func (f *Finding) syncLoopState() {
f.LoopState = string(deriveLoopState(f))
}
+func normalizeResourceCriticality(value string) string {
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "high", "medium", "low":
+ return strings.ToLower(strings.TrimSpace(value))
+ default:
+ return ""
+ }
+}
+
// ShouldInvestigate returns true if this finding should be automatically investigated
// based on autonomy level, severity, and investigation history.
// A finding will NOT be investigated if:
@@ -801,6 +817,8 @@ type ResourceOperatorStateMaintenanceWindow struct {
// does not multiply round-trips per finding. MaintenanceWindow is nil
// when no window is currently active; IntentionallyOffline reflects
// the operator's "this resource is expected to be offline" flag.
+// Criticality is an operator-set Patrol queue hint: high promotes
+// same-severity findings, low demotes them, and empty means default.
type ResourceOperatorStateProjection struct {
MaintenanceWindow *ResourceOperatorStateMaintenanceWindow
IntentionallyOffline bool
@@ -812,6 +830,7 @@ type ResourceOperatorStateProjection struct {
// the same projection means the suppression and investigation
// hot paths share a single read.
NeverAutoRemediate bool
+ Criticality string
}
// ResourceOperatorStateProvider is the narrow interface the findings
@@ -1612,6 +1631,9 @@ func (s *FindingsStore) mergeEquivalentFindingLocked(existing, incoming *Finding
if existing.Node == "" && incoming.Node != "" {
existing.Node = incoming.Node
}
+ if criticality := normalizeResourceCriticality(incoming.ResourceCriticality); criticality != "" {
+ existing.ResourceCriticality = criticality
+ }
s.syncLoopStateLocked(existing)
if incoming.ResourceID != "" && incoming.ResourceID != existing.ResourceID {
appendFindingResourceIndexUnique(s.byResource, incoming.ResourceID, existing.ID)
@@ -1703,8 +1725,31 @@ func (s *FindingsStore) Add(f *Finding) bool {
f.syncLoopState()
existing, exists := s.findings[f.ID]
+ operatorStateProviderPresent := false
+ operatorProjectionOK := false
+ var operatorProjection ResourceOperatorStateProjection
+ if provider := s.resourceOperatorStateProvider; provider != nil {
+ operatorResourceID := strings.TrimSpace(f.ResourceID)
+ if operatorResourceID == "" && existing != nil {
+ operatorResourceID = strings.TrimSpace(existing.ResourceID)
+ }
+ if operatorResourceID != "" {
+ operatorStateProviderPresent = true
+ operatorProjection, operatorProjectionOK = provider.OperatorStateProjection(operatorResourceID, time.Now())
+ if operatorProjectionOK {
+ f.ResourceCriticality = normalizeResourceCriticality(operatorProjection.Criticality)
+ } else {
+ f.ResourceCriticality = ""
+ }
+ }
+ } else {
+ f.ResourceCriticality = normalizeResourceCriticality(f.ResourceCriticality)
+ }
if exists {
wasResolved := existing.ResolvedAt != nil
+ if operatorStateProviderPresent || f.ResourceCriticality != "" {
+ existing.ResourceCriticality = normalizeResourceCriticality(f.ResourceCriticality)
+ }
if existing.ResourceType == "" {
if f.ResourceType != "" {
existing.ResourceType = f.ResourceType
@@ -1743,10 +1788,9 @@ func (s *FindingsStore) Add(f *Finding) bool {
operatorStateLifted := false
if !willFixReminderDue && existing.DismissedReason == "expected_behavior" && !existing.Suppressed {
if cause := findOperatorStateDismissCause(existing); cause != "" {
- if provider := s.resourceOperatorStateProvider; provider != nil && existing.ResourceID != "" {
- projection, ok := provider.OperatorStateProjection(existing.ResourceID, time.Now())
- currentlySuppressing := ok &&
- (projection.MaintenanceWindow != nil || projection.IntentionallyOffline)
+ if operatorStateProviderPresent {
+ currentlySuppressing := operatorProjectionOK &&
+ (operatorProjection.MaintenanceWindow != nil || operatorProjection.IntentionallyOffline)
operatorStateLifted = !currentlySuppressing
} else {
// No provider currently wired but the finding was
@@ -1929,8 +1973,8 @@ func (s *FindingsStore) Add(f *Finding) bool {
// the operator can audit what tripped during the suppression;
// severity escalation paths still wake it later if the underlying
// condition stays after the operator clears the state.
- if provider := s.resourceOperatorStateProvider; provider != nil && f.ResourceID != "" {
- if projection, ok := provider.OperatorStateProjection(f.ResourceID, time.Now()); ok {
+ if operatorStateProviderPresent {
+ if projection, ok := operatorProjection, operatorProjectionOK; ok {
now := time.Now()
switch {
case projection.MaintenanceWindow != nil:
diff --git a/internal/ai/findings_persistence.go b/internal/ai/findings_persistence.go
index 28eb09bb9e..104d1d3d04 100644
--- a/internal/ai/findings_persistence.go
+++ b/internal/ai/findings_persistence.go
@@ -37,33 +37,34 @@ func findingsToRecords(findings map[string]*Finding) map[string]*config.AIFindin
})
}
records[id] = &config.AIFindingRecord{
- ID: f.ID,
- Key: f.Key,
- Severity: string(f.Severity),
- Category: string(f.Category),
- ResourceID: f.ResourceID,
- ResourceName: f.ResourceName,
- ResourceType: f.ResourceType,
- Node: f.Node,
- Title: f.Title,
- Description: f.Description,
- Recommendation: f.Recommendation,
- Evidence: f.Evidence,
- Source: f.Source,
- DetectedAt: f.DetectedAt,
- LastSeenAt: f.LastSeenAt,
- ResolvedAt: f.ResolvedAt,
- AutoResolved: f.AutoResolved,
- ResolveReason: f.ResolveReason,
- AcknowledgedAt: f.AcknowledgedAt,
- SnoozedUntil: f.SnoozedUntil,
- AlertIdentifier: f.AlertIdentifier,
- DismissedReason: f.DismissedReason,
- UserNote: f.UserNote,
- TimesRaised: f.TimesRaised,
- Suppressed: f.Suppressed,
- RemindAt: f.RemindAt,
- RemindCount: f.RemindCount,
+ ID: f.ID,
+ Key: f.Key,
+ Severity: string(f.Severity),
+ Category: string(f.Category),
+ ResourceID: f.ResourceID,
+ ResourceName: f.ResourceName,
+ ResourceType: f.ResourceType,
+ ResourceCriticality: f.ResourceCriticality,
+ Node: f.Node,
+ Title: f.Title,
+ Description: f.Description,
+ Recommendation: f.Recommendation,
+ Evidence: f.Evidence,
+ Source: f.Source,
+ DetectedAt: f.DetectedAt,
+ LastSeenAt: f.LastSeenAt,
+ ResolvedAt: f.ResolvedAt,
+ AutoResolved: f.AutoResolved,
+ ResolveReason: f.ResolveReason,
+ AcknowledgedAt: f.AcknowledgedAt,
+ SnoozedUntil: f.SnoozedUntil,
+ AlertIdentifier: f.AlertIdentifier,
+ DismissedReason: f.DismissedReason,
+ UserNote: f.UserNote,
+ TimesRaised: f.TimesRaised,
+ Suppressed: f.Suppressed,
+ RemindAt: f.RemindAt,
+ RemindCount: f.RemindCount,
// Investigation fields
InvestigationSessionID: f.InvestigationSessionID,
InvestigationStatus: f.InvestigationStatus,
@@ -96,33 +97,34 @@ func recordsToFindings(records map[string]*config.AIFindingRecord) map[string]*F
})
}
findings[id] = &Finding{
- ID: r.ID,
- Key: r.Key,
- Severity: FindingSeverity(r.Severity),
- Category: FindingCategory(r.Category),
- ResourceID: r.ResourceID,
- ResourceName: r.ResourceName,
- ResourceType: r.ResourceType,
- Node: r.Node,
- Title: r.Title,
- Description: r.Description,
- Recommendation: r.Recommendation,
- Evidence: r.Evidence,
- Source: r.Source,
- DetectedAt: r.DetectedAt,
- LastSeenAt: r.LastSeenAt,
- ResolvedAt: r.ResolvedAt,
- AutoResolved: r.AutoResolved,
- ResolveReason: r.ResolveReason,
- AcknowledgedAt: r.AcknowledgedAt,
- SnoozedUntil: r.SnoozedUntil,
- AlertIdentifier: r.AlertIdentifier,
- DismissedReason: r.DismissedReason,
- UserNote: r.UserNote,
- TimesRaised: r.TimesRaised,
- Suppressed: r.Suppressed,
- RemindAt: r.RemindAt,
- RemindCount: r.RemindCount,
+ ID: r.ID,
+ Key: r.Key,
+ Severity: FindingSeverity(r.Severity),
+ Category: FindingCategory(r.Category),
+ ResourceID: r.ResourceID,
+ ResourceName: r.ResourceName,
+ ResourceType: r.ResourceType,
+ ResourceCriticality: r.ResourceCriticality,
+ Node: r.Node,
+ Title: r.Title,
+ Description: r.Description,
+ Recommendation: r.Recommendation,
+ Evidence: r.Evidence,
+ Source: r.Source,
+ DetectedAt: r.DetectedAt,
+ LastSeenAt: r.LastSeenAt,
+ ResolvedAt: r.ResolvedAt,
+ AutoResolved: r.AutoResolved,
+ ResolveReason: r.ResolveReason,
+ AcknowledgedAt: r.AcknowledgedAt,
+ SnoozedUntil: r.SnoozedUntil,
+ AlertIdentifier: r.AlertIdentifier,
+ DismissedReason: r.DismissedReason,
+ UserNote: r.UserNote,
+ TimesRaised: r.TimesRaised,
+ Suppressed: r.Suppressed,
+ RemindAt: r.RemindAt,
+ RemindCount: r.RemindCount,
// Investigation fields
InvestigationSessionID: r.InvestigationSessionID,
InvestigationStatus: r.InvestigationStatus,
diff --git a/internal/ai/findings_persistence_test.go b/internal/ai/findings_persistence_test.go
index 5bc07f9d51..3fe1257799 100644
--- a/internal/ai/findings_persistence_test.go
+++ b/internal/ai/findings_persistence_test.go
@@ -208,30 +208,31 @@ func TestFindingsPersistenceAdapter_PreservesAllFields(t *testing.T) {
snoozed := now.Add(24 * time.Hour)
originalFinding := &Finding{
- ID: "test-finding",
- Key: "test-key",
- Severity: FindingSeverityCritical,
- Category: FindingCategorySecurity,
- ResourceID: "resource-123",
- ResourceName: "Test Resource",
- ResourceType: "vm",
- Node: "node1",
- Title: "Test Title",
- Description: "Test Description",
- Recommendation: "Test Recommendation",
- Evidence: "Test Evidence",
- Source: "ai-analysis",
- DetectedAt: now,
- LastSeenAt: now,
- ResolvedAt: &resolved,
- AutoResolved: true,
- AcknowledgedAt: &acked,
- SnoozedUntil: &snoozed,
- AlertIdentifier: "alert-456",
- DismissedReason: "expected_behavior",
- UserNote: "This is intentional for Frigate recordings",
- TimesRaised: 5,
- Suppressed: false,
+ ID: "test-finding",
+ Key: "test-key",
+ Severity: FindingSeverityCritical,
+ Category: FindingCategorySecurity,
+ ResourceID: "resource-123",
+ ResourceName: "Test Resource",
+ ResourceType: "vm",
+ ResourceCriticality: "high",
+ Node: "node1",
+ Title: "Test Title",
+ Description: "Test Description",
+ Recommendation: "Test Recommendation",
+ Evidence: "Test Evidence",
+ Source: "ai-analysis",
+ DetectedAt: now,
+ LastSeenAt: now,
+ ResolvedAt: &resolved,
+ AutoResolved: true,
+ AcknowledgedAt: &acked,
+ SnoozedUntil: &snoozed,
+ AlertIdentifier: "alert-456",
+ DismissedReason: "expected_behavior",
+ UserNote: "This is intentional for Frigate recordings",
+ TimesRaised: 5,
+ Suppressed: false,
}
findings := map[string]*Finding{"test-finding": originalFinding}
@@ -267,6 +268,9 @@ func TestFindingsPersistenceAdapter_PreservesAllFields(t *testing.T) {
if f.ResourceID != originalFinding.ResourceID {
t.Errorf("ResourceID mismatch: got %q", f.ResourceID)
}
+ if f.ResourceCriticality != originalFinding.ResourceCriticality {
+ t.Errorf("ResourceCriticality mismatch: got %q", f.ResourceCriticality)
+ }
if f.AutoResolved != originalFinding.AutoResolved {
t.Errorf("AutoResolved mismatch: got %v", f.AutoResolved)
}
diff --git a/internal/ai/findings_test.go b/internal/ai/findings_test.go
index 33fc13d9fe..8e42ff6408 100644
--- a/internal/ai/findings_test.go
+++ b/internal/ai/findings_test.go
@@ -2166,6 +2166,64 @@ func TestToCoreFinding_LeavesOperationalMemoryNilForFreshFindings(t *testing.T)
}
}
+func TestFindingsStore_Add_StampsResourceCriticalityFromOperatorState(t *testing.T) {
+ store := NewFindingsStore()
+ criticality := "high"
+ store.SetResourceOperatorStateProvider(
+ ResourceOperatorStateProviderFunc(func(canonicalID string, _ time.Time) (ResourceOperatorStateProjection, bool) {
+ if canonicalID != "vm:101" {
+ return ResourceOperatorStateProjection{}, false
+ }
+ return ResourceOperatorStateProjection{Criticality: criticality}, true
+ }),
+ )
+
+ store.Add(&Finding{
+ ID: "finding-priority",
+ ResourceID: "vm:101",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ Title: "CPU saturated",
+ Description: "CPU is high",
+ })
+ if got := store.Get("finding-priority"); got == nil || got.ResourceCriticality != "high" {
+ t.Fatalf("new finding ResourceCriticality = %q, want high", findingResourceCriticalityForTest(got))
+ }
+
+ criticality = "low"
+ store.Add(&Finding{
+ ID: "finding-priority",
+ ResourceID: "vm:101",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ Title: "CPU still saturated",
+ Description: "CPU is still high",
+ })
+ if got := store.Get("finding-priority"); got == nil || got.ResourceCriticality != "low" {
+ t.Fatalf("re-detected finding ResourceCriticality = %q, want low", findingResourceCriticalityForTest(got))
+ }
+
+ criticality = ""
+ store.Add(&Finding{
+ ID: "finding-priority",
+ ResourceID: "vm:101",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ Title: "CPU saturated again",
+ Description: "CPU is high again",
+ })
+ if got := store.Get("finding-priority"); got == nil || got.ResourceCriticality != "" {
+ t.Fatalf("cleared finding ResourceCriticality = %q, want empty", findingResourceCriticalityForTest(got))
+ }
+}
+
+func findingResourceCriticalityForTest(f *Finding) string {
+ if f == nil {
+ return "<nil>"
+ }
+ return f.ResourceCriticality
+}
+
func TestFindingsStore_OperatorStateProjectionFor_ReturnsFalseWithoutProvider(t *testing.T) {
// Default store with no provider wired must report false so
// callers can branch on absence rather than parsing zero-valued
@@ -2189,6 +2247,7 @@ func TestFindingsStore_OperatorStateProjectionFor_ProxiesProvider(t *testing.T)
expected := ResourceOperatorStateProjection{
IntentionallyOffline: true,
NeverAutoRemediate: true,
+ Criticality: "high",
}
store.SetResourceOperatorStateProvider(
ResourceOperatorStateProviderFunc(func(_ string, _ time.Time) (ResourceOperatorStateProjection, bool) {
@@ -2206,6 +2265,9 @@ func TestFindingsStore_OperatorStateProjectionFor_ProxiesProvider(t *testing.T)
if got.NeverAutoRemediate != expected.NeverAutoRemediate {
t.Errorf("NeverAutoRemediate must round-trip — investigation runtime reads this projection too; got %v want %v", got.NeverAutoRemediate, expected.NeverAutoRemediate)
}
+ if got.Criticality != expected.Criticality {
+ t.Errorf("Criticality must round-trip — Patrol attention ordering reads this projection too; got %q want %q", got.Criticality, expected.Criticality)
+ }
}
func TestFindingsStore_OperatorStateProjectionFor_RejectsEmptyResourceID(t *testing.T) {
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 6df4e3b58f..98e4a5e86b 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -62,6 +62,7 @@ type AISettingsHandler struct {
stateProvider ai.StateProvider
readState unifiedresources.ReadState
unifiedResourceProvider ai.UnifiedResourceProvider
+ resourceStoreProvider func(orgID string) (unifiedresources.ResourceStore, error)
metadataProvider ai.MetadataProvider
patrolThresholdProvider ai.ThresholdProvider
metricsHistoryProvider ai.MetricsHistoryProvider
@@ -118,6 +119,20 @@ func (h *AISettingsHandler) SetAIAutoFixEndpoints(ep extensions.AIAutoFixEndpoin
h.aiAutoFixEndpoints = ep
}
+// SetResourceStoreProvider installs the resource-store resolver used by
+// read-side Patrol response enrichment. The findings store owns durable
+// suppression/stamping during Add; this provider lets the HTTP response
+// reflect operator priority changes immediately, without waiting for the
+// next Patrol detection pass.
+func (h *AISettingsHandler) SetResourceStoreProvider(provider func(orgID string) (unifiedresources.ResourceStore, error)) {
+ if h == nil {
+ return
+ }
+ h.stateMu.Lock()
+ defer h.stateMu.Unlock()
+ h.resourceStoreProvider = provider
+}
+
func (h *AISettingsHandler) stateRefs() (
*config.MultiTenantPersistence,
*monitoring.MultiTenantMonitor,
@@ -5648,12 +5663,74 @@ func (h *AISettingsHandler) HandleGetPatrolFindings(w http.ResponseWriter, r *ht
if limit > 0 && limit < len(findings) {
findings = findings[:limit]
}
+ h.applyResourceCriticalityToPatrolFindings(r.Context(), findings)
if err := utils.WriteJSONResponse(w, findings); err != nil {
log.Error().Err(err).Msg("Failed to write patrol findings response")
}
}
+func (h *AISettingsHandler) applyResourceCriticalityToPatrolFindings(ctx context.Context, findings []*ai.Finding) {
+ if h == nil || len(findings) == 0 {
+ return
+ }
+ h.stateMu.RLock()
+ provider := h.resourceStoreProvider
+ h.stateMu.RUnlock()
+ if provider == nil {
+ return
+ }
+ store, err := provider(GetOrgID(ctx))
+ if err != nil || store == nil {
+ if err != nil {
+ log.Debug().Err(err).Msg("Failed to resolve resource store for Patrol finding priority enrichment")
+ }
+ return
+ }
+
+ criticalityByResourceID := make(map[string]string)
+ for _, finding := range findings {
+ if finding == nil {
+ continue
+ }
+ resourceID := strings.TrimSpace(finding.ResourceID)
+ if resourceID == "" {
+ continue
+ }
+ if _, exists := criticalityByResourceID[resourceID]; exists {
+ continue
+ }
+ state, found, fetchErr := store.GetResourceOperatorState(resourceID)
+ if fetchErr != nil {
+ log.Debug().Err(fetchErr).Str("resource_id", resourceID).Msg("Failed to load resource operator priority for Patrol finding")
+ continue
+ }
+ if !found {
+ criticalityByResourceID[resourceID] = ""
+ continue
+ }
+ criticalityByResourceID[resourceID] = normalizePatrolResourceCriticality(string(state.Criticality))
+ }
+
+ for _, finding := range findings {
+ if finding == nil {
+ continue
+ }
+ resourceID := strings.TrimSpace(finding.ResourceID)
+ if criticality, ok := criticalityByResourceID[resourceID]; ok {
+ finding.ResourceCriticality = criticality
+ }
+ }
+}
+
+func normalizePatrolResourceCriticality(value string) string {
+ normalized := strings.ToLower(strings.TrimSpace(value))
+ if !unifiedresources.IsValidCriticality(normalized) {
+ return ""
+ }
+ return normalized
+}
+
func patrolFindingsLimitFromQuery(query url.Values, includeResolved bool) int {
limit := 0
if includeResolved {
diff --git a/internal/api/ai_patrol_handlers_test.go b/internal/api/ai_patrol_handlers_test.go
index dfcaa362a2..2eda227b4c 100644
--- a/internal/api/ai_patrol_handlers_test.go
+++ b/internal/api/ai_patrol_handlers_test.go
@@ -217,6 +217,57 @@ func TestHandleGetPatrolFindings_WithResourceIDFilter(t *testing.T) {
}
}
+func TestHandleGetPatrolFindings_AppliesResourceCriticalityFromOperatorState(t *testing.T) {
+ t.Parallel()
+ handler := createTestAIHandler(t)
+ patrol := ai.NewPatrolService(nil, nil)
+ patrol.GetFindings().Add(&ai.Finding{
+ ID: "finding-priority",
+ ResourceID: "vm:101",
+ ResourceName: "db-primary",
+ ResourceType: "vm",
+ Severity: ai.FindingSeverityWarning,
+ Category: ai.FindingCategoryPerformance,
+ Title: "CPU saturated",
+ Description: "CPU is high",
+ })
+ setUnexportedField(t, handler.defaultAIService, "patrolService", patrol)
+
+ resourceStore := unifiedresources.NewMemoryStore()
+ if err := resourceStore.SetResourceOperatorState(unifiedresources.ResourceOperatorState{
+ CanonicalID: "vm:101",
+ Criticality: unifiedresources.CriticalityHigh,
+ SetAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+ handler.SetResourceStoreProvider(func(orgID string) (unifiedresources.ResourceStore, error) {
+ if orgID != "" && orgID != "default" {
+ t.Fatalf("unexpected org id %q", orgID)
+ }
+ return resourceStore, nil
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/findings", nil)
+ rec := httptest.NewRecorder()
+
+ handler.HandleGetPatrolFindings(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
+ }
+ var findings []ai.Finding
+ if err := json.Unmarshal(rec.Body.Bytes(), &findings); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+ if len(findings) != 1 {
+ t.Fatalf("expected one finding, got %d", len(findings))
+ }
+ if findings[0].ResourceCriticality != "high" {
+ t.Fatalf("ResourceCriticality = %q, want high", findings[0].ResourceCriticality)
+ }
+}
+
func TestHandleForcePatrol_MethodNotAllowed(t *testing.T) {
t.Parallel()
handler := createTestAIHandler(t)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 905c5e4397..91a4a865ad 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -19242,6 +19242,9 @@ func TestContract_FindingsResourceOperatorStateProviderIsWired(t *testing.T) {
if !strings.Contains(src, "SetResourceOperatorStateProvider(") {
t.Error("router.go must call SetResourceOperatorStateProvider on the findings store at startup")
}
+ if !strings.Contains(src, "SetResourceStoreProvider(r.resourceHandlers.getStore)") {
+ t.Error("router.go must expose the resource store to the Patrol findings handler so read-time priority changes surface immediately")
+ }
if !strings.Contains(src, "ResourceOperatorStateProviderFunc(") {
t.Error("router.go must use the ai.ResourceOperatorStateProviderFunc adapter so the closure satisfies the provider interface")
}
@@ -19254,6 +19257,9 @@ func TestContract_FindingsResourceOperatorStateProviderIsWired(t *testing.T) {
if !strings.Contains(src, "IntentionallyOffline: state.IntentionallyOffline") {
t.Error("router.go must propagate state.IntentionallyOffline through the projection so the findings runtime sees it")
}
+ if !strings.Contains(src, "Criticality: string(state.Criticality)") {
+ t.Error("router.go must propagate state.Criticality through the projection so Patrol attention ordering sees it")
+ }
}
// TestContract_ResourceOperatorStateUrlCanonicalIDWinsOverBody pins the
diff --git a/internal/api/router.go b/internal/api/router.go
index f777051d48..b4cf08d365 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -619,6 +619,9 @@ func (r *Router) setupRoutes() {
// AI settings endpoints
r.aiSettingsHandler = NewAISettingsHandler(r.multiTenant, r.mtMonitor, r.agentExecServer)
+ if r.resourceHandlers != nil {
+ r.aiSettingsHandler.SetResourceStoreProvider(r.resourceHandlers.getStore)
+ }
r.aiSettingsHandler.SetConfig(r.config)
// Inject state provider so AI has access to full infrastructure context (VMs, containers, IPs)
if r.monitor != nil {
@@ -2066,6 +2069,7 @@ func (r *Router) startPatrolForContext(ctx context.Context, orgID string) bool {
projection := ai.ResourceOperatorStateProjection{
IntentionallyOffline: state.IntentionallyOffline,
NeverAutoRemediate: state.NeverAutoRemediate,
+ Criticality: string(state.Criticality),
}
if state.IsInMaintenanceAt(now) {
projection.MaintenanceWindow = &ai.ResourceOperatorStateMaintenanceWindow{
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 761c25919f..fa47d58ff7 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -2292,27 +2292,28 @@ type AISuppressionRuleRecord struct {
// AIFindingRecord is a persisted finding with full history
type AIFindingRecord struct {
- ID string `json:"id"`
- Key string `json:"key,omitempty"`
- Severity string `json:"severity"`
- Category string `json:"category"`
- ResourceID string `json:"resource_id"`
- ResourceName string `json:"resource_name"`
- ResourceType string `json:"resource_type"`
- Node string `json:"node,omitempty"`
- Title string `json:"title"`
- Description string `json:"description"`
- Recommendation string `json:"recommendation,omitempty"`
- Evidence string `json:"evidence,omitempty"`
- Source string `json:"source,omitempty"`
- DetectedAt time.Time `json:"detected_at"`
- LastSeenAt time.Time `json:"last_seen_at"`
- ResolvedAt *time.Time `json:"resolved_at,omitempty"`
- AutoResolved bool `json:"auto_resolved"`
- ResolveReason string `json:"resolve_reason,omitempty"`
- AcknowledgedAt *time.Time `json:"acknowledged_at,omitempty"`
- SnoozedUntil *time.Time `json:"snoozed_until,omitempty"`
- AlertIdentifier string `json:"-"`
+ ID string `json:"id"`
+ Key string `json:"key,omitempty"`
+ Severity string `json:"severity"`
+ Category string `json:"category"`
+ ResourceID string `json:"resource_id"`
+ ResourceName string `json:"resource_name"`
+ ResourceType string `json:"resource_type"`
+ ResourceCriticality string `json:"resource_criticality,omitempty"`
+ Node string `json:"node,omitempty"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Recommendation string `json:"recommendation,omitempty"`
+ Evidence string `json:"evidence,omitempty"`
+ Source string `json:"source,omitempty"`
+ DetectedAt time.Time `json:"detected_at"`
+ LastSeenAt time.Time `json:"last_seen_at"`
+ ResolvedAt *time.Time `json:"resolved_at,omitempty"`
+ AutoResolved bool `json:"auto_resolved"`
+ ResolveReason string `json:"resolve_reason,omitempty"`
+ AcknowledgedAt *time.Time `json:"acknowledged_at,omitempty"`
+ SnoozedUntil *time.Time `json:"snoozed_until,omitempty"`
+ AlertIdentifier string `json:"-"`
// User feedback fields - enables persistence of dismissal state
DismissedReason string `json:"dismissed_reason,omitempty"`
UserNote string `json:"user_note,omitempty"`