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
feat(ai): surface deterministic capacity forecasts as first-class finding signals
rcourtmand45715d083af
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 75a0b25d7e..889c5c8766 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -55,6 +55,19 @@ generic usage/capacity finding for the same normalized storage identity are oneoperator issue, while distinct backup, health, and pool-vs-device findingsremain separate. This consolidation belongs in the finding store, not thefrontend row renderer.+Capacity forecasts (days-to-full, current utilization, daily change rate) are+computed deterministically by linear regression over a resource's utilization+history and must persist as structured data on the Finding+(`capacity_forecast`), stamped by the finding store after a successful Patrol+analysis via `StampCapacityForecasts`. That structured field is the canonical+operator urgency source for capacity-relevant findings; the model-authored+description must never be treated as the urgency signal when a deterministic+forecast is present. A forecast requires the resource's utilization to be+ingested as a time-series in metrics history; resources without recorded+history cannot produce a forecast and must report its absence honestly rather+than fabricate one, and stable-high (>=80%) pools with no clear fill trend must+carry the deterministic "no fill trend" reading so the model's speculation+cannot override the verified trend.The public Pulse Intelligence overview is a projection of those runtimecontracts, not a second Assistant tool inventory. It must point readers at thediff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex b44bf12a38..9244b03d69 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -837,6 +837,13 @@ payload shape change when the portal presents compact client rows.`/api/ai/patrol/runs` records may expose bounded `source` provenance so demoevidence can be separated from live runtime assessment state withoutchanging the stable run payload shape.+ The Patrol findings payload carries `capacity_forecast` as a structured+ deterministic field (`current_pct`, `daily_change`, `days_to_full`) on+ capacity-relevant findings whose resource has enough utilization history to+ compute a trend. The frontend client must mirror it verbatim so the+ deterministic urgency reading reaches the surface unchanged; it must not be+ synthesized, inferred, or overridden client-side, and a missing forecast+ must mean "no recorded history to compute one," not a default urgency.The Patrol status payload's `trigger_status` object is the canonicaltransport for alert/anomaly trigger queue and mode facts. Patrol summary UImay present that state as factual trigger-mode context, but it must not inferdiff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 71c43d0bc5..2972479b34 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -735,9 +735,18 @@ clear`, `Found N new issues`, `Fixed N issues`, `N issues still open`, oroperators see "what worked last time" inline without having toopen Assistant. The summary lives on the finding shell(`UnifiedFinding`/`Finding`), not on the per-record investigation- presentation; the Patrol-owned investigation-context model must not- absorb it into impact, verification, or rollback (those represent- the current investigation, not history).+ presentation; the Patrol-owned investigation-context model must not+ absorb it into impact, verification, or rollback (those represent+ the current investigation, not history).+ `FindingsPanel.tsx` also renders the deterministic `capacityForecast`+ urgency line on the expanded finding card, projected through+ `presentCapacityForecast` (`patrolCapacityForecastPresentation`). That line+ is the operator's primary capacity-urgency signal: it states direction+ (Filling up / Stable / Declining), days-to-full, daily change rate, and+ current utilization from the backend-computed forecast, and it must take+ precedence over the model-authored description whenever a forecast is+ present. The panel must not invent, smooth, or client-side infer a forecast;+ a missing forecast simply means no urgency line renders.The Patrol page must not render a standalone Trust strip above theFindings/Runs tab bar or a parallel header trust line. The primaryPatrol assessment readout is the default owner for current operatordiff --git a/frontend-modern/src/api/__tests__/patrol.test.ts b/frontend-modern/src/api/__tests__/patrol.test.tsindex 1ad65438c0..4f00447726 100644--- a/frontend-modern/src/api/__tests__/patrol.test.ts+++ b/frontend-modern/src/api/__tests__/patrol.test.ts@@ -432,6 +432,45 @@ describe('patrol api', () => {expect(findings[0]?.dismissed_reason).toBe('will_fix_later');expect(findings[0]?.remind_at).toBe('2026-05-16T10:00:00Z');});++ it('round-trips the deterministic capacity_forecast block on patrol findings', async () => {+ // capacity_forecast is a backend-computed fact (days-to-full, current %,+ // daily change) that the surface renders as the operator's primary urgency+ // signal instead of the model-authored prose. The TS client must mirror it+ // verbatim so the deterministic reading reaches the panel unchanged.+ const filling: PatrolFinding = {+ id: 'finding-forecast',+ severity: 'warning',+ category: 'capacity',+ resource_id: 'storage-tower',+ resource_name: 'Tower Array',+ resource_type: 'storage',+ title: 'Storage pool Tower Array at 86% usage',+ description: 'Pool is filling.',+ detected_at: '2026-05-09T10:00:00Z',+ last_seen_at: '2026-05-09T10:05:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 0,+ capacity_forecast: {+ metric: 'storage',+ current_pct: 86,+ daily_change: 1.4,+ days_to_full: 10,+ },+ };+ apiFetchJSONMock.mockResolvedValueOnce([filling] as any);++ const findings = await getPatrolFindings();+ expect(findings).toHaveLength(1);+ expect(findings[0]?.capacity_forecast).toEqual({+ metric: 'storage',+ current_pct: 86,+ daily_change: 1.4,+ days_to_full: 10,+ });+ });});describe('triggerPatrolRun scope body', () => {diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.tsindex 44217e5b6a..28f7d12616 100644--- a/frontend-modern/src/api/patrol.ts+++ b/frontend-modern/src/api/patrol.ts@@ -65,6 +65,24 @@ export interface Finding {}>;regression_count?: number;last_regression_at?: string;+ // Deterministic capacity forecast (trend/eta) computed by Patrol+ // independently of the model-authored prose body. Surfaced as a first-class+ // urgency signal. Present only for capacity-relevant findings whose resource+ // has enough utilization history to compute a trend.+ capacity_forecast?: CapacityForecast;+}++/**+ * CapacityForecast is a deterministic, backend-computed capacity trend for a+ * finding's resource. Unlike the model-authored prose (description/impact/+ * recommendation), this is a computed fact and is the operator's primary+ * urgency signal: "fills in ~N days at +X%/day".+ */+export interface CapacityForecast {+ metric?: string; // e.g. 'storage', 'disk'+ current_pct: number; // current utilization %+ daily_change: number; // avg % change per day (negative = declining)+ days_to_full: number; // days to 100% at current rate; -1 if stable/declining}export type InvestigationStatus =diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsxindex 6937fb7767..0c6dcd555c 100644--- a/frontend-modern/src/components/AI/FindingsPanel.tsx+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx@@ -42,6 +42,7 @@ import { getSemanticTonePresentation } from '@/utils/semanticTonePresentation';import { formatIdentifierLabel } from '@/utils/textPresentation';import type { IntelligenceHealthScore } from '@/types/aiIntelligence';import { getPatrolFindingsEmptyState } from '@/utils/patrolEmptyStatePresentation';+import { presentCapacityForecast } from '@/utils/patrolCapacityForecastPresentation';import type { UpgradeDestination } from '@/utils/upgradeNavigation';import CheckCircleIcon from 'lucide-solid/icons/check-circle';import AlertCircleIcon from 'lucide-solid/icons/alert-circle';@@ -98,6 +99,19 @@ export type FindingsPanelFilter =| 'attention'| 'overdue';+function capacityForecastToneClass(+ tone: 'critical' | 'warning' | 'info',+): string {+ switch (tone) {+ case 'critical':+ return 'text-red-700 dark:text-red-300';+ case 'warning':+ return 'text-amber-700 dark:text-amber-300';+ default:+ return 'text-sky-700 dark:text-sky-300';+ }+}+interface FindingsPanelProps {resourceId?: string;showResolved?: boolean;@@ -1296,6 +1310,20 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {</div></Show><p class="text-sm text-muted">{finding.description}</p>+ <Show when={presentCapacityForecast(finding.capacityForecast)}>+ {(fc) => (+ <p+ class={`mt-2 text-sm ${capacityForecastToneClass(fc().tone)}`}+ title="Patrol computed this trend from recent utilization history."+ >+ <span class="font-medium">{fc().direction}</span>+ <span class="text-muted font-normal">+ {' '}+ · {fc().detail} · {fc().current}+ </span>+ </p>+ )}+ </Show><Show when={finding.impact}><p class="text-sm text-base-content mt-2"><span class="font-medium">Impact:</span> {finding.impact}diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.tsindex 250065ff16..033391d709 100644--- a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts@@ -70,6 +70,18 @@ describe('FindingsPanel assistant handoff', () => {expect(findingsPanelSource).toContain('<LoadingSpinner size="md" />');});+ it('renders the deterministic capacity-forecast urgency line in expanded finding detail', () => {+ // capacity_forecast is a backend-computed fact, not model prose. The panel+ // must project it through presentCapacityForecast so the operator sees a+ // deterministic "Filling up / Stable · days-to-full · % used" line rather+ // than relying on the model-authored description for urgency.+ expect(findingsPanelSource).toContain(+ "from '@/utils/patrolCapacityForecastPresentation'",+ );+ expect(findingsPanelSource).toContain('presentCapacityForecast(finding.capacityForecast)');+ expect(findingsPanelSource).toContain('capacityForecastToneClass');+ });+it('renders the plan-locked at-need Pulse Pro handoff in the finding primary-action area', () => {expect(findingsPanelSource).toContain('patrolProHandoff?:');expect(findingsPanelSource).toContain('{proHandoff!.detail}');diff --git a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts b/frontend-modern/src/stores/__tests__/aiIntelligence.test.tsindex e0e4e27e13..c6fc914d69 100644--- a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts+++ b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts@@ -360,6 +360,51 @@ describe('aiIntelligenceStore', () => {});});+ it('promotes capacity_forecast on patrol findings to camelCase capacityForecast', async () => {+ // capacity_forecast is the deterministic urgency signal (days-to-full,+ // current %, daily change). The store-level UnifiedFinding is what the+ // findings panel reads; if the normalizer drops capacity_forecast, the+ // deterministic urgency line can never render and the operator only sees+ // the model's prose. Pin the wiring through both the patrol-direct and+ // unified-finding paths.+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([+ {+ id: 'patrol-finding-forecast',+ severity: 'warning',+ category: 'capacity',+ resource_id: 'storage-tower',+ resource_name: 'Tower Array',+ resource_type: 'storage',+ title: 'Storage pool Tower Array at 86% usage',+ description: 'Pool is filling.',+ detected_at: '2026-05-09T10:00:00Z',+ last_seen_at: '2026-05-09T10:05:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 0,+ capacity_forecast: {+ metric: 'storage',+ current_pct: 86,+ daily_change: 1.4,+ days_to_full: 10,+ },+ },+ ]);++ await aiIntelligenceStore.loadPatrolFindings();+ expect(aiIntelligenceStore.patrolFindings).toHaveLength(1);+ expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({+ id: 'patrol-finding-forecast',+ capacityForecast: {+ metric: 'storage',+ current_pct: 86,+ daily_change: 1.4,+ days_to_full: 10,+ },+ });+ });+it('loads the canonical intelligence summary', async () => {vi.mocked(AIAPI.getIntelligenceSummary).mockResolvedValueOnce({timestamp: '2026-03-01T00:00:00Z',diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.tsindex 71c1211b05..033f1d4bfd 100644--- a/frontend-modern/src/stores/aiIntelligence.ts+++ b/frontend-modern/src/stores/aiIntelligence.ts@@ -18,6 +18,7 @@ import {setFindingNote,getPatrolFindings,type Finding as PatrolFinding,+ type CapacityForecast,} from '@/api/patrol';import type {RemediationPlan,@@ -197,6 +198,10 @@ export interface UnifiedFinding {timesRaised?: number;regressionCount?: number;lastRegressionAt?: string;+ // Deterministic capacity forecast (trend/eta), computed by Patrol+ // independently of the model prose. Surfaced as a first-class urgency+ // signal on capacity-relevant findings.+ capacityForecast?: CapacityForecast;}const [unifiedFindings, setUnifiedFindings] = createSignal<UnifiedFinding[]>([]);@@ -299,6 +304,7 @@ function normalizePatrolFindingRecord(item: PatrolFinding, now: number): UnifiedtimesRaised: item.times_raised || 0,regressionCount: item.regression_count || 0,lastRegressionAt: item.last_regression_at || undefined,+ capacityForecast: item.capacity_forecast,};}diff --git a/frontend-modern/src/utils/__tests__/patrolCapacityForecastPresentation.test.ts b/frontend-modern/src/utils/__tests__/patrolCapacityForecastPresentation.test.tsnew file mode 100644index 0000000000..3059d3bae0--- /dev/null+++ b/frontend-modern/src/utils/__tests__/patrolCapacityForecastPresentation.test.ts@@ -0,0 +1,43 @@+import { describe, it, expect } from 'vitest';+import { presentCapacityForecast } from '../patrolCapacityForecastPresentation';++describe('presentCapacityForecast', () => {+ it('returns null when no forecast is present', () => {+ expect(presentCapacityForecast(undefined)).toBeNull();+ expect(presentCapacityForecast(null)).toBeNull();+ });++ it('renders a critical urgency line when filling within days', () => {+ const out = presentCapacityForecast({ current_pct: 92, daily_change: 3, days_to_full: 3 });+ expect(out).not.toBeNull();+ expect(out!.direction).toBe('Filling up');+ expect(out!.detail).toBe('3 days to full at +3.0%/day');+ expect(out!.current).toBe('92% used');+ expect(out!.tone).toBe('critical');+ });++ it('renders a warning urgency line when filling within a month', () => {+ const out = presentCapacityForecast({ current_pct: 86, daily_change: 1.2, days_to_full: 11 });+ expect(out!.tone).toBe('warning');+ expect(out!.detail).toBe('~1 week to full at +1.2%/day');+ });++ it('renders info tone when fill is far out', () => {+ const out = presentCapacityForecast({ current_pct: 55, daily_change: 0.2, days_to_full: 200 });+ expect(out!.tone).toBe('info');+ expect(out!.direction).toBe('Filling up');+ });++ it('renders declining when usage is falling', () => {+ const out = presentCapacityForecast({ current_pct: 40, daily_change: -0.5, days_to_full: -1 });+ expect(out!.direction).toBe('Declining');+ expect(out!.tone).toBe('info');+ expect(out!.detail).toContain('falling');+ });++ it('renders stable when no meaningful trend', () => {+ const out = presentCapacityForecast({ current_pct: 60, daily_change: 0, days_to_full: -1 });+ expect(out!.direction).toBe('Stable');+ expect(out!.current).toBe('60% used');+ });+});diff --git a/frontend-modern/src/utils/patrolCapacityForecastPresentation.ts b/frontend-modern/src/utils/patrolCapacityForecastPresentation.tsnew file mode 100644index 0000000000..d7214179b9--- /dev/null+++ b/frontend-modern/src/utils/patrolCapacityForecastPresentation.ts@@ -0,0 +1,75 @@+import type { CapacityForecast } from '@/api/patrol';++export type CapacityForecastTone = 'critical' | 'warning' | 'info';++export interface CapacityForecastPresentation {+ /** Short scannable direction: "Filling up", "Stable", "Declining". */+ direction: string;+ /** Urgency detail, e.g. "~5 days to full at +1.2%/day". */+ detail: string;+ /** Current utilization readout, e.g. "86% used". */+ current: string;+ tone: CapacityForecastTone;+}++function formatDays(days: number): string {+ if (days <= 0) return 'now';+ if (days === 1) return '1 day';+ if (days < 7) return `${days} days`;+ if (days < 14) return '~1 week';+ if (days < 30) return `~${Math.round(days / 7)} weeks`;+ const months = Math.round(days / 30);+ if (months <= 1) return '~1 month';+ if (months < 12) return `~${months} months`;+ return 'over a year';+}++function formatRate(changePerDay: number): string {+ const sign = changePerDay > 0 ? '+' : '';+ return `${sign}${changePerDay.toFixed(changePerDay >= 1 || changePerDay <= -1 ? 1 : 2)}%/day`;+}++/**+ * Turn a deterministic capacity forecast into a plain operator-facing urgency+ * line. Returns null when no forecast applies so callers can skip rendering.+ *+ * This is the canonical projection for the capacity-forecast signal: the+ * backend owns the computation (linear regression over utilization samples),+ * this helper owns the operator vocabulary. Kept free of component concerns so+ * it can be exercised directly in tests and reused across surfaces.+ */+export function presentCapacityForecast(+ fc?: CapacityForecast | null,+): CapacityForecastPresentation | null {+ if (!fc) return null;++ const days = fc.days_to_full;+ const change = fc.daily_change ?? 0;+ const current = `${Math.round(fc.current_pct)}% used`;++ if (days > 0) {+ const tone: CapacityForecastTone = days <= 7 ? 'critical' : days <= 30 ? 'warning' : 'info';+ return {+ direction: 'Filling up',+ detail: `${formatDays(days)} to full at ${formatRate(change)}`,+ current,+ tone,+ };+ }++ if (change < -0.1) {+ return {+ direction: 'Declining',+ detail: `usage falling ${formatRate(Math.abs(change))}`,+ current,+ tone: 'info',+ };+ }++ return {+ direction: 'Stable',+ detail: 'no clear fill trend',+ current,+ tone: 'info',+ };+}diff --git a/internal/ai/findings.go b/internal/ai/findings.goindex 89b2f72f39..0e3580eae4 100644--- a/internal/ai/findings.go+++ b/internal/ai/findings.go@@ -156,6 +156,21 @@ const maxFindingLifecycleEvents = 50// (marshal-mirror pattern); merging them would change the public literal API.// TestFindingJSONMirrorStaysInSync enforces the mirror.//+// CapacityForecast is a deterministic, backend-computed capacity trend+// attached to a finding when its resource is trending toward exhaustion.+// Unlike the model-authored prose body (Description/Impact/Recommendation),+// this is a computed fact (linear regression over recent utilization+// samples) and gives the operator a first-class urgency signal independent+// of whether the model chose to mention it: "fills in ~N days at +X%/day".+// Populated by Patrol at run time from the deterministic forecast layer and+// joined onto the finding by resource ID; nil when no trend applies.+type CapacityForecast struct {+ Metric string `json:"metric,omitempty"` // e.g. "storage", "disk"+ CurrentPct float64 `json:"current_pct"` // current utilization %+ DailyChange float64 `json:"daily_change"` // avg % change per day (negative = declining)+ DaysToFull int `json:"days_to_full"` // days to 100% at current rate; -1 if stable/declining+}+//nolint:dupl // deliberate marshal-mirror twin of findingJSONtype Finding struct {ID string `json:"id"`@@ -219,6 +234,11 @@ type Finding struct {Lifecycle []FindingLifecycleEvent `json:"lifecycle,omitempty"` // Bounded, append-only lifecycle logRegressionCount int `json:"regression_count,omitempty"` // Times the issue reappeared after resolutionLastRegressionAt *time.Time `json:"last_regression_at,omitempty"` // Timestamp of most recent regression+ // CapacityForecast is the deterministic capacity trend for this finding's+ // resource (when applicable). Computed by Patrol independently of the+ // model prose and surfaced as a first-class urgency signal. Nil when no+ // trend applies or the finding predates forecast stamping.+ CapacityForecast *CapacityForecast `json:"capacity_forecast,omitempty"`}// findingJSON is the marshal mirror of Finding: identical fields, but@@ -268,6 +288,7 @@ type findingJSON struct {Lifecycle []FindingLifecycleEvent `json:"lifecycle,omitempty"`RegressionCount int `json:"regression_count,omitempty"`LastRegressionAt *time.Time `json:"last_regression_at,omitempty"`+ CapacityForecast *CapacityForecast `json:"capacity_forecast,omitempty"`}func (f Finding) MarshalJSON() ([]byte, error) {@@ -313,6 +334,7 @@ func (f Finding) MarshalJSON() ([]byte, error) {Lifecycle: f.Lifecycle,RegressionCount: f.RegressionCount,LastRegressionAt: f.LastRegressionAt,+ CapacityForecast: f.CapacityForecast,})}@@ -363,6 +385,7 @@ func (f *Finding) UnmarshalJSON(data []byte) error {Lifecycle: payload.Lifecycle,RegressionCount: payload.RegressionCount,LastRegressionAt: payload.LastRegressionAt,+ CapacityForecast: payload.CapacityForecast,}return nil}@@ -2240,6 +2263,62 @@ func (s *FindingsStore) SetUserNote(id, note string) bool {return true}+// StampCapacityForecasts attaches the given deterministic capacity forecasts+// to matching active findings, joined by resource ID. A forecast applies to a+// finding when the finding concerns capacity on that resource (capacity+// category, or a storage/disk resource). The forecast is recomputed every run,+// so this is per-run data maintenance, not operator history: no lifecycle+// event is recorded and findings already holding an equal forecast are skipped+// to avoid spurious saves. Returns the number of findings updated.+func (s *FindingsStore) StampCapacityForecasts(byResource map[string]CapacityForecast) int {+ if s == nil || len(byResource) == 0 {+ return 0+ }+ s.mu.Lock()+ changed := 0+ for _, f := range s.findings {+ if f == nil || !f.IsActive() {+ continue+ }+ fc, ok := byResource[f.ResourceID]+ if !ok {+ continue+ }+ if !capacityForecastAppliesTo(f) {+ continue+ }+ if f.CapacityForecast != nil && *f.CapacityForecast == fc {+ continue+ }+ fcCopy := fc+ f.CapacityForecast = &fcCopy+ changed+++ }+ s.mu.Unlock()+ if changed > 0 {+ s.scheduleSave()+ }+ return changed+}++// capacityForecastAppliesTo reports whether a deterministic capacity forecast+// is meaningful for this finding: a capacity finding, or any finding on a+// storage/disk resource where utilization trend is directly relevant.+func capacityForecastAppliesTo(f *Finding) bool {+ if f == nil {+ return false+ }+ if f.Category == FindingCategoryCapacity {+ return true+ }+ switch f.ResourceType {+ case "storage", "physical_disk":+ return true+ default:+ return false+ }+}+// UpdateInvestigationOutcome updates the investigation outcome on a findingfunc (s *FindingsStore) UpdateInvestigationOutcome(id, outcome string) bool {s.mu.Lock()diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex 026e2d959c..34b48e7252 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -40,6 +40,12 @@ type AIAnalysisResult struct {ReportedIDs []string // Finding IDs reported (created/re-reported) this runResolvedIDs []string // Finding IDs explicitly resolved by LLM this runSeededFindingIDs []string // Finding IDs that were presented in seed context+ // Forecasts are the deterministic capacity forecasts computed this run,+ // stamped onto matching findings so the surface shows a first-class+ // urgency signal instead of relying on model prose. Carried as the+ // in-package seed type so the resource ID is available for the join; the+ // persisted CapacityForecast (without resource ID) is built at stamp time.+ Forecasts []seedForecast}const (@@ -642,6 +648,7 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntiReportedIDs: adapter.getReportedFindingIDs(),ResolvedIDs: adapter.getResolvedIDs(),SeededFindingIDs: seededFindingIDs,+ Forecasts: triageResult.Intel.forecasts,}, nil}@@ -1533,7 +1540,14 @@ func (p *PatrolService) seedPrecomputeIntelligenceState(snap patrolRuntimeState,}}- // Capacity forecasts+ // Capacity forecasts. A forecast is kept when the resource is trending+ // toward exhaustion (DaysToFull > 0) OR when utilization is already+ // elevated (>= 80%) even if flat/declining — in the high-but-stable case+ // the deterministic "no fill trend" reading is still more trustworthy than+ // leaving the operator with the model's speculation, and it stamps the+ // finding with a verified capacity signal. Low, stable utilization is+ // ignored so calm resources do not add noise.+ const elevatedUsagePct = 80.0if mh != nil {addForecast := func(resourceID, resourceName, metricName string, points []MetricPoint, currentValue float64) {if len(points) < 5 {@@ -1544,17 +1558,23 @@ func (p *PatrolService) seedPrecomputeIntelligenceState(snap patrolRuntimeState,samples[i] = pt.Value}trend := baseline.CalculateTrend(samples, currentValue)- if trend != nil && trend.DaysToFull > 0 && trend.DaysToFull <= 30 {- intel.forecasts = append(intel.forecasts, seedForecast{- name: resourceName,- resourceID: resourceID,- metric: metricName,- severity: trend.Severity,- daysToFull: trend.DaysToFull,- dailyChange: trend.DailyChange,- current: currentValue,- })+ if trend == nil {+ return+ }+ filling := trend.DaysToFull > 0 && trend.DaysToFull <= 30+ elevated := currentValue >= elevatedUsagePct+ if !filling && !elevated {+ return}+ intel.forecasts = append(intel.forecasts, seedForecast{+ name: resourceName,+ resourceID: resourceID,+ metric: metricName,+ severity: trend.Severity,+ daysToFull: trend.DaysToFull,+ dailyChange: trend.DailyChange,+ current: currentValue,+ })}for _, n := range nodeSources {if pts := mh.GetNodeMetrics(n.id, "memory", 48*time.Hour); len(pts) >= 5 {@@ -1616,10 +1636,14 @@ func (p *PatrolService) seedPrecomputeIntelligenceState(snap patrolRuntimeState,}}- // Determine if infrastructure is quiet+ // Determine if infrastructure is quiet. Only forecasts that are actually+ // filling (daysToFull > 0) count as a warning; stable/declining forecasts+ // carry an elevated-usage readout but are not themselves a fill warning, so+ // they must not mark the whole estate non-quiet. (daysToFull is -1 for+ // stable/declining trends, which would otherwise satisfy a bare <= 30.)hasWarningForecasts := falsefor _, f := range intel.forecasts {- if f.daysToFull <= 30 {+ if f.daysToFull > 0 && f.daysToFull <= 30 {hasWarningForecasts = truebreak}@@ -3232,8 +3256,13 @@ func (p *PatrolService) seedIntelligenceContext(intel seedIntelligence, now timeif len(intel.forecasts) > 0 {sb.WriteString("# Capacity Forecasts\n")for _, f := range intel.forecasts {- sb.WriteString(fmt.Sprintf("- [%s] %s %s: full in ~%d days (current: %.0f%%, growing +%.1f%%/day)\n",- f.severity, f.name, f.metric, f.daysToFull, f.current, f.dailyChange))+ if f.daysToFull > 0 {+ sb.WriteString(fmt.Sprintf("- [%s] %s %s: full in ~%d days (current: %.0f%%, growing +%.1f%%/day)\n",+ f.severity, f.name, f.metric, f.daysToFull, f.current, f.dailyChange))+ } else {+ sb.WriteString(fmt.Sprintf("- [%s] %s %s: %.0f%% used, no fill trend (%+.1f%%/day)\n",+ f.severity, f.name, f.metric, f.current, f.dailyChange))+ }}sb.WriteString("\n")}diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.goindex 95d9eeaf4e..dc20d5a972 100644--- a/internal/ai/patrol_findings.go+++ b/internal/ai/patrol_findings.go@@ -90,6 +90,70 @@ func (p *PatrolService) recordFinding(f *Finding) bool {return isNew}+// stampCapacityForecasts joins the deterministic capacity forecasts computed+// during a run onto matching active findings. This makes the trend/eta a+// first-class structured signal on the finding instead of relying on the+// model to optionally mention it in prose. When several metrics forecast the+// same resource, the most urgent (soonest to fill) wins. No-op without+// forecasts or a findings store.+func (p *PatrolService) stampCapacityForecasts(forecasts []seedForecast) {+ resources := 0+ for _, sf := range forecasts {+ if strings.TrimSpace(sf.resourceID) != "" {+ resources+++ }+ }+ log.Info().+ Int("forecasts", len(forecasts)).+ Int("resources", resources).+ Msg("AI Patrol: Capacity forecasts available for stamping")++ if p == nil || p.findings == nil || len(forecasts) == 0 {+ return+ }+ best := make(map[string]CapacityForecast, len(forecasts))+ for _, sf := range forecasts {+ rid := strings.TrimSpace(sf.resourceID)+ if rid == "" {+ continue+ }+ want := CapacityForecast{+ Metric: sf.metric,+ CurrentPct: sf.current,+ DailyChange: sf.dailyChange,+ DaysToFull: sf.daysToFull,+ }+ if cur, ok := best[rid]; !ok || forecastMoreUrgent(want, cur) {+ best[rid] = want+ }+ }+ if len(best) == 0 {+ return+ }+ changed := p.findings.StampCapacityForecasts(best)+ log.Info().+ Int("forecasts", len(forecasts)).+ Int("resources", len(best)).+ Int("stamped", changed).+ Msg("AI Patrol: Stamped capacity forecasts onto findings")+}++// forecastMoreUrgent reports whether forecast a is more urgent than b: a+// filling (positive days-to-full) estimate beats a stable/declining one, and+// among filling estimates the soonest wins. Among non-filling estimates the+// faster-rising one wins as a tiebreaker.+func forecastMoreUrgent(a, b CapacityForecast) bool {+ aFilling := a.DaysToFull > 0+ bFilling := b.DaysToFull > 0+ if aFilling != bFilling {+ return aFilling+ }+ if aFilling {+ return a.DaysToFull < b.DaysToFull+ }+ return a.DailyChange > b.DailyChange+}+// RejectManualActionForRuntimeFinding fails closed when a manual lifecycle action targets// a Patrol-owned runtime finding such as the synthetic ai-service provider/runtime error.func (p *PatrolService) RejectManualActionForRuntimeFinding(findingID string, action string) error {diff --git a/internal/ai/patrol_findings_forecast_test.go b/internal/ai/patrol_findings_forecast_test.gonew file mode 100644index 0000000000..a4836583bf--- /dev/null+++ b/internal/ai/patrol_findings_forecast_test.go@@ -0,0 +1,177 @@+package ai++import (+ "testing"+ "time"+)++func TestStampCapacityForecasts_AttachesToCapacityFindingByResourceID(t *testing.T) {+ store := NewFindingsStore()+ f := &Finding{+ ID: "f1",+ Key: "disk-usage",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ ResourceID: "storage-tower-array",+ ResourceName: "Tower Array",+ ResourceType: "storage",+ Title: "Tower Array at 86%",+ Description: "Storage pool near capacity.",+ DetectedAt: time.Now(),+ LastSeenAt: time.Now(),+ }+ if !store.Add(f) {+ t.Fatal("expected Add to create the finding")+ }++ forecasts := []seedForecast{+ {resourceID: "storage-tower-array", metric: "storage", current: 86.0, dailyChange: 1.2, daysToFull: 11},+ {resourceID: "unrelated", metric: "storage", current: 50.0, dailyChange: 0.1, daysToFull: 500},+ }+ changed := store.StampCapacityForecasts(mustForecastMap(forecasts))+ if changed != 1 {+ t.Fatalf("changed = %d, want 1", changed)+ }++ stored := store.Get("f1")+ if stored.CapacityForecast == nil {+ t.Fatal("expected CapacityForecast to be set")+ }+ if stored.CapacityForecast.DaysToFull != 11 {+ t.Fatalf("DaysToFull = %d, want 11", stored.CapacityForecast.DaysToFull)+ }+ if stored.CapacityForecast.CurrentPct != 86.0 {+ t.Fatalf("CurrentPct = %v, want 86", stored.CapacityForecast.CurrentPct)+ }+}++func TestStampCapacityForecasts_DoesNotAttachToNonCapacityUnrelatedResource(t *testing.T) {+ store := NewFindingsStore()+ // A reliability finding on a node (neither capacity category nor storage/disk+ // resource type) must not receive a storage utilization forecast.+ f := &Finding{+ ID: "f2",+ Key: "node-reboot",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryReliability,+ ResourceID: "node-pve1",+ ResourceName: "pve1",+ ResourceType: "node",+ Title: "Node rebooted unexpectedly",+ Description: "Unexpected reboot.",+ DetectedAt: time.Now(),+ LastSeenAt: time.Now(),+ }+ store.Add(f)++ changed := store.StampCapacityForecasts(map[string]CapacityForecast{+ "node-pve1": {Metric: "storage", CurrentPct: 86, DailyChange: 1.2, DaysToFull: 11},+ })+ if changed != 0 {+ t.Fatalf("changed = %d, want 0 (non-capacity, non-storage finding)", changed)+ }+ if store.Get("f2").CapacityForecast != nil {+ t.Fatal("CapacityForecast must remain nil for a non-capacity node finding")+ }+}++func TestStampCapacityForecasts_StorageResourceStampsRegardlessOfCategory(t *testing.T) {+ store := NewFindingsStore()+ // A storage resource finding categorized as "general" still concerns the+ // underlying utilization, so the forecast applies.+ f := &Finding{+ ID: "f3",+ Key: "pool-noise",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryGeneral,+ ResourceID: "storage-zfs-1",+ ResourceName: "zfs-1",+ ResourceType: "storage",+ Title: "Pool utilization high",+ Description: "High utilization.",+ DetectedAt: time.Now(),+ LastSeenAt: time.Now(),+ }+ store.Add(f)++ changed := store.StampCapacityForecasts(map[string]CapacityForecast{+ "storage-zfs-1": {Metric: "storage", CurrentPct: 91, DailyChange: 0.5, DaysToFull: 18},+ })+ if changed != 1 {+ t.Fatalf("changed = %d, want 1", changed)+ }+ if store.Get("f3").CapacityForecast == nil {+ t.Fatal("expected forecast on storage finding regardless of category")+ }+}++func TestStampCapacityForecasts_SkipsResolvedAndUnchanged(t *testing.T) {+ store := NewFindingsStore()+ active := &Finding{+ ID: "a", Key: "k", Severity: FindingSeverityWarning, Category: FindingCategoryCapacity,+ ResourceID: "r-a", ResourceType: "storage", Title: "t", Description: "d",+ DetectedAt: time.Now(), LastSeenAt: time.Now(),+ }+ resolved := &Finding{+ ID: "z", Key: "k", Severity: FindingSeverityWarning, Category: FindingCategoryCapacity,+ ResourceID: "r-z", ResourceType: "storage", Title: "t", Description: "d",+ DetectedAt: time.Now(), LastSeenAt: time.Now(),+ }+ store.Add(active)+ store.Add(resolved)+ now := time.Now()+ resolved.ResolvedAt = &now+ // Mutate resolved under lock like the store mutators do.+ store.mu.Lock()+ if rf := store.findings["z"]; rf != nil {+ rf.ResolvedAt = &now+ }+ store.mu.Unlock()++ fc := map[string]CapacityForecast{+ "r-a": {CurrentPct: 80, DailyChange: 1, DaysToFull: 20},+ "r-z": {CurrentPct: 80, DailyChange: 1, DaysToFull: 20},+ }+ if changed := store.StampCapacityForecasts(fc); changed != 1 {+ t.Fatalf("first stamp changed = %d, want 1 (resolved skipped)", changed)+ }+ // Second identical stamp must be a no-op (equal forecast already present).+ if changed := store.StampCapacityForecasts(fc); changed != 0 {+ t.Fatalf("second stamp changed = %d, want 0 (idempotent)", changed)+ }+ if store.Get("z").CapacityForecast != nil {+ t.Fatal("resolved finding must not be stamped")+ }+}++func TestForecastMoreUrgent(t *testing.T) {+ filling := CapacityForecast{DaysToFull: 5, DailyChange: 2}+ fillingLater := CapacityForecast{DaysToFull: 30, DailyChange: 0.5}+ stable := CapacityForecast{DaysToFull: -1, DailyChange: 0}+ declining := CapacityForecast{DaysToFull: -1, DailyChange: -1}++ if !forecastMoreUrgent(filling, stable) {+ t.Error("filling should beat stable")+ }+ if !forecastMoreUrgent(filling, fillingLater) {+ t.Error("sooner fill should beat later fill")+ }+ if forecastMoreUrgent(stable, filling) {+ t.Error("stable should not beat filling")+ }+ if !forecastMoreUrgent(declining, stable) && !forecastMoreUrgent(stable, declining) {+ // both non-filling: tie-break by dailyChange sign; either ordering is+ // acceptable as long as it is deterministic. Just ensure no panic.+ }+}++func mustForecastMap(seeds []seedForecast) map[string]CapacityForecast {+ out := make(map[string]CapacityForecast, len(seeds))+ for _, sf := range seeds {+ want := CapacityForecast{Metric: sf.metric, CurrentPct: sf.current, DailyChange: sf.dailyChange, DaysToFull: sf.daysToFull}+ if cur, ok := out[sf.resourceID]; !ok || forecastMoreUrgent(want, cur) {+ out[sf.resourceID] = want+ }+ }+ return out+}diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.goindex b508b143be..530b4e7c5b 100644--- a/internal/ai/patrol_run.go+++ b/internal/ai/patrol_run.go@@ -483,6 +483,11 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger TriggerunStats.runtimeResolved = p.resolvePatrolRuntimeFailureFinding("full_patrol_success")}+ // Attach the deterministic capacity forecasts computed this run to+ // matching findings, so the surface shows a first-class urgency+ // signal (trend/eta) instead of relying on model prose.+ p.stampCapacityForecasts(aiResult.Forecasts)+// Findings are already recorded via patrol_report_finding tool calls.// Track stats from the collected findings.for _, f := range aiResult.Findings {diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex d65f58d2ed..f075f013c7 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -2916,7 +2916,7 @@ class SubsystemLookupTest(unittest.TestCase):{"heading": "## Shared Boundaries","path": "internal/api/access_control_handlers.go",- "line": 1080,+ "line": 1087,"heading_line": 136,}],