Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Name Patrol inbox alert subjects by their unified resource
rcourtman1120502a1dd4
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex ca50cb0bc7..fad0bfaec4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -8199,6 +8199,13 @@ deliver a command itself or add an agent wire shape. Actual dispatch retainsthe canonical action executor, exact agent/resource binding, command-enabledtoken policy, durable attempt/receipt, timeout, and restart-reconciliationboundaries.+The attention read handler binds each alert's subject reference to the org's+current unified inventory (`ResolveAlertResourceReference`), so an agent's+disk, RAID and sensor alerts name the agent's machine and a Docker container+alert names the collected container; the restart plan therefore targets the+unified container ID the executor resolves. This reads the existing registry+only: it registers no agent, accepts no report, and changes no command,+credential or token path.### Operational Trust lifecycle mutation boundarydiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex accf9a6fca..66544d0517 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -3610,6 +3610,28 @@ alert keeps `Message`, which tracks the breach, and a stale or missing statusfalls back to it. The Patrol inbox, the investigation handoff and API clientsread that summary, so none of them re-derives the phase.+An item names its subject by the unified resource its record's subject+reference resolves to in current inventory (`AttentionSubjectResourceID`,+through the org registry's `ResolveAlertResourceReference`): Proxmox guest,+node and storage source IDs, `agent:<host ID>` references with their disk,+RAID and sensor children, ZFS pool children, and Docker host, Swarm service and+container references all become the unified resource ID that Patrol findings,+protection postures and resource actions carry. `operationalRecord` keeps the+alert's own reference, and a reference inventory does not bind (a removed+resource, or the moments after a restart before the agent reports) stays the+item's subject too. Before 24 October 2026 the projection passed the reference+through, so "Browse Patrol findings for this resource" scoped the findings list+to an ID no finding carries, postures keyed by unified ID never attached, and+the Docker restart offer's `registry.Get` never found a real container. The+offer still binds its evidence to the record: `ProjectAttentionAction` compares+each evidence subject with the record's subject reference and the candidate+resource with the item's unified subject. Proof:+`TestProjectAttentionItemsNamesTheUnifiedSubjectOfEveryAlertKind` and+`TestProjectAttentionActionRequiresFreshConfirmedCanonicalEvidence` in+`internal/ai`, `TestAttentionHandlersNameTheInventorySubjectOfEachAlert` and+`TestAttentionActionPlanBindsCanonicalRecordEvidenceAndReplaysIdempotently`+(now with a real container reference and unified container) in `internal/api`.+### Patrol model-readiness evidenceKeep the Patrol model-readiness advisor provider-neutral and evidence-based.@@ -5189,6 +5211,12 @@ to scope by, so only the unified read state can scope its alerts. Proof:`internal/ai/patrol_run_test.go` and`TestDockerServiceAlertScopeAliasesDeriveIDFromName` in`internal/ai/patrol_state_scope_alias_test.go`.+Since 24 October 2026 the alert reference resolver also binds a container+reference with a complete ID (see unified-resources), so an alert-triggered+scope over the unified read state keeps the triggering container alert and its+`AlertContext`; before, the scoped state dropped the alert that raised the run+(`TestPatrolDockerContainerAlertScopeKeepsTheTriggeringAlert` in+`internal/ai/patrol_alert_scope_test.go`).The same governed-context rule also applies to the main unified AI resourceoverview: infrastructure, workload, alert-label, and top-consumer summariesmust not leak raw resource names, cluster labels, IP addresses, or unresolved@@ -7068,7 +7096,20 @@ demo patrol cycle against the unscoped active-alert snapshot and stamps`FindingsStore.StampAlertMirrors`, clearing the stamp once the alert resolves.The stamp is a derived read-model annotation: it is not persisted and is not areason to drop the finding. Surfaces demote stamped findings under the alert-instead of listing the same problem twice.+instead of listing the same problem twice. Alerts name resources by their+producer's reference while findings carry the unified resource ID, so the+reconcile resolves each alert's reference through Patrol's alert reference+resolver and the matcher accepts either identity+(`alertMirrorCandidate.CanonicalResourceID`). Before 24 October 2026 it+compared the raw strings, so no Proxmox, agent or Docker alert folded a+finding on its unified resource. A component alert (a filesystem, disk+temperature, RAID device or sensor, or a ZFS pool or device) resolves only to+the owner its siblings share (`AlertResourceReference.Component`), so it+contributes no canonical ID and folds only a finding linked to it explicitly:+a capacity finding about `/backup` must not hide under the `/data` alert+(`TestReconcileAlertMirrorsMatchesFindingsOnTheUnifiedResource`). Clients join+a stamped finding to its alert by `mirrors_alert_id`, which is the attention+item's operational record ID.Flapping is owned by the existing storm throttler rather than a parallelmechanism. `FindingsStore.recordTransitionLifecycleLocked` routes everydiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 8ec0e85cfa..832feea4e1 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -4803,6 +4803,17 @@ canonically confirmed postcondition before applying the requested maximum ofpresentation fields. A client must not scan a generic resolved-attention orsettled-action page and filter it after pagination, because unrelated historycan otherwise hide genuine verified work.+An item's `subjectResourceId` is the unified resource ID the alert's subject+reference resolves to in the org's current inventory, the same ID+`GET /api/ai/patrol/findings` carries as `resource_id` and that protection+postures and resource actions use, so clients scope findings and open+resources with it directly. The detail's `operationalRecord.subjectResourceId`+keeps the alert's own reference (`docker:<host ID>/<container ID>`, a Proxmox+source ID, `agent:<host ID>/disk:<label>`), and an item whose reference+inventory does not bind keeps that reference as its subject. Before+24 October 2026 the item carried the reference, which no finding matched. The+field's name, type and presence are unchanged for the relay mobile surface.+Proof: `TestAttentionHandlersNameTheInventorySubjectOfEachAlert`.The Patrol workbench may project the summary counts into its fixed lifecyclefilter labels at either desktop or narrow widths, but changing presentationdoes not create a parallel count or filter vocabulary: every selection still@@ -5155,7 +5166,10 @@ itself is unchanged. `GET /api/ai/patrol/findings` findings may carry`flapping` (`transition_count`, `window_hours`, `first_transition_at`,`last_transition_at`) under the same rule, plus `mirrors_alert_id` and`mirrors_alert_type` naming the active alert the finding restates (same-canonical resource, same condition class). All four fields are omitted when+canonical resource, same condition class). `mirrors_alert_id` equals that+alert's attention item `id` (its operational record ID), and clients join on+it, never on resource plus kind, which several alerts on one host can share.+All four fields are omitted whennot applicable and are derived read-model annotations, not lifecycle state;clients must not treat their absence as evidence of stability.`frontend-modern/src/api/patrolAttention.ts` (`AttentionFlapping`) anddiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 24ae5091c0..5cd32a7864 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -4462,7 +4462,10 @@ triggers are shared `Button` primitives in a labelled list, the inlineconfirmation note or rule reason is a `FormTextarea`, and the alert-onlyguidance link is a `ButtonLink`. `PatrolIntelligenceSurface.tsx` passes thePatrol findings accessor into the workbench; the workbench does not fetch or-poll findings itself.+poll findings itself. The alert-only guidance names Patrol's open findings on+the same resource from that accessor, and its `Browse Patrol findings for this+resource` trigger stays a shared `Button`, rendered only when that list is+non-empty.`Open resource` in the attention detail is a `ButtonLink` whose destinationcomes from `buildResourcePagePath`; the workbench hides it when no platformpage can show the subject instead of linking to a page that cannot.diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex eeb7f788b5..7d70cd70d9 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -2598,9 +2598,11 @@ Two users in a row (discussions #1623 and #1699) could not find the durablePatrol outcomes because they sat two levels below the Needs attention detail.The selected detail in `PatrolAttentionWorkbench.tsx` now owns a `Lastingdecisions` section beside the alert lifecycle controls. When a Patrol finding-mirrors the selected alert (same resource, backend-stamped `mirrorsAlertType`-equal to the item kind, joined by `getLinkedPatrolFindings` in-`patrolHomePresentation.ts` over the surface-supplied `findings` accessor),+mirrors the selected alert (backend-stamped `mirrorsAlertId` equal to the+item's operational record ID, joined by `getLinkedPatrolFindings` in+`patrolHomePresentation.ts` over the surface-supplied `findings` accessor;+before 24 October 2026 the join was resource plus kind, which cannot tell+apart two filesystem alerts on one host),the section lists Remember as expected, Dismiss: Not an issue, Dismiss: Later,and Create rule, each with one line stating what it does and how long it lasts(`PATROL_LASTING_DECISIONS`). Choosing one opens an inline confirmation with an@@ -2615,6 +2617,17 @@ active-only default set and the detail would otherwise claim Patrol hasnothing to remember. An alert with no mirrored finding saysplainly that Patrol has nothing to remember and points at alert thresholds,because the only durable control for a bare alert is the alert configuration.+When Patrol has open findings on the same resource that do not restate the+alert (`getPatrolFindingsOnSubject`: active findings on the item's subject,+the list "Browse Patrol findings for this resource" opens), the guidance names+the finding (or the count) and says Patrol keeps it separate from the alert,+so the decision is made on the finding; it no longer claims Patrol has raised+nothing. The browse button appears only when that list is non-empty, so it+never opens an empty scope. The join works because the attention item's+subject is the unified resource ID findings carry (see ai-runtime, 24 October+2026); before, a Docker container alert's raw `docker:<host>/<container>`+reference scoped the list to nothing and the detail denied a finding Patrol+had raised on that container.The temporary controls state in one visible line that acknowledgement andsuppression are short-term; the former `More ways to manage this issue`disclosure is gone.@@ -2636,7 +2649,8 @@ intermediate and narrow linked journey is exercised by`scripts/check-patrol-assistant-journey.mjs`.`PatrolAttentionWorkbench.test.tsx` pins the four decisions and their copy, therule reason requirement, the remembered-decision path, the alert-only-guidance, and the flapping collapse.+guidance with and without unlinked findings on the resource, and the flapping+collapse.### Open resource goes to the page that shows the resourcediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex d5508509e7..936836901d 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -3176,6 +3176,12 @@ as a bounded subject-ID batch. Recovery remains the sole owner of protected,attention, unprotected, and unknown derivation and its provider evidence.Attention projection may order and display that posture but cannot recompute itor call the store once per item.+The batch is keyed by each item's subject: the unified resource ID the alert's+own reference resolves to in current inventory, which is the ID recovery+records postures under. Before 24 October 2026 the batch asked for the alerts'+raw references (`pve1:node1:100`, `docker:<host>/<container>`), so a guest's+posture never attached to its alert. Only the requested IDs changed; no+recovery read, write or derivation path did.If posture lookup fails, lifecycle work remains visible with partial coverage.If no subject-linked posture exists, the UI says protection is unknown ratherdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 73f1543d14..5852f4af2c 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -223,6 +223,28 @@ select the canonical owner without interpreting alert strings independently.`alert_scope_test.go` verifies the registry and both read adapters, rejectedreferences and absent current owners. Scoped Patrol tests cover linked ownersand conflicting unqualified source IDs.+A Docker container alert (`docker:<host ID>/<container ID>`, built by+`alerts.DockerContainerResourceID`) binds the container collected under exactly+that host and complete 64-character ID, through the registry's own Docker+source key (`<host ID>/container/<container ID>`), the key `RecordChange`+already joins that alert's history to. A shortened ID, a container reported+without an ID (`docker:<host ID>/name:<name>`), a hostname or another host+binds nothing. Before 24 October 2026 only Docker host and Swarm service+references resolved here, so the Patrol inbox named container alerts by the+raw reference and never matched the unified container Patrol findings carry.+History recording is unchanged: `RecordChange` resolves complete container IDs+before this resolver and the journal backfill skips container references.+Proof: `TestAlertResourceReferenceBindsCollectedDockerContainer` in+`history_identity_test.go`, from a snapshot and from unified rows.+A binding reached through a component's owner (an agent's filesystem, disk+temperature, RAID device or custom sensor; a storage's ZFS pool or device)+carries `Component`: its owner is shared by sibling components, so consumers+that match one alert to one finding must not treat the owner as the alert's+subject. The Unraid array reference names the array's storage itself and is+not a component. Source targets come from the registry's view cache, which the+first resolution of a generation builds, instead of a scan of every source+mapping per reference, so resolving a page of alerts stays linear+(`TestAlertResourceReferenceMarksComponentOwners`).### Resource CPU temperature uses the one primary rulediff --git a/frontend-modern/browser-verification/d2b533c532891cf3.json b/frontend-modern/browser-verification/d2b533c532891cf3.jsonnew file mode 100644index 0000000000..bfe80471bd--- /dev/null+++ b/frontend-modern/browser-verification/d2b533c532891cf3.json@@ -0,0 +1,48 @@+{+ "version": 1,+ "base_sha": "31b3d3f2ea3744acb76e4e8f74968c0c828afa18",+ "verified_at": "2026-10-24T08:37:23Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx",+ "frontend-modern/src/features/patrol/patrolHomePresentation.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx": "43e9ab24dbd398710dfdde315e8bcd212532eab9a4a1ecfa88862d540a6107bd",+ "frontend-modern/src/features/patrol/patrolHomePresentation.ts": "b25847ef54b0742e672cb4d2b12868b4ab21e2869b2f7a5d88cb523d887eef69"+ },+ "routes": [+ "/patrol",+ "/patrol/activity"+ ],+ "viewports": [+ {+ "width": 1440,+ "height": 900+ },+ {+ "width": 1024,+ "height": 768+ },+ {+ "width": 390,+ "height": 844+ }+ ],+ "states": [+ "private Pulse Pro stack rebuilt from these exact bytes (embedded bundle; sha256 of both changed files matched this receipt) on pulse-dev, dev Pro licence, real Pulse agent reporting a private rootless Docker engine, busybox container afs-web made unhealthy by killing its httpd, so a real docker-container-health alert is open; Patrol model pointed at a local stub that answers only the tool-call self-test",+ "inbox item for the alert: subjectResourceId app-container-deef7b15adf61e36 (unified container) while operationalRecord.subjectResourceId keeps docker:afs-check-agent/ab9a99e3dc4c... (the alert's reference); Open resource links /docker/overview?q=afs-web and Adjust alert thresholds /alerts/thresholds/docker?q=afs-web",+ "unlinked state (two Patrol findings on the unified container, neither stamped yet): Lasting decisions read 'Patrol also raised 2 findings for this resource and keeps them separate from this alert, so decide on them from the findings' with Adjust alert thresholds and Browse Patrol findings for this resource; no lasting-decision list. An earlier build of the same flow with one unlinked finding read 'Patrol also raised Web server in container afs-web stopped answering for this resource and keeps it separate from this alert'",+ "Activity after Browse: 'Showing Patrol findings for afs-web' with both afs-web (app-container) rows and their Finding options (on main this scope was empty, 'No current issues are listed')",+ "linked state after one manual Patrol pass (analysis failed at the stub, end-of-cycle reconcile ran): mirrors_alert_id on 'Container afs-web is unhealthy' equals the item's operational record ID, the other finding stays unstamped, and the detail shows 'Patrol also raised Container afs-web is unhealthy for this resource. Decide once here' with the four lasting decisions and no Browse button; unscoped Activity folds it under '1 finding mirrors an active alert'",+ "1440 light, 1024 dark and 390 phone (mobile emulation) in headless Chromium on pulse-dev; zero console or page errors at every width; the earlier build was also checked in the in-app browser through a tunnel (DOM reads, pane hidden)"+ ],+ "interactions": [+ "opened the afs-web Docker container health item from the Patrol inbox list at each width",+ "read the Lasting decisions section text and buttons, screenshotted it and the detail at each width, before and after the Patrol pass",+ "clicked Browse Patrol findings for this resource: the view switched to Activity with Finding options and history open and scoped to afs-web; read and screenshotted the scoped list at each width",+ "ran one Patrol pass through the API and reopened the item: the linked-finding branch replaced the alert-only guidance",+ "opened Activity > Finding options and history unscoped and read the mirrored-findings fold",+ "component tests with negative controls cover the branches (no findings: browse hidden; one and two unlinked findings: named, browse opens the item's resource; a finding stamped for a sibling alert on the same host is not offered under this alert)"+ ]+}diff --git a/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx b/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsxindex e169843a01..5463aa0abb 100644--- a/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx+++ b/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx@@ -73,6 +73,7 @@ import {getAttentionFlappingPresentation,getAttentionHandoverClose,getLinkedPatrolFindings,+ getPatrolFindingsOnSubject,getPatrolRememberedDecisionPresentation,partitionPatrolAttention,PATROL_AUTONOMY_EXPERIENCE,@@ -902,6 +903,12 @@ function AttentionDetail(props: {if (!current || !findings) return [];return getLinkedPatrolFindings(current.item, findings);});+ const subjectFindings = createMemo(() => {+ const current = detail();+ const findings = props.findings?.();+ if (!current || !findings) return [];+ return getPatrolFindingsOnSubject(current.item, findings);+ });const orderedEvidence = createMemo(() =>[...(detail()?.evidence ?? [])].sort((left, right) => new Date(right.observedAt).getTime() - new Date(left.observedAt).getTime(),@@ -1177,6 +1184,7 @@ function AttentionDetail(props: {<AttentionLastingDecisionsitem={loaded().item}linkedFindings={linkedFindings()}+ subjectFindings={subjectFindings()}onOpenFindings={props.onOpenFindings}thresholdsHref={thresholdsHref()}/>@@ -1532,6 +1540,7 @@ function AttentionTimelineList(props: { timeline: AttentionItemDetail['timeline'function AttentionLastingDecisions(props: {item: AttentionItem;linkedFindings: UnifiedFinding[];+ subjectFindings: UnifiedFinding[];onOpenFindings?: (item: AttentionItem) => void;thresholdsHref: string;}) {@@ -1631,6 +1640,7 @@ function AttentionLastingDecisions(props: {fallback={<AttentionAlertOnlyGuidanceitem={props.item}+ subjectFindings={props.subjectFindings}onOpenFindings={props.onOpenFindings}thresholdsHref={props.thresholdsHref}/>@@ -1759,18 +1769,49 @@ function AttentionLastingDecisions(props: {);}+// Findings on the same resource that do not restate this alert keep their own+// lasting decisions, so the guidance names them and opens them instead of+// saying Patrol has raised nothing.function AttentionAlertOnlyGuidance(props: {item: AttentionItem;+ subjectFindings: UnifiedFinding[];onOpenFindings?: (item: AttentionItem) => void;thresholdsHref: string;}) {return (<div>- <p class="text-xs leading-5 text-muted">- This is an alert and Patrol has not raised a finding about it, so there is nothing for- Patrol to remember here. To change it for good, adjust when this alert fires or turn it off- for {props.item.subjectResourceName} under alert thresholds.- </p>+ <Show+ when={props.subjectFindings.length > 0}+ fallback={+ <p class="text-xs leading-5 text-muted">+ This is an alert and Patrol has not raised a finding about it, so there is nothing for+ Patrol to remember here. To change it for good, adjust when this alert fires or turn it+ off for {props.item.subjectResourceName} under alert thresholds.+ </p>+ }+ >+ <p class="text-xs leading-5 text-muted">+ <Show+ when={props.subjectFindings.length === 1}+ fallback={+ <>+ Patrol also raised{' '}+ <span class="font-medium text-base-content">+ {props.subjectFindings.length} findings+ </span>{' '}+ for this resource and keeps them separate from this alert, so decide on them from+ the findings.+ </>+ }+ >+ Patrol also raised{' '}+ <span class="font-medium text-base-content">{props.subjectFindings[0]?.title}</span> for+ this resource and keeps it separate from this alert, so decide on it from the finding.+ </Show>{' '}+ To change this alert for good, adjust when it fires or turn it off for{' '}+ {props.item.subjectResourceName} under alert thresholds.+ </p>+ </Show><div class="mt-2 flex flex-wrap gap-2"><ButtonLinkhref={props.thresholdsHref}@@ -1780,7 +1821,7 @@ function AttentionAlertOnlyGuidance(props: {>Adjust alert thresholds</ButtonLink>- <Show when={props.onOpenFindings}>+ <Show when={props.onOpenFindings && props.subjectFindings.length > 0}><Buttonvariant="ghost"size="sm"diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsx b/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsxindex b8960c4150..3357415d91 100644--- a/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsx+++ b/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsx@@ -1,5 +1,6 @@import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';import { Route, Router } from '@solidjs/router';+import { createSignal } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type {AttentionItem,@@ -172,7 +173,7 @@ const mirroredFinding = (overrides: Partial<UnifiedFinding> = {}): UnifiedFindindescription: 'The root volume has been filling for a week.',detectedAt: '2026-07-19T07:00:00Z',status: 'active',- mirrorsAlertId: 'alert-record-1',+ mirrorsAlertId: 'record-1',mirrorsAlertType: 'disk',...overrides,});@@ -1344,10 +1345,108 @@ describe('PatrolAttentionWorkbench', () => {'href','/alerts/thresholds/proxmox?q=Database+VM',);+ // With no open finding on the resource the scoped list would be empty.+ expect(+ screen.queryByRole('button', { name: 'Browse Patrol findings for this resource' }),+ ).not.toBeInTheDocument();+ });++ it('offers lasting decisions only for the finding that restates this alert, not a sibling alert on the same resource', async () => {+ // Two filesystem alerts on one host share the host's resource ID and kind.+ const active = item();+ apiMocks.getList.mockResolvedValue(+ listResponse([active], summary({ activeCount: 1, openCount: 1, calm: false })),+ );+ apiMocks.getDetail.mockResolvedValue(detail(active));+ render(() => (+ <Router>+ <Route+ path="/patrol"+ component={() => (+ <PatrolAttentionWorkbench+ findings={() => [+ mirroredFinding({+ id: 'finding-other-disk',+ title: 'Disk /backup on Database VM is 92% full',+ mirrorsAlertId: 'record-2',+ }),+ ]}+ />+ )}+ />+ </Router>+ ));+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'Open Database VM · Disk pressure',+ }),+ );++ expect(await screen.findByText(/keeps it separate from this alert/i)).toHaveTextContent(+ 'Patrol also raised Disk /backup on Database VM is 92% full for this resource',+ );+ expect(screen.queryByRole('list', { name: 'Lasting decisions' })).not.toBeInTheDocument();+ });++ it('names Patrol findings on the same resource that do not restate the alert and opens them', async () => {+ const active = item();+ apiMocks.getList.mockResolvedValue(+ listResponse([active], summary({ activeCount: 1, openCount: 1, calm: false })),+ );+ apiMocks.getDetail.mockResolvedValue(detail(active));+ const onOpenFindings = vi.fn();+ const [findings, setFindings] = createSignal<UnifiedFinding[]>([+ mirroredFinding({+ id: 'finding-restarts',+ category: 'reliability',+ title: 'Database VM restarted three times today',+ mirrorsAlertId: undefined,+ mirrorsAlertType: undefined,+ }),+ mirroredFinding({ id: 'finding-resolved', status: 'resolved', mirrorsAlertId: undefined }),+ mirroredFinding({+ id: 'finding-elsewhere',+ resourceId: 'pve:vm:102',+ mirrorsAlertId: undefined,+ }),+ ]);+ render(() => (+ <Router>+ <Route+ path="/patrol"+ component={() => (+ <PatrolAttentionWorkbench findings={findings} onOpenFindings={onOpenFindings} />+ )}+ />+ </Router>+ ));+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'Open Database VM · Disk pressure',+ }),+ );++ expect(await screen.findByText(/keeps it separate from this alert/i)).toHaveTextContent(+ 'Patrol also raised Database VM restarted three times today for this resource',+ );+ expect(screen.queryByText(/has not raised a finding/i)).not.toBeInTheDocument();+ expect(screen.queryByRole('list', { name: 'Lasting decisions' })).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: 'Browse Patrol findings for this resource' }),);expect(onOpenFindings).toHaveBeenCalledWith(active);++ setFindings((current) => [+ ...current,+ mirroredFinding({+ id: 'finding-io',+ title: 'Database VM disk latency is high',+ mirrorsAlertId: undefined,+ }),+ ]);+ expect(await screen.findByText(/keeps them separate from this alert/i)).toHaveTextContent(+ 'Patrol also raised 2 findings for this resource',+ );});it('collapses a flapping item into one label and a summarised timeline', async () => {diff --git a/frontend-modern/src/features/patrol/__tests__/patrolHomePresentation.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolHomePresentation.test.tsindex 9b07da74a7..5b42ace2db 100644--- a/frontend-modern/src/features/patrol/__tests__/patrolHomePresentation.test.ts+++ b/frontend-modern/src/features/patrol/__tests__/patrolHomePresentation.test.ts@@ -1,9 +1,12 @@import { describe, expect, it } from 'vitest';import type { PatrolObjective } from '@/api/patrol';import type { AttentionItem, AttentionItemDetail } from '@/api/patrolAttention';+import type { UnifiedFinding } from '@/stores/aiIntelligence';import {getAttentionHandoverClose,+ getLinkedPatrolFindings,getPatrolAttentionDecisionReason,+ getPatrolFindingsOnSubject,getPatrolObjectiveProtectionSummary,partitionPatrolAttention,} from '../patrolHomePresentation';@@ -205,3 +208,81 @@ describe('getAttentionHandoverClose', () => {).toBeNull();});});++describe('getPatrolFindingsOnSubject', () => {+ const finding = (overrides: Partial<UnifiedFinding> = {}): UnifiedFinding => ({+ id: 'finding-1',+ source: 'ai-patrol',+ resourceId: 'app-container-a1bf6ef7c728a8db',+ resourceName: 'pulse-live-web',+ resourceType: 'app-container',+ category: 'reliability',+ severity: 'warning',+ title: 'Web server in container pulse-live-web stopped answering',+ description: 'The health check has been refused for 40 minutes.',+ detectedAt: '2026-10-24T07:00:00Z',+ status: 'active',+ ...overrides,+ });++ it('lists the open findings on the unified resource the alert item names', () => {+ // The backend resolves the alert's own reference ("docker:<host>/<container>")+ // to the unified container the findings carry.+ const item = attentionItem({ subjectResourceId: 'app-container-a1bf6ef7c728a8db' });+ const onSubject = finding();+ const mirroring = finding({+ id: 'finding-2',+ mirrorsAlertId: 'record-1',+ mirrorsAlertType: 'availability',+ });+ const findings = [+ onSubject,+ mirroring,+ finding({ id: 'resolved', status: 'resolved' }),+ finding({ id: 'dismissed', status: 'dismissed', dismissedReason: 'not_an_issue' }),+ finding({ id: 'elsewhere', resourceId: 'app-container-0594de6a76cb71fe' }),+ ];++ expect(getPatrolFindingsOnSubject(item, findings).map(({ id }) => id)).toEqual([+ 'finding-1',+ 'finding-2',+ ]);+ expect(getLinkedPatrolFindings(item, findings).map(({ id }) => id)).toEqual(['finding-2']);+ expect(getPatrolFindingsOnSubject(attentionItem({ subjectResourceId: ' ' }), findings)).toEqual(+ [],+ );+ });++ it('links a finding only to the alert it restates when alerts share a resource and kind', () => {+ // Two filesystem alerts on one host name the same unified host and kind.+ const data = attentionItem({+ id: 'record-data',+ operationalRecordId: 'record-data',+ subjectResourceId: 'agent-6e63a900bdf8d8b7',+ kind: 'disk',+ });+ const backup = attentionItem({+ id: 'record-backup',+ operationalRecordId: 'record-backup',+ subjectResourceId: 'agent-6e63a900bdf8d8b7',+ kind: 'disk',+ });+ const backupFull = finding({+ id: 'backup-full',+ resourceId: 'agent-6e63a900bdf8d8b7',+ category: 'capacity',+ title: 'Disk /backup is 92% full',+ mirrorsAlertId: 'record-backup',+ mirrorsAlertType: 'disk',+ });++ expect(getLinkedPatrolFindings(backup, [backupFull]).map(({ id }) => id)).toEqual([+ 'backup-full',+ ]);+ expect(getLinkedPatrolFindings(data, [backupFull])).toEqual([]);+ // The other filesystem's finding is still an open finding on the host.+ expect(getPatrolFindingsOnSubject(data, [backupFull]).map(({ id }) => id)).toEqual([+ 'backup-full',+ ]);+ });+});diff --git a/frontend-modern/src/features/patrol/patrolHomePresentation.ts b/frontend-modern/src/features/patrol/patrolHomePresentation.tsindex 29ae650713..d4e38c1369 100644--- a/frontend-modern/src/features/patrol/patrolHomePresentation.ts+++ b/frontend-modern/src/features/patrol/patrolHomePresentation.ts@@ -231,23 +231,37 @@ const normalizeResourceKey = (value: string | undefined): string =>(value ?? '').trim().toLowerCase();/**- * Patrol findings that restate this attention item's alert: same resource and- * the backend-stamped mirror type equals the alert kind. Resolved findings are- * history and are not linked.+ * Patrol findings that restate this attention item's alert: the backend stamps+ * the alert's ID, which is the item's operational record ID, on each one.+ * Several alerts can share one resource and kind (a host's filesystems), so the+ * resource is not enough to tell them apart. Resolved findings are history and+ * are not linked.*/export function getLinkedPatrolFindings(item: AttentionItem,findings: readonly UnifiedFinding[],+): UnifiedFinding[] {+ const alertId = item.operationalRecordId.trim();+ if (!alertId) return [];+ return findings.filter(+ (finding) => finding.status !== 'resolved' && finding.mirrorsAlertId?.trim() === alertId,+ );+}++/**+ * Open Patrol findings on this attention item's subject: the list "Browse+ * Patrol findings for this resource" opens. The item names the unified+ * resource its alert resolves to, the ID Patrol findings carry.+ */+export function getPatrolFindingsOnSubject(+ item: AttentionItem,+ findings: readonly UnifiedFinding[],): UnifiedFinding[] {const resource = normalizeResourceKey(item.subjectResourceId);- const kind = normalizeResourceKey(item.kind);- if (!resource || !kind) return [];+ if (!resource) return [];return findings.filter((finding) =>- finding.status !== 'resolved' &&- Boolean(finding.mirrorsAlertId) &&- normalizeResourceKey(finding.resourceId) === resource &&- normalizeResourceKey(finding.mirrorsAlertType) === kind,+ finding.status === 'active' && normalizeResourceKey(finding.resourceId) === resource,);}diff --git a/internal/ai/attention.go b/internal/ai/attention.goindex b43400b45c..62e186b692 100644--- a/internal/ai/attention.go+++ b/internal/ai/attention.go@@ -13,6 +13,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"recoverymodel "github.com/rcourtman/pulse-go-rewrite/internal/recovery/model"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")const (@@ -140,11 +141,17 @@ type AttentionProjection struct {// ProjectAttentionItems is the single Patrol read-model projection over the// canonical alert lifecycle. It does not inspect loose alert metadata to-// invent work and it never creates a second writable lifecycle.+// invent work and it never creates a second writable lifecycle. An item's+// subject is the unified resource its record's subject reference resolves to+// in current inventory (AttentionSubjectResourceID), the identity Patrol+// findings, protection postures and resource actions carry; the operational+// record keeps the alert's own reference. A nil subjects resolver keeps every+// record's reference.func ProjectAttentionItems(active []alerts.Alert,history []alerts.Alert,postures map[string]recoverymodel.ProtectionPosture,+ subjects unifiedresources.AlertResourceReferenceResolver,now time.Time,) AttentionProjection {if now.IsZero() {@@ -162,7 +169,7 @@ func ProjectAttentionItems(details := make([]AttentionItemDetail, 0, len(records))for _, alert := range records {- detail, ok := projectAttentionAlert(alert, postures, now)+ detail, ok := projectAttentionAlert(alert, postures, subjects, now)if !ok {continue}@@ -208,9 +215,28 @@ func attentionAlertNewer(candidate, existing alerts.Alert) bool {return candidate.OperationalRecord.LastObservedAt.After(existing.OperationalRecord.LastObservedAt)}+// AttentionSubjectResourceID names the unified resource an alert lifecycle+// record's subject reference ("docker:<host>/<container>", a Proxmox source+// ID, "agent:<host>/disk:<label>") resolves to in current inventory, or the+// reference itself when inventory does not bind it.+func AttentionSubjectResourceID(+ subjects unifiedresources.AlertResourceReferenceResolver,+ reference string,+) string {+ reference = strings.TrimSpace(reference)+ if subjects == nil || reference == "" {+ return reference+ }+ if binding, _ := subjects.ResolveAlertResourceReference(reference); binding.ResourceID != "" {+ return binding.ResourceID+ }+ return reference+}+func projectAttentionAlert(alert alerts.Alert,postures map[string]recoverymodel.ProtectionPosture,+ subjects unifiedresources.AlertResourceReferenceResolver,now time.Time,) (AttentionItemDetail, bool) {if alert.OperationalRecord == nil {@@ -233,8 +259,9 @@ func projectAttentionAlert(related = append(related, AttentionResource{ResourceID: resourceID})}+ subjectResourceID := AttentionSubjectResourceID(subjects, record.SubjectResourceID)var posture *recoverymodel.ProtectionPosture- if candidate, found := postures[record.SubjectResourceID]; found {+ if candidate, found := postures[subjectResourceID]; found {value := candidate.Clone()posture = &value}@@ -242,7 +269,7 @@ func projectAttentionAlert(item := AttentionItem{ID: record.ID,OperationalRecordID: record.ID,- SubjectResourceID: record.SubjectResourceID,+ SubjectResourceID: subjectResourceID,SubjectResourceName: resourceName,SubjectResourceType: attentionResourceType(alert),Kind: strings.TrimSpace(alert.Type),diff --git a/internal/ai/attention_actions.go b/internal/ai/attention_actions.goindex 95c8251a42..2c62d16601 100644--- a/internal/ai/attention_actions.go+++ b/internal/ai/attention_actions.go@@ -82,8 +82,10 @@ func ProjectAttentionAction(if evidence.Permissions != operationaltrust.EvidencePermissionsSufficient {return AttentionActionOffer{}, AttentionActionEvidencePermissionLimited}+ // Evidence names the record's own subject reference; the item's+ // subject is the unified resource that reference resolves to.if unified.CanonicalResourceID(evidence.Subject.ResourceID) !=- unified.CanonicalResourceID(item.SubjectResourceID) {+ unified.CanonicalResourceID(detail.OperationalRecord.SubjectResourceID) {return AttentionActionOffer{}, AttentionActionEvidenceSubjectMismatch}if evidence.Correlation != nil && evidence.Correlation.CandidateCount != 1 {diff --git a/internal/ai/attention_actions_test.go b/internal/ai/attention_actions_test.goindex a55a3acfb5..9ecc02d4f8 100644--- a/internal/ai/attention_actions_test.go+++ b/internal/ai/attention_actions_test.go@@ -1,6 +1,7 @@package aiimport (+ "strings""testing""time"@@ -70,6 +71,20 @@ func TestProjectAttentionActionRequiresFreshConfirmedCanonicalEvidence(t *testin},want: AttentionActionEvidenceSubjectMismatch,},+ {+ name: "evidence about another container",+ mutate: func(detail *AttentionItemDetail, _ *AttentionActionCandidate) {+ detail.Evidence[0].Subject.ResourceID = "docker:host-1/" + strings.Repeat("d2", 32)+ },+ want: AttentionActionEvidenceSubjectMismatch,+ },+ {+ name: "resource is another container",+ mutate: func(_ *AttentionItemDetail, candidate *AttentionActionCandidate) {+ candidate.Resource.ID = "app-container-0000000000000000"+ },+ want: AttentionActionResourceUnavailable,+ },{name: "capability missing",mutate: func(_ *AttentionItemDetail, candidate *AttentionActionCandidate) {@@ -189,9 +204,12 @@ func TestAttentionActionVerificationStatePreservesExecutionAndPostconditionTruth}}+// The alert lifecycle record and its evidence name the container by the alert's+// own reference; the item names the unified container it resolves to.func attentionDockerHealthDetail(now time.Time) AttentionItemDetail {- resourceID := "docker:host-1/container-1"- evidence := attentionTestEvidence(resourceID, now)+ reference := "docker:host-1/" + strings.Repeat("c1", 32)+ resourceID := "app-container-5f0c2d7a91b3e4f6"+ evidence := attentionTestEvidence(reference, now)return AttentionItemDetail{Item: AttentionItem{ID: "operational-docker-health",@@ -204,7 +222,7 @@ func attentionDockerHealthDetail(now time.Time) AttentionItemDetail {},OperationalRecord: operationaltrust.OperationalRecord{ID: "operational-docker-health",- SubjectResourceID: resourceID,+ SubjectResourceID: reference,},Evidence: []operationaltrust.EvidenceEnvelope{evidence},}diff --git a/internal/ai/attention_performance_test.go b/internal/ai/attention_performance_test.goindex fcddd1a07d..8075aacc9e 100644--- a/internal/ai/attention_performance_test.go+++ b/internal/ai/attention_performance_test.go@@ -2,16 +2,30 @@ package aiimport ("fmt"+ "strings""testing""time""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")func TestAttentionProjectionLargeCardinalityKeepsResponseBounded(t *testing.T) {const cardinality = 10_000+ const guests = 2_000now := time.Date(2026, 7, 19, 9, 0, 0, 0, time.UTC)+ // Every alert names a guest by its Proxmox reference, so the projection+ // resolves each subject against a populated inventory.+ snapshot := models.StateSnapshot{VMs: make([]models.VM, guests)}+ for index := range snapshot.VMs {+ vmid := 100 + index+ snapshot.VMs[index] = models.VM{ID: fmt.Sprintf("pve1:node1:%d", vmid), VMID: vmid, Name: fmt.Sprintf("guest-%d", vmid),+ Node: "node1", Instance: "pve1", Status: "running", Type: "qemu", LastSeen: now}+ }+ registry := unifiedresources.NewRegistry(nil)+ registry.IngestSnapshot(snapshot)active := make([]alerts.Alert, cardinality)for index := range active {active[index] = attentionTestAlert(@@ -21,10 +35,13 @@ func TestAttentionProjectionLargeCardinalityKeepsResponseBounded(t *testing.T) {now.Add(-time.Duration(index)*time.Second),now,)+ reference := snapshot.VMs[index%guests].ID+ active[index].ResourceID = reference+ active[index].OperationalRecord.SubjectResourceID = reference}startedAt := time.Now()- projection := ProjectAttentionItems(active, nil, nil, now)+ projection := ProjectAttentionItems(active, nil, nil, registry, now)elapsed := time.Since(startedAt)if projection.Summary.ActiveCount != cardinality {t.Fatalf(@@ -33,6 +50,11 @@ func TestAttentionProjectionLargeCardinalityKeepsResponseBounded(t *testing.T) {cardinality,)}+ for _, detail := range projection.Details {+ if !strings.HasPrefix(detail.Item.SubjectResourceID, "vm-") {+ t.Fatalf("subject %q was not resolved to its unified guest", detail.Item.SubjectResourceID)+ }+ }page, err := PaginateAttentionDetails(projection.Details, 1, MaxAttentionPageSize)if err != nil {t.Fatalf("PaginateAttentionDetails(): %v", err)diff --git a/internal/ai/attention_test.go b/internal/ai/attention_test.goindex 6e89d5fc08..6a53464885 100644--- a/internal/ai/attention_test.go+++ b/internal/ai/attention_test.go@@ -1,6 +1,8 @@package aiimport (+ "fmt"+ "strings""testing""time"@@ -8,6 +10,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"recoverymodel "github.com/rcourtman/pulse-go-rewrite/internal/recovery/model"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")func TestProjectAttentionItemsUsesCanonicalLifecycleAndStableOrdering(t *testing.T) {@@ -26,7 +29,7 @@ func TestProjectAttentionItemsUsesCanonicalLifecycleAndStableOrdering(t *testing),}- projected := ProjectAttentionItems(active, nil, postures, now)+ projected := ProjectAttentionItems(active, nil, postures, nil, now)if projected.Summary.ActiveCount != 3 {t.Fatalf("ActiveCount = %d, want 3", projected.Summary.ActiveCount)}@@ -75,7 +78,7 @@ func TestProjectAttentionItemsDeduplicatesHistoryAndActiveByOperationalRecord(tnow,)- projected := ProjectAttentionItems([]alerts.Alert{active}, []alerts.Alert{historical}, nil, now)+ projected := ProjectAttentionItems([]alerts.Alert{active}, []alerts.Alert{historical}, nil, nil, now)if len(projected.Details) != 1 {t.Fatalf("details = %d, want one canonical item", len(projected.Details))}@@ -107,6 +110,7 @@ func TestProjectAttentionItemsDoesNotReviveNonTerminalHistorySnapshots(t *testinnil,[]alerts.Alert{orphanedOpen, resolved},nil,+ nil,now,)if len(projected.Details) != 1 {@@ -139,7 +143,7 @@ func TestProjectAttentionItemsRepresentsUncertainEvidenceHonestly(t *testing.T))unknown.Evidence = nil- projected := ProjectAttentionItems([]alerts.Alert{stale, unknown}, nil, nil, now)+ projected := ProjectAttentionItems([]alerts.Alert{stale, unknown}, nil, nil, nil, now)if projected.Summary.UncertainCount != 2 || projected.Summary.ActiveCount != 2 {t.Fatalf("summary = %+v, want two uncertain active items", projected.Summary)}@@ -203,7 +207,7 @@ func TestAttentionFiltersAndPaginationCoverLifecycleStates(t *testing.T) {active = append(active, alert)}- projected := ProjectAttentionItems(active, history, nil, now)+ projected := ProjectAttentionItems(active, history, nil, nil, now)checks := map[AttentionFilter]int{AttentionFilterActive: 3,AttentionFilterOpen: 1,@@ -233,7 +237,7 @@ func TestAttentionFiltersAndPaginationCoverLifecycleStates(t *testing.T) {func TestProjectAttentionItemsProducesCurrentCalmEvaluation(t *testing.T) {now := time.Date(2026, 7, 19, 5, 0, 0, 0, time.UTC)- projected := ProjectAttentionItems(nil, nil, nil, now)+ projected := ProjectAttentionItems(nil, nil, nil, nil, now)if !projected.Summary.Calm || projected.Summary.ActiveCount != 0 {t.Fatalf("summary = %+v, want current calm evaluation", projected.Summary)}@@ -344,7 +348,7 @@ func TestProjectAttentionItemsLeadsHeldMetricAlertsWithTheLiveReading(t *testingalert.Value = 80alert.Metadata = tt.metadataalert.MetricStatus = tt.status- projected := ProjectAttentionItems([]alerts.Alert{alert}, nil, nil, now)+ projected := ProjectAttentionItems([]alerts.Alert{alert}, nil, nil, nil, now)if len(projected.Details) != 1 {t.Fatalf("details = %d, want 1", len(projected.Details))}@@ -605,7 +609,7 @@ func TestProjectAttentionItemsCollapsesOpenResolvedChurnIntoFlapping(t *testing.},)- projected := ProjectAttentionItems([]alerts.Alert{alert}, nil, nil, now)+ projected := ProjectAttentionItems([]alerts.Alert{alert}, nil, nil, nil, now)if len(projected.Details) != 1 {t.Fatalf("details = %d, want 1", len(projected.Details))}@@ -640,8 +644,104 @@ func TestProjectAttentionItemsLeavesSingleRecurrenceUnlabelled(t *testing.T) {},)- projected := ProjectAttentionItems([]alerts.Alert{alert}, nil, nil, now)+ projected := ProjectAttentionItems([]alerts.Alert{alert}, nil, nil, nil, now)if projected.Details[0].Item.Flapping != nil {t.Fatalf("one recurrence was labelled flapping: %+v", projected.Details[0].Item.Flapping)}}++// An alert lifecycle record names its subject by the alert producer's own+// reference. The item names the unified resource that reference binds in+// current inventory, the ID Patrol findings and protection postures carry,+// for every producer shape; the record keeps the alert's reference.+func TestProjectAttentionItemsNamesTheUnifiedSubjectOfEveryAlertKind(t *testing.T) {+ now := time.Date(2026, 10, 24, 8, 0, 0, 0, time.UTC)+ containerID := strings.Repeat("ab12", 16)+ snapshot := models.StateSnapshot{+ Nodes: []models.Node{{ID: "pve1-node1", Name: "node1", Instance: "pve1", Status: "online", LastSeen: now}},+ VMs: []models.VM{{ID: "pve1:node1:100", VMID: 100, Name: "web-vm", Node: "node1", Instance: "pve1", Status: "running", Type: "qemu", LastSeen: now}},+ Containers: []models.Container{{ID: "pve1:node1:101", VMID: 101, Name: "dns-ct", Node: "node1", Instance: "pve1", Status: "running", Type: "lxc", LastSeen: now}},+ Storage: []models.Storage{{ID: "pve1-node1-local", Name: "local", Node: "node1", Instance: "pve1", Type: "dir", Status: "available", Enabled: true, Active: true}},+ Hosts: []models.Host{{ID: "host-src-1", Hostname: "backup-box", MachineID: "machine-1", Status: "online", LastSeen: now}},+ DockerHosts: []models.DockerHost{{ID: "dock-agent-1", AgentID: "dock-agent-1", Hostname: "docker-box", Status: "online", LastSeen: now,+ Containers: []models.DockerContainer{{ID: containerID, Name: "web", State: "running", Health: "unhealthy"}}}},+ }+ registry := unifiedresources.NewRegistry(nil)+ registry.IngestSnapshot(snapshot)+ resourceIDByName := map[string]string{}+ for _, resource := range registry.List() {+ resourceIDByName[resource.Name] = resource.ID+ }+ cases := []struct {+ reference string+ resource string+ }{+ {"pve1-node1", "node1"},+ {"pve1:node1:100", "web-vm"},+ {"pve1:node1:101", "dns-ct"},+ {"pve1-node1-local", "local"},+ {"pve1-node1-local/zfs-pool:tank", "local"},+ {"agent:host-src-1", "backup-box"},+ {"agent:host-src-1/disk:docker-data", "backup-box"},+ {alerts.DockerHostResourceID("dock-agent-1"), "docker-box"},+ {alerts.DockerContainerResourceID("dock-agent-1", containerID, "web"), "web"},+ }+ active := make([]alerts.Alert, 0, len(cases)+2)+ want := make(map[string]string, len(cases)+2)+ for i, tc := range cases {+ resourceID := resourceIDByName[tc.resource]+ if resourceID == "" || resourceID == tc.reference {+ t.Fatalf("fixture resource %q missing or named like its alert reference: %q", tc.resource, resourceID)+ }+ id := fmt.Sprintf("record-%d", i)+ active = append(active, attentionSubjectTestAlert(id, tc.reference, now))+ want[id] = resourceID+ }+ // A reference inventory does not bind keeps its own name, as does an alert+ // already raised on the unified resource.+ active = append(active,+ attentionSubjectTestAlert("record-removed", "agent:removed-host/disk:data", now),+ attentionSubjectTestAlert("record-unified", resourceIDByName["web-vm"], now),+ )+ want["record-removed"] = "agent:removed-host/disk:data"+ want["record-unified"] = resourceIDByName["web-vm"]+ postures := map[string]recoverymodel.ProtectionPosture{+ resourceIDByName["web-vm"]: attentionTestPosture(resourceIDByName["web-vm"], recoverymodel.ProtectionStateProtected, now),+ }++ projected := ProjectAttentionItems(active, nil, postures, registry, now)+ if len(projected.Details) != len(want) {+ t.Fatalf("details = %d, want %d", len(projected.Details), len(want))+ }+ references := map[string]string{"record-removed": "agent:removed-host/disk:data", "record-unified": resourceIDByName["web-vm"]}+ for i, tc := range cases {+ references[fmt.Sprintf("record-%d", i)] = tc.reference+ }+ for _, detail := range projected.Details {+ id := detail.Item.ID+ if got := detail.Item.SubjectResourceID; got != want[id] {+ t.Errorf("%s (%s): subject = %q, want %q", id, references[id], got, want[id])+ }+ if got := detail.OperationalRecord.SubjectResourceID; got != references[id] {+ t.Errorf("%s: record subject = %q, want the alert's reference %q", id, got, references[id])+ }+ if got := detail.Item.ProtectionPosture != nil; got != (want[id] == resourceIDByName["web-vm"]) {+ t.Errorf("%s: posture attached = %v", id, got)+ }+ }++ // Without inventory every item keeps its record's reference.+ for _, detail := range ProjectAttentionItems(active, nil, postures, nil, now).Details {+ if detail.Item.SubjectResourceID != references[detail.Item.ID] {+ t.Errorf("%s: subject = %q without inventory, want %q", detail.Item.ID, detail.Item.SubjectResourceID, references[detail.Item.ID])+ }+ }+}++func attentionSubjectTestAlert(id, reference string, now time.Time) alerts.Alert {+ alert := attentionTestAlert(id, operationaltrust.OperationalOpen, operationaltrust.SeverityWarning, now.Add(-time.Hour), now)+ alert.ResourceID = reference+ alert.OperationalRecord.SubjectResourceID = reference+ alert.Evidence[0].Subject.ResourceID = reference+ return alert+}diff --git a/internal/ai/findings.go b/internal/ai/findings.goindex 9b719ab5f8..8067da065d 100644--- a/internal/ai/findings.go+++ b/internal/ai/findings.go@@ -263,10 +263,11 @@ type Finding struct {// this finding restates (for example a Proxmox guest stopped finding// beside a powered-off alert). Stamped by Patrol after every run and// cleared when the alert resolves; the attention surface folds such- // findings under the alert instead of listing them twice.+ // findings under the alert instead of listing them twice. The ID is the+ // alert's attention item (operational record) ID, which is what clients+ // join on: several alerts can share a resource and kind.MirrorsAlertID string `json:"mirrors_alert_id,omitempty"`- // MirrorsAlertType is the alert type of MirrorsAlertID, so a client- // holding the alert projection can join on resource plus kind.+ // MirrorsAlertType is the alert type of MirrorsAlertID.MirrorsAlertType string `json:"mirrors_alert_type,omitempty"`}diff --git a/internal/ai/findings_alert_mirror.go b/internal/ai/findings_alert_mirror.goindex 23571199a7..8a2741deca 100644--- a/internal/ai/findings_alert_mirror.go+++ b/internal/ai/findings_alert_mirror.go@@ -17,10 +17,17 @@ import ()// alertMirrorCandidate is the minimal alert shape the matcher needs.+// ResourceID is the alert's own reference ("docker:<host>/<container>", a+// Proxmox source ID); CanonicalResourceID is the unified resource it resolves+// to in current inventory. It stays empty when inventory does not bind the+// reference or binds only an owner the alert shares with sibling components+// (a host's filesystems or sensors, a storage's ZFS pool), so a finding about+// one filesystem never folds under another's alert.type alertMirrorCandidate struct {- ID string- ResourceID string- Type string+ ID string+ ResourceID string+ CanonicalResourceID string+ Type string}// Condition classes shared by alerts and findings. An empty class never@@ -129,7 +136,8 @@ func findingConditionClass(f *Finding) string {// findingMirrorsAlert reports whether f restates alert: an explicit// AlertIdentifier link, or the same canonical resource with the same-// condition class.+// condition class. A finding names the unified resource, or rarely the alert's+// own reference, so either identity of the alert's subject matches.func findingMirrorsAlert(f *Finding, alert alertMirrorCandidate) bool {if f == nil {return false@@ -139,8 +147,9 @@ func findingMirrorsAlert(f *Finding, alert alertMirrorCandidate) bool {return true}findingResource := unified.CanonicalResourceID(f.ResourceID)- alertResource := unified.CanonicalResourceID(alert.ResourceID)- if findingResource == "" || alertResource == "" || findingResource != alertResource {+ if findingResource == "" ||+ (findingResource != unified.CanonicalResourceID(alert.ResourceID) &&+ findingResource != unified.CanonicalResourceID(alert.CanonicalResourceID)) {return false}class := findingConditionClass(f)@@ -177,19 +186,26 @@ func matchFindingsToAlerts(findings []*Finding, alerts []alertMirrorCandidate) m// reconcileAlertMirrors re-stamps every unresolved finding against the// current unscoped active-alert set. It runs at the end of every patrol// cycle so a finding that mirrors an alert is folded while the alert is-// active and released once the alert resolves.+// active and released once the alert resolves. Each alert's reference is+// resolved to the unified resource it names, which Patrol findings carry.func (p *PatrolService) reconcileAlertMirrors() int {if p == nil || p.findings == nil || p.stateProvider == nil {return 0}- snapshot := p.stateProvider.ReadSnapshot()- candidates := make([]alertMirrorCandidate, 0, len(snapshot.ActiveAlerts))- for _, alert := range snapshot.ActiveAlerts {- candidates = append(candidates, alertMirrorCandidate{- ID: alert.ID,- ResourceID: alert.ResourceID,- Type: alert.Type,- })+ state := p.currentPatrolRuntimeState()+ var subjects unified.AlertResourceReferenceResolver+ if len(state.ActiveAlerts) > 0 {+ subjects = patrolAlertReferenceResolver(state)+ }+ candidates := make([]alertMirrorCandidate, 0, len(state.ActiveAlerts))+ for _, alert := range state.ActiveAlerts {+ candidate := alertMirrorCandidate{ID: alert.ID, ResourceID: alert.ResourceID, Type: alert.Type}+ if subjects != nil {+ if binding, _ := subjects.ResolveAlertResourceReference(alert.ResourceID); !binding.Component {+ candidate.CanonicalResourceID = binding.ResourceID+ }+ }+ candidates = append(candidates, candidate)}findings := p.findings.GetAll(nil)return p.findings.StampAlertMirrors(matchFindingsToAlerts(findings, candidates))diff --git a/internal/ai/findings_alert_mirror_test.go b/internal/ai/findings_alert_mirror_test.goindex 5a2b0e40ca..8a4fe50703 100644--- a/internal/ai/findings_alert_mirror_test.go+++ b/internal/ai/findings_alert_mirror_test.go@@ -1,8 +1,13 @@package aiimport (+ "strings""testing""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")func TestFindingMirrorsAlert_SameResourceSameCondition(t *testing.T) {@@ -154,3 +159,61 @@ func TestStampAlertMirrors_SetsAndClears(t *testing.T) {t.Fatalf("f1 stamp was not cleared: %+v", f)}}++// Alerts name resources by their producer's references while Patrol findings+// carry the unified resource ID. The patrol-end reconcile resolves each+// alert's reference through current inventory before matching, so a container+// health finding folds under the Docker health alert on that container and a+// guest-stopped finding under the guest's powered-off alert. A filesystem alert+// resolves only to the host its sibling filesystems share, so it never folds a+// finding about another filesystem.+func TestReconcileAlertMirrorsMatchesFindingsOnTheUnifiedResource(t *testing.T) {+ webID := strings.Repeat("ab12", 16)+ now := time.Now()+ snapshot := models.StateSnapshot{+ VMs: []models.VM{{ID: "pve1:node1:100", VMID: 100, Name: "db", Node: "node1", Instance: "pve1", Status: "stopped", Type: "qemu", LastSeen: now}},+ Hosts: []models.Host{{ID: "host-src-1", Hostname: "backup-box", MachineID: "machine-1", Status: "online", LastSeen: now}},+ DockerHosts: []models.DockerHost{{ID: "dock-agent-1", Hostname: "docker-box", Status: "online", LastSeen: now,+ Containers: []models.DockerContainer{+ {ID: webID, Name: "web", State: "running", Health: "unhealthy"},+ {ID: strings.Repeat("cd34", 16), Name: "api", State: "running", Health: "unhealthy"},+ }}},+ ActiveAlerts: []models.Alert{+ {ID: "docker-container-health-web", ResourceID: alerts.DockerContainerResourceID("dock-agent-1", webID, "web"), Type: "docker-container-health"},+ {ID: "guest-powered-off-db", ResourceID: "pve1:node1:100", Type: "powered-off"},+ {ID: "host-disk-data", ResourceID: "agent:host-src-1/disk:data", Type: "disk"},+ },+ }+ registry := unifiedresources.NewRegistry(nil)+ registry.IngestSnapshot(snapshot)+ resourceIDByName := map[string]string{}+ for _, resource := range registry.List() {+ resourceIDByName[resource.Name] = resource.ID+ }++ ps := NewPatrolService(nil, &mockStateProvider{state: snapshot})+ for id, finding := range map[string]Finding{+ "web-unhealthy": {ResourceID: resourceIDByName["web"], ResourceType: "app-container", Title: "Container web is unhealthy"},+ "api-unhealthy": {ResourceID: resourceIDByName["api"], ResourceType: "app-container", Title: "Container api is unhealthy"},+ "db-stopped": {ResourceID: resourceIDByName["db"], ResourceType: "vm", Title: "Proxmox VM db stopped"},+ "backup-full": {ResourceID: resourceIDByName["backup-box"], ResourceType: "agent", Title: "Disk /backup on backup-box is 92% full", Category: FindingCategoryCapacity},+ } {+ if finding.ResourceID == "" {+ t.Fatalf("fixture resource for %s missing", id)+ }+ if finding.Category == "" {+ finding.Category = FindingCategoryReliability+ }+ finding.ID, finding.Severity = id, FindingSeverityWarning+ ps.findings.Add(&finding)+ }++ if changed := ps.reconcileAlertMirrors(); changed != 2 {+ t.Fatalf("reconcile stamped %d findings, want the web and db findings", changed)+ }+ for id, want := range map[string]string{"web-unhealthy": "docker-container-health-web", "db-stopped": "guest-powered-off-db", "api-unhealthy": "", "backup-full": ""} {+ if got := ps.findings.Get(id).MirrorsAlertID; got != want {+ t.Errorf("%s mirrors %q, want %q", id, got, want)+ }+ }+}diff --git a/internal/ai/patrol_alert_scope_test.go b/internal/ai/patrol_alert_scope_test.goindex e75ed7a6e6..51cf2715e7 100644--- a/internal/ai/patrol_alert_scope_test.go+++ b/internal/ai/patrol_alert_scope_test.go@@ -5,6 +5,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -167,3 +168,33 @@ func TestPatrolDiskAlertRejectsUntrustedSubjects(t *testing.T) {})}}++// A Docker container alert ("docker:<host ID>/<container ID>") binds the+// collected container, so an alert-triggered run over the unified inventory+// keeps the triggering alert and its trusted context in scope instead of+// investigating the container without the alert that raised it.+func TestPatrolDockerContainerAlertScopeKeepsTheTriggeringAlert(t *testing.T) {+ containerID := strings.Repeat("ab12", 16)+ alert := models.Alert{ID: "docker-container-health-web", Type: "docker-container-health", Level: "critical",+ ResourceID: alerts.DockerContainerResourceID("dock-agent-1", containerID, "web"), ResourceName: "web",+ Message: "Docker container 'web' health is unhealthy"}+ snapshot := models.StateSnapshot{+ DockerHosts: []models.DockerHost{{ID: "dock-agent-1", Hostname: "docker-box", Status: "online", LastSeen: time.Now(),+ Containers: []models.DockerContainer{{ID: containerID, Name: "web", State: "running", Health: "unhealthy"}}}},+ ActiveAlerts: []models.Alert{alert},+ }+ registry := unifiedresources.NewRegistry(nil)+ registry.IngestSnapshot(snapshot)+ state := newPatrolRuntimeStateWithProviders(snapshot, registry, unifiedresources.NewUnifiedAIAdapter(registry))++ resolved, resolution := resolvePatrolScopeState(state, AlertTriggeredPatrolScope(alert.ID, alert.ResourceID, "app-container", alert.Type))+ if len(resolution.UnmatchedResourceIDs)+len(resolution.AmbiguousResourceIDs) != 0 || len(resolution.EffectiveResourceIDs) == 0 {+ t.Fatalf("container alert scope did not resolve: %+v", resolution)+ }+ if resolved.AlertContext == nil || resolved.AlertContext.ResourceID != alert.ResourceID || resolved.AlertContext.Message != alert.Message {+ t.Fatalf("lost the triggering alert's context: %+v", resolved.AlertContext)+ }+ if filtered := filterPatrolStateByScopeState(state, resolved); len(filtered.ActiveAlerts) != 1 || filtered.ActiveAlerts[0].ID != alert.ID {+ t.Fatalf("scoped state dropped the triggering alert: %+v", filtered.ActiveAlerts)+ }+}diff --git a/internal/api/attention_actions_test.go b/internal/api/attention_actions_test.goindex f048ab38de..aabb885fdd 100644--- a/internal/api/attention_actions_test.go+++ b/internal/api/attention_actions_test.go@@ -6,6 +6,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "strings""testing""time"@@ -41,13 +42,17 @@ func (*attentionActionTestExecutor) CheckActionAvailable(func TestAttentionActionPlanBindsCanonicalRecordEvidenceAndReplaysIdempotently(t *testing.T) {now := time.Now().UTC()alert := attentionHandlerAlert("docker-health-record", operationaltrust.OperationalOpen, now)- resourceID := "docker:host-1/container-1"+ // The alert names the container by its own reference; Pulse inventory+ // names it by the unified ID the action must target.+ containerID := strings.Repeat("c1", 32)+ reference := alerts.DockerContainerResourceID("host-1", containerID, "api")+ resourceID := "app-container-5f0c2d7a91b3e4f6"alert.Type = ai.AttentionDockerHealthKind- alert.ResourceID = resourceID+ alert.ResourceID = referencealert.ResourceName = "API container"alert.Metadata = map[string]interface{}{"resourceType": string(unified.ResourceTypeAppContainer)}- alert.OperationalRecord.SubjectResourceID = resourceID- alert.Evidence[0].Subject.ResourceID = resourceID+ alert.OperationalRecord.SubjectResourceID = reference+ alert.Evidence[0].Subject.ResourceID = referenceresources := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})resources.SetStateProvider(resourceUnifiedSeedProvider{@@ -59,6 +64,8 @@ func TestAttentionActionPlanBindsCanonicalRecordEvidenceAndReplaysIdempotently(tStatus: unified.StatusWarning,LastSeen: now,UpdatedAt: now,+ Sources: []unified.DataSource{unified.SourceDocker},+ Docker: &unified.DockerData{HostSourceID: "host-1", ContainerID: containerID},Capabilities: []unified.ResourceCapability{{Name: ai.AttentionDockerRestartCapability,Type: unified.CapabilityTypeCommon,@@ -109,8 +116,13 @@ func TestAttentionActionPlanBindsCanonicalRecordEvidenceAndReplaysIdempotently(tif err := json.Unmarshal(detailResponse.Body.Bytes(), &detail); err != nil {t.Fatalf("decode detail: %v", err)}+ if detail.Item.SubjectResourceID != resourceID || detail.OperationalRecord.SubjectResourceID != reference {+ t.Fatalf("subject = %q record subject = %q, want %q and %q",+ detail.Item.SubjectResourceID, detail.OperationalRecord.SubjectResourceID, resourceID, reference)+ }if len(detail.Item.AvailableActions) != 1 ||detail.Item.AvailableActions[0].Capability != ai.AttentionDockerRestartCapability ||+ detail.Item.AvailableActions[0].TargetResourceID != resourceID ||detail.Item.AvailableActions[0].ActionID != "" {t.Fatalf("initial offers = %+v", detail.Item.AvailableActions)}@@ -160,6 +172,7 @@ func TestAttentionActionPlanBindsCanonicalRecordEvidenceAndReplaysIdempotently(tt.Fatalf("origin audit found=%t err=%v", found, err)}if audit.ID != first.ActionID ||+ audit.Request.ResourceID != resourceID ||audit.Origin == nil ||audit.Origin.OperationalRecordID != "docker-health-record" ||len(audit.Origin.EvidenceIDs) != 1 ||diff --git a/internal/api/attention_handlers.go b/internal/api/attention_handlers.goindex d4134ca2c4..f37892b89d 100644--- a/internal/api/attention_handlers.go+++ b/internal/api/attention_handlers.go@@ -17,6 +17,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/recovery"recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager"recoverymodel "github.com/rcourtman/pulse-go-rewrite/internal/recovery/model"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rs/zerolog/log")@@ -234,17 +235,18 @@ func (h *AttentionHandlers) project(if err != nil {return ai.AttentionProjection{}, err}+ subjects := h.attentionSubjects(ctx)postures := map[string]recoverymodel.ProtectionPosture{}postureComplete := trueif includeProtectionPosture {- resourceIDs := attentionResourceIDs(active, history)+ resourceIDs := attentionResourceIDs(active, history, subjects)postures, postureComplete = h.loadProtectionPostures(ctx,GetOrgID(ctx),resourceIDs,)}- projection := ai.ProjectAttentionItems(active, history, postures, time.Now().UTC())+ projection := ai.ProjectAttentionItems(active, history, postures, subjects, time.Now().UTC())if !postureComplete {projection.Summary.CoverageState = "partial"}@@ -252,6 +254,21 @@ func (h *AttentionHandlers) project(return projection, nil}+// attentionSubjects binds alert subject references to the org's current+// unified inventory, so items name the resources Patrol findings, postures and+// actions carry. Without inventory, items keep the alerts' own references.+func (h *AttentionHandlers) attentionSubjects(ctx context.Context) unified.AlertResourceReferenceResolver {+ if h == nil || h.resources == nil {+ return nil+ }+ registry, err := h.resources.buildRegistry(GetOrgID(ctx))+ if err != nil || registry == nil {+ log.Debug().Err(err).Msg("Patrol attention subject inventory is unavailable")+ return nil+ }+ return registry+}+func (h *AttentionHandlers) loadProtectionPostures(ctx context.Context,orgID string,@@ -361,7 +378,10 @@ func parsePositiveAttentionInt(return value, true}-func attentionResourceIDs(active, history []alerts.Alert) []string {+func attentionResourceIDs(+ active, history []alerts.Alert,+ subjects unified.AlertResourceReferenceResolver,+) []string {unique := make(map[string]struct{}, len(active)+len(history))add := func(values []alerts.Alert, history bool) {for _, alert := range values {@@ -371,7 +391,7 @@ func attentionResourceIDs(active, history []alerts.Alert) []string {if history && alert.OperationalRecord.State != operationaltrust.OperationalResolved {continue}- if resourceID := strings.TrimSpace(alert.OperationalRecord.SubjectResourceID); resourceID != "" {+ if resourceID := ai.AttentionSubjectResourceID(subjects, alert.OperationalRecord.SubjectResourceID); resourceID != "" {unique[resourceID] = struct{}{}}}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex c7b60cdd9a..acaebe5486 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -55,6 +55,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/internal/notifications"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust""github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rcourtman/pulse-go-rewrite/internal/recovery""github.com/rcourtman/pulse-go-rewrite/internal/relay"@@ -860,6 +861,86 @@ func TestContract_PatrolAttentionRoutesAcceptMobileRelayCapability(t *testing.T)}}+// The inbox names each alert's subject by the unified resource Pulse inventory+// resolves the alert's own reference to, the ID Patrol findings carry, so the+// "Browse Patrol findings for this resource" scope matches them. The record+// keeps the alert's reference.+func TestContract_PatrolAttentionSubjectIsTheInventoryResource(t *testing.T) {+ now := time.Now().UTC()+ containerID := strings.Repeat("ab12", 16)+ inventory := unifiedresources.NewRegistry(nil)+ inventory.IngestSnapshot(models.StateSnapshot{+ VMs: []models.VM{{ID: "pve1:node1:100", VMID: 100, Name: "web-vm", Node: "node1", Instance: "pve1", Status: "running", Type: "qemu", LastSeen: now}},+ Hosts: []models.Host{{ID: "host-src-1", Hostname: "backup-box", MachineID: "machine-1", Status: "online", LastSeen: now}},+ DockerHosts: []models.DockerHost{{ID: "dock-agent-1", Hostname: "docker-box", Status: "online", LastSeen: now,+ Containers: []models.DockerContainer{{ID: containerID, Name: "web", State: "running", Health: "unhealthy"}}}},+ })+ resourceIDByName := map[string]string{}+ for _, resource := range inventory.List() {+ resourceIDByName[resource.Name] = resource.ID+ }+ resources := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})+ resources.SetStateProvider(resourceUnifiedSeedProvider{+ snapshot: models.StateSnapshot{LastUpdate: now},+ resources: inventory.List(),+ })+ references := map[string]string{+ "guest-cpu": "pve1:node1:100",+ "host-disk": "agent:host-src-1/disk:docker-data",+ "web-health": alerts.DockerContainerResourceID("dock-agent-1", containerID, "web"),+ "removed-machine": "agent:removed-host",+ }+ want := map[string]string{+ "guest-cpu": resourceIDByName["web-vm"],+ "host-disk": resourceIDByName["backup-box"],+ "web-health": resourceIDByName["web"],+ "removed-machine": "agent:removed-host",+ }+ active := make([]alerts.Alert, 0, len(references))+ for id, reference := range references {+ alert := attentionHandlerAlert(id, operationaltrust.OperationalOpen, now)+ alert.ResourceID = reference+ alert.OperationalRecord.SubjectResourceID = reference+ alert.Evidence[0].Subject.ResourceID = reference+ active = append(active, alert)+ }+ handler := &AttentionHandlers{+ readAlerts: func(context.Context) ([]alerts.Alert, []alerts.Alert, error) {+ return active, nil, nil+ },+ }+ handler.SetActionDependencies(resources, testActionAuthority())++ response := httptest.NewRecorder()+ handler.HandleAttention(response, httptest.NewRequest(http.MethodGet, "/api/ai/patrol/attention?limit=10", nil))+ if response.Code != http.StatusOK {+ t.Fatalf("status = %d body=%s", response.Code, response.Body.String())+ }+ var payload attentionListResponse+ if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(payload.Data) != len(want) {+ t.Fatalf("data = %+v, want %d items", payload.Data, len(want))+ }+ for _, item := range payload.Data {+ if want[item.ID] == "" || item.SubjectResourceID != want[item.ID] {+ t.Errorf("%s: subject = %q, want %q", item.ID, item.SubjectResourceID, want[item.ID])+ }+ }++ response = httptest.NewRecorder()+ handler.HandleAttention(response, httptest.NewRequest(http.MethodGet, "/api/ai/patrol/attention/web-health", nil))+ var detail ai.AttentionItemDetail+ if err := json.Unmarshal(response.Body.Bytes(), &detail); err != nil {+ t.Fatalf("decode detail: %v (status %d)", err, response.Code)+ }+ if detail.Item.SubjectResourceID != want["web-health"] ||+ detail.OperationalRecord.SubjectResourceID != references["web-health"] {+ t.Fatalf("detail subject = %q record subject = %q", detail.Item.SubjectResourceID, detail.OperationalRecord.SubjectResourceID)+ }+}+func TestContract_AlertDeliveryDiagnosisRouteIsReadOnlyMonitoringRead(t *testing.T) {source, err := os.ReadFile(filepath.Join("alerting", "alerts.go"))if err != nil {diff --git a/internal/unifiedresources/history_identity.go b/internal/unifiedresources/history_identity.goindex 5c9ea41a1d..a37700bdc3 100644--- a/internal/unifiedresources/history_identity.go+++ b/internal/unifiedresources/history_identity.go@@ -12,10 +12,15 @@ import (// AlertResourceReference binds a collected alert subject to current canonical// inventory. Source targets are durable identities, never display names.+// Component reports that the reference names a part of ResourceID that is not+// a resource of its own (an agent's filesystem, disk temperature, RAID device+// or custom sensor, or a storage's ZFS pool or pool device): ResourceID is its+// owner, which several such alerts share.type AlertResourceReference struct {ResourceID stringResourceType ResourceTypeSourceTargets []SourceTarget+ Component bool}type AlertResourceReferenceResolver interface {@@ -46,27 +51,34 @@ func (rr *ResourceRegistry) AlertResourceReferences() map[string]AlertResourceRe// correlation. It never consults retained history bindings or matches names.// claimed is true for an inventory conflict as well as a successful binding;// conflicts have an empty ResourceID and must not fall back to another source.+// Source targets come from the view cache, built once per registry generation:+// a per-reference scan of every source mapping made a batch of references+// cost alerts × inventory.func (rr *ResourceRegistry) ResolveAlertResourceReference(ref string) (AlertResourceReference, bool) {if rr == nil {return AlertResourceReference{}, false}- rr.mu.RLock()- defer rr.mu.RUnlock()- id, claimed := rr.resolveHistoryReferenceLocked(ref)- if id == "" {- return AlertResourceReference{}, claimed- }- resource := rr.resources[id]- if resource == nil {- return AlertResourceReference{}, true+ type resolution struct {+ binding AlertResourceReference+ claimed bool}- var targets []SourceTarget- if !rr.viewsDirty && rr.cachedSourceTargets != nil {- targets = append([]SourceTarget(nil), rr.cachedSourceTargets[id]...)- } else {- targets = rr.collectSourceTargetsLocked(id, resource.Type)- }- return AlertResourceReference{ResourceID: id, ResourceType: resource.Type, SourceTargets: targets}, true+ result := withViewCache(rr, func() resolution {+ id, claimed, component := rr.resolveAlertReferenceLocked(ref)+ if id == "" {+ return resolution{claimed: claimed}+ }+ resource := rr.resources[id]+ if resource == nil {+ return resolution{claimed: true}+ }+ return resolution{binding: AlertResourceReference{+ ResourceID: id,+ ResourceType: resource.Type,+ SourceTargets: append([]SourceTarget(nil), rr.cachedSourceTargets[id]...),+ Component: component,+ }, claimed: true}+ })+ return result.binding, result.claimed}func (a *UnifiedAIAdapter) ResolveAlertResourceReference(ref string) (AlertResourceReference, bool) {@@ -145,12 +157,22 @@ func dockerHostHistoryReference(ref string) (hostID, serviceID string, ok bool)return hostID, serviceID, true}-// dockerHistoryOwnerLocked resolves a Docker host or Swarm service alert-// reference through the registry's own Docker source identities. The host ID-// is the Docker host's source ID. A service reference names the service with-// that exact ID in the host's Swarm cluster, which every manager of the-// cluster reports under its own host ID.+// dockerHistoryOwnerLocked resolves a Docker host, Swarm service or container+// alert reference through the registry's own Docker source identities. The+// host ID is the Docker host's source ID. A service reference names the service+// with that exact ID in the host's Swarm cluster, which every manager of the+// cluster reports under its own host ID. A container reference binds only with+// a complete container ID, to the container collected under that host and ID:+// the same source key RecordChange joins its history to.func (rr *ResourceRegistry) dockerHistoryOwnerLocked(ref string) string {+ if sourceID, _, ok := legacyDockerHistoryIdentity(ref); ok {+ containerResourceID := rr.bySource[SourceDocker][sourceID]+ container := rr.resources[containerResourceID]+ if container == nil || CanonicalResourceType(container.Type) != ResourceTypeAppContainer {+ return ""+ }+ return containerResourceID+ }hostID, serviceID, ok := dockerHostHistoryReference(ref)if !ok {return ""@@ -223,7 +245,8 @@ func historySubResourceOwner(ref string) (ownerRef string, ownerType ResourceTyp// history it joins. Only durable identities qualify: the canonical ID, a// retired era, a source ID (Proxmox node, guest and storage IDs), a// node-scoped Proxmox guest reference, an agent alert reference-// ("agent:<host ID>"), a Docker host or Swarm service ID, or the owner of a+// ("agent:<host ID>"), a Docker host, Swarm service or complete container ID,+// or the owner of a// sub-resource reference (historySubResourceOwner). Names and hostnames never// bind history, so a resource named like a system reference cannot capture// its events. claimed reports that inventory answers to the reference,@@ -239,17 +262,26 @@ func (rr *ResourceRegistry) resolveHistoryReference(ref string) (resourceID stri}func (rr *ResourceRegistry) resolveHistoryReferenceLocked(ref string) (resourceID string, claimed bool) {+ resourceID, claimed, _ = rr.resolveAlertReferenceLocked(ref)+ return resourceID, claimed+}++// resolveAlertReferenceLocked is resolveHistoryReferenceLocked that also+// reports whether the reference names a component of the resource it resolves+// to (AlertResourceReference.Component). An agent's Unraid array reference+// ("agent:<host ID>/storage:<array>") names the array's storage itself.+func (rr *ResourceRegistry) resolveAlertReferenceLocked(ref string) (resourceID string, claimed, component bool) {ref = CanonicalResourceID(ref)if ref == "" {- return "", false+ return "", false, false}if isDockerHistoryReference(ref) {resourceID = rr.dockerHistoryOwnerLocked(ref)- return resourceID, resourceID != ""+ return resourceID, resourceID != "", false}if isProxmoxPhysicalDiskAlertReference(ref) {// A device path is not durable identity (proxmoxDiskAlertOwner).- return "", false+ return "", false, false}matches := rr.durableHistoryMatchesLocked(ref)if ownerRef, ownerType, ok := historySubResourceOwner(ref); ok && len(matches) == 0 {@@ -263,18 +295,19 @@ func (rr *ResourceRegistry) resolveHistoryReferenceLocked(ref string) (resourceI// when its canonical resource is a VM, container or node.typeMatches := CanonicalResourceType(owner.Type) == ownerType || (ownerType == ResourceTypeAgent && owner.Agent != nil)if len(owners) != 1 || !typeMatches {- return "", true+ return "", true, false}matches[id] = struct{}{}}+ component = !(strings.HasPrefix(ref, "agent:") && ownerType == ResourceTypeStorage)}if len(matches) != 1 {- return "", len(matches) > 1+ return "", len(matches) > 1, false}for id := range matches {resourceID = id}- return resourceID, true+ return resourceID, true, component}// durableHistoryMatchesLocked lists the resources that answer to a referencediff --git a/internal/unifiedresources/history_identity_test.go b/internal/unifiedresources/history_identity_test.goindex 41de0ef61a..95f12c8e32 100644--- a/internal/unifiedresources/history_identity_test.go+++ b/internal/unifiedresources/history_identity_test.go@@ -893,6 +893,102 @@ func TestAlertResourceReferenceRequiresCurrentDurableOwner(t *testing.T) {}}+// A Docker container alert ("docker:<host ID>/<container ID>") binds the+// container collected under that host and complete ID, from a snapshot or from+// unified rows, so Patrol and the inbox name the container Patrol findings+// carry. Shortened IDs, names, another host and a removed container bind+// nothing.+func TestAlertResourceReferenceBindsCollectedDockerContainer(t *testing.T) {+ container := strings.Repeat("ab12", 16)+ now := time.Now()+ snapshot := models.StateSnapshot{DockerHosts: []models.DockerHost{+ {ID: "dh-7f3a", Hostname: "tower", Status: "online", LastSeen: now, Containers: []models.DockerContainer{+ {ID: container, Name: "web", State: "running"},+ {ID: container[:12], Name: "short", State: "running"},+ {Name: "nameless", State: "running"},+ }},+ {ID: "dh-91c0", Hostname: "rack", Status: "online", LastSeen: now},+ }}+ collected := NewRegistry(nil)+ collected.IngestSnapshot(snapshot)+ containerID := collected.sourceResourceID(SourceDocker, "dh-7f3a/container/"+container)+ require.NotEmpty(t, containerID)+ rehydrated := NewRegistry(nil)+ rehydrated.IngestResources(collected.List())+ for name, registry := range map[string]*ResourceRegistry{"snapshot": collected, "unified rows": rehydrated} {+ binding, claimed := registry.ResolveAlertResourceReference("docker:dh-7f3a/" + container)+ require.True(t, claimed, name)+ require.Equal(t, containerID, binding.ResourceID, name)+ require.Equal(t, ResourceTypeAppContainer, binding.ResourceType, name)+ sourceKeys := make([]string, 0, len(binding.SourceTargets))+ for _, target := range binding.SourceTargets {+ sourceKeys = append(sourceKeys, string(target.Source)+"="+target.SourceID)+ }+ require.Contains(t, sourceKeys, "docker=dh-7f3a/container/"+container, name)+ for _, ref := range []string{+ "docker:dh-7f3a/" + container[:12], // shortened ID+ "docker:dh-7f3a/web", // container name+ "docker:dh-7f3a/name:nameless", // container without an ID+ "docker:dh-91c0/" + container, // another host+ "docker:tower/" + container, // hostname+ } {+ binding, claimed := registry.ResolveAlertResourceReference(ref)+ require.Empty(t, binding.ResourceID, "%s: %s", name, ref)+ require.False(t, claimed, "%s: %s", name, ref)+ }+ }+ snapshot.DockerHosts[0].Containers = nil+ removed := NewRegistry(nil)+ removed.IngestSnapshot(snapshot)+ binding, claimed := removed.ResolveAlertResourceReference("docker:dh-7f3a/" + container)+ require.Empty(t, binding.ResourceID)+ require.False(t, claimed)+}++// A filesystem, sensor or ZFS pool alert resolves to the owner it shares with+// its sibling components, so the binding says so; a reference to the resource+// itself does not. Resolution reads source targets from the view cache, which+// the first lookup builds, instead of scanning every mapping per reference.+func TestAlertResourceReferenceMarksComponentOwners(t *testing.T) {+ now := time.Now()+ container := strings.Repeat("cd34", 16)+ registry := NewRegistry(nil)+ registry.IngestSnapshot(models.StateSnapshot{+ Nodes: []models.Node{{ID: "pve1-node1", Name: "node1", Instance: "pve1", Status: "online", LastSeen: now}},+ VMs: []models.VM{{ID: "pve1:node1:100", VMID: 100, Name: "web-vm", Node: "node1", Instance: "pve1", Status: "running", Type: "qemu", LastSeen: now}},+ Storage: []models.Storage{{ID: "pve1-node1-local", Name: "local", Node: "node1", Instance: "pve1", Type: "zfspool", Status: "available", Enabled: true, Active: true}},+ Hosts: []models.Host{{ID: "host-src-1", Hostname: "backup-box", MachineID: "machine-1", Status: "online", LastSeen: now}},+ DockerHosts: []models.DockerHost{{ID: "dh-7f3a", Hostname: "tower", Status: "online", LastSeen: now,+ Containers: []models.DockerContainer{{ID: container, Name: "web", State: "running"}}}},+ })+ registry.mu.RLock()+ require.True(t, registry.viewsDirty, "fixture must start without built views")+ registry.mu.RUnlock()+ for ref, component := range map[string]bool{+ "pve1-node1": false,+ "pve1:node1:100": false,+ "pve1-node1-local": false,+ "pve1-node1-local/zfs-pool:tank": true,+ "pve1-node1-local/zfs-pool:tank/device:sda": true,+ "agent:host-src-1": false,+ "agent:host-src-1/disk:data": true,+ "agent:host-src-1/disk_temp:sda": true,+ "agent:host-src-1/raid:md0": true,+ "agent:host-src-1/custom:fan": true,+ "docker:dh-7f3a": false,+ "docker:dh-7f3a/" + container: false,+ } {+ binding, claimed := registry.ResolveAlertResourceReference(ref)+ require.True(t, claimed, ref)+ require.NotEmpty(t, binding.ResourceID, ref)+ require.Equal(t, component, binding.Component, ref)+ }+ registry.mu.RLock()+ defer registry.mu.RUnlock()+ require.False(t, registry.viewsDirty)+ require.NotNil(t, registry.cachedSourceTargets)+}+func TestHistoryIdentityLinkedAgentDiskUsesCanonicalOwner(t *testing.T) {store := NewMemoryStore()snapshot := models.StateSnapshot{