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
Harden Operational Trust rollout contracts
rcourtman83672a00a890
diff --git a/docs/AI.md b/docs/AI.mdindex 0db5677fcd..d11ab87ad5 100644--- a/docs/AI.md+++ b/docs/AI.md@@ -121,6 +121,13 @@ only inside selected context and receives policy-shaped summaries andreferences. Assistant can explain the item, but it cannot create lifecycletruth, invent action authority, or hide uncertainty.+Open items can be acknowledged directly. Suppression is temporary and requires+an operator reason plus a bounded expiry; it never resolves the detector's+finding. Eligible Pulse Pro Docker health items can offer a governed restart.+That journey uses the canonical action plan, approval, execution, audit, and+verification APIs. A successful command does not resolve the attention item;+fresh detector evidence must still confirm recovery.+### What Patrol SeesEvery patrol run passes the LLM comprehensive context about your environment:diff --git a/docs/API.md b/docs/API.mdindex 364eb0a266..22c47b5426 100644--- a/docs/API.md+++ b/docs/API.md@@ -1066,9 +1066,27 @@ Runs a focused investigation for an alert payload (used by the UI).- Returns one attention item with its operational record, lifecycletimeline, typed evidence, recommended next step, relationships, andprotection posture.-- All three attention routes require `monitoring:read`. They are read-side- projections only; alert lifecycle mutations remain owned by the canonical- alert routes.+- `GET /api/ai/patrol/attention/{id}/evidence/{evidenceId}`+ - Returns one exact retained evidence envelope with its current freshness.+ - Returns `410 attention_evidence_detail_expired` when the operational+ record still links the ID but the bounded detail has expired.+- `POST /api/ai/patrol/attention/{id}/acknowledge`+- `POST /api/ai/patrol/attention/{id}/unacknowledge`+- `POST /api/ai/patrol/attention/{id}/suppress`+ - Body: `{ "reason": "...", "expiresAt": "<RFC3339>" }`.+ - The expiry must be in the future and no more than 30 days away.+- `POST /api/ai/patrol/attention/{id}/unsuppress`+- `POST /api/ai/patrol/attention/{id}/actions/restart/plan`+ - Creates or replays the one server-owned Docker restart plan attached to+ this operational record and its exact evidence IDs.+ - Requires the canonical action authorization, an eligible server-side+ offer, and the Pulse Pro `ai_autofix` entitlement. Clients cannot supply+ command authority or override the target.+- Attention reads require `monitoring:read`; lifecycle mutations require+ `monitoring:write`. Action decision and execution use `/api/actions` and+ retain their existing action-specific scopes.+- Attention IDs and evidence IDs are opaque and can contain slashes. Clients+ must path-escape each ID.- `GET /api/ai/patrol/autonomy`- `PUT /api/ai/patrol/autonomy`- `GET /api/ai/patrol/status`diff --git a/docs/OPERATIONAL_TRUST.md b/docs/OPERATIONAL_TRUST.mdnew file mode 100644index 0000000000..af24e836eb--- /dev/null+++ b/docs/OPERATIONAL_TRUST.md@@ -0,0 +1,202 @@+# Operational Trust++Operational Trust is Pulse v6's shared model for answering five operator+questions:++1. What needs attention now?+2. What evidence supports that conclusion?+3. Is the affected resource protected by usable recovery history?+4. What changed in the issue lifecycle?+5. Can Pulse offer a narrow action, and did fresh evidence verify its result?++Alerts, the Patrol attention queue, navigation counts, attached availability+checks, notifications, protection posture, and governed actions project the+same canonical records. None of those views owns a second writable lifecycle.++## Lifecycle states++| State | Operator meaning |+| :--- | :--- |+| `observing` | Evidence is being confirmed. This is not yet active work. |+| `open` | Current evidence supports an operational issue. |+| `acknowledged` | An operator has seen the issue. The issue is not resolved. |+| `suppressed` | The issue is temporarily removed from active attention with an actor, reason, and bounded expiry. |+| `resolving` | Recovery evidence exists, but the detector has not yet confirmed normal health. |+| `resolved` | Fresh detector evidence confirms that the issue no longer applies. |+| `stale` | The prior issue remains relevant, but its collection evidence is no longer current. |+| `unknown` | Permissions, completeness, provider state, or identity prevent a stronger conclusion. |++Missing observations never resolve an open record. Collector disconnects move+existing work to `stale`; permission or provider uncertainty moves it to+`unknown`. A successful action result also does not close a record. Only fresh+detector evidence can confirm recovery.++Acknowledgement is reversible and does not reduce the active issue truth.+Suppression requires a non-empty reason and an expiry no more than 30 days in+the future. The Patrol UI offers shorter 1-hour, 24-hour, and 7-day choices by+default.++## Evidence++Every evidence envelope records:++- a stable opaque evidence ID;+- provider, collector, and optional provider instance;+- one canonical resource ID or one unresolved provider-scoped reference;+- observation, ingestion, and optional validity times;+- completeness, confidence, and permission state;+- an optional bounded payload reference and identity-correlation proof.++`fresh`, `complete`, and `confirmed` are independent dimensions. Partial,+denied, unavailable, stale, inferred, ambiguous, and unknown evidence is+represented explicitly and never upgraded to healthy by a client.++The attention detail response contains the retained envelopes needed for the+normal operator journey. An authorized client can request one exact envelope+through the evidence endpoint. If the record still links the evidence ID but+its bounded detail has expired, the endpoint returns `410+attention_evidence_detail_expired`; it does not pretend the evidence never+existed.++## Protection posture++Protection posture is evaluated server-side per canonical subject resource:++- `protected`: current usable protection satisfies policy;+- `attention`: protection exists but freshness, verification, or provider+ outcome needs attention;+- `unprotected`: sufficient evidence confirms that required protection is+ absent;+- `unknown`: identity, history, permissions, or collection coverage cannot+ support a stronger claim.++The response explains the conclusion, preserves provider-specific state, and+links the recovery and repository resources involved. Platform tables fetch+posture in batches of at most 200 resource IDs. They must not issue one network+request per row.++## Availability++An availability check attaches to an existing unified resource only when an+explicit link resolves or identity correlation yields exactly one candidate.+The relationship carries a stable relationship ID and the evidence ID that+supports it. Ambiguous checks remain standalone. An attached check appears on+the owning platform row and detail; it is not duplicated as another inventory+resource.++Availability success is time-bounded. A stale successful observation is+`stale`, not healthy. A failure enters the same alert lifecycle and Patrol+attention queue as other detectors.++## Patrol workflow++The normal operator path is:++1. Open Patrol from the monitor shell.+2. Review the urgency-ordered active queue.+3. Select an item for impact, next step, resource, evidence, protection, and+ lifecycle detail.+4. Acknowledge it, or temporarily suppress it with a reason and expiry.+5. If an eligible Pulse Pro action is offered, review the server-owned plan,+ approve it, run it, and inspect execution and verification separately.++A calm state appears only when the lifecycle evaluation succeeded, coverage is+current, and no active item exists. A failed read or partial coverage never+becomes a calm claim.++The first governed action is a Docker container restart. It is offered only+for a uniquely identified container with fresh confirmed unhealthy evidence,+declared executor readiness, the required authorization scope, and the+`ai_autofix` entitlement. The action framework owns plan hashing, approval,+idempotent execution, durable audit, restart reconciliation, and verification.++## API and authorization++Read routes require `monitoring:read`:++- `GET /api/ai/patrol/attention`+- `GET /api/ai/patrol/attention/summary`+- `GET /api/ai/patrol/attention/{id}`+- `GET /api/ai/patrol/attention/{id}/evidence/{evidenceId}`++Lifecycle mutations require `monitoring:write`:++- `POST /api/ai/patrol/attention/{id}/acknowledge`+- `POST /api/ai/patrol/attention/{id}/unacknowledge`+- `POST /api/ai/patrol/attention/{id}/suppress`+- `POST /api/ai/patrol/attention/{id}/unsuppress`++Suppression body:++```json+{+ "reason": "Planned host maintenance",+ "expiresAt": "2026-07-20T08:00:00Z"+}+```++Planning an offered restart requires the action scopes enforced by the+canonical action API and an active `ai_autofix` entitlement:++```text+POST /api/ai/patrol/attention/{id}/actions/restart/plan+```++Action decision, execution, detail, and audit use `/api/actions`.++All IDs are opaque. Clients must path-escape operational-record and evidence+IDs because canonical IDs can contain `/`, `:`, and provider-specific+segments.++## Metrics++The `/metrics` listener exposes Operational Trust counters and histograms under+`pulse_operational_trust_*`. Labels use closed, low-cardinality vocabularies;+resource IDs, evidence IDs, provider-instance names, actors, and destination+IDs never appear as labels.++Useful alerts include:++- sustained growth in `active_count_mismatch_total`;+- notification `failed` or `dead_letter` outcomes;+- growing stale, unavailable, denied, or partial evidence observations;+- identity `ambiguous` or `unresolved` outcomes;+- action verification `contradicted`, `inconclusive`, or `timed_out` outcomes.++## Upgrade and compatibility++Operational Trust migrations are additive. Existing alert, notification,+recovery, relationship, availability, and action records are normalized on+read or migrated in their owning stores. Read-side compatibility fields remain+supported where older clients need them, but new writes go only through the+canonical lifecycle, recovery, unified-resource, notification, and action+owners.++The Pulse Mobile primary backlog uses `/api/ai/patrol/attention` and preserves+operational record, evidence, and action-verification identity. Its old finding+shape is now a local display adapter, not a writable source of truth.++Before upgrading:++1. back up the Pulse data directory;+2. confirm that the v6 process can write its alert, notification, recovery, and+ action database directories;+3. confirm supported clients can read additive JSON fields;+4. expose the metrics listener to a protected scraper if rollout telemetry is+ required;+5. verify Pulse Pro entitlement connectivity before relying on action offers.++After upgrading:++1. confirm the Patrol navigation count matches the active queue;+2. inspect an active item through its deepest evidence and protection detail;+3. acknowledge and unacknowledge a test item;+4. verify a bounded suppression returns to active attention;+5. confirm stale collection remains visible rather than resolving;+6. exercise notification retry/dead-letter monitoring;+7. if using Pulse Pro actions, complete a review/approve/run/verify journey.++If a migration fails, stop the upgraded process, preserve the data directory+and logs, and restore the prior release with the pre-upgrade data backup. Do+not delete lifecycle, evidence, notification, recovery, or action records to+force startup.diff --git a/docs/UPGRADE_v6.md b/docs/UPGRADE_v6.mdindex 74eee91e33..0981c6664c 100644--- a/docs/UPGRADE_v6.md+++ b/docs/UPGRADE_v6.md@@ -294,6 +294,37 @@ Practical recommendation:- Before upgrading, keep console access available so you can retry activation from the v6 license panel if the exchange service is temporarily unavailable.+## Operational Trust migration++Pulse v6 consolidates alerts, Patrol attention, evidence, protection posture,+attached availability checks, notifications, and governed action verification+onto one Operational Trust lifecycle. See+[`OPERATIONAL_TRUST.md`](OPERATIONAL_TRUST.md) for the operator contract and+post-upgrade checks.++The migrations are additive:++- existing alert state is normalized into operational records and transitions;+- notification delivery keeps exact operational-record and transition links;+- recovery points and provider observations materialize provider-aware+ protection posture;+- unified-resource relationships and availability facets gain stable evidence+ linkage;+- action audit records preserve execution and verification as separate truth.++Supported legacy JSON fields remain readable where older clients need them,+but the primary v6 runtime has one writable owner for each domain. Pulse Mobile+now reads the canonical Patrol attention queue. Operators should upgrade+desktop and mobile clients together when they depend on acknowledgement,+evidence, protection, or action-verification parity.++Before the upgrade, back up the Pulse data directory and confirm the service+account can write the alert, notification, recovery, and action stores. After+startup, verify that the Patrol navigation count matches the active queue,+inspect one evidence/protection drill-down, and confirm stale collection does+not appear resolved. Pulse Pro users should also verify entitlement+connectivity before relying on restart offers.+### Multi-Tenant (Opt-In)Multi-tenant mode is opt-in and additionally license-gated:diff --git a/docs/monitoring/PROMETHEUS_METRICS.md b/docs/monitoring/PROMETHEUS_METRICS.mdindex b98a129557..51e348cb90 100644--- a/docs/monitoring/PROMETHEUS_METRICS.md+++ b/docs/monitoring/PROMETHEUS_METRICS.md@@ -78,6 +78,31 @@ In Docker and Kubernetes you must expose `9091` explicitly if you want to scrape| `pulse_alerts_rate_limited_total` | Counter | Alerts suppressed due to rate limiting. || `pulse_alert_duration_seconds` | Histogram | Time from alert fire to resolve (by `type`). |+## Operational Trust++Operational Trust metrics use closed low-cardinality labels. They never label+series with resource, operational-record, evidence, actor, provider-instance,+or notification-destination IDs.++| Metric | Type | Description |+| :--- | :--- | :--- |+| `pulse_operational_trust_observation_to_open_seconds` | Histogram | Time from the first canonical observation to an open operational record. |+| `pulse_operational_trust_open_to_notification_enqueue_seconds` | Histogram | Time from an open transition to durable notification enqueue. |+| `pulse_operational_trust_evidence_observations_total` | Counter | Evidence observations by bounded `source` and state (`current`, `stale`, `unknown`, `partial`, `unavailable`, `partial_permission`, `denied`, or `other`). |+| `pulse_operational_trust_identity_correlations_total` | Counter | Resource correlation outcomes (`attached`, `standalone`, `ambiguous`, `unresolved`, or `other`). |+| `pulse_operational_trust_protection_posture_evaluations_total` | Counter | Protection posture evaluations by state. |+| `pulse_operational_trust_protection_posture_evaluation_failures_total` | Counter | Posture evaluation failures by bounded reason. |+| `pulse_operational_trust_notification_delivery_total` | Counter | Transition-linked delivery outcomes (`queued`, `retry`, `sent`, `failed`, `dead_letter`, `cancelled`, or `other`). |+| `pulse_operational_trust_active_count_mismatch_total` | Counter | Detected disagreement between the canonical active records and attention projection. |+| `pulse_operational_trust_action_offers_total` | Counter | Action-offer projections by eligibility. |+| `pulse_operational_trust_action_verification_total` | Counter | Verification outcomes, including confirmed, contradicted, inconclusive, timed out, and not attempted. |++Example rollout alerts:++- `increase(pulse_operational_trust_active_count_mismatch_total[15m]) > 0`+- `increase(pulse_operational_trust_notification_delivery_total{outcome="dead_letter"}[15m]) > 0`+- `increase(pulse_operational_trust_action_verification_total{outcome=~"contradicted|timed_out"}[30m]) > 0`+## 🚨 Alerting Examples- **High Error Rate**: `rate(pulse_http_request_errors_total[5m]) > 0.05`- **Stale Node**: `pulse_monitor_node_poll_staleness_seconds > 300`diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex ed243644aa..fd4c092f29 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -4660,3 +4660,15 @@ 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.++### Operational Trust lifecycle mutation boundary++The attention evidence and lifecycle mutation handlers under `internal/api/`+remain resource-monitoring consumers. Acknowledge, unacknowledge, suppress, and+unsuppress call the alerts-owned operational lifecycle and persist through the+active-alert store; they do not mint agent credentials, alter observer config,+or dispatch commands. Evidence reads require `monitoring:read`, lifecycle+mutations require `monitoring:write`, and slash-containing canonical record IDs+are parsed as opaque identities. Governed action planning still enters the+existing action lifecycle and entitlement boundary before any agent executor+is considered.diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex fb96d65252..fe87c81e17 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -6635,3 +6635,14 @@ review. Verification presentation is derived only from the durable canonicalaction state and `ActionResultV2`: confirmed, contradicted, inconclusive, andnot-attempted remain distinct. The projection has no authority to resolve theoperational record.++### Operational Trust rollout telemetry and lifecycle controls++Patrol exposes evidence-backed lifecycle controls only for the selected+canonical attention item. Acknowledge is reversible. Suppression requires a+reason and bounded expiry. Neither action changes detector truth, and stale or+unknown collection state remains stronger than a retained legacy+acknowledgement flag. `internal/ai/patrol_metrics.go` compares the canonical+active summary with the projected state set and increments one unlabeled+low-cardinality mismatch counter on contradiction. It never labels metrics with+resource, record, evidence, actor, or provider-instance identity.diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 0662a477a0..89942ad1a1 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -1137,3 +1137,21 @@ That same ownership also governs acknowledgement and manual-clear cleanup.Clearing an alert through the canonical alerts runtime must remove both legacypublic-id tracking and canonical-state acknowledgement records so old aliasescannot keep an alert acknowledged after the canonical alert has been removed.++### Operational Trust writable lifecycle++`internal/alerts/active_lifecycle.go` is the single writable owner for+acknowledge, unacknowledge, suppress, unsuppress, collection-stale,+collection-unknown, resolving, and collection-restored transitions. Every+writer is idempotent under retry, retains new evidence without duplicating a+same-state transition, persists through the active-alert store, and survives+restart. Explicit stale, unknown, resolving, or suppressed state takes+precedence over the legacy `Alert.Acknowledged` projection. The canonical+record's `LastObservedAt` is the maximum of retained record, alert, and evidence+timestamps so a fresh outage observation cannot be rolled back by an older+legacy alert timestamp.++Suppression is bounded and reasoned, leaves the default active queue, and+remains inspectable. Expiry or explicit unsuppression returns the record to its+detector-owned state; it never resolves it. Only fresh sufficient recovery+evidence may enter resolving, and only detector recovery may resolve.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 1952172b22..5a24d6298a 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -7844,3 +7844,23 @@ plan is replayed rather than duplicated.Decision, execution, receipt, reconciliation, result, and verification remainon the existing `/api/actions` contract. Provider success does not mutate theoperational record; only fresh detector recovery evidence may resolve it.++### Operational Trust evidence and lifecycle mutation transport++The canonical selected-item transport now includes:++1. `GET /api/ai/patrol/attention/{id}/evidence/{evidenceId}` under+ `monitoring:read`; retained evidence returns its typed envelope and+ freshness, while an expired referenced envelope returns typed `410 Gone`+ instead of false absence or health.+2. `POST /api/ai/patrol/attention/{id}/acknowledge` and+ `/unacknowledge` under `monitoring:write`.+3. `POST /api/ai/patrol/attention/{id}/suppress` with a non-empty reason and+ bounded future `expiresAt`, and `/unsuppress`, under `monitoring:write`.++Every mutation reloads the canonical active record, delegates to the+alerts-owned lifecycle writer, and returns the refreshed shared detail+projection. The browser cannot submit operational state, transition,+evidence, actor, or subject identity. Action offers and planning additionally+require the canonical `ai_autofix` entitlement and return the normal+license-required `402` contract when it is absent.diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 163950d047..7aef463446 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -5101,3 +5101,15 @@ Protection table controls continue to compose shared filter, table, status,counter, loading, error, disclosure, and inline-detail primitives. The boundedbatch hook retains fulfilled values during refresh and issues at most onerequest per 200 resource rows, rather than placing a request under each row.++### Operational Trust attention interaction boundary++The Patrol selected-detail surface owns the smallest lifecycle interaction+set: acknowledge, return to open, temporary suppression with a required reason+and one of the bounded 1-hour, 24-hour, or 7-day durations, and return to+active. Every mutation refreshes both the shared detail and list projection.+The queue retains screen-reader names, keyboard activation, focus restoration+after node replacement, reduced-motion behavior, and a no-overflow phone+layout. Raw evidence history, lifecycle timeline, provider limitations, and+action audit remain one disclosure or shared review deeper; no platform table+or Assistant surface recreates these controls.diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.mdindex 48a294dbee..58b4f95d57 100644--- a/docs/release-control/v6/internal/subsystems/notifications.md+++ b/docs/release-control/v6/internal/subsystems/notifications.md@@ -244,3 +244,15 @@ channel targeting.`api-contracts`: they are the product-facing control surface fornotification-management transport, while canonical payload-shape governancestill remains explicit in the shared API contract boundary.++### Operational Trust delivery observability++Notification queue rows retain the exact operational record and lifecycle+transition IDs through grouping, retry, restart, send, cancellation, and dead+letter. Restart during a queued retry must reopen the same durable delivery+with the same transition links; it must not synthesize a new operational+transition. `internal/notifications/queue.go` records bounded queue,+retry/sent/failed/dead-letter/cancelled outcomes and open-to-enqueue latency+without destination, record, resource, or evidence labels. Delivery state+remains notification truth only and cannot resolve or reopen the alert+lifecycle.diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex f941539aca..3652480217 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -2109,3 +2109,15 @@ nor its action authorizes a reboot. Contradicted, inconclusive, or health-unknowpostconditions remain actionable; only canonical confirmed postcondition truthmay support resolution. Package-manager internals remain forensic detail ratherthan the least-expert default.++### Operational Trust attention queue completion++Patrol is the named monitor-first attention destination over one canonical+operational lifecycle. Active, open, acknowledged, suppressed, stale/unknown,+resolved, unavailable-evaluation, and honest calm states share one summary and+detail projection. The selected detail owns reversible acknowledgement and+bounded reasoned suppression, while Assistant remains explanation-only selected+context. Evidence, impact, relationships, protection posture, lifecycle+timeline, action origin, and verification truth remain linked to the same+record. Mobile consumes the same list/detail and acknowledgement contracts; it+does not revive the retired primary findings feed.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex b43c6ade14..7179f72119 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -1941,3 +1941,19 @@ the indexed `origin_json` operational-record expression; MemoryStore performsone bounded pass. The summary path performs no registry, action-store,executor-readiness, or action-origin work. Readiness checks remain local tothe already-bounded visible page and do not issue browser requests per row.++### Operational Trust rollout bounds++The completed Operational Trust path preserves these explicit bounds:++1. active-count and summary evaluation use the in-memory canonical projection;+2. attention pages are capped at 200 items and a 10,000-record projection has+ a five-second shared-CI ceiling;+3. recovery posture joins batch at 200 subjects and platform tables issue one+ bounded request rather than one request per row;+4. action enrichment occurs after pagination and uses one registry, authority,+ and latest-origin batch;+5. evidence and recovery retention remain store-owned, indexed, bounded, and+ covered by query-plan and retention tests;+6. Operational Trust telemetry uses bounded enumerated labels only and never+ introduces resource-cardinality labels.diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 3f16f76983..716359def0 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -1444,3 +1444,15 @@ origin, target, evidence set, handler, actor, or parameters. The server bindsthe exact operational record and policy-shaped evidence IDs internally.Unauthorized, stale, partial, permission-limited, ambiguous, unsupported, orexecutor-unready records return no offer and no cross-resource detail.++### Operational Trust evidence and mutation authorization++Evidence detail is tenant-scoped through the selected canonical record and+requires `monitoring:read`; lifecycle mutation requires `monitoring:write`.+Unknown record/evidence pairs do not permit cross-resource enumeration, and an+expired referenced envelope returns typed expiry without disclosing another+record. Acknowledge and suppression actors are server-derived. Suppression+accepts only a non-empty reason and bounded future expiry. Action offer and+planning require the `ai_autofix` entitlement in addition to current RBAC,+evidence, resource-capability, executor-readiness, approval, and action-policy+checks.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 64f837911b..6709e63f02 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -2180,6 +2180,17 @@ while storage detail drawers and filter controls must route summary series IDs,source tones, and disk metrics through the shared storage helpers instead ofreconstructing them from local table state.+### Operational Trust posture rollout++Protection posture remains a provider-aware, subject-linked read model over+recovery points and provider collection evidence. Invalid policy falls back to+the canonical bounded default and records a bounded failure reason; invalid,+partial, permission-denied, failed, stale, missing, or unknown provider+evidence cannot produce `protected`. Evaluations record only the four canonical+posture states. Platform and Patrol consumers use bounded batch posture reads,+retain evidence and repository links, and never infer protection from the+existence of a row, snapshot, or provider connection.+The adjacent Operational Trust attention action transport does not turnprotection posture into mutation authority. The selected item may displaystorage/recovery-owned posture beside a separately declared Docker restartdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 7ab89279c7..8b156a3575 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1815,6 +1815,17 @@ through the canonical resource model, but unified-resource consumers must notreintroduce removed workload aliases or feature-local resource-type shims justto satisfy one table, drawer, or badge surface.+### Operational Trust relationship identity++Operational Trust relationships use a stable normalized relationship ID and+may bind an exact evidence ID. Availability attachment, hosting, storage,+protection, and membership relationships normalize through the unified+registry; ambiguous identity remains unattached and emits only a bounded+correlation outcome. Attached availability is a facet of the known resource+and must not create a duplicate standalone resource or second primary+presentation. Supported legacy relationship payloads may omit the additive ID,+but all primary runtime projections author the canonical stable identity.+Patrol attention resource navigation carries the canonical subject resource IDthrough shared route builders as an opaque query value. Attention deep linkscarry the canonical operational-record ID separately. Neither link may derivediff --git a/frontend-modern/src/api/__tests__/patrolAttention.test.ts b/frontend-modern/src/api/__tests__/patrolAttention.test.tsindex 1e4f017f6a..fb5296015f 100644--- a/frontend-modern/src/api/__tests__/patrolAttention.test.ts+++ b/frontend-modern/src/api/__tests__/patrolAttention.test.ts@@ -5,10 +5,15 @@ vi.mock('@/utils/apiClient', () => ({}));import {+ acknowledgePatrolAttention,getPatrolAttention,getPatrolAttentionDetail,+ getPatrolAttentionEvidence,getPatrolAttentionSummary,planPatrolAttentionAction,+ suppressPatrolAttention,+ unacknowledgePatrolAttention,+ unsuppressPatrolAttention,} from '@/api/patrolAttention';import { apiFetchJSON } from '@/utils/apiClient';@@ -33,6 +38,40 @@ describe('Patrol attention API', () => {await getPatrolAttentionDetail('record/one');expect(fetchMock).toHaveBeenLastCalledWith('/api/ai/patrol/attention/record%2Fone');++ await getPatrolAttentionEvidence('record/one', 'evidence/two');+ expect(fetchMock).toHaveBeenLastCalledWith(+ '/api/ai/patrol/attention/record%2Fone/evidence/evidence%2Ftwo',+ );+ });++ it('uses canonical item-scoped lifecycle mutations with bounded suppression input', async () => {+ await acknowledgePatrolAttention('record/one');+ expect(fetchMock).toHaveBeenLastCalledWith(+ '/api/ai/patrol/attention/record%2Fone/acknowledge',+ { method: 'POST', body: '{}' },+ );++ await unacknowledgePatrolAttention('record/one');+ expect(fetchMock).toHaveBeenLastCalledWith(+ '/api/ai/patrol/attention/record%2Fone/unacknowledge',+ { method: 'POST', body: '{}' },+ );++ await suppressPatrolAttention('record/one', 'Maintenance window', '2026-07-20T08:00:00Z');+ expect(fetchMock).toHaveBeenLastCalledWith('/api/ai/patrol/attention/record%2Fone/suppress', {+ method: 'POST',+ body: JSON.stringify({+ reason: 'Maintenance window',+ expiresAt: '2026-07-20T08:00:00Z',+ }),+ });++ await unsuppressPatrolAttention('record/one');+ expect(fetchMock).toHaveBeenLastCalledWith('/api/ai/patrol/attention/record%2Fone/unsuppress', {+ method: 'POST',+ body: '{}',+ });});it('plans the fixed attention capability without accepting public action authority', async () => {diff --git a/frontend-modern/src/api/patrolAttention.ts b/frontend-modern/src/api/patrolAttention.tsindex b1c957a32f..7ef8a416aa 100644--- a/frontend-modern/src/api/patrolAttention.ts+++ b/frontend-modern/src/api/patrolAttention.ts@@ -91,6 +91,16 @@ export interface AttentionListResponse {};}+export interface AttentionEvidenceResponse {+ evidence: EvidenceEnvelope;+ freshness: EvidenceFreshness;+ retained: boolean;+}++export interface AttentionMutationResponse {+ success: boolean;+}+export async function getPatrolAttention(filter: AttentionFilter = 'active',page = 1,@@ -114,6 +124,62 @@ export async function getPatrolAttentionDetail(itemId: string): Promise<Attentio);}+export async function getPatrolAttentionEvidence(+ itemId: string,+ evidenceId: string,+): Promise<AttentionEvidenceResponse> {+ return apiFetchJSON<AttentionEvidenceResponse>(+ `/api/ai/patrol/attention/${encodeURIComponent(itemId)}/evidence/${encodeURIComponent(evidenceId)}`,+ );+}++async function mutatePatrolAttention(+ itemId: string,+ mutation: 'acknowledge' | 'unacknowledge' | 'suppress' | 'unsuppress',+ body = '{}',+): Promise<AttentionMutationResponse> {+ return apiFetchJSON<AttentionMutationResponse>(+ `/api/ai/patrol/attention/${encodeURIComponent(itemId)}/${mutation}`,+ {+ method: 'POST',+ body,+ },+ );+}++export async function acknowledgePatrolAttention(+ itemId: string,+): Promise<AttentionMutationResponse> {+ return mutatePatrolAttention(itemId, 'acknowledge');+}++export async function unacknowledgePatrolAttention(+ itemId: string,+): Promise<AttentionMutationResponse> {+ return mutatePatrolAttention(itemId, 'unacknowledge');+}++export async function suppressPatrolAttention(+ itemId: string,+ reason: string,+ expiresAt: string,+): Promise<AttentionMutationResponse> {+ return mutatePatrolAttention(+ itemId,+ 'suppress',+ JSON.stringify({+ reason,+ expiresAt,+ }),+ );+}++export async function unsuppressPatrolAttention(+ itemId: string,+): Promise<AttentionMutationResponse> {+ return mutatePatrolAttention(itemId, 'unsuppress');+}+export async function planPatrolAttentionAction(itemId: string,capability: string,diff --git a/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx b/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsxindex d3b1f2607f..5c2f14efe8 100644--- a/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx+++ b/frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx@@ -16,6 +16,7 @@ import ClockIcon from 'lucide-solid/icons/clock';import ExternalLinkIcon from 'lucide-solid/icons/external-link';import RefreshIcon from 'lucide-solid/icons/refresh-cw';import RotateCwIcon from 'lucide-solid/icons/rotate-cw';+import ShieldOffIcon from 'lucide-solid/icons/shield-off';import SparklesIcon from 'lucide-solid/icons/sparkles';import XIcon from 'lucide-solid/icons/x';import type {@@ -24,7 +25,13 @@ import type {AttentionItem,AttentionItemDetail,} from '@/api/patrolAttention';-import { planPatrolAttentionAction } from '@/api/patrolAttention';+import {+ acknowledgePatrolAttention,+ planPatrolAttentionAction,+ suppressPatrolAttention,+ unacknowledgePatrolAttention,+ unsuppressPatrolAttention,+} from '@/api/patrolAttention';import { ResourceActionsAPI } from '@/api/resourceActions';import { Button, ButtonLink } from '@/components/shared/Button';import { LoadingSpinner } from '@/components/shared/LoadingSpinner';@@ -40,6 +47,7 @@ import {} from '@/routing/resourceLinks';import type { EvidenceEnvelope } from '@/types/operationalTrust';import type { ActionDetailResponse } from '@/types/actionAudit';+import { getAlertResourceIncidentAcknowledgedByLabel } from '@/utils/alertIncidentPresentation';import { formatRelativeTime } from '@/utils/format';const PRIMARY_EVIDENCE_LIMIT = 3;@@ -59,6 +67,8 @@ export function PatrolAttentionWorkbench() {const [actionDetail, setActionDetail] = createSignal<ActionDetailResponse | null>(null);const [actionBusy, setActionBusy] = createSignal(false);const [actionError, setActionError] = createSignal('');+ const [lifecycleBusy, setLifecycleBusy] = createSignal(false);+ const [lifecycleError, setLifecycleError] = createSignal('');const itemButtons = new Map<string, HTMLButtonElement>();let detailPanel: HTMLDivElement | undefined;let actionTrigger: HTMLButtonElement | undefined;@@ -149,6 +159,25 @@ export function PatrolAttentionWorkbench() {patrolAttentionStore.load(patrolAttentionStore.filter()),]);};+ const changeLifecycle = async (operation: () => Promise<unknown>) => {+ if (lifecycleBusy()) return;+ setLifecycleBusy(true);+ setLifecycleError('');+ try {+ await operation();+ const selected = selectedItemId();+ await Promise.all([+ selected ? patrolAttentionStore.select(selected) : Promise.resolve(),+ patrolAttentionStore.load(patrolAttentionStore.filter()),+ ]);+ } catch (cause) {+ setLifecycleError(+ cause instanceof Error ? cause.message : 'The lifecycle change could not be saved.',+ );+ } finally {+ setLifecycleBusy(false);+ }+ };onMount(() => {void patrolAttentionStore.load('active');@@ -271,6 +300,16 @@ export function PatrolAttentionWorkbench() {actionBusy={actionBusy()}actionError={actionError()}onReviewAction={reviewAction}+ lifecycleBusy={lifecycleBusy()}+ lifecycleError={lifecycleError()}+ onAcknowledge={(itemId) => changeLifecycle(() => acknowledgePatrolAttention(itemId))}+ onUnacknowledge={(itemId) =>+ changeLifecycle(() => unacknowledgePatrolAttention(itemId))+ }+ onSuppress={(itemId, reason, expiresAt) =>+ changeLifecycle(() => suppressPatrolAttention(itemId, reason, expiresAt))+ }+ onUnsuppress={(itemId) => changeLifecycle(() => unsuppressPatrolAttention(itemId))}/></div></Show>@@ -425,6 +464,12 @@ function AttentionDetail(props: {offer: AttentionActionOffer,trigger: HTMLButtonElement,) => void;+ lifecycleBusy: boolean;+ lifecycleError: string;+ onAcknowledge: (itemId: string) => Promise<void>;+ onUnacknowledge: (itemId: string) => Promise<void>;+ onSuppress: (itemId: string, reason: string, expiresAt: string) => Promise<void>;+ onUnsuppress: (itemId: string) => Promise<void>;}) {const detail = () => props.detail;const item = () => detail()?.item;@@ -548,6 +593,16 @@ function AttentionDetail(props: {</p></section>+ <AttentionLifecycleControls+ detail={loaded()}+ busy={props.lifecycleBusy}+ error={props.lifecycleError}+ onAcknowledge={props.onAcknowledge}+ onUnacknowledge={props.onUnacknowledge}+ onSuppress={props.onSuppress}+ onUnsuppress={props.onUnsuppress}+ />+<DetailSection title="Affected resource"><p class="text-sm font-medium text-base-content">{loaded().item.subjectResourceName}@@ -739,6 +794,185 @@ function AttentionDetail(props: {);}+const SUPPRESSION_DURATIONS = [+ { value: 60 * 60 * 1000, label: '1 hour' },+ { value: 24 * 60 * 60 * 1000, label: '24 hours' },+ { value: 7 * 24 * 60 * 60 * 1000, label: '7 days' },+] as const;++function AttentionLifecycleControls(props: {+ detail: AttentionItemDetail;+ busy: boolean;+ error: string;+ onAcknowledge: (itemId: string) => Promise<void>;+ onUnacknowledge: (itemId: string) => Promise<void>;+ onSuppress: (itemId: string, reason: string, expiresAt: string) => Promise<void>;+ onUnsuppress: (itemId: string) => Promise<void>;+}) {+ const [showSuppression, setShowSuppression] = createSignal(false);+ const [reason, setReason] = createSignal('');+ const [durationMs, setDurationMs] = createSignal<number>(SUPPRESSION_DURATIONS[1].value);+ const state = () => props.detail.item.state;+ const canAcknowledge = () => ['open', 'stale', 'unknown', 'resolving'].includes(state());+ const canSuppress = () =>+ ['open', 'acknowledged', 'stale', 'unknown', 'resolving'].includes(state());+ const submitSuppression = async (event: SubmitEvent) => {+ event.preventDefault();+ const value = reason().trim();+ if (!value) return;+ await props.onSuppress(+ props.detail.item.id,+ value,+ new Date(Date.now() + durationMs()).toISOString(),+ );+ setShowSuppression(false);+ setReason('');+ };++ return (+ <DetailSection title="Lifecycle">+ <div class="rounded-md border border-border-subtle bg-surface-alt/40 p-3">+ <Show when={props.detail.operationalRecord.acknowledgement}>+ {(acknowledgement) => (+ <p class="mb-2 text-xs leading-5 text-muted">+ {getAlertResourceIncidentAcknowledgedByLabel(acknowledgement().by)}{' '}+ {formatRelativeTime(acknowledgement().at, { compact: true })}.+ </p>+ )}+ </Show>+ <Show when={props.detail.operationalRecord.suppression}>+ {(suppression) => (+ <div class="mb-3 text-xs leading-5 text-muted">+ <p>+ Suppressed by {suppression().by}: {suppression().reason}+ </p>+ <Show when={suppression().expiresAt}>+ {(expiresAt) => (+ <p>+ Returns to active attention {formatRelativeTime(expiresAt(), { compact: true })}+ .+ </p>+ )}+ </Show>+ </div>+ )}+ </Show>+ <div class="flex flex-wrap gap-2">+ <Show when={canAcknowledge()}>+ <Button+ variant="primary"+ size="sm"+ isLoading={props.busy}+ onClick={() => void props.onAcknowledge(props.detail.item.id)}+ >+ Acknowledge+ </Button>+ </Show>+ <Show when={state() === 'acknowledged'}>+ <Button+ variant="secondary"+ size="sm"+ isLoading={props.busy}+ onClick={() => void props.onUnacknowledge(props.detail.item.id)}+ >+ Return to open+ </Button>+ </Show>+ <Show when={state() === 'suppressed'}>+ <Button+ variant="secondary"+ size="sm"+ isLoading={props.busy}+ onClick={() => void props.onUnsuppress(props.detail.item.id)}+ >+ Return to active attention+ </Button>+ </Show>+ <Show when={canSuppress() && !showSuppression()}>+ <Button+ variant="secondary"+ size="sm"+ class="gap-1.5"+ disabled={props.busy}+ onClick={() => setShowSuppression(true)}+ >+ <ShieldOffIcon class="h-4 w-4" aria-hidden="true" />+ Suppress temporarily+ </Button>+ </Show>+ </div>+ <Show when={showSuppression()}>+ <form+ class="mt-3 space-y-3 border-t border-border-subtle pt-3"+ onSubmit={submitSuppression}+ >+ <div>+ <label+ for={`attention-suppression-reason-${props.detail.item.id}`}+ class="text-xs font-medium text-base-content"+ >+ Why is this safe to hide from active attention?+ </label>+ <textarea+ id={`attention-suppression-reason-${props.detail.item.id}`}+ class="mt-1 min-h-20 w-full rounded-md border border-border bg-surface px-3 py-2 text-sm text-base-content focus:outline-none focus:ring-2 focus:ring-blue-500"+ value={reason()}+ maxlength={240}+ required+ disabled={props.busy}+ onInput={(event) => setReason(event.currentTarget.value)}+ />+ </div>+ <div>+ <label+ for={`attention-suppression-duration-${props.detail.item.id}`}+ class="text-xs font-medium text-base-content"+ >+ Return it to active attention after+ </label>+ <select+ id={`attention-suppression-duration-${props.detail.item.id}`}+ class="mt-1 block min-h-9 rounded-md border border-border bg-surface px-3 py-1.5 text-sm text-base-content focus:outline-none focus:ring-2 focus:ring-blue-500"+ value={String(durationMs())}+ disabled={props.busy}+ onChange={(event) => setDurationMs(Number(event.currentTarget.value))}+ >+ <For each={SUPPRESSION_DURATIONS}>+ {(duration) => <option value={duration.value}>{duration.label}</option>}+ </For>+ </select>+ </div>+ <div class="flex flex-wrap gap-2">+ <Button+ variant="warning"+ size="sm"+ isLoading={props.busy}+ disabled={!reason().trim()}+ type="submit"+ >+ Suppress temporarily+ </Button>+ <Button+ variant="ghost"+ size="sm"+ disabled={props.busy}+ onClick={() => setShowSuppression(false)}+ >+ Cancel+ </Button>+ </div>+ </form>+ </Show>+ <Show when={props.error}>+ <p role="alert" class="mt-3 text-xs leading-5 text-red-700 dark:text-red-300">+ {props.error}+ </p>+ </Show>+ </div>+ </DetailSection>+ );+}+function ActionVerificationMessage(props: { state: AttentionItem['verificationState'] }) {const message = () => {switch (props.state) {diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsx b/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsxindex d2eceb331e..639e3aba0a 100644--- a/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsx+++ b/frontend-modern/src/features/patrol/__tests__/PatrolAttentionWorkbench.test.tsx@@ -12,6 +12,10 @@ const apiMocks = vi.hoisted(() => ({getList: vi.fn(),getDetail: vi.fn(),getSummary: vi.fn(),+ acknowledge: vi.fn(),+ unacknowledge: vi.fn(),+ suppress: vi.fn(),+ unsuppress: vi.fn(),planAction: vi.fn(),getAction: vi.fn(),}));@@ -23,6 +27,10 @@ vi.mock('@/api/patrolAttention', async (importOriginal) => {getPatrolAttention: (...args: unknown[]) => apiMocks.getList(...args),getPatrolAttentionDetail: (...args: unknown[]) => apiMocks.getDetail(...args),getPatrolAttentionSummary: (...args: unknown[]) => apiMocks.getSummary(...args),+ acknowledgePatrolAttention: (...args: unknown[]) => apiMocks.acknowledge(...args),+ unacknowledgePatrolAttention: (...args: unknown[]) => apiMocks.unacknowledge(...args),+ suppressPatrolAttention: (...args: unknown[]) => apiMocks.suppress(...args),+ unsuppressPatrolAttention: (...args: unknown[]) => apiMocks.unsuppress(...args),planPatrolAttentionAction: (...args: unknown[]) => apiMocks.planAction(...args),};});@@ -170,6 +178,10 @@ describe('PatrolAttentionWorkbench', () => {apiMocks.getList.mockReset();apiMocks.getDetail.mockReset();apiMocks.getSummary.mockReset();+ apiMocks.acknowledge.mockReset();+ apiMocks.unacknowledge.mockReset();+ apiMocks.suppress.mockReset();+ apiMocks.unsuppress.mockReset();apiMocks.planAction.mockReset();apiMocks.getAction.mockReset();});@@ -268,6 +280,95 @@ describe('PatrolAttentionWorkbench', () => {).not.toBeInTheDocument();});+ it('acknowledges an operational item and refreshes the shared lifecycle projection', async () => {+ const active = item();+ const acknowledged = item({ state: 'acknowledged' });+ const acknowledgedDetail = detail(acknowledged);+ acknowledgedDetail.operationalRecord.acknowledgement = {+ at: evaluatedAt,+ by: 'operator',+ };+ apiMocks.getList+ .mockResolvedValueOnce(+ listResponse([active], summary({ activeCount: 1, openCount: 1, calm: false })),+ )+ .mockResolvedValue(+ listResponse(+ [acknowledged],+ summary({ activeCount: 1, acknowledgedCount: 1, calm: false }),+ ),+ );+ apiMocks.getDetail.mockResolvedValueOnce(detail(active)).mockResolvedValue(acknowledgedDetail);+ apiMocks.acknowledge.mockResolvedValue({ success: true });+ renderWorkbench();++ fireEvent.click(+ await screen.findByRole('button', {+ name: 'Open Disk pressure on Database VM',+ }),+ );+ fireEvent.click(await screen.findByRole('button', { name: 'Acknowledge' }));++ await waitFor(() => expect(apiMocks.acknowledge).toHaveBeenCalledWith('record-1'));+ expect(await screen.findByText(/Acknowledged by operator/i)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Return to open' })).toBeInTheDocument();+ });++ it('requires an explicit reason and bounded duration before temporary suppression', async () => {+ const active = item();+ const suppressed = item({ state: 'suppressed' });+ const suppressedDetail = detail(suppressed);+ suppressedDetail.operationalRecord.suppression = {+ at: evaluatedAt,+ by: 'operator',+ reason: 'Planned storage maintenance',+ expiresAt: '2026-07-20T08:00:00Z',+ };+ apiMocks.getList+ .mockResolvedValueOnce(+ listResponse([active], summary({ activeCount: 1, openCount: 1, calm: false })),+ )+ .mockResolvedValue(+ listResponse([suppressed], summary({ activeCount: 0, suppressedCount: 1, calm: true })),+ );+ apiMocks.getDetail.mockResolvedValueOnce(detail(active)).mockResolvedValue(suppressedDetail);+ apiMocks.suppress.mockResolvedValue({ success: true });+ renderWorkbench();++ fireEvent.click(+ await screen.findByRole('button', {+ name: 'Open Disk pressure on Database VM',+ }),+ );+ fireEvent.click(await screen.findByRole('button', { name: 'Suppress temporarily' }));++ const submit = screen.getByRole('button', { name: 'Suppress temporarily' });+ expect(submit).toBeDisabled();+ fireEvent.input(+ screen.getByRole('textbox', {+ name: 'Why is this safe to hide from active attention?',+ }),+ { target: { value: 'Planned storage maintenance' } },+ );+ fireEvent.change(+ screen.getByRole('combobox', {+ name: 'Return it to active attention after',+ }),+ { target: { value: String(60 * 60 * 1000) } },+ );+ fireEvent.click(submit);++ await waitFor(() => {+ expect(apiMocks.suppress).toHaveBeenCalledWith(+ 'record-1',+ 'Planned storage maintenance',+ expect.any(String),+ );+ });+ expect(await screen.findByText(/Suppressed by operator/i)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Return to active attention' })).toBeInTheDocument();+ });+it('opens the canonical governed action review from an eligible attention item', async () => {const actionOffer = {targetResourceId: 'docker:host-1/container-1',diff --git a/internal/actionlifecycle/service.go b/internal/actionlifecycle/service.goindex 8587025c4f..d33f2c6391 100644--- a/internal/actionlifecycle/service.go+++ b/internal/actionlifecycle/service.go@@ -18,6 +18,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/actionplanner"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -1199,6 +1200,15 @@ func (s *Service) completeCorrelatedDispatch(orgID string, store Store, record u}s.publishTransition(orgID, completed)s.publishCompleted(completed)+ truth := unified.CanonicalActionResultV2(completed)+ verificationOutcome := string(truth.Verification.Status)+ if truth.Verification.Status == unified.ActionVerificationInconclusive &&+ strings.Contains(strings.ToLower(truth.Verification.ReasonCode), "timeout") {+ verificationOutcome = "timed_out"+ }+ operationaltrust.GetMetrics().ObserveActionVerification(+ verificationOutcome,+ )return completed, nil}diff --git a/internal/ai/patrol_metrics.go b/internal/ai/patrol_metrics.goindex 56626b1494..c8dfee0cd6 100644--- a/internal/ai/patrol_metrics.go+++ b/internal/ai/patrol_metrics.go@@ -350,6 +350,15 @@ func (m *PatrolMetrics) ObserveAttentionProjection(for _, state := range states {m.attentionItems.WithLabelValues(string(state)).Set(float64(counts[state]))}+ projectedActiveCount := 0+ for state, count := range counts {+ if attentionStateCountsAsActive(state) {+ projectedActiveCount += count+ }+ }+ if projectedActiveCount != projection.Summary.ActiveCount {+ operationaltrust.GetMetrics().RecordActiveCountMismatch()+ }m.attentionOldestAge.Set(oldestAge.Seconds())m.attentionAckLatest.Set(latestAcknowledgementElapsed.Seconds())m.calmEvaluationTime.Set(float64(projection.Summary.EvaluatedAt.Unix()))diff --git a/internal/ai/patrol_metrics_test.go b/internal/ai/patrol_metrics_test.goindex 6556627e2a..548c8bf3b5 100644--- a/internal/ai/patrol_metrics_test.go+++ b/internal/ai/patrol_metrics_test.go@@ -2,8 +2,10 @@ package aiimport ("testing"+ "time""github.com/prometheus/client_golang/prometheus/testutil"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust")func TestPatrolMetrics_StreamRecorders(t *testing.T) {@@ -16,3 +18,31 @@ func TestPatrolMetrics_StreamRecorders(t *testing.T) {t.Fatalf("expected stream replay batch histogram to be registered once, got %d", got)}}++func TestPatrolMetrics_ObserveAttentionProjectionUsesCanonicalStates(t *testing.T) {+ m := GetPatrolMetrics()+ now := time.Date(2026, 7, 19, 8, 0, 0, 0, time.UTC)+ m.ObserveAttentionProjection(AttentionProjection{+ Details: []AttentionItemDetail{{+ Item: AttentionItem{+ State: operationaltrust.OperationalOpen,+ FirstObservedAt: now.Add(-time.Minute),+ },+ }},+ Summary: AttentionSummary{+ ActiveCount: 1,+ EvaluatedAt: now,+ },+ }, now)++ if got := testutil.ToFloat64(+ m.attentionItems.WithLabelValues(string(operationaltrust.OperationalOpen)),+ ); got != 1 {+ t.Fatalf("open attention gauge = %v, want 1", got)+ }+ if got := testutil.ToFloat64(+ m.attentionItems.WithLabelValues(string(operationaltrust.OperationalResolved)),+ ); got != 0 {+ t.Fatalf("resolved attention gauge = %v, want 0", got)+ }+}diff --git a/internal/alerts/active_lifecycle.go b/internal/alerts/active_lifecycle.goindex 7833f81c67..e63b551f8d 100644--- a/internal/alerts/active_lifecycle.go+++ b/internal/alerts/active_lifecycle.go@@ -6,6 +6,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust""github.com/rs/zerolog/log")@@ -105,6 +106,10 @@ func (m *Manager) AcknowledgeAlert(alertID, user string) error {m.mu.Unlock()return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)}+ if alert.Acknowledged {+ m.mu.Unlock()+ return nil+ }alert.Acknowledged = truenow := time.Now()@@ -120,6 +125,7 @@ func (m *Manager) AcknowledgeAlert(alertID, user string) error {alertCopy := alert.Clone()m.mu.Unlock()+ m.saveActiveAlertsAsync("acknowledge")log.Debug().Str("alertID", alertID).@@ -145,6 +151,10 @@ func (m *Manager) UnacknowledgeAlert(alertID string) error {m.mu.Unlock()return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)}+ if !alert.Acknowledged {+ m.mu.Unlock()+ return nil+ }alert.Acknowledged = falsealert.AckTime = nil@@ -155,6 +165,7 @@ func (m *Manager) UnacknowledgeAlert(alertID string) error {alertCopy := alert.Clone()m.mu.Unlock()+ m.saveActiveAlertsAsync("unacknowledge")log.Info().Str("alertID", alertID).@@ -164,6 +175,269 @@ func (m *Manager) UnacknowledgeAlert(alertID string) error {return nil}+// SuppressOperationalAlert moves one canonical operational record out of the+// default attention queue without changing the detector's underlying finding.+// Suppression is bounded by an optional expiry and remains inspectable.+func (m *Manager) SuppressOperationalAlert(+ alertID string,+ actor string,+ reason string,+ expiresAt *time.Time,+) error {+ actor = strings.TrimSpace(actor)+ reason = strings.TrimSpace(reason)+ if actor == "" {+ return fmt.Errorf("suppression actor is required")+ }+ if reason == "" {+ return fmt.Errorf("suppression reason is required")+ }++ now := time.Now().UTC()+ if expiresAt != nil {+ value := expiresAt.UTC()+ if !value.After(now) {+ return fmt.Errorf("suppression expiry must be in the future")+ }+ expiresAt = &value+ }++ m.mu.Lock()+ key, exists := m.resolveActiveAlertKeyNoLock(alertID)+ if !exists {+ m.mu.Unlock()+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)+ }+ alert, ok := m.getActiveAlertNoLock(key)+ if !ok || alert == nil {+ m.mu.Unlock()+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)+ }+ ensureOperationalContract(alert, now)+ if alert.OperationalRecord == nil {+ m.mu.Unlock()+ return fmt.Errorf("operational record is unavailable: %s", alertID)+ }++ from := alert.OperationalRecord.State+ alert.OperationalRecord.State = operationaltrust.OperationalSuppressed+ alert.OperationalRecord.StateChangedAt = now+ alert.OperationalRecord.Suppression = &operationaltrust.Suppression{+ At: now,+ By: actor,+ Reason: reason,+ ExpiresAt: expiresAt,+ }+ appendExplicitOperationalTransition(+ alert,+ from,+ operationaltrust.OperationalSuppressed,+ now,+ operationaltrust.TransitionSuppression,+ reason,+ alert.OperationalRecord.EvidenceIDs,+ )+ m.setActiveAlertNoLock(key, alert)+ m.mu.Unlock()+ m.saveActiveAlertsAsync("operational suppression")+ return nil+}++// UnsuppressOperationalAlert returns a suppressed record to the detector-owned+// active state. It does not resolve or erase the underlying alert.+func (m *Manager) UnsuppressOperationalAlert(alertID string) error {+ return m.updateExplicitOperationalState(+ alertID,+ operationaltrust.OperationalOpen,+ operationaltrust.TransitionSuppressionExpired,+ "suppression_removed",+ nil,+ func(record *operationaltrust.OperationalRecord) {+ record.Suppression = nil+ },+ )+}++// MarkOperationalCollectionStale preserves an open finding when its source is+// no longer current. Missing observations therefore cannot resolve it.+func (m *Manager) MarkOperationalCollectionStale(+ alertID string,+ evidence operationaltrust.EvidenceEnvelope,+ reason string,+) error {+ return m.updateExplicitOperationalState(+ alertID,+ operationaltrust.OperationalStale,+ operationaltrust.TransitionCollectionStale,+ reason,+ &evidence,+ nil,+ )+}++// MarkOperationalCollectionUnknown preserves an open finding when collection+// completeness, permission, or provider state cannot support a stronger claim.+func (m *Manager) MarkOperationalCollectionUnknown(+ alertID string,+ evidence operationaltrust.EvidenceEnvelope,+ reason string,+) error {+ return m.updateExplicitOperationalState(+ alertID,+ operationaltrust.OperationalUnknown,+ operationaltrust.TransitionCollectionUnknown,+ reason,+ &evidence,+ nil,+ )+}++// MarkOperationalResolving records fresh recovery evidence while verification+// is still pending. Resolution remains detector-owned and requires a later+// decisive recovery observation.+func (m *Manager) MarkOperationalResolving(+ alertID string,+ evidence operationaltrust.EvidenceEnvelope,+ reason string,+) error {+ return m.updateExplicitOperationalState(+ alertID,+ operationaltrust.OperationalResolving,+ operationaltrust.TransitionRecoveryEvidence,+ reason,+ &evidence,+ nil,+ )+}++// RestoreOperationalCollectionState reopens a stale or unknown record from a+// fresh detector observation while retaining its timeline and evidence.+func (m *Manager) RestoreOperationalCollectionState(+ alertID string,+ evidence operationaltrust.EvidenceEnvelope,+) error {+ return m.updateExplicitOperationalState(+ alertID,+ operationaltrust.OperationalOpen,+ operationaltrust.TransitionDetectorDecision,+ "collection_restored",+ &evidence,+ nil,+ )+}++func (m *Manager) updateExplicitOperationalState(+ alertID string,+ state operationaltrust.OperationalState,+ cause operationaltrust.TransitionCause,+ reason string,+ evidence *operationaltrust.EvidenceEnvelope,+ mutate func(*operationaltrust.OperationalRecord),+) error {+ now := time.Now().UTC()+ reason = strings.TrimSpace(reason)+ if reason == "" {+ return fmt.Errorf("operational transition reason is required")+ }+ if evidence != nil {+ if err := evidence.Validate(); err != nil {+ return fmt.Errorf("operational transition evidence: %w", err)+ }+ }++ m.mu.Lock()+ key, exists := m.resolveActiveAlertKeyNoLock(alertID)+ if !exists {+ m.mu.Unlock()+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)+ }+ alert, ok := m.getActiveAlertNoLock(key)+ if !ok || alert == nil {+ m.mu.Unlock()+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)+ }+ ensureOperationalContract(alert, now)+ if alert.OperationalRecord == nil {+ m.mu.Unlock()+ return fmt.Errorf("operational record is unavailable: %s", alertID)+ }+ from := alert.OperationalRecord.State+ if from == state {+ if evidence != nil {+ alert.Evidence = appendOperationalEvidence(alert.Evidence, evidence.Clone())+ alert.OperationalRecord.EvidenceIDs = operationalEvidenceIDs(alert.Evidence)+ if evidence.ObservedAt.After(alert.OperationalRecord.LastObservedAt) {+ alert.OperationalRecord.LastObservedAt = evidence.ObservedAt.UTC()+ }+ m.setActiveAlertNoLock(key, alert)+ m.mu.Unlock()+ operationaltrust.GetMetrics().ObserveEvidence(*evidence, now)+ m.saveActiveAlertsAsync("operational evidence refresh")+ return nil+ }+ m.mu.Unlock()+ return nil+ }++ evidenceIDs := append([]string(nil), alert.OperationalRecord.EvidenceIDs...)+ if evidence != nil {+ alert.Evidence = appendOperationalEvidence(alert.Evidence, evidence.Clone())+ evidenceIDs = []string{evidence.ID}+ alert.OperationalRecord.EvidenceIDs = operationalEvidenceIDs(alert.Evidence)+ operationaltrust.GetMetrics().ObserveEvidence(*evidence, now)+ }+ alert.OperationalRecord.State = state+ alert.OperationalRecord.StateChangedAt = now+ alert.OperationalRecord.ResolvedAt = nil+ if mutate != nil {+ mutate(alert.OperationalRecord)+ }+ appendExplicitOperationalTransition(alert, from, state, now, cause, reason, evidenceIDs)+ m.setActiveAlertNoLock(key, alert)+ m.mu.Unlock()+ m.saveActiveAlertsAsync("operational lifecycle transition")+ return nil+}++func appendExplicitOperationalTransition(+ alert *Alert,+ from operationaltrust.OperationalState,+ to operationaltrust.OperationalState,+ at time.Time,+ cause operationaltrust.TransitionCause,+ reason string,+ evidenceIDs []string,+) {+ if alert == nil || alert.OperationalRecord == nil || from == to {+ return+ }+ id, err := operationaltrust.NewTransitionID(+ alert.OperationalRecord.ID,+ from,+ to,+ at,+ cause,+ alert.OperationalRecord.CauseKey,+ evidenceIDs,+ )+ if err != nil {+ return+ }+ transition := operationaltrust.LifecycleTransition{+ ID: id,+ OperationalRecordID: alert.OperationalRecord.ID,+ From: from,+ To: to,+ At: at,+ Cause: cause,+ CauseKey: alert.OperationalRecord.CauseKey,+ EvidenceIDs: append([]string(nil), evidenceIDs...),+ Reason: strings.TrimSpace(reason),+ }+ alert.LatestTransition = &transition+ alert.Transitions = appendOperationalTransition(alert.Transitions, transition.Clone())+}+// preserveAlertState copies acknowledgement and escalation metadata from an existing alert// into a freshly constructed alert before it replaces the existing entry in the map. This// prevents UI state from regressing when alerts are rebuilt during polling.diff --git a/internal/alerts/operational_contract.go b/internal/alerts/operational_contract.goindex ef06cd5dab..98176d2f6d 100644--- a/internal/alerts/operational_contract.go+++ b/internal/alerts/operational_contract.go@@ -48,6 +48,15 @@ func ensureOperationalContract(alert *Alert, ingestedAt time.Time) {if lastObservedAt.IsZero() || lastObservedAt.Before(firstObservedAt) {lastObservedAt = firstObservedAt}+ if alert.OperationalRecord != nil &&+ alert.OperationalRecord.LastObservedAt.After(lastObservedAt) {+ lastObservedAt = alert.OperationalRecord.LastObservedAt+ }+ for _, envelope := range alert.Evidence {+ if envelope.ObservedAt.After(lastObservedAt) {+ lastObservedAt = envelope.ObservedAt+ }+ }causeKey := strings.TrimSpace(alert.CanonicalState)if causeKey == "" {causeKey = strings.TrimSpace(alert.ID)@@ -131,6 +140,21 @@ func ensureOperationalContract(alert *Alert, ingestedAt time.Time) {alert.LatestTransition.OperationalRecordID != record.ID ||alert.LatestTransition.To != record.State {alert.LatestTransition = buildCurrentTransition(record, previousState)+ if alert.LatestTransition != nil {+ metrics := operationaltrust.GetMetrics()+ if alert.LatestTransition.To == operationaltrust.OperationalOpen {+ metrics.ObserveObservationToOpen(record.FirstObservedAt, ingestedAt)+ }+ transitionEvidence := make(map[string]struct{}, len(alert.LatestTransition.EvidenceIDs))+ for _, evidenceID := range alert.LatestTransition.EvidenceIDs {+ transitionEvidence[evidenceID] = struct{}{}+ }+ for _, envelope := range alert.Evidence {+ if _, ok := transitionEvidence[envelope.ID]; ok {+ metrics.ObserveEvidence(envelope, ingestedAt)+ }+ }+ }}if alert.LatestTransition != nil {alert.Transitions = appendOperationalTransition(@@ -490,7 +514,27 @@ func legacyAlertRecoveryEvidenceEnvelope(}func operationalStateForAlert(alert *Alert) operationaltrust.OperationalState {- if alert != nil && alert.Acknowledged {+ if alert == nil {+ return operationaltrust.OperationalOpen+ }+ if alert.OperationalRecord != nil &&+ alert.OperationalRecord.State == operationaltrust.OperationalSuppressed &&+ alert.OperationalRecord.Suppression != nil {+ suppression := alert.OperationalRecord.Suppression+ if suppression.ExpiresAt == nil || suppression.ExpiresAt.After(time.Now()) {+ return operationaltrust.OperationalSuppressed+ }+ alert.OperationalRecord.Suppression = nil+ }+ if alert.OperationalRecord != nil {+ switch alert.OperationalRecord.State {+ case operationaltrust.OperationalResolving,+ operationaltrust.OperationalStale,+ operationaltrust.OperationalUnknown:+ return alert.OperationalRecord.State+ }+ }+ if alert.Acknowledged {return operationaltrust.OperationalAcknowledged}return operationaltrust.OperationalOpen@@ -580,10 +624,26 @@ func buildCurrentTransition(if record.State == operationaltrust.OperationalAcknowledged {cause = operationaltrust.TransitionAcknowledgementat = record.StateChangedAt+ } else if record.State == operationaltrust.OperationalSuppressed {+ cause = operationaltrust.TransitionSuppression+ at = record.StateChangedAt} else if previousState == operationaltrust.OperationalAcknowledged &&record.State == operationaltrust.OperationalOpen {cause = operationaltrust.TransitionUnacknowledgementat = record.StateChangedAt+ } else if previousState == operationaltrust.OperationalSuppressed &&+ record.State == operationaltrust.OperationalOpen {+ cause = operationaltrust.TransitionSuppressionExpired+ at = record.StateChangedAt+ } else if record.State == operationaltrust.OperationalStale {+ cause = operationaltrust.TransitionCollectionStale+ at = record.StateChangedAt+ } else if record.State == operationaltrust.OperationalUnknown {+ cause = operationaltrust.TransitionCollectionUnknown+ at = record.StateChangedAt+ } else if record.State == operationaltrust.OperationalResolving {+ cause = operationaltrust.TransitionRecoveryEvidence+ at = record.StateChangedAt}if from == record.State {return nildiff --git a/internal/alerts/operational_contract_test.go b/internal/alerts/operational_contract_test.goindex 566c93fb85..229f15b1f6 100644--- a/internal/alerts/operational_contract_test.go+++ b/internal/alerts/operational_contract_test.go@@ -531,3 +531,38 @@ func TestAlertOperationalContractJSONRemainsAdditive(t *testing.T) {t.Fatalf("round-trip alert = %+v", roundTrip)}}++func TestEnsureOperationalContractKeepsExplicitUncertainStateAheadOfLegacyAcknowledgement(t *testing.T) {+ observedAt := time.Date(2026, 7, 19, 6, 0, 0, 0, time.UTC)+ alert := &Alert{+ ID: "alert-uncertain",+ Type: "availability",+ ResourceID: "app-container:web",+ CanonicalSpecID: "availability",+ CanonicalState: "app-container:web::availability",+ StartTime: observedAt.Add(-time.Hour),+ LastSeen: observedAt.Add(-time.Minute),+ Acknowledged: true,+ OperationalRecord: &operationaltrust.OperationalRecord{+ ID: "alert-uncertain",+ CanonicalSpecID: "availability",+ SubjectResourceID: "app-container:web",+ State: operationaltrust.OperationalStale,+ Severity: operationaltrust.SeverityWarning,+ FirstObservedAt: observedAt.Add(-time.Hour),+ LastObservedAt: observedAt,+ StateChangedAt: observedAt.Add(-time.Minute),+ CauseKey: "availability",+ EvidenceIDs: []string{},+ },+ }++ ensureOperationalContract(alert, observedAt.Add(time.Minute))++ if got := alert.OperationalRecord.State; got != operationaltrust.OperationalStale {+ t.Fatalf("operational state = %q, want stale", got)+ }+ if got := alert.OperationalRecord.LastObservedAt; !got.Equal(observedAt) {+ t.Fatalf("LastObservedAt = %s, want %s", got, observedAt)+ }+}diff --git a/internal/alerts/operational_state_writers_test.go b/internal/alerts/operational_state_writers_test.gonew file mode 100644index 0000000000..ceb06afe94--- /dev/null+++ b/internal/alerts/operational_state_writers_test.go@@ -0,0 +1,400 @@+package alerts++import (+ "slices"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"+)++func TestOperationalStateWritersPreserveFindingTruthAcrossSuppressionAndCollectionFailure(t *testing.T) {+ manager := newTestManager(t)+ alertID := "docker-container-health:container/web"+ now := time.Now().UTC()+ alert := &Alert{+ ID: alertID,+ CanonicalState: alertID,+ CanonicalSpecID: "docker-container-health",+ Type: "docker-container-health",+ Level: AlertLevelCritical,+ ResourceID: "app-container:web",+ ResourceName: "web",+ StartTime: now.Add(-time.Minute),+ LastSeen: now,+ Message: "Container health check is failing.",+ }+ manager.mu.Lock()+ manager.setActiveAlertNoLock(alertID, alert)+ manager.mu.Unlock()++ expiresAt := now.Add(time.Hour)+ if err := manager.SuppressOperationalAlert(+ alertID,+ "[email protected]",+ "Maintenance is in progress.",+ &expiresAt,+ ); err != nil {+ t.Fatalf("SuppressOperationalAlert() error = %v", err)+ }+ suppressed := activeAlert(t, manager, alertID)+ if suppressed.OperationalRecord.State != operationaltrust.OperationalSuppressed {+ t.Fatalf("suppressed state = %q", suppressed.OperationalRecord.State)+ }+ if suppressed.LatestTransition == nil ||+ suppressed.LatestTransition.Cause != operationaltrust.TransitionSuppression {+ t.Fatalf("suppression transition = %+v", suppressed.LatestTransition)+ }++ if err := manager.UnsuppressOperationalAlert(alertID); err != nil {+ t.Fatalf("UnsuppressOperationalAlert() error = %v", err)+ }+ reopened := activeAlert(t, manager, alertID)+ if reopened.OperationalRecord.State != operationaltrust.OperationalOpen {+ t.Fatalf("reopened state = %q", reopened.OperationalRecord.State)+ }+ if reopened.LatestTransition == nil ||+ reopened.LatestTransition.Cause != operationaltrust.TransitionSuppressionExpired {+ t.Fatalf("unsuppression transition = %+v", reopened.LatestTransition)+ }++ staleEvidence := operationalStateWriterEvidence(+ t,+ "availability",+ "app-container:web",+ now.Add(-2*time.Minute),+ now.Add(-time.Minute),+ operationaltrust.EvidenceUnavailable,+ operationaltrust.EvidencePermissionsSufficient,+ "collector_disconnected",+ )+ if err := manager.MarkOperationalCollectionStale(+ alertID,+ staleEvidence,+ "Collector has not completed a current observation.",+ ); err != nil {+ t.Fatalf("MarkOperationalCollectionStale() error = %v", err)+ }+ stale := activeAlert(t, manager, alertID)+ if stale.OperationalRecord.State != operationaltrust.OperationalStale {+ t.Fatalf("stale state = %q", stale.OperationalRecord.State)+ }+ if stale.OperationalRecord.ResolvedAt != nil {+ t.Fatal("stale collection must not resolve the operational record")+ }++ unknownEvidence := operationalStateWriterEvidence(+ t,+ "docker",+ "app-container:web",+ now,+ now.Add(time.Minute),+ operationaltrust.EvidencePartial,+ operationaltrust.EvidencePermissionsDenied,+ "provider_permission_denied",+ )+ if err := manager.MarkOperationalCollectionUnknown(+ alertID,+ unknownEvidence,+ "Provider permissions no longer support a health decision.",+ ); err != nil {+ t.Fatalf("MarkOperationalCollectionUnknown() error = %v", err)+ }+ unknown := activeAlert(t, manager, alertID)+ if unknown.OperationalRecord.State != operationaltrust.OperationalUnknown {+ t.Fatalf("unknown state = %q", unknown.OperationalRecord.State)+ }+ if unknown.LatestTransition == nil ||+ unknown.LatestTransition.Cause != operationaltrust.TransitionCollectionUnknown {+ t.Fatalf("unknown transition = %+v", unknown.LatestTransition)+ }++ freshEvidence := operationalStateWriterEvidence(+ t,+ "docker",+ "app-container:web",+ now.Add(time.Second),+ now.Add(2*time.Minute),+ operationaltrust.EvidenceComplete,+ operationaltrust.EvidencePermissionsSufficient,+ "",+ )+ if err := manager.RestoreOperationalCollectionState(alertID, freshEvidence); err != nil {+ t.Fatalf("RestoreOperationalCollectionState() error = %v", err)+ }+ restored := activeAlert(t, manager, alertID)+ if restored.OperationalRecord.State != operationaltrust.OperationalOpen {+ t.Fatalf("restored state = %q", restored.OperationalRecord.State)+ }+ if restored.OperationalRecord.ResolvedAt != nil {+ t.Fatal("restored collection must reopen, not resolve, the finding")+ }+}++func TestMarkOperationalResolvingRequiresFreshRecoveryEvidence(t *testing.T) {+ manager := newTestManager(t)+ now := time.Now().UTC()+ alert := &Alert{+ ID: "container-health",+ CanonicalState: "container-health",+ CanonicalSpecID: "docker-container-health",+ Type: "docker-container-health",+ Level: AlertLevelWarning,+ ResourceID: "app-container:web",+ StartTime: now.Add(-time.Minute),+ LastSeen: now,+ }+ manager.mu.Lock()+ manager.setActiveAlertNoLock(alert.ID, alert)+ manager.mu.Unlock()++ invalid := operationaltrust.EvidenceEnvelope{}+ if err := manager.MarkOperationalResolving(+ alert.ID,+ invalid,+ "Waiting for a post-action health observation.",+ ); err == nil {+ t.Fatal("invalid recovery evidence must fail closed")+ }++ recovery := operationalStateWriterEvidence(+ t,+ "docker",+ "app-container:web",+ now.Add(time.Second),+ now.Add(time.Minute),+ operationaltrust.EvidenceComplete,+ operationaltrust.EvidencePermissionsSufficient,+ "",+ )+ if err := manager.MarkOperationalResolving(+ alert.ID,+ recovery,+ "Waiting for a post-action health observation.",+ ); err != nil {+ t.Fatalf("MarkOperationalResolving() error = %v", err)+ }+ current := activeAlert(t, manager, alert.ID)+ if current.OperationalRecord.State != operationaltrust.OperationalResolving {+ t.Fatalf("resolving state = %q", current.OperationalRecord.State)+ }+ if current.LatestTransition == nil ||+ current.LatestTransition.Cause != operationaltrust.TransitionRecoveryEvidence {+ t.Fatalf("resolving transition = %+v", current.LatestTransition)+ }+}++func TestOperationalSuppressionSurvivesManagerRestart(t *testing.T) {+ dataDir := t.TempDir()+ manager := NewManagerWithDataDir(dataDir)+ now := time.Now().UTC()+ alert := &Alert{+ ID: "container-health",+ CanonicalState: "container-health",+ CanonicalSpecID: "docker-container-health",+ Type: "docker-container-health",+ Level: AlertLevelWarning,+ ResourceID: "app-container:web",+ ResourceName: "web",+ StartTime: now.Add(-time.Minute),+ LastSeen: now,+ }+ manager.mu.Lock()+ manager.setActiveAlertNoLock(alert.ID, alert)+ manager.mu.Unlock()++ expiresAt := now.Add(2 * time.Hour)+ if err := manager.SuppressOperationalAlert(+ alert.ID,+ "operator",+ "Planned maintenance",+ &expiresAt,+ ); err != nil {+ t.Fatalf("SuppressOperationalAlert() error = %v", err)+ }+ if err := manager.SaveActiveAlerts(); err != nil {+ t.Fatalf("SaveActiveAlerts() error = %v", err)+ }+ manager.Stop()++ reloaded := NewManagerWithDataDir(dataDir)+ t.Cleanup(reloaded.Stop)+ if err := reloaded.LoadActiveAlerts(); err != nil {+ t.Fatalf("LoadActiveAlerts() error = %v", err)+ }+ current := activeAlert(t, reloaded, alert.ID)+ if current.OperationalRecord == nil ||+ current.OperationalRecord.State != operationaltrust.OperationalSuppressed {+ t.Fatalf("reloaded record = %+v", current.OperationalRecord)+ }+ if current.OperationalRecord.Suppression == nil ||+ current.OperationalRecord.Suppression.Reason != "Planned maintenance" {+ t.Fatalf("reloaded suppression = %+v", current.OperationalRecord.Suppression)+ }+ if current.LatestTransition == nil ||+ current.LatestTransition.Cause != operationaltrust.TransitionSuppression {+ t.Fatalf("reloaded transition = %+v", current.LatestTransition)+ }+}++func TestOperationalLifecycleRetriesDoNotDuplicateTransitionsAndRetainNewEvidence(t *testing.T) {+ manager := newTestManager(t)+ now := time.Now().UTC()+ alert := &Alert{+ ID: "container-health",+ CanonicalState: "container-health",+ CanonicalSpecID: "docker-container-health",+ Type: "docker-container-health",+ Level: AlertLevelWarning,+ ResourceID: "app-container:web",+ StartTime: now.Add(-time.Minute),+ LastSeen: now,+ }+ manager.mu.Lock()+ manager.setActiveAlertNoLock(alert.ID, alert)+ manager.mu.Unlock()++ acknowledgementCallbacks := make(chan struct{}, 2)+ manager.SetAcknowledgedCallback(func(*Alert, string) {+ acknowledgementCallbacks <- struct{}{}+ })+ if err := manager.AcknowledgeAlert(alert.ID, "operator"); err != nil {+ t.Fatalf("first AcknowledgeAlert() error = %v", err)+ }+ select {+ case <-acknowledgementCallbacks:+ case <-time.After(time.Second):+ t.Fatal("first acknowledgement callback did not run")+ }+ firstAcknowledged := activeAlert(t, manager, alert.ID)+ firstAckTime := *firstAcknowledged.AckTime+ if err := manager.AcknowledgeAlert(alert.ID, "operator"); err != nil {+ t.Fatalf("retry AcknowledgeAlert() error = %v", err)+ }+ retriedAcknowledged := activeAlert(t, manager, alert.ID)+ select {+ case <-acknowledgementCallbacks:+ t.Fatal("idempotent acknowledgement retry emitted another callback")+ case <-time.After(50 * time.Millisecond):+ }+ if retriedAcknowledged.AckTime == nil ||+ !retriedAcknowledged.AckTime.Equal(firstAckTime) {+ t.Fatalf(+ "retry changed acknowledgement time from %s to %v",+ firstAckTime,+ retriedAcknowledged.AckTime,+ )+ }++ firstEvidence := operationalStateWriterEvidence(+ t,+ "docker",+ "app-container:web",+ now.Add(time.Second),+ now.Add(2*time.Second),+ operationaltrust.EvidenceUnavailable,+ operationaltrust.EvidencePermissionsSufficient,+ "collector_timeout",+ )+ if err := manager.MarkOperationalCollectionStale(+ alert.ID,+ firstEvidence,+ "Collector timed out.",+ ); err != nil {+ t.Fatalf("first stale transition error = %v", err)+ }+ firstStale := activeAlert(t, manager, alert.ID)+ if firstStale.LatestTransition == nil {+ t.Fatal("first stale transition is missing")+ }+ transitionID := firstStale.LatestTransition.ID++ secondEvidence := operationalStateWriterEvidence(+ t,+ "docker",+ "app-container:web",+ now.Add(3*time.Second),+ now.Add(4*time.Second),+ operationaltrust.EvidenceUnavailable,+ operationaltrust.EvidencePermissionsSufficient,+ "collector_timeout",+ )+ if err := manager.MarkOperationalCollectionStale(+ alert.ID,+ secondEvidence,+ "Collector timed out.",+ ); err != nil {+ t.Fatalf("retry stale observation error = %v", err)+ }+ refreshed := activeAlert(t, manager, alert.ID)+ if refreshed.LatestTransition == nil ||+ refreshed.LatestTransition.ID != transitionID {+ t.Fatalf(+ "retry created a new transition: first=%q current=%+v",+ transitionID,+ refreshed.LatestTransition,+ )+ }+ retainedIDs := operationalEvidenceIDs(refreshed.Evidence)+ if !slices.Contains(retainedIDs, firstEvidence.ID) ||+ !slices.Contains(retainedIDs, secondEvidence.ID) {+ t.Fatalf(+ "retained evidence IDs = %v, want %q and %q",+ retainedIDs,+ firstEvidence.ID,+ secondEvidence.ID,+ )+ }+ if !refreshed.OperationalRecord.LastObservedAt.Equal(secondEvidence.ObservedAt) {+ t.Fatalf(+ "LastObservedAt = %s, want %s",+ refreshed.OperationalRecord.LastObservedAt,+ secondEvidence.ObservedAt,+ )+ }+}++func operationalStateWriterEvidence(+ t *testing.T,+ provider string,+ resourceID string,+ observedAt time.Time,+ validUntil time.Time,+ completeness operationaltrust.EvidenceCompleteness,+ permissions operationaltrust.EvidencePermissions,+ reasonCode string,+) operationaltrust.EvidenceEnvelope {+ t.Helper()+ source := operationaltrust.EvidenceSource{+ Provider: provider,+ Collector: provider + "-collector",+ }+ subject := operationaltrust.EvidenceSubject{ResourceID: resourceID}+ id, err := operationaltrust.NewEvidenceID(+ source,+ subject,+ observedAt,+ provider+"-observation",+ )+ if err != nil {+ t.Fatalf("NewEvidenceID() error = %v", err)+ }+ envelope := operationaltrust.EvidenceEnvelope{+ ID: id,+ Source: source,+ Subject: subject,+ ObservedAt: observedAt,+ IngestedAt: observedAt,+ ValidUntil: &validUntil,+ Completeness: completeness,+ Confidence: operationaltrust.EvidenceConfirmed,+ Permissions: permissions,+ }+ if reasonCode != "" {+ envelope.Reason = &operationaltrust.EvidenceReason{Code: reasonCode}+ }+ if err := envelope.Validate(); err != nil {+ t.Fatalf("evidence Validate() error = %v", err)+ }+ return envelope+}diff --git a/internal/api/attention_actions.go b/internal/api/attention_actions.goindex 976e784704..55bdf643a8 100644--- a/internal/api/attention_actions.go+++ b/internal/api/attention_actions.go@@ -10,6 +10,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/mock"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rcourtman/pulse-go-rewrite/pkg/auth"@@ -59,6 +60,8 @@ func (h *AttentionHandlers) projectAttentionActions(store, storeErr := h.resources.getStore(orgID)actor, actorErr := actionActorForRequest(h.resources.cfg, r, orgID)authorized := actorErr == nil &&+ h.hasAutoFixLicense != nil &&+ h.hasAutoFixLicense(r.Context()) &&h.actionAuthority.authorizeActor(r.Context(), orgID, actor, auth.ActionPlan) == nil &&h.actionAuthority.authorizeActor(r.Context(), orgID, actor, auth.ActionApprove) == nil &&h.actionAuthority.authorizeActor(r.Context(), orgID, actor, auth.ActionExecute) == nil@@ -112,6 +115,11 @@ func (h *AttentionHandlers) projectAttentionActions(}}offer, reason := ai.ProjectAttentionAction(detail, candidate, now)+ if reason == ai.AttentionActionEligible {+ operationaltrust.GetMetrics().ObserveActionOffer("eligible")+ } else {+ operationaltrust.GetMetrics().ObserveActionOffer("ineligible")+ }if reason == ai.AttentionActionEligible {detail.Item.AvailableActions = []ai.AttentionActionOffer{offer}}@@ -140,6 +148,14 @@ func (h *AttentionHandlers) handleAttentionActionPlan(writeJSONError(w, http.StatusServiceUnavailable, "attention_actions_unavailable", "Governed actions are unavailable")return}+ if h.hasAutoFixLicense == nil || !h.hasAutoFixLicense(r.Context()) {+ WriteLicenseRequired(+ w,+ featureAIAutoFixKey,+ "Patrol fix actions require Pulse Pro",+ )+ return+ }projection, err := h.project(r, true)if err != nil {diff --git a/internal/api/attention_actions_test.go b/internal/api/attention_actions_test.goindex cb319cb0f7..f048ab38de 100644--- a/internal/api/attention_actions_test.go+++ b/internal/api/attention_actions_test.go@@ -90,6 +90,7 @@ func TestAttentionActionPlanBindsCanonicalRecordEvidenceAndReplaysIdempotently(t},}handler.SetActionDependencies(resources, authority)+ handler.SetActionLicenseChecker(func(context.Context) bool { return true })detailRequest := actionHandlerTestRequest(httptest.NewRequest(@@ -287,3 +288,30 @@ func TestAttentionActionOfferFailsClosedWithoutFreshEvidenceOrExecutorReadiness(t.Fatalf("stale offer=%+v reason=%q", offer, reason)}}++func TestAttentionActionPlanRequiresAutoFixEntitlementBeforeProjection(t *testing.T) {+ handler := &AttentionHandlers{resources: &ResourceHandlers{}}+ handler.SetActionLicenseChecker(func(context.Context) bool { return false })+ request := httptest.NewRequest(+ http.MethodPost,+ "/api/ai/patrol/attention/docker-health/actions/restart/plan",+ nil,+ )+ response := httptest.NewRecorder()++ handler.HandleAttention(response, request)++ if response.Code != http.StatusPaymentRequired {+ t.Fatalf("status = %d, want %d: %s", response.Code, http.StatusPaymentRequired, response.Body.String())+ }+ var payload struct {+ Error string `json:"error"`+ Feature string `json:"feature"`+ }+ if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload.Error != "license_required" || payload.Feature != featureAIAutoFixKey {+ t.Fatalf("license response = %+v", payload)+ }+}diff --git a/internal/api/attention_evidence.go b/internal/api/attention_evidence.gonew file mode 100644index 0000000000..74265ccb19--- /dev/null+++ b/internal/api/attention_evidence.go@@ -0,0 +1,113 @@+package api++import (+ "net/http"+ "net/url"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai"+ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"+)++type attentionEvidenceResponse struct {+ Evidence operationaltrust.EvidenceEnvelope `json:"evidence"`+ Freshness operationaltrust.EvidenceFreshness `json:"freshness"`+ Retained bool `json:"retained"`+}++func parseAttentionEvidencePath(path string) (string, string, bool) {+ path = strings.Trim(path, "/")+ boundary := strings.LastIndex(path, "/evidence/")+ if boundary <= 0 {+ return "", "", false+ }+ itemID, itemErr := url.PathUnescape(path[:boundary])+ evidenceID, evidenceErr := url.PathUnescape(path[boundary+len("/evidence/"):])+ itemID = strings.TrimSpace(itemID)+ evidenceID = strings.TrimSpace(evidenceID)+ return itemID, evidenceID, itemErr == nil && evidenceErr == nil &&+ itemID != "" && evidenceID != ""+}++func (h *AttentionHandlers) handleAttentionEvidence(+ w http.ResponseWriter,+ r *http.Request,+ path string,+) {+ itemID, evidenceID, ok := parseAttentionEvidencePath(path)+ if !ok {+ writeErrorResponse(+ w,+ http.StatusBadRequest,+ "invalid_attention_evidence_id",+ "Attention evidence reference is invalid.",+ nil,+ )+ return+ }+ projection, err := h.project(r, true)+ if err != nil {+ writeAttentionUnavailable(w, err)+ return+ }+ var detail *ai.AttentionItemDetail+ for index := range projection.Details {+ if projection.Details[index].Item.ID == itemID {+ detail = &projection.Details[index]+ break+ }+ }+ if detail == nil {+ writeErrorResponse(+ w,+ http.StatusNotFound,+ "attention_item_not_found",+ "Attention item was not found.",+ nil,+ )+ return+ }+ for _, evidence := range detail.Evidence {+ if evidence.ID != evidenceID {+ continue+ }+ response := attentionEvidenceResponse{+ Evidence: evidence.Clone(),+ Freshness: evidence.FreshnessAt(time.Now().UTC()),+ Retained: true,+ }+ if err := utils.WriteJSONResponse(w, response); err != nil {+ writeJSONError(+ w,+ http.StatusInternalServerError,+ "attention_evidence_encode_failed",+ "Failed to encode attention evidence.",+ )+ }+ return+ }+ for _, referencedID := range detail.OperationalRecord.EvidenceIDs {+ if referencedID == evidenceID {+ writeErrorResponse(+ w,+ http.StatusGone,+ "attention_evidence_detail_expired",+ "The retained evidence summary is still linked, but its bounded detail has expired.",+ map[string]string{+ "evidenceId": evidenceID,+ "retained": "false",+ },+ )+ return+ }+ }+ writeErrorResponse(+ w,+ http.StatusNotFound,+ "attention_evidence_not_found",+ "Evidence was not found for this attention item.",+ nil,+ )+}diff --git a/internal/api/attention_handlers.go b/internal/api/attention_handlers.goindex f7782e98a8..042ba14dbc 100644--- a/internal/api/attention_handlers.go+++ b/internal/api/attention_handlers.go@@ -29,10 +29,12 @@ const (type attentionAlertSnapshot func(context.Context) ([]alerts.Alert, []alerts.Alert, error)type AttentionHandlers struct {- readAlerts attentionAlertSnapshot- recoveryManager *recoverymanager.Manager- resources *ResourceHandlers- actionAuthority actionAuthority+ getMonitor func(context.Context) *monitoring.Monitor+ readAlerts attentionAlertSnapshot+ recoveryManager *recoverymanager.Manager+ resources *ResourceHandlers+ actionAuthority actionAuthority+ hasAutoFixLicense func(context.Context) bool}func NewAttentionHandlers(@@ -40,6 +42,7 @@ func NewAttentionHandlers(recoveryManager *recoverymanager.Manager,) *AttentionHandlers {return &AttentionHandlers{+ getMonitor: getMonitor,readAlerts: func(ctx context.Context) ([]alerts.Alert, []alerts.Alert, error) {if getMonitor == nil {return nil, nil, fmt.Errorf("monitor is not configured")@@ -66,6 +69,15 @@ func (h *AttentionHandlers) SetActionDependencies(h.actionAuthority = authority}+func (h *AttentionHandlers) SetActionLicenseChecker(+ hasAutoFixLicense func(context.Context) bool,+) {+ if h == nil {+ return+ }+ h.hasAutoFixLicense = hasAutoFixLicense+}+type attentionListResponse struct {Data []ai.AttentionItem `json:"data"`Summary ai.AttentionSummary `json:"summary"`@@ -83,6 +95,10 @@ func (h *AttentionHandlers) HandleAttention(w http.ResponseWriter, r *http.Requeh.handleAttentionActionPlan(w, r, path)return}+ if r.Method == http.MethodPost && isAttentionMutationPath(path) {+ h.handleAttentionMutation(w, r, path)+ return+ }if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return@@ -92,6 +108,8 @@ func (h *AttentionHandlers) HandleAttention(w http.ResponseWriter, r *http.Requeh.handleAttentionList(w, r)case path == "/summary":h.handleAttentionSummary(w, r)+ case strings.Contains(path, "/evidence/"):+ h.handleAttentionEvidence(w, r, path)case strings.HasPrefix(path, "/"):h.handleAttentionDetail(w, r, strings.TrimPrefix(path, "/"))default:diff --git a/internal/api/attention_handlers_test.go b/internal/api/attention_handlers_test.goindex 80f133d027..161a97f817 100644--- a/internal/api/attention_handlers_test.go+++ b/internal/api/attention_handlers_test.go@@ -1,16 +1,20 @@package apiimport (+ "bytes""context""encoding/json""errors""net/http""net/http/httptest"+ "net/url""testing""time""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust")@@ -186,6 +190,198 @@ func TestParseAttentionActionPlanPathPreservesOperationalIDsContainingSlashes(t}}+func TestAttentionEvidenceDetailIsBoundedAndReportsExpiredRetention(t *testing.T) {+ now := time.Date(2026, 7, 19, 8, 0, 0, 0, time.UTC)+ const recordID = "agent:node-1/disk:mnt-disk2::metric-threshold:disk"+ alert := attentionHandlerAlert(recordID, operationaltrust.OperationalOpen, now)+ handler := &AttentionHandlers{+ readAlerts: func(context.Context) ([]alerts.Alert, []alerts.Alert, error) {+ return []alerts.Alert{alert}, nil, nil+ },+ }++ request := httptest.NewRequest(+ http.MethodGet,+ "/api/ai/patrol/attention/agent:node-1/disk:mnt-disk2::metric-threshold:disk/evidence/"++ url.PathEscape(alert.Evidence[0].ID),+ nil,+ )+ response := httptest.NewRecorder()+ handler.HandleAttention(response, request)+ if response.Code != http.StatusOK {+ t.Fatalf("status = %d body=%s", response.Code, response.Body.String())+ }+ var payload attentionEvidenceResponse+ if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode evidence response: %v", err)+ }+ if !payload.Retained || payload.Evidence.ID != alert.Evidence[0].ID {+ t.Fatalf("evidence response = %+v", payload)+ }++ alert.OperationalRecord.EvidenceIDs = append(+ alert.OperationalRecord.EvidenceIDs,+ "evidence-expired",+ )+ expiredRequest := httptest.NewRequest(+ http.MethodGet,+ "/api/ai/patrol/attention/agent:node-1/disk:mnt-disk2::metric-threshold:disk/evidence/evidence-expired",+ nil,+ )+ expiredResponse := httptest.NewRecorder()+ handler.HandleAttention(expiredResponse, expiredRequest)+ if expiredResponse.Code != http.StatusGone {+ t.Fatalf(+ "expired status = %d, want %d: %s",+ expiredResponse.Code,+ http.StatusGone,+ expiredResponse.Body.String(),+ )+ }+}++func TestAttentionMutationPathPreservesOperationalIDsContainingSlashes(t *testing.T) {+ for _, kind := range []attentionMutationKind{+ attentionMutationAcknowledge,+ attentionMutationUnacknowledge,+ attentionMutationSuppress,+ attentionMutationUnsuppress,+ } {+ itemID, gotKind, ok := parseAttentionMutationPath(+ "/agent:node-1/disk:mnt-disk2::metric-threshold:disk/" + string(kind),+ )+ if !ok ||+ itemID != "agent:node-1/disk:mnt-disk2::metric-threshold:disk" ||+ gotKind != kind {+ t.Fatalf("item=%q kind=%q ok=%t", itemID, gotKind, ok)+ }+ }+}++func TestAttentionLifecycleMutationsRefreshTheCanonicalProjection(t *testing.T) {+ now := time.Now().UTC()+ alert := attentionHandlerAlert(+ "agent:node-1/disk:mnt-disk2::metric-threshold:disk",+ operationaltrust.OperationalOpen,+ now,+ )+ manager := alerts.NewManagerWithDataDir(t.TempDir())+ t.Cleanup(manager.Stop)+ setUnexportedField(+ t,+ manager,+ "activeAlerts",+ map[string]*alerts.Alert{alert.ID: alert.Clone()},+ )+ setUnexportedField(+ t,+ manager,+ "activeAlertAlias",+ map[string]string{alert.OperationalRecord.ID: alert.ID},+ )+ monitor := &monitoring.Monitor{}+ setUnexportedField(t, monitor, "state", models.NewState())+ setUnexportedField(t, monitor, "alertManager", manager)+ handler := NewAttentionHandlers(+ func(context.Context) *monitoring.Monitor { return monitor },+ nil,+ )++ acknowledge := httptest.NewRequest(+ http.MethodPost,+ "/api/ai/patrol/attention/agent:node-1/disk:mnt-disk2::metric-threshold:disk/acknowledge",+ bytes.NewBufferString("{}"),+ )+ acknowledgeResponse := httptest.NewRecorder()+ handler.HandleAttention(acknowledgeResponse, acknowledge)+ if acknowledgeResponse.Code != http.StatusOK {+ t.Fatalf(+ "acknowledge status = %d: %s",+ acknowledgeResponse.Code,+ acknowledgeResponse.Body.String(),+ )+ }+ assertAttentionHandlerState(+ t,+ handler,+ alert.ID,+ operationaltrust.OperationalAcknowledged,+ )++ suppress := httptest.NewRequest(+ http.MethodPost,+ "/api/ai/patrol/attention/agent:node-1/disk:mnt-disk2::metric-threshold:disk/suppress",+ bytes.NewBufferString(`{+ "reason":"Planned storage maintenance",+ "expiresAt":"`+now.Add(time.Hour).Format(time.RFC3339Nano)+`"+ }`),+ )+ suppressResponse := httptest.NewRecorder()+ handler.HandleAttention(suppressResponse, suppress)+ if suppressResponse.Code != http.StatusOK {+ t.Fatalf(+ "suppress status = %d: %s",+ suppressResponse.Code,+ suppressResponse.Body.String(),+ )+ }+ assertAttentionHandlerState(+ t,+ handler,+ alert.ID,+ operationaltrust.OperationalSuppressed,+ )++ activeList := httptest.NewRequest(+ http.MethodGet,+ "/api/ai/patrol/attention?filter=active",+ nil,+ )+ activeResponse := httptest.NewRecorder()+ handler.HandleAttention(activeResponse, activeList)+ if activeResponse.Code != http.StatusOK {+ t.Fatalf("active list status = %d: %s", activeResponse.Code, activeResponse.Body.String())+ }+ var active attentionListResponse+ if err := json.Unmarshal(activeResponse.Body.Bytes(), &active); err != nil {+ t.Fatalf("decode active list: %v", err)+ }+ if len(active.Data) != 0 || active.Summary.SuppressedCount != 1 {+ t.Fatalf("suppressed active projection = %+v", active)+ }+}++func assertAttentionHandlerState(+ t *testing.T,+ handler *AttentionHandlers,+ itemID string,+ want operationaltrust.OperationalState,+) {+ t.Helper()+ request := httptest.NewRequest(+ http.MethodGet,+ "/api/ai/patrol/attention/"+url.PathEscape(itemID),+ nil,+ )+ response := httptest.NewRecorder()+ handler.HandleAttention(response, request)+ if response.Code != http.StatusOK {+ t.Fatalf("detail status = %d: %s", response.Code, response.Body.String())+ }+ var detail ai.AttentionItemDetail+ if err := json.Unmarshal(response.Body.Bytes(), &detail); err != nil {+ t.Fatalf("decode detail: %v", err)+ }+ if detail.Item.State != want || detail.OperationalRecord.State != want {+ t.Fatalf(+ "detail state item=%q record=%q, want %q",+ detail.Item.State,+ detail.OperationalRecord.State,+ want,+ )+ }+}+func attentionHandlerAlert(id string,state operationaltrust.OperationalState,diff --git a/internal/api/attention_mutations.go b/internal/api/attention_mutations.gonew file mode 100644index 0000000000..2f8353e1e9--- /dev/null+++ b/internal/api/attention_mutations.go@@ -0,0 +1,152 @@+package api++import (+ "encoding/json"+ "net/http"+ "net/url"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++const (+ maxAttentionSuppressionDuration = 30 * 24 * time.Hour+ maxAttentionMutationBodyBytes = 4096+)++type attentionMutationKind string++const (+ attentionMutationAcknowledge attentionMutationKind = "acknowledge"+ attentionMutationUnacknowledge attentionMutationKind = "unacknowledge"+ attentionMutationSuppress attentionMutationKind = "suppress"+ attentionMutationUnsuppress attentionMutationKind = "unsuppress"+)++type attentionSuppressionRequest struct {+ Reason string `json:"reason"`+ ExpiresAt time.Time `json:"expiresAt"`+}++func parseAttentionMutationPath(+ path string,+) (string, attentionMutationKind, bool) {+ path = strings.Trim(path, "/")+ for _, kind := range []attentionMutationKind{+ attentionMutationAcknowledge,+ attentionMutationUnacknowledge,+ attentionMutationSuppress,+ attentionMutationUnsuppress,+ } {+ suffix := "/" + string(kind)+ if !strings.HasSuffix(path, suffix) {+ continue+ }+ itemID, err := url.PathUnescape(strings.TrimSuffix(path, suffix))+ itemID = strings.TrimSpace(itemID)+ return itemID, kind, err == nil && itemID != ""+ }+ return "", "", false+}++func isAttentionMutationPath(path string) bool {+ _, _, ok := parseAttentionMutationPath(path)+ return ok+}++func (h *AttentionHandlers) handleAttentionMutation(+ w http.ResponseWriter,+ r *http.Request,+ path string,+) {+ if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ return+ }+ itemID, kind, ok := parseAttentionMutationPath(path)+ if !ok {+ writeJSONError(+ w,+ http.StatusNotFound,+ "attention_mutation_not_found",+ "Attention mutation was not found.",+ )+ return+ }+ if h == nil || h.getMonitor == nil {+ writeAttentionUnavailable(w, nil)+ return+ }+ monitor := h.getMonitor(r.Context())+ if monitor == nil || monitor.GetAlertManager() == nil {+ writeAttentionUnavailable(w, nil)+ return+ }+ manager := monitor.GetAlertManager()+ actor := strings.TrimSpace(auth.GetUser(r.Context()))+ if actor == "" {+ actor = "unknown"+ }++ var err error+ switch kind {+ case attentionMutationAcknowledge:+ err = manager.AcknowledgeAlert(itemID, actor)+ case attentionMutationUnacknowledge:+ err = manager.UnacknowledgeAlert(itemID)+ case attentionMutationSuppress:+ var request attentionSuppressionRequest+ r.Body = http.MaxBytesReader(w, r.Body, maxAttentionMutationBodyBytes)+ if decodeErr := json.NewDecoder(r.Body).Decode(&request); decodeErr != nil {+ writeJSONError(+ w,+ http.StatusBadRequest,+ "invalid_attention_suppression",+ "Suppression requires a reason and expiry.",+ )+ return+ }+ now := time.Now().UTC()+ if strings.TrimSpace(request.Reason) == "" ||+ request.ExpiresAt.IsZero() ||+ !request.ExpiresAt.After(now) ||+ request.ExpiresAt.After(now.Add(maxAttentionSuppressionDuration)) {+ writeJSONError(+ w,+ http.StatusBadRequest,+ "invalid_attention_suppression",+ "Suppression requires a reason and an expiry within 30 days.",+ )+ return+ }+ expiresAt := request.ExpiresAt.UTC()+ err = manager.SuppressOperationalAlert(+ itemID,+ actor,+ request.Reason,+ &expiresAt,+ )+ case attentionMutationUnsuppress:+ err = manager.UnsuppressOperationalAlert(itemID)+ }+ if err != nil {+ writeJSONError(+ w,+ http.StatusNotFound,+ "attention_item_not_found",+ "Attention item was not found.",+ )+ return+ }+ monitor.SyncAlertState()+ if err := utils.WriteJSONResponse(w, map[string]bool{"success": true}); err != nil {+ writeJSONError(+ w,+ http.StatusInternalServerError,+ "attention_mutation_encode_failed",+ "Failed to encode attention mutation result.",+ )+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 8702d16bdf..e212de02cc 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -13906,6 +13906,7 @@ func TestContract_ResourceFacetsDeriveCanonicalParentRelationship(t *testing.T)"resourceId":"agent-1","relationships":[{+ "id":"relationship_aed4b8896bb2a8ca119ef1547a93e944","sourceId":"agent-1","targetId":"k8s-cluster-1","type":"owned_by",diff --git a/internal/api/router.go b/internal/api/router.goindex 82e917f7a3..9d6f02a49a 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -675,6 +675,12 @@ func (r *Router) setupRoutes() {// AI settings endpointsr.aiSettingsHandler = NewAISettingsHandler(r.multiTenant, r.mtMonitor, r.agentExecServer)+ if r.attentionHandlers != nil {+ r.attentionHandlers.SetActionLicenseChecker(func(ctx context.Context) bool {+ service := r.aiSettingsHandler.GetAIService(ctx)+ return service != nil && service.HasLicenseFeature(ai.FeatureAIAutoFix)+ })+ }if r.resourceHandlers != nil {r.resourceHandlers.SetActionEmergencyStopChecker(func(orgID string) (bool, error) {orgCtx := context.WithValue(context.Background(), OrgIDContextKey, approval.NormalizeOrgID(orgID))diff --git a/internal/notifications/queue.go b/internal/notifications/queue.goindex be50a30821..dfd1ca3171 100644--- a/internal/notifications/queue.go+++ b/internal/notifications/queue.go@@ -518,6 +518,19 @@ func (nq *NotificationQueue) Enqueue(notif *QueuedNotification) error {Str("type", notif.Type).Int("alertCount", len(notif.Alerts)).Msg("notification enqueued")+ metrics := operationaltrust.GetMetrics()+ metrics.ObserveNotificationDelivery("queued")+ for _, alert := range notif.Alerts {+ if alert == nil ||+ alert.LatestTransition == nil ||+ alert.LatestTransition.To != operationaltrust.OperationalOpen {+ continue+ }+ metrics.ObserveOpenToNotification(+ alert.LatestTransition.At,+ notif.CreatedAt,+ )+ }// Signal processor that new work is availableselect {@@ -949,7 +962,20 @@ func (nq *NotificationQueue) RecordAudit(notif *QueuedNotification, success boolnotif.PayloadBytes,time.Now().Unix(),)-+ if err == nil {+ outcome := "failed"+ switch {+ case success && notif.Status == QueueStatusSent:+ outcome = "sent"+ case notif.Status == QueueStatusDLQ:+ outcome = "dead_letter"+ case notif.Status == QueueStatusCancelled:+ outcome = "cancelled"+ case notif.Status == QueueStatusPending && notif.Attempts > 0:+ outcome = "retry"+ }+ operationaltrust.GetMetrics().ObserveNotificationDelivery(outcome)+ }return err}diff --git a/internal/notifications/queue_test.go b/internal/notifications/queue_test.goindex b105e1da31..61083332f4 100644--- a/internal/notifications/queue_test.go+++ b/internal/notifications/queue_test.go@@ -1621,7 +1621,8 @@ func TestSetProcessorTriggersPendingDelivery(t *testing.T) {}func TestNotificationQueuePersistsGroupedOperationalLinksAcrossDeliveryStates(t *testing.T) {- nq, err := NewNotificationQueue(t.TempDir())+ dataDir := t.TempDir()+ nq, err := NewNotificationQueue(dataDir)if err != nil {t.Fatalf("NewNotificationQueue() error = %v", err)}@@ -1708,6 +1709,27 @@ func TestNotificationQueuePersistsGroupedOperationalLinksAcrossDeliveryStates(t}}+ if err := nq.Stop(); err != nil {+ t.Fatalf("Stop() before restart error = %v", err)+ }+ nq, err = NewNotificationQueue(dataDir)+ if err != nil {+ t.Fatalf("NewNotificationQueue() after restart error = %v", err)+ }+ restarted, err := nq.getNotificationLinks(notif.ID)+ if err != nil {+ t.Fatalf("get restarted links error = %v", err)+ }+ for index, link := range restarted {+ if link.NotificationID != notif.ID ||+ link.TransitionID != retrying[index].TransitionID ||+ link.DeliveryState != operationaltrust.NotificationRetrying ||+ link.AttemptedAt == nil ||+ link.CompletedAt != nil {+ t.Fatalf("restarted link = %+v", link)+ }+ }+if err := nq.UpdateStatus(notif.ID, QueueStatusSent, ""); err != nil {t.Fatalf("UpdateStatus(sent) error = %v", err)}diff --git a/internal/operationaltrust/metrics.go b/internal/operationaltrust/metrics.gonew file mode 100644index 0000000000..1f018b9478--- /dev/null+++ b/internal/operationaltrust/metrics.go@@ -0,0 +1,266 @@+package operationaltrust++import (+ "strings"+ "sync"+ "time"++ "github.com/prometheus/client_golang/prometheus"+)++// Metrics exposes low-cardinality health measurements for the canonical+// operational-trust loop. Raw resource, record, evidence, actor, destination,+// and provider-instance identifiers are deliberately never used as labels.+type Metrics struct {+ observationToOpen prometheus.Histogram+ openToNotification prometheus.Histogram+ evidenceObservations *prometheus.CounterVec+ identityCorrelations *prometheus.CounterVec+ protectionEvaluations *prometheus.CounterVec+ protectionFailures *prometheus.CounterVec+ notificationDeliveries *prometheus.CounterVec+ activeCountMismatches prometheus.Counter+ actionOffers *prometheus.CounterVec+ actionVerification *prometheus.CounterVec+}++var (+ metricsInstance *Metrics+ metricsOnce sync.Once+)++// GetMetrics returns the process-wide operational-trust metrics owner.+func GetMetrics() *Metrics {+ metricsOnce.Do(func() {+ metricsInstance = newMetrics(prometheus.DefaultRegisterer)+ })+ return metricsInstance+}++func newMetrics(registerer prometheus.Registerer) *Metrics {+ metrics := &Metrics{+ observationToOpen: prometheus.NewHistogram(prometheus.HistogramOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "observation_to_open_seconds",+ Help: "Elapsed seconds from the first canonical observation to an open operational record",+ Buckets: []float64{0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 15, 30, 60},+ }),+ openToNotification: prometheus.NewHistogram(prometheus.HistogramOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "open_to_notification_enqueue_seconds",+ Help: "Elapsed seconds from an open lifecycle transition to notification enqueue",+ Buckets: []float64{0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 15, 30, 60},+ }),+ evidenceObservations: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "evidence_observations_total",+ Help: "Canonical evidence observations by bounded source and evidence state",+ }, []string{"source", "state"}),+ identityCorrelations: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "identity_correlations_total",+ Help: "Canonical resource identity correlation decisions by outcome",+ }, []string{"outcome"}),+ protectionEvaluations: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "protection_posture_evaluations_total",+ Help: "Protection posture evaluations by canonical posture state",+ }, []string{"state"}),+ protectionFailures: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "protection_posture_evaluation_failures_total",+ Help: "Protection posture evaluation failures by bounded reason",+ }, []string{"reason"}),+ notificationDeliveries: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "notification_delivery_total",+ Help: "Transition-linked notification delivery outcomes",+ }, []string{"outcome"}),+ activeCountMismatches: prometheus.NewCounter(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "active_count_mismatch_total",+ Help: "Detected mismatches between the canonical active count and active attention projection",+ }),+ actionOffers: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "action_offers_total",+ Help: "Operational Trust action offer projections by eligibility",+ }, []string{"eligibility"}),+ actionVerification: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "pulse",+ Subsystem: "operational_trust",+ Name: "action_verification_total",+ Help: "Operational Trust action verification outcomes",+ }, []string{"outcome"}),+ }+ registerer.MustRegister(+ metrics.observationToOpen,+ metrics.openToNotification,+ metrics.evidenceObservations,+ metrics.identityCorrelations,+ metrics.protectionEvaluations,+ metrics.protectionFailures,+ metrics.notificationDeliveries,+ metrics.activeCountMismatches,+ metrics.actionOffers,+ metrics.actionVerification,+ )+ return metrics+}++func (metrics *Metrics) ObserveObservationToOpen(firstObservedAt, openedAt time.Time) {+ if metrics == nil {+ return+ }+ if elapsed, ok := nonNegativeElapsed(firstObservedAt, openedAt); ok {+ metrics.observationToOpen.Observe(elapsed.Seconds())+ }+}++func (metrics *Metrics) ObserveOpenToNotification(openedAt, enqueuedAt time.Time) {+ if metrics == nil {+ return+ }+ if elapsed, ok := nonNegativeElapsed(openedAt, enqueuedAt); ok {+ metrics.openToNotification.Observe(elapsed.Seconds())+ }+}++func (metrics *Metrics) ObserveEvidence(envelope EvidenceEnvelope, at time.Time) {+ if metrics == nil {+ return+ }+ metrics.evidenceObservations.WithLabelValues(+ operationalMetricSource(envelope.Source.Provider),+ operationalEvidenceMetricState(envelope, at),+ ).Inc()+}++func (metrics *Metrics) ObserveIdentityCorrelation(outcome string) {+ if metrics == nil {+ return+ }+ metrics.identityCorrelations.WithLabelValues(+ boundedMetricLabel(outcome, map[string]struct{}{+ "attached": {}, "standalone": {}, "ambiguous": {}, "unresolved": {},+ }),+ ).Inc()+}++func (metrics *Metrics) ObserveProtectionEvaluation(state string) {+ if metrics == nil {+ return+ }+ metrics.protectionEvaluations.WithLabelValues(+ boundedMetricLabel(state, map[string]struct{}{+ "protected": {}, "attention": {}, "unprotected": {}, "unknown": {},+ }),+ ).Inc()+}++func (metrics *Metrics) ObserveProtectionEvaluationFailure(reason string) {+ if metrics == nil {+ return+ }+ metrics.protectionFailures.WithLabelValues(+ boundedMetricLabel(reason, map[string]struct{}{+ "invalid_policy": {}, "invalid_posture": {}, "store": {}, "provider": {},+ }),+ ).Inc()+}++func (metrics *Metrics) ObserveNotificationDelivery(outcome string) {+ if metrics == nil {+ return+ }+ metrics.notificationDeliveries.WithLabelValues(+ boundedMetricLabel(outcome, map[string]struct{}{+ "queued": {}, "retry": {}, "sent": {}, "failed": {}, "dead_letter": {}, "cancelled": {},+ }),+ ).Inc()+}++func (metrics *Metrics) RecordActiveCountMismatch() {+ if metrics != nil {+ metrics.activeCountMismatches.Inc()+ }+}++func (metrics *Metrics) ObserveActionOffer(eligibility string) {+ if metrics == nil {+ return+ }+ metrics.actionOffers.WithLabelValues(+ boundedMetricLabel(eligibility, map[string]struct{}{+ "eligible": {}, "ineligible": {}, "unknown": {},+ }),+ ).Inc()+}++func (metrics *Metrics) ObserveActionVerification(outcome string) {+ if metrics == nil {+ return+ }+ metrics.actionVerification.WithLabelValues(+ boundedMetricLabel(outcome, map[string]struct{}{+ "pending": {}, "confirmed": {}, "contradicted": {}, "inconclusive": {}, "timed_out": {}, "not_attempted": {},+ }),+ ).Inc()+}++func nonNegativeElapsed(start, end time.Time) (time.Duration, bool) {+ if start.IsZero() || end.IsZero() || end.Before(start) {+ return 0, false+ }+ return end.Sub(start), true+}++func operationalMetricSource(source string) string {+ return boundedMetricLabel(source, map[string]struct{}{+ "agent": {}, "availability": {}, "docker": {}, "host": {}, "k8s": {},+ "kubernetes": {}, "pbs": {}, "podman": {}, "proxmox": {}, "pulse": {},+ "pve": {}, "qnap": {}, "synology": {}, "truenas": {}, "unraid": {},+ "vmware": {},+ })+}++func operationalEvidenceMetricState(envelope EvidenceEnvelope, at time.Time) string {+ switch envelope.Permissions {+ case EvidencePermissionsDenied:+ return "denied"+ case EvidencePermissionsPartial:+ return "partial_permission"+ }+ switch envelope.Completeness {+ case EvidenceUnavailable:+ return "unavailable"+ case EvidencePartial:+ return "partial"+ }+ switch envelope.FreshnessAt(at) {+ case EvidenceStale:+ return "stale"+ case EvidenceFreshnessUnknown:+ return "unknown"+ default:+ return "current"+ }+}++func boundedMetricLabel(value string, allowed map[string]struct{}) string {+ value = strings.ToLower(strings.TrimSpace(value))+ value = strings.ReplaceAll(value, "-", "_")+ if _, ok := allowed[value]; ok {+ return value+ }+ return "other"+}diff --git a/internal/operationaltrust/metrics_test.go b/internal/operationaltrust/metrics_test.gonew file mode 100644index 0000000000..32e7bd7083--- /dev/null+++ b/internal/operationaltrust/metrics_test.go@@ -0,0 +1,77 @@+package operationaltrust++import (+ "testing"+ "time"++ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/testutil"+)++func TestOperationalTrustMetricsUseBoundedLabelsAndRecordRequiredOutcomes(t *testing.T) {+ registry := prometheus.NewRegistry()+ metrics := newMetrics(registry)+ now := time.Date(2026, 7, 19, 6, 0, 0, 0, time.UTC)+ validUntil := now.Add(-time.Minute)++ metrics.ObserveObservationToOpen(now.Add(-2*time.Second), now)+ metrics.ObserveOpenToNotification(now, now.Add(time.Second))+ metrics.ObserveEvidence(EvidenceEnvelope{+ Source: EvidenceSource{Provider: "customer-controlled-provider-name"},+ ObservedAt: now.Add(-time.Minute),+ ValidUntil: &validUntil,+ Completeness: EvidenceComplete,+ Permissions: EvidencePermissionsSufficient,+ }, now)+ metrics.ObserveIdentityCorrelation("ambiguous")+ metrics.ObserveProtectionEvaluation("protected")+ metrics.ObserveProtectionEvaluationFailure("invalid_policy")+ metrics.ObserveNotificationDelivery("dead-letter")+ metrics.RecordActiveCountMismatch()+ metrics.ObserveActionOffer("eligible")+ metrics.ObserveActionVerification("inconclusive")++ for name, collector := range map[string]prometheus.Collector{+ "observation latency": metrics.observationToOpen,+ "notification latency": metrics.openToNotification,+ "evidence": metrics.evidenceObservations,+ "identity": metrics.identityCorrelations,+ "posture": metrics.protectionEvaluations,+ "posture failure": metrics.protectionFailures,+ "delivery": metrics.notificationDeliveries,+ "mismatch": metrics.activeCountMismatches,+ "offer": metrics.actionOffers,+ "verification": metrics.actionVerification,+ } {+ if count := testutil.CollectAndCount(collector); count != 1 {+ t.Fatalf("%s metric family count = %d, want 1", name, count)+ }+ }++ if got := testutil.ToFloat64(+ metrics.evidenceObservations.WithLabelValues("other", "stale"),+ ); got != 1 {+ t.Fatalf("bounded evidence metric = %v, want 1", got)+ }+ if got := testutil.ToFloat64(+ metrics.notificationDeliveries.WithLabelValues("dead_letter"),+ ); got != 1 {+ t.Fatalf("dead-letter metric = %v, want 1", got)+ }+}++func TestOperationalTrustMetricsIgnoreInvalidNegativeLatency(t *testing.T) {+ registry := prometheus.NewRegistry()+ metrics := newMetrics(registry)+ now := time.Now().UTC()++ metrics.ObserveObservationToOpen(now, now.Add(-time.Second))+ metrics.ObserveOpenToNotification(time.Time{}, now)++ if got := testutil.CollectAndCount(metrics.observationToOpen); got != 1 {+ t.Fatalf("observation histogram family count = %d, want 1", got)+ }+ if got := testutil.CollectAndCount(metrics.openToNotification); got != 1 {+ t.Fatalf("notification histogram family count = %d, want 1", got)+ }+}diff --git a/internal/recovery/posture.go b/internal/recovery/posture.goindex 3d8cb64aa4..f182849d4e 100644--- a/internal/recovery/posture.go+++ b/internal/recovery/posture.go@@ -361,6 +361,7 @@ func DeriveProtectionPostureAt() ProtectionPosture {subjectResourceID = strings.TrimSpace(subjectResourceID)if err := policy.Validate(); err != nil {+ operationaltrust.GetMetrics().ObserveProtectionEvaluationFailure("invalid_policy")policy = DefaultProtectionPosturePolicy}if now.IsZero() {@@ -585,6 +586,7 @@ func DeriveProtectionPostureAt(posture.State = ProtectionStateUnknown}+ operationaltrust.GetMetrics().ObserveProtectionEvaluation(string(posture.State))return posture}diff --git a/internal/recovery/posture_test.go b/internal/recovery/posture_test.goindex 5468ba0b49..42c175e572 100644--- a/internal/recovery/posture_test.go+++ b/internal/recovery/posture_test.go@@ -319,3 +319,23 @@ func TestNewProtectionProviderObservationRequiresTypedLimitation(t *testing.T) {t.Fatalf("permissions = %q, want denied", observation.Evidence.Permissions)}}++func TestDeriveProtectionPostureFailsClosedToDefaultPolicy(t *testing.T) {+ t.Parallel()++ now := time.Date(2026, 7, 19, 8, 0, 0, 0, time.UTC)+ recent := now.Add(-time.Hour)+ posture := DeriveProtectionPostureAt(+ "resource:vm-100",+ []ProtectionProviderSummary{protectionTestSummary(now, &recent)},+ ProtectionPosturePolicy{},+ now,+ )++ if posture.State != ProtectionStateProtected {+ t.Fatalf("state = %q, want protected after default-policy fallback", posture.State)+ }+ if posture.Freshness != ProtectionFreshnessCurrent {+ t.Fatalf("freshness = %q, want current after default-policy fallback", posture.Freshness)+ }+}diff --git a/internal/unifiedresources/availability_link_test.go b/internal/unifiedresources/availability_link_test.goindex a788cf870f..231a51259c 100644--- a/internal/unifiedresources/availability_link_test.go+++ b/internal/unifiedresources/availability_link_test.go@@ -130,6 +130,16 @@ func TestAvailabilityExplicitLinkAttachesFacetToKnownResource(t *testing.T) {if relationship.Type == RelChecks &&relationship.TargetID == hostID &&relationship.Metadata["targetId"] == "probe-1" {+ if relationship.ID == "" {+ t.Fatal("availability relationship is missing its stable ID")+ }+ if relationship.EvidenceID != host.Availability.Evidence.ID {+ t.Fatalf(+ "availability relationship evidence = %q, want %q",+ relationship.EvidenceID,+ host.Availability.Evidence.ID,+ )+ }foundChecksRelationship = true}}diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.goindex 28b1ede478..34ae5d6114 100644--- a/internal/unifiedresources/registry.go+++ b/internal/unifiedresources/registry.go@@ -612,6 +612,7 @@ func (rr *ResourceRegistry) ingestResources(resources []Resource, thresholds map}resource.Type = CanonicalResourceType(resource.Type)normalizeResourceAvailability(resource)+ normalizeResourceRelationships(resource)if resource.SourceStatus == nil && len(resource.Sources) > 0 {resource.SourceStatus = make(map[DataSource]SourceStatus, len(resource.Sources))for _, source := range resource.Sources {@@ -1831,6 +1832,7 @@ func (rr *ResourceRegistry) refreshDockerNetworkAttachmentRelationships(host modDiscoverer: dockerAdapterRelationshipDiscoverer,Metadata: dockerNetworkAttachmentMetadata(host, attachment),}+ normalizeResourceRelationship(&relationship)relationshipsByContainer[containerID] = append(relationshipsByContainer[containerID], relationship)relationshipsByNetwork[networkID] = append(relationshipsByNetwork[networkID], relationship)}@@ -1909,6 +1911,7 @@ func (rr *ResourceRegistry) setDockerNetworkAttachmentRelationshipsLocked(})resource.Relationships = append(base, nextDockerRelationships...)+ normalizeResourceRelationships(resource)}func isDockerNetworkAttachmentRelationship(relationship ResourceRelationship) bool {@@ -2403,6 +2406,7 @@ func (rr *ResourceRegistry) ingest(source DataSource, sourceID string, resourcevar availabilityResolution availabilityLinkResolutionif source == SourceAvailability && resource.Type == ResourceTypeNetworkEndpoint {availabilityResolution = rr.resolveAvailabilityLink(resource)+ operationaltrust.GetMetrics().ObserveIdentityCorrelation(string(availabilityResolution.State))applyAvailabilityResolution(resource.Availability, availabilityResolution)if linked := availabilityResolution.ResourceID; linked != "" {if existing := rr.resources[linked]; existing != nil {@@ -2443,6 +2447,7 @@ func (rr *ResourceRegistry) ingest(source DataSource, sourceID string, resourcebindAvailabilityEvidence(resource.Availability, resource.ID, availabilityResolution)normalizeResourceAvailability(&resource)}+ normalizeResourceRelationships(&resource)if existing := rr.resources[resource.ID]; existing != nil {rr.mergeInto(existing, resource, source)rr.bySource[source][sourceID] = existing.ID@@ -2843,6 +2848,10 @@ func upsertAvailabilityCheckRelationship("correlationRule": resolution.Rule,},}+ if availability.Evidence != nil {+ relation.EvidenceID = availability.Evidence.ID+ }+ normalizeResourceRelationship(&relation)out := append([]ResourceRelationship(nil), relationships...)for index := range out {diff --git a/internal/unifiedresources/relationship_presentation_test.go b/internal/unifiedresources/relationship_presentation_test.goindex 1b2143a621..77ba3d769d 100644--- a/internal/unifiedresources/relationship_presentation_test.go+++ b/internal/unifiedresources/relationship_presentation_test.go@@ -159,6 +159,53 @@ func TestResourceRelationshipsWithCanonicalParent(t *testing.T) {}}+func TestNormalizeResourceRelationshipAddsStableAuditIdentity(t *testing.T) {+ relationship := ResourceRelationship{+ SourceID: " network-endpoint:check-1 ",+ TargetID: " app-container:web ",+ Type: RelChecks,+ Confidence: 1,+ Discoverer: " availability_attachment ",+ EvidenceID: " evidence-1 ",+ }+ normalizeResourceRelationship(&relationship)+ firstID := relationship.ID++ if firstID == "" {+ t.Fatal("relationship ID was not derived")+ }+ if relationship.SourceID != "network-endpoint:check-1" ||+ relationship.TargetID != "app-container:web" {+ t.Fatalf("canonical endpoints = %q -> %q", relationship.SourceID, relationship.TargetID)+ }+ if relationship.EvidenceID != "evidence-1" {+ t.Fatalf("evidence ID = %q", relationship.EvidenceID)+ }++ relationship.ID = ""+ normalizeResourceRelationship(&relationship)+ if relationship.ID != firstID {+ t.Fatalf("relationship ID changed: got %q want %q", relationship.ID, firstID)+ }+}++func TestOperationalTrustRelationshipVocabularyIsTyped(t *testing.T) {+ for _, relationshipType := range []RelationshipType{+ RelRunsOn,+ RelHostedBy,+ RelDependsOn,+ RelStoresOn,+ RelProtectedBy,+ RelChecks,+ RelMemberOf,+ RelExposedBy,+ } {+ if relationshipType == "" {+ t.Fatal("relationship type must not be empty")+ }+ }+}+func contains(s, substr string) bool {for i := 0; i <= len(s)-len(substr); i++ {if s[i:i+len(substr)] == substr {diff --git a/internal/unifiedresources/relationships.go b/internal/unifiedresources/relationships.goindex 3ae4ce758e..a56c87c91d 100644--- a/internal/unifiedresources/relationships.go+++ b/internal/unifiedresources/relationships.go@@ -1,6 +1,11 @@package unifiedresources-import "time"+import (+ "crypto/sha256"+ "encoding/hex"+ "strings"+ "time"+)const parentRelationshipDiscoverer = "resource_registry"@@ -8,21 +13,27 @@ const parentRelationshipDiscoverer = "resource_registry"type RelationshipType stringconst (- RelRunsOn RelationshipType = "runs_on" // e.g., container runs_on machine- RelDependsOn RelationshipType = "depends_on" // e.g., app depends_on database- RelMountedTo RelationshipType = "mounted_to" // e.g., volume mounted_to container- RelExposedBy RelationshipType = "exposed_by" // e.g., container exposed_by ingress- RelOwnedBy RelationshipType = "owned_by" // e.g., pod owned_by deployment- RelAttachedTo RelationshipType = "attached_to" // e.g., container attached_to network- RelChecks RelationshipType = "checks" // e.g., availability check checks resource+ RelRunsOn RelationshipType = "runs_on" // e.g., container runs_on machine+ RelDependsOn RelationshipType = "depends_on" // e.g., app depends_on database+ RelMountedTo RelationshipType = "mounted_to" // e.g., volume mounted_to container+ RelExposedBy RelationshipType = "exposed_by" // e.g., container exposed_by ingress+ RelOwnedBy RelationshipType = "owned_by" // e.g., pod owned_by deployment+ RelAttachedTo RelationshipType = "attached_to" // e.g., container attached_to network+ RelChecks RelationshipType = "checks" // e.g., availability check checks resource+ RelHostedBy RelationshipType = "hosted_by"+ RelStoresOn RelationshipType = "stores_on"+ RelProtectedBy RelationshipType = "protected_by"+ RelMemberOf RelationshipType = "member_of")// ResourceRelationship represents a typed relationship edge between two unified resources.type ResourceRelationship struct {+ ID string `json:"id,omitempty"`SourceID string `json:"sourceId"`TargetID string `json:"targetId"`Type RelationshipType `json:"type"`Confidence float64 `json:"confidence"` // 1.0 for defined relationships, lower for heuristics+ EvidenceID string `json:"evidenceId,omitempty"`// Provenance and time boundariesActive bool `json:"active"` // False means historical edge@@ -36,7 +47,8 @@ type ResourceRelationship struct {// relationships plus a canonical relationship derived from ParentID when the// resource has a parent but no equivalent typed edge.func ResourceRelationshipsWithCanonicalParent(resource Resource) []ResourceRelationship {- relationships := append([]ResourceRelationship(nil), resource.Relationships...)+ normalizeResourceRelationships(&resource)+ relationships := resource.RelationshipssourceID := CanonicalResourceID(resource.ID)parentID := ""@@ -65,7 +77,7 @@ func ResourceRelationshipsWithCanonicalParent(resource Resource) []ResourceRelatobservedAt = resource.LastSeen}- return append(relationships, ResourceRelationship{+ parent := ResourceRelationship{SourceID: sourceID,TargetID: parentID,Type: relationshipType,@@ -77,7 +89,42 @@ func ResourceRelationshipsWithCanonicalParent(resource Resource) []ResourceRelatMetadata: map[string]any{"source": "parentId",},- })+ }+ normalizeResourceRelationship(&parent)+ return append(relationships, parent)+}++func normalizeResourceRelationships(resource *Resource) {+ if resource == nil || len(resource.Relationships) == 0 {+ return+ }+ for index := range resource.Relationships {+ normalizeResourceRelationship(&resource.Relationships[index])+ }+}++func normalizeResourceRelationship(relationship *ResourceRelationship) {+ if relationship == nil {+ return+ }+ relationship.SourceID = CanonicalResourceID(relationship.SourceID)+ relationship.TargetID = CanonicalResourceID(relationship.TargetID)+ relationship.Discoverer = strings.TrimSpace(relationship.Discoverer)+ relationship.EvidenceID = strings.TrimSpace(relationship.EvidenceID)+ if strings.TrimSpace(relationship.ID) != "" ||+ relationship.SourceID == "" ||+ relationship.TargetID == "" ||+ relationship.Type == "" {+ return+ }+ sum := sha256.Sum256([]byte(strings.Join([]string{+ relationship.SourceID,+ relationship.TargetID,+ string(relationship.Type),+ relationship.Discoverer,+ relationship.EvidenceID,+ }, "\x00")))+ relationship.ID = "relationship_" + hex.EncodeToString(sum[:16])}func parentRelationshipType(resourceType ResourceType) RelationshipType {diff --git a/scripts/release_control/ai_runtime_docs_policy_test.py b/scripts/release_control/ai_runtime_docs_policy_test.pyindex 95b0a28426..a743f77e1e 100644--- a/scripts/release_control/ai_runtime_docs_policy_test.py+++ b/scripts/release_control/ai_runtime_docs_policy_test.py@@ -64,6 +64,14 @@ class AIRuntimeDocsPolicyTest(unittest.TestCase):"it cannot create lifecycle truth, invent action authority, or hide uncertainty",normalized_content,)+ self.assertIn(+ "Suppression is temporary and requires an operator reason plus a bounded expiry",+ normalized_content,+ )+ self.assertIn(+ "A successful command does not resolve the attention item",+ normalized_content,+ )self.assertIn("The Assistant model matrix below proves Assistant orchestration only",normalized_content,diff --git a/tests/integration/tests/91-operational-trust-attention-workbench.spec.ts b/tests/integration/tests/91-operational-trust-attention-workbench.spec.tsindex 796fec1f0f..9c4b4ec68e 100644--- a/tests/integration/tests/91-operational-trust-attention-workbench.spec.ts+++ b/tests/integration/tests/91-operational-trust-attention-workbench.spec.ts@@ -296,6 +296,68 @@ async function mockAttention(initialMode: AttentionMode,): Promise<{ setMode: (mode: AttentionMode) => void }> {let mode = initialMode;+ let primaryState: "open" | "acknowledged" | "suppressed" = "open";+ let suppressionReason = "";+ const primaryItem = () => ({+ ...openAttentionItem,+ state: primaryState,+ });+ const primaryDetail = () => ({+ ...detail,+ item: primaryItem(),+ operationalRecord: {+ ...detail.operationalRecord,+ state: primaryState,+ ...(primaryState === "acknowledged"+ ? {+ acknowledgement: {+ at: evaluatedAt,+ by: "operator",+ },+ }+ : {}),+ ...(primaryState === "suppressed"+ ? {+ suppression: {+ at: evaluatedAt,+ by: "operator",+ reason: suppressionReason,+ expiresAt: new Date(now.getTime() + 60 * 60_000).toISOString(),+ },+ }+ : {}),+ },+ timeline:+ primaryState === "open"+ ? detail.timeline+ : [+ ...detail.timeline,+ {+ id: `transition-${primaryState}`,+ operationalRecordId: attentionID,+ from: "open",+ to: primaryState,+ at: evaluatedAt,+ cause:+ primaryState === "acknowledged"+ ? "acknowledgement"+ : "suppression",+ causeKey: attentionID,+ evidenceIds: ["metric-evidence-1"],+ reason:+ primaryState === "suppressed"+ ? suppressionReason+ : "Operator acknowledged the issue.",+ },+ ],+ });+ const currentSummary = () => ({+ ...activeSummary,+ activeCount: primaryState === "suppressed" ? 1 : 2,+ openCount: primaryState === "open" ? 1 : 0,+ acknowledgedCount: primaryState === "acknowledged" ? 2 : 1,+ suppressedCount: primaryState === "suppressed" ? 2 : 1,+ });await page.route("**/api/resources**", async (route) => {const url = new URL(route.request().url());if (url.pathname !== "/api/resources") {@@ -496,6 +558,28 @@ async function mockAttention(}const url = new URL(route.request().url());+ if (route.request().method() === "POST") {+ if (url.pathname.endsWith("/acknowledge")) {+ primaryState = "acknowledged";+ } else if (url.pathname.endsWith("/unacknowledge")) {+ primaryState = "open";+ } else if (url.pathname.endsWith("/suppress")) {+ const body = route.request().postDataJSON() as {+ reason?: string;+ };+ suppressionReason = body.reason ?? "";+ primaryState = "suppressed";+ } else if (url.pathname.endsWith("/unsuppress")) {+ primaryState = "open";+ suppressionReason = "";+ }+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ success: true }),+ });+ return;+ }if (url.pathname.endsWith("/summary")) {await route.fulfill({status: 200,@@ -513,7 +597,7 @@ async function mockAttention(coverageState: "current",evaluatedAt,}- : activeSummary,+ : currentSummary(),),});return;@@ -523,7 +607,7 @@ async function mockAttention(await route.fulfill({status: 200,contentType: "application/json",- body: JSON.stringify(detail),+ body: JSON.stringify(primaryDetail()),});return;}@@ -542,7 +626,9 @@ async function mockAttention(? [suppressedAttentionItem]: filter === "resolved"? [resolvedAttentionItem]- : [openAttentionItem, uncertainAttentionItem];+ : primaryState === "suppressed"+ ? [uncertainAttentionItem]+ : [primaryItem(), uncertainAttentionItem];await route.fulfill({status: 200,contentType: "application/json",@@ -561,7 +647,7 @@ async function mockAttention(coverageState: "current",evaluatedAt,}- : activeSummary,+ : currentSummary(),meta: {page: 1,limit: 50,@@ -578,6 +664,27 @@ async function mockAttention(};}+test("starts from the normal monitor shell and reaches the canonical attention queue", async ({+ page,+}) => {+ await mockAttention(page, "active");+ await page.goto("/", { waitUntil: "domcontentloaded" });++ await page+ .getByRole("tab", { name: /Patrol/ })+ .or(page.getByRole("button", { name: /Patrol/ }))+ .or(page.getByRole("link", { name: /Patrol/ }))+ .click();++ await expect(page).toHaveURL(/\/patrol/);+ await expect(+ page.getByRole("region", { name: "Needs attention" }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Open CPU pressure on pve-main" }),+ ).toBeVisible();+});+test("makes active operational work primary and preserves the evidence boundary", async ({page,}) => {@@ -659,6 +766,40 @@ test("makes active operational work primary and preserves the evidence boundary"new RegExp(`attention=${encodeURIComponent(attentionID)}`),);+ await detailPanel.getByRole("button", { name: "Acknowledge" }).click();+ await expect(+ detailPanel.getByText(/Acknowledged by operator/i),+ ).toBeVisible();+ await expect(+ detailPanel.getByRole("button", { name: "Return to open" }),+ ).toBeVisible();++ await detailPanel+ .getByRole("button", { name: "Suppress temporarily" })+ .click();+ await detailPanel+ .getByRole("textbox", {+ name: "Why is this safe to hide from active attention?",+ })+ .fill("Planned host maintenance");+ await detailPanel+ .getByRole("combobox", {+ name: "Return it to active attention after",+ })+ .selectOption(String(60 * 60 * 1000));+ await detailPanel+ .getByRole("button", { name: "Suppress temporarily" })+ .click();+ await expect(+ detailPanel.getByText(/Suppressed by operator: Planned host maintenance/i),+ ).toBeVisible();+ await detailPanel+ .getByRole("button", { name: "Return to active attention" })+ .click();+ await expect(+ detailPanel.getByRole("button", { name: "Acknowledge" }),+ ).toBeVisible();+await detailPanel.getByRole("button", { name: "Close attention detail" }).click();