Carry host filesystem pressure through Patrol verdicts (#5784)

A host check could count one host while telling the model it had scanned
zero resources. On a host with a 99%-full secondary filesystem, the
completed check could say everything was healthy.

Patrol now reads current filesystem usage for each host in scope and
uses the same mount identity and threshold as host alerts. A measured
capacity observation survives a completed check that filed no finding.
The Inbox and run history show the mount and its usage.

Verification covers a healthy root filesystem, a 99%-full secondary
mount, existing and absent mount alerts, policy overrides, stale
readings and scoped checks. The Inbox and History were exercised at
desktop and phone widths.
This commit is contained in:
rcourtman
2026-12-03 10:19:19 +00:00
committed by GitHub
23 changed files with 516 additions and 31 deletions
@@ -25,6 +25,10 @@ that same result. Successful reads retain their content and execution provenance
## Purpose
### Host filesystem observations in Patrol checks
Patrol counts agent hosts in its scan briefing and reads their current per-mount usage from the unified host view. A mount at or above its configured threshold remains in the briefing even under a reduced model budget. The briefing identifies whether an active disk alert exists for that mount. Scoped filesystem checks stay with their subject. When no higher-priority finding or execution failure determines the result, the run records the measured usage as an observation. A fresh reading below the threshold can produce a healthy control.
### Full Patrol checks require resource coverage
A full check with no resources in its enabled inventory records an incomplete
@@ -15,6 +15,10 @@
## Purpose
### Host filesystem fill policy
Patrol reads the same filesystem identity and usage threshold as the host alert evaluator. The read honors per-mount and inherited settings, hardware defaults, and disabled monitoring. Reading the policy leaves the alert activation and recovery timers untouched.
A runtime-scoped container mute uses the raw Docker host ID. Saving it closes
open child detector occurrences with a policy reason and clears pending
confirmations, restart counts and image-update delays. New containers inherit
@@ -21,6 +21,10 @@
## Purpose
### Patrol run observations
A completed run can return `status: "observations"` and the measured filesystem usage in `findings_summary` with zero errors and zero findings. History preserves this status and summary on reload. The service reports `healthy: false` when this is the latest run.
### Patrol run coverage errors
The run history API returns `error_code: "no_resources"` for a full check
@@ -20,6 +20,10 @@
## Purpose
### Patrol observation presentation
The shared run presentation renders the recorded filesystem summary and a warning badge for the observations status. The empty Inbox uses that same measured summary.
### Stage 2 Cloud Companion Settings surface gated by featureReleases.json (1 December 2026)
`frontend-modern/src/utils/featureReleases.json` adds `cloudCompanion` at stage `build` (`guides: []`). `settingsNavigationModel.ts`, `settingsNavCatalog.ts`, `settingsNavVisibility.ts`, `settingsHeaderMeta.ts`, `settingsPanelRegistry*.ts`, `CloudCompanionPanel.tsx`, and the EN/DE/ES/FR message catalogs add `system-cloud-companion` behind `featureGate: 'cloudCompanion'`. Whenever `isFeatureAvailable('cloudCompanion')` is false (every release build), Settings navigation hides the item and route guards block `/settings/system-cloud-companion`. In development builds, unlicensed installs see a calm `FeatureGateSection` preview and licensed installs manage the off-site watchdog and browser remote access links. Covered by `CloudCompanionPanel.test.tsx`, `settingsArchitecture.test.ts`, `settingsLocalization.test.ts`, `npm run lint:feature-releases`, and Playwright verification across release-hidden and build-enabled modes.
@@ -15,6 +15,10 @@
## Purpose
### Filesystem observations without an open finding
The Inbox and check history show the measured host, mount, and usage when a run records a filesystem observation without filing a finding. The run detail retains the coverage count. An observation alone offers no provider-settings action.
### Patrol setup stays interactive while off and empty Inbox never claims unverified health (2 December 2026)
When Patrol requires setup, the setup card on the Inbox tab stays interactive even while Patrol is turned off, so operators can connect a provider and run the model check without implicitly enabling scheduled background scans. The independent operational Inbox remains available alongside setup for alert-backed items, and its empty state distinguishes Patrol readiness (`setup_required`, `off`, `pending_first_check`, `checking`, `failed`, `stale`, `uncovered`, and `ready`): it only shows the green calm reassurance after Patrol is ready and has completed a fresh healthy check with positive resource coverage. Protection posture metadata appears in the Inbox detail strip only when the item carries a protection posture.
@@ -0,0 +1,45 @@
{
"version": 1,
"base_sha": "277cba4e5612509d10a117adea726b73265b5e06",
"verified_at": "2026-12-03T09:50:10Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/api/patrol.ts",
"frontend-modern/src/components/patrol/RunHistoryEntry.tsx",
"frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx",
"frontend-modern/src/features/patrol/patrolControlPresentation.ts",
"frontend-modern/src/utils/patrolRunPresentation.ts"
],
"content_sha256": {
"frontend-modern/src/api/patrol.ts": "251874aa5255b65afe5af8822705eeadf36d2fda4c6f1bb8b6f0f67654bb966a",
"frontend-modern/src/components/patrol/RunHistoryEntry.tsx": "83f19de61833c18d20eb38514ab2862b339cff49ef0bdb54d80e597cdcf6de71",
"frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx": "e64e159d566723775f0e4591eec3dd8b027bccc6df1ace9028c42295a9e7598a",
"frontend-modern/src/features/patrol/patrolControlPresentation.ts": "ce500210a089f85d31ebc9ab919a5fab74369e17e10f03905789e0e9eeade06d",
"frontend-modern/src/utils/patrolRunPresentation.ts": "1bfc732bf34e61c2761cf022a659779bd6af18c3b537888f15a578c4325b6c65"
},
"routes": [
"/patrol",
"/patrol/activity"
],
"viewports": [
{
"width": 1440,
"height": 900
},
{
"width": 390,
"height": 844
}
],
"states": [
"Empty Inbox showing the last observed 99%-full mount on a single host",
"Empty Inbox for a healthy control and for a check that ended with a coverage or provider error",
"Existing alert in the Inbox and selected History details for an observation or a healthy check"
],
"interactions": [
"Inspected both Inbox layouts and the named mount after reload. Confirmed the observation heading stayed visible and the healthy control still showed its all-clear state",
"Used the keyboard to open an existing alert and read its detail, then navigated to Activity and History",
"Selected the observation with Enter, refreshed and reselected it, and inspected its coverage and mount summary. Confirmed the detail offered no model settings action",
"Inspected screenshots at both widths and checked for horizontal overflow"
]
}
+1 -1
View File
@@ -867,7 +867,7 @@ export const investigationOutcomeColors: Record<InvestigationOutcome, string> =
// Patrol Run History APIs
// =============================================================================
export type PatrolRunStatus = 'healthy' | 'issues_found' | 'critical' | 'error';
export type PatrolRunStatus = 'healthy' | 'issues_found' | 'observations' | 'critical' | 'error';
export type ToolCallVerificationStatus = 'unknown' | 'verified' | 'unverified' | 'failed';
@@ -304,6 +304,9 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
</span>
</div>
<div class="flex flex-wrap gap-1.5">
<Show when={run.status === 'observations'}>
<MetadataBadge tone="warning">High filesystem usage</MetadataBadge>
</Show>
<Show when={run.new_findings > 0}>
<MetadataBadge tone="warning">
<AlertTriangleIcon class="w-3 h-3" /> {run.new_findings} new
@@ -353,6 +353,7 @@ export function PatrolAttentionWorkbench(
return `${count} reviewed or suppressed ${count === 1 ? 'issue' : 'issues'}`;
}
if (count === 0) {
if (typeof props.patrolCheckState === 'object') return 'Latest check';
return isPassiveWatchOnly() ? 'No issues to review' : 'No decisions are waiting';
}
if (isPassiveWatchOnly()) {
@@ -814,3 +814,24 @@ describe('resolvePatrolCheckReadinessState and getPatrolInboxEmptyStatePresentat
});
});
});
it('keeps the last observed filesystem visible in an empty Inbox', () => {
const observation = '/fixture-disk on lab-host is 99% full.';
const latestRun = {
status: 'observations' as const,
resources_checked: 1,
error_count: 0,
findings_summary: observation,
completed_at: '2026-12-03T09:00:00Z',
};
const state = resolvePatrolCheckReadinessState({
latestRun,
patrolEnabled: true,
setupRequired: false,
nowMs: Date.parse('2026-12-03T09:01:00Z'),
});
expect(getPatrolInboxEmptyStatePresentation(state)).toMatchObject({
trustworthyCalm: false,
detail: observation,
});
});
@@ -678,6 +678,7 @@ export type PatrolCheckReadinessState =
| 'failed'
| 'stale'
| 'uncovered'
| { observation: string }
| 'ready';
export interface PatrolCheckReadinessInput {
@@ -686,7 +687,7 @@ export interface PatrolCheckReadinessInput {
checking?: boolean;
latestRun?:
| (Pick<PatrolRunRecord, 'error_count' | 'status'> &
Partial<Pick<PatrolRunRecord, 'completed_at' | 'resources_checked'>>)
Partial<Pick<PatrolRunRecord, 'completed_at' | 'resources_checked' | 'findings_summary'>>)
| null;
patrolStatus?:
| (Pick<PatrolStatus, 'running'> &
@@ -744,12 +745,21 @@ export function resolvePatrolCheckReadinessState(
const checked = input.latestRun
? input.latestRun.resources_checked
: input.patrolStatus?.resources_checked;
if (input.latestRun?.status === 'observations') {
return {
observation:
input.latestRun.findings_summary || 'The last check observed high filesystem usage.',
};
}
return normalizeCount(checked) > 0 ? 'ready' : 'uncovered';
}
export function getPatrolInboxEmptyStatePresentation(
state: PatrolCheckReadinessState,
): PatrolInboxEmptyStatePresentation {
if (typeof state === 'object') {
return { trustworthyCalm: false, heading: 'High filesystem usage', detail: state.observation };
}
switch (state) {
case 'setup_required':
return {
@@ -439,3 +439,22 @@ describe('patrolRunPresentation', () => {
);
});
});
it('shows measured filesystem usage even when the run filed no finding', () => {
const run = {
status: 'observations' as const,
findings_summary: '/fixture-disk on lab-host is 99% full.',
duration_ms: 42_000,
resources_checked: 1,
finding_ids: [],
error_count: 0,
new_findings: 0,
existing_findings: 0,
resolved_findings: 0,
auto_fix_count: 0,
};
expect(getPatrolRunOperatorRecordPresentation(run).detail).toBe(run.findings_summary);
expect(getPatrolRunRecordSummaryPresentation(run).outcome).toBe(run.findings_summary);
expect(getPatrolRunStatusPresentation(run.status).variant).toBe('warning');
expect(getPatrolRunPrimaryActionPresentation(run)).toBeUndefined();
});
@@ -142,7 +142,8 @@ export function getPatrolRunOperatorRecordPresentation(
| 'resolved_findings'
| 'scope_resource_ids'
| 'status'
>,
> &
Partial<Pick<PatrolRunRecord, 'findings_summary'>>,
): PatrolRunOperatorRecordPresentation {
const context = formatRunActionContext(run);
const runtimeFailure = formatPatrolRuntimeFailureSummary({
@@ -163,6 +164,13 @@ export function getPatrolRunOperatorRecordPresentation(
};
}
if (run.status === 'observations') {
return {
headline: 'High filesystem usage',
detail: run.findings_summary || 'The check observed high filesystem usage.',
};
}
if (run.finding_ids === undefined) {
return {
headline: 'Completed check',
@@ -251,7 +259,8 @@ export function getPatrolRunRecordSummaryPresentation(
| 'resources_checked'
| 'scope_resource_ids'
| 'status'
>,
> &
Partial<Pick<PatrolRunRecord, 'findings_summary'>>,
): PatrolRunRecordSummaryPresentation {
const coverageSummary = getPatrolRunCoverageSummary(run);
const duration = formatDurationMs(run.duration_ms);
@@ -264,6 +273,13 @@ export function getPatrolRunRecordSummaryPresentation(
});
const action = getPatrolRunPrimaryActionPresentation(run);
if (run.status === 'observations' && !run.error_count) {
return {
summary,
outcome: run.findings_summary || 'The check observed high filesystem usage.',
};
}
if (!isPatrolRunHealthy(run.status, run.error_count)) {
return {
action,
@@ -322,11 +338,12 @@ export function getPatrolRunStatusPresentation(
variant: 'danger',
label: formatIdentifierLabel(normalized),
};
case 'observations':
case 'issues_found':
return {
badgeClass: 'bg-amber-100 text-amber-700 dark:bg-amber-900/25 dark:text-amber-300',
variant: 'warning',
label: 'issues found',
label: normalized === 'observations' ? 'observation' : 'issues found',
};
case 'healthy':
if (!findingsSnapshotAvailable) {
+5
View File
@@ -2,6 +2,7 @@ package ai
import (
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
// AlertThresholdAdapter adapts alerts.Manager to the ThresholdProvider interface
@@ -28,6 +29,10 @@ func (a *AlertThresholdAdapter) getThreshold(extract func(alerts.AlertConfig) (f
return defaultVal
}
func (a *AlertThresholdAdapter) GetHostFilesystemPolicy(host models.Host, disk models.Disk) (string, float64) {
return a.manager.HostFilesystemPolicy(host, disk)
}
// GetNodeCPUThreshold returns the CPU alert trigger threshold for nodes (0-100%)
func (a *AlertThresholdAdapter) GetNodeCPUThreshold() float64 {
return a.getThreshold(func(cfg alerts.AlertConfig) (float64, bool) {
+1
View File
@@ -597,6 +597,7 @@ type PatrolService struct {
lastActivity time.Time
lastDuration time.Duration
resourcesChecked int
lastRunStatus string
errorCount int
lastBlockedReason string
lastBlockedCause PatrolFailureCause
+18 -8
View File
@@ -34,13 +34,14 @@ import (
// AIAnalysisResult contains the results of an AI analysis
type AIAnalysisResult struct {
Response string // The AI's raw response text
Findings []*Finding // Parsed findings from the response
RejectedFindings int // Findings rejected by threshold validation
TriageFlags int // Number of deterministic triage flags
TriageSkippedLLM bool // Legacy: true for older records where quiet triage skipped LLM
InputTokens int
OutputTokens int
filesystemObservation string
Response string // The AI's raw response text
Findings []*Finding // Parsed findings from the response
RejectedFindings int // Findings rejected by threshold validation
TriageFlags int // Number of deterministic triage flags
TriageSkippedLLM bool // Legacy: true for older records where quiet triage skipped LLM
InputTokens int
OutputTokens int
// Prompt-cache buckets, disjoint from InputTokens (providers.ChatResponse).
CacheCreationInputTokens int
CacheReadInputTokens int
@@ -248,7 +249,11 @@ func patrolRunAIAnalysisForRecord(result *AIAnalysisResult, ctx patrolRunAnalysi
return ""
}
response = replacePatrolSummarySection(response, "Infrastructure Status", renderPatrolRecordStatusLine(ctx))
statusLine := renderPatrolRecordStatusLine(ctx)
if result.filesystemObservation != "" {
statusLine += " " + result.filesystemObservation
}
response = replacePatrolSummarySection(response, "Infrastructure Status", statusLine)
response = replacePatrolSummarySection(response, "Actions Taken", renderPatrolAcceptedActions(result, ctx))
return response
}
@@ -305,6 +310,8 @@ func renderPatrolAcceptedActions(result *AIAnalysisResult, ctx patrolRunAnalysis
return alertLine
case ctx.FiringAlert != "":
return fmt.Sprintf("- No findings reported. The %s is still active.", ctx.FiringAlert)
case result != nil && result.filesystemObservation != "":
return "- No finding recorded for the high filesystem usage."
}
return "- No findings reported — all clear."
}
@@ -852,6 +859,7 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRunti
SeededFindingIDs: seededFindingIDs,
QueriedFindingIDs: adapter.getQueriedFindingIDs(),
Forecasts: triageResult.Intel.forecasts,
filesystemObservation: patrolFilesystemObservation(triageResult.hostFilesystems),
}
}
@@ -1200,10 +1208,12 @@ func (p *PatrolService) buildTriageSeedSectionsState(
sections := []seedSection{
// P0 — always include.
{priority: 0, name: "triage_overview", content: formatTriageOverviewSection(triage)},
{priority: 0, name: "filesystem_observation", content: patrolFilesystemObservationBriefing(triage.hostFilesystems)},
{priority: 0, name: "operator_objectives", content: p.seedPatrolObjectives(sortedScopedIDs(seedSet), scope != nil, now)},
{priority: 0, name: "findings", content: findingsCtx},
{priority: 0, name: "health_alerts", content: p.seedHealthAndAlertsState(snap, seedSet, cfg, now)},
{priority: 0, name: "scope", content: buildScopeSection(scope, sortedScopedIDs(seedSet))},
{priority: 2, name: "host_filesystems", content: patrolFilesystemSeed(triage.hostFilesystems)},
{priority: 1, name: "guest_memory_evidence", content: patrolGuestMemoryEvidenceSection(snap, p.buildScopedSetForRuntime(scope, snap), cfg)},
// P2 — triage already preserves the flagged set, so these sections can
+1
View File
@@ -2421,6 +2421,7 @@ func (p *PatrolService) VerifyFixResolved(ctx context.Context, resourceID, resou
p.mu.Lock()
p.lastActivity = endTime
p.lastDuration = duration
p.lastRunStatus = verifyRecord.Status
p.resourcesChecked = verifyRecord.ResourcesChecked
p.errorCount = verifyRecord.ErrorCount
p.mu.Unlock()
+155
View File
@@ -0,0 +1,155 @@
package ai
import (
"fmt"
"slices"
"sort"
"strconv"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
// A sampled filesystem can need attention before the alert engine has seen
// enough consecutive samples to open an incident. Keep that distinction
// through the model briefing and the completed run record.
type patrolFilesystemReading struct {
hostID, hostName, mount string
percent, threshold float64
free int64
activeAlert bool
}
func (r patrolFilesystemReading) high() bool {
return r.threshold > 0 && r.percent >= r.threshold
}
func (r patrolFilesystemReading) description() string {
percent := strings.TrimSuffix(strconv.FormatFloat(r.percent, 'f', 1, 64), ".0")
return fmt.Sprintf("%s on %s is %s%% full", patrolSummaryInline(r.mount), patrolSummaryInline(r.hostName), percent)
}
type hostFilesystemThresholdProvider interface {
GetHostFilesystemPolicy(host models.Host, disk models.Disk) (string, float64)
}
func patrolHostFilesystemReadings(snap patrolRuntimeState, scopedSet map[string]bool, scope *PatrolScope) []patrolFilesystemReading {
if snap.readState == nil {
return nil
}
var policy hostFilesystemThresholdProvider = &AlertThresholdAdapter{}
if configured, ok := snap.thresholdProvider.(hostFilesystemThresholdProvider); ok {
policy = configured
}
activeDisks := make(map[string]bool)
for _, alert := range snap.ActiveAlerts {
if alert.Type == "disk" {
activeDisks[alert.ResourceID] = true
}
}
var readings []patrolFilesystemReading
for _, host := range snap.readState.Hosts() {
// A correlated host can provide context for another resource. Its
// mounts do not decide a check requested for that other resource.
if !seedIsInScope(scopedSet, host.ID()) || (scope != nil && len(scope.ResourceIDs) > 0 && !slices.Contains(scope.ResourceIDs, host.ID())) {
continue
}
disks, _, current := host.CurrentAgentDisks()
if !current {
continue
}
owner := models.Host{
ID: host.AgentID(), LinkedNodeID: host.LinkedNodeID(),
LinkedVMID: host.LinkedVMID(), LinkedContainerID: host.LinkedContainerID(),
}
for _, d := range disks {
mount := strings.TrimSpace(d.Mountpoint)
if mount == "" {
mount = strings.TrimSpace(d.Device)
}
if mount == "" {
continue
}
if scope != nil && scope.AlertContext != nil && scope.AlertContext.Mountpoint != "" && scope.AlertContext.Mountpoint != mount {
continue
}
disk := models.Disk{Mountpoint: d.Mountpoint, Device: d.Device, Used: d.Used, Total: d.Total, Free: d.Free, Usage: d.Usage}
percent, ok := unifiedresources.DiskUsagePercent(disk)
if !ok {
continue
}
id, threshold := policy.GetHostFilesystemPolicy(owner, disk)
readings = append(readings, patrolFilesystemReading{
hostID: host.ID(), hostName: triageResourceName(host.Name(), host.ID()),
mount: mount, percent: percent, free: d.Free,
threshold: threshold, activeAlert: activeDisks[id],
})
}
}
sort.Slice(readings, func(i, j int) bool {
a, b := readings[i], readings[j]
if a.high() != b.high() {
return a.high()
}
if a.percent != b.percent {
return a.percent > b.percent
}
if a.hostID != b.hostID {
return a.hostID < b.hostID
}
return a.mount < b.mount
})
return readings
}
func patrolFilesystemSeed(readings []patrolFilesystemReading) string {
if len(readings) == 0 {
return ""
}
var b strings.Builder
b.WriteString("# Current host filesystem readings\n")
for _, r := range readings {
fmt.Fprintf(&b, "- %q on %q [%s]: %.1f%% used, %d bytes free.", r.mount, r.hostName, patrolSeedID(r.hostID), r.percent, r.free)
if r.high() {
if r.activeAlert {
b.WriteString(" A disk usage alert is active for this mount.")
} else {
b.WriteString(" No active disk usage alert was recorded for this mount.")
}
}
b.WriteByte('\n')
}
b.WriteString("\n")
return b.String()
}
func patrolFilesystemObservationBriefing(readings []patrolFilesystemReading) string {
summary := patrolFilesystemObservation(readings)
if summary == "" {
return ""
}
alertState := "No disk usage alert is active for this mount."
if readings[0].activeAlert {
alertState = "A disk usage alert is active for this mount."
}
return fmt.Sprintf("# Highest filesystem usage\n%s %s\n\n", summary, alertState)
}
func patrolFilesystemObservation(readings []patrolFilesystemReading) string {
// Readings are sorted with above-threshold mounts first.
if len(readings) == 0 || !readings[0].high() {
return ""
}
count := 0
for _, r := range readings {
if r.high() {
count++
}
}
summary := readings[0].description() + "."
if count > 1 {
summary += fmt.Sprintf(" %d other %s above the configured threshold.", count-1, seedCountLabel(count-1, "filesystem is", "filesystems are"))
}
return summary
}
+107
View File
@@ -0,0 +1,107 @@
package ai
import (
"strings"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
func TestPatrolHostFilesystemCoverageAndVerdict(t *testing.T) {
host := unifiedresources.Resource{
ID: "host-01", Name: "lab-host", Type: unifiedresources.ResourceTypeAgent,
SourceStatus: map[unifiedresources.DataSource]unifiedresources.SourceStatus{unifiedresources.SourceAgent: {Status: "online", LastSeen: time.Now()}},
Agent: &unifiedresources.AgentData{AgentID: "source-01", Disks: []unifiedresources.DiskInfo{
{Mountpoint: "/", Total: 100, Used: 20, Free: 80, Usage: 20},
{Mountpoint: "/media", Total: 100, Used: 99, Free: 1, Usage: 99},
{Mountpoint: "/unavailable", Usage: 100},
}},
}
view := unifiedresources.NewHostView(&host)
state := patrolRuntimeState{readState: &mockReadState{hosts: []*unifiedresources.HostView{&view}}}
p := NewPatrolService(nil, nil)
p.SetConfig(PatrolConfig{AnalyzeHosts: true})
triage := p.runDeterministicTriageState(t.Context(), state, nil, nil)
seed, _ := p.buildTriageSeedContextState(triage, state, nil, nil)
if triage.Summary.TotalHosts != 1 || len(triage.Flags) != 1 || triage.IsQuiet ||
!strings.Contains(seed, "Scanned 1 resource") || !strings.Contains(seed, "/media") ||
!strings.Contains(seed, "20.0% used") || strings.Contains(seed, "/unavailable") {
t.Fatalf("host triage lost or fabricated readings: %+v\n%s", triage, seed)
}
result := &AIAnalysisResult{Response: "### Key Observations\nCould not identify the largest folder.", filesystemObservation: patrolFilesystemObservation(triage.hostFilesystems)}
record := PatrolRunRecord{Status: "healthy", ResourcesChecked: 1}
applyPatrolFilesystemVerdict(&record, result, "")
record.AIAnalysis = patrolRunAIAnalysisForRecord(result, patrolRunAnalysisRecordContext{ResourcesChecked: 1})
if record.Status != patrolRunObservations || record.FindingsSummary != "/media on lab-host is 99% full." || strings.Contains(record.AIAnalysis, "all clear") || !strings.Contains(record.AIAnalysis, record.FindingsSummary) || !strings.Contains(record.AIAnalysis, "largest folder") {
t.Fatalf("misleading run: %+v", record)
}
for _, initial := range []string{"error", "issues_found", "critical"} {
record := PatrolRunRecord{Status: initial, FindingsSummary: "Existing outcome"}
applyPatrolFilesystemVerdict(&record, result, "")
if record.Status != initial || record.FindingsSummary != "Existing outcome" {
t.Fatalf("replaced prior outcome: %+v", record)
}
}
state.ActiveAlerts = []models.Alert{{Type: "disk", ResourceID: "agent:source-01/disk:other"}}
if text := patrolFilesystemObservationBriefing(patrolHostFilesystemReadings(state, nil, nil)); !strings.Contains(text, "No disk usage alert is active") {
t.Fatal(text)
}
state.ActiveAlerts[0].ResourceID = "agent:source-01/disk:media"
if text := patrolFilesystemObservationBriefing(patrolHostFilesystemReadings(state, nil, nil)); !strings.Contains(text, "A disk usage alert is active") {
t.Fatal(text)
}
state.ActiveAlerts = nil
rows := patrolHostFilesystemReadings(state, nil, &PatrolScope{AlertContext: &PatrolAlertContext{Mountpoint: "/"}})
if len(rows) != 1 || patrolFilesystemObservation(rows) != "" {
t.Fatalf("unrelated mount changed targeted verdict: %v", rows)
}
rows = patrolHostFilesystemReadings(state, map[string]bool{"host-01": true}, &PatrolScope{ResourceIDs: []string{"another-resource"}})
if len(rows) != 0 {
t.Fatal("correlated host changed an unrelated check")
}
scope := map[string]bool{"different-host": true}
if got := patrolHostFilesystemReadings(state, scope, nil); len(got) != 0 {
t.Fatalf("unrelated host leaked into scope: %v", got)
}
host.Agent.Disks[1].Usage = 50
host.Agent.Disks[1].Used = 50
host.Agent.Disks[1].Free = 50
healthy := p.runDeterministicTriageState(t.Context(), state, nil, nil)
if !healthy.IsQuiet || patrolFilesystemObservation(healthy.hostFilesystems) != "" {
t.Fatalf("healthy control flagged: %+v", healthy)
}
host.Agent.Stale = true
if got := patrolHostFilesystemReadings(state, nil, nil); len(got) != 0 {
t.Fatalf("stale samples admitted: %v", got)
}
host.Agent.Stale = false
p.SetConfig(PatrolConfig{AnalyzeHosts: false})
disabled := p.runDeterministicTriageState(t.Context(), state, nil, nil)
if disabled.Summary.TotalHosts != 0 || len(disabled.hostFilesystems) != 0 {
t.Fatal("host analysis disabled but host included")
}
}
func TestPatrolHostFilesystemThresholdMatchesMountPolicy(t *testing.T) {
mgr := alerts.NewManager()
cfg := mgr.GetConfig()
cfg.Overrides = map[string]alerts.ThresholdConfig{}
cfg.Overrides["agent:source-01/disk:media"] = alerts.ThresholdConfig{Disk: &alerts.HysteresisThreshold{Trigger: 98, Clear: 95}}
cfg.Overrides["agent:source-01/disk:off"] = alerts.ThresholdConfig{Disabled: true}
mgr.UpdateConfig(cfg)
adapter := NewAlertThresholdAdapter(mgr)
host := models.Host{ID: "source-01"}
for _, tc := range []struct {
mount, device string
want float64
}{
{"/media", "/dev/nvme0n1p1", 98}, {"/other", "/dev/nvme0n1p1", 92}, {"/off", "/dev/sdb1", 0}, {"/", "/dev/sda1", 90},
} {
if _, got := adapter.GetHostFilesystemPolicy(host, models.Disk{Mountpoint: tc.mount, Device: tc.device}); got != tc.want {
t.Errorf("%s: got %v, want %v", tc.mount, got, tc.want)
}
}
}
+20 -1
View File
@@ -118,6 +118,7 @@ func (p *PatrolService) patrolLoop(ctx context.Context) {
for _, run := range history {
if !lastActivity.IsZero() && run.CompletedAt.Equal(lastActivity) {
p.resourcesChecked = run.ResourcesChecked
p.lastRunStatus = run.Status
p.errorCount = run.ErrorCount
p.lastDuration = run.Duration
break
@@ -338,6 +339,18 @@ type patrolRunStart struct {
startedAt time.Time
}
const patrolRunObservations = "observations"
func applyPatrolFilesystemVerdict(record *PatrolRunRecord, result *AIAnalysisResult, activeAlert string) {
if record.Status == "healthy" && result != nil && result.filesystemObservation != "" {
record.Status = patrolRunObservations
record.FindingsSummary = result.filesystemObservation
if activeAlert != "" {
record.FindingsSummary += " The " + activeAlert + " is still active."
}
}
}
const patrolRunErrorNoResources = "no_resources"
const patrolNoResourcesSummary = "No resources checked"
const patrolNoResourcesDetail = "Patrol could not assess infrastructure health because the check covered no resources."
@@ -368,6 +381,7 @@ func (p *PatrolService) recordAcceptedRunFailure(start *patrolRunStart, trigger
p.lastFullPatrol = completedAt
p.lastDuration = duration
p.resourcesChecked = 0
p.lastRunStatus = "error"
p.errorCount = 1
p.mu.Unlock()
}
@@ -818,6 +832,7 @@ func (p *PatrolService) runPatrolWithTriggerStart(ctx context.Context, trigger T
// Add AI analysis details if available
if runStats.aiAnalysis != nil {
applyPatrolFilesystemVerdict(&runRecord, runStats.aiAnalysis, "")
runRecord.AIAnalysis = patrolRunAIAnalysisForRecord(runStats.aiAnalysis, patrolRunAnalysisRecordContext{
ResourcesChecked: runStats.resourceCount,
NewFindings: runStats.newFindings,
@@ -854,6 +869,7 @@ func (p *PatrolService) runPatrolWithTriggerStart(ctx context.Context, trigger T
p.lastFullPatrol = completedAt
p.lastDuration = duration
p.resourcesChecked = runStats.resourceCount
p.lastRunStatus = runRecord.Status
p.errorCount = runStats.errors
p.mu.Unlock()
@@ -1365,6 +1381,7 @@ func (p *PatrolService) runScopedPatrolWithStart(ctx context.Context, scope Patr
}
if runStats.aiAnalysis != nil {
applyPatrolFilesystemVerdict(&runRecord, runStats.aiAnalysis, activeAlertName)
runRecord.AIAnalysis = patrolRunAIAnalysisForRecord(runStats.aiAnalysis, patrolRunAnalysisRecordContext{
ResourcesChecked: runStats.resourceCount,
NewFindings: runStats.newFindings,
@@ -1394,6 +1411,7 @@ func (p *PatrolService) runScopedPatrolWithStart(ctx context.Context, scope Patr
p.lastActivity = completedAt
p.lastDuration = duration
p.resourcesChecked = runStats.resourceCount
p.lastRunStatus = runRecord.Status
p.errorCount = runStats.errors
p.mu.Unlock()
@@ -1493,6 +1511,7 @@ func (p *PatrolService) recordScopedPatrolScopeFailure(start time.Time, runID st
p.lastActivity = completedAt
p.lastDuration = record.Duration
p.resourcesChecked = 0
p.lastRunStatus = "error"
p.errorCount = 1
p.mu.Unlock()
p.runHistoryStore.Add(record)
@@ -2234,7 +2253,7 @@ func (p *PatrolService) GetStatus() PatrolStatus {
}
summary := p.findings.GetSummary()
status.Healthy = summary.IsHealthy() && p.errorCount == 0 && (p.lastActivity.IsZero() || p.resourcesChecked > 0)
status.Healthy = summary.IsHealthy() && p.lastRunStatus != patrolRunObservations && p.errorCount == 0 && (p.lastActivity.IsZero() || p.resourcesChecked > 0)
if status.RuntimeState == PatrolRuntimeStateBlocked {
status.Healthy = false
}
+42 -16
View File
@@ -30,12 +30,13 @@ type TriageFlag struct {
// TriageResult is the output of deterministic triage.
type TriageResult struct {
Flags []TriageFlag
Summary TriageSummary
IsQuiet bool // True when no flags AND no active findings
Intel seedIntelligence // Pre-computed intelligence (anomalies, forecasts, etc.)
GuestIntel map[string]*GuestIntelligence // Guest reachability data
FlaggedIDs map[string]bool // Set of flagged resource IDs for scoped seed building
hostFilesystems []patrolFilesystemReading
Flags []TriageFlag
Summary TriageSummary
IsQuiet bool // True when no flags AND no active findings
Intel seedIntelligence // Pre-computed intelligence (anomalies, forecasts, etc.)
GuestIntel map[string]*GuestIntelligence // Guest reachability data
FlaggedIDs map[string]bool // Set of flagged resource IDs for scoped seed building
// unalertedStopKeys are the container exits this run was asked to judge
// as job or service. A run that completes remembers them.
unalertedStopKeys []string
@@ -43,6 +44,7 @@ type TriageResult struct {
// TriageSummary provides top-level infrastructure counts.
type TriageSummary struct {
TotalHosts int
TotalNodes int
TotalGuests int
RunningGuests int
@@ -73,7 +75,21 @@ func (p *PatrolService) runDeterministicTriageState(
thresholds = DefaultPatrolThresholds()
}
var filesystems []patrolFilesystemReading
flags := make([]TriageFlag, 0)
analyzeHosts := p.GetConfig().AnalyzeHosts
if analyzeHosts {
filesystems = patrolHostFilesystemReadings(snap, scopedSet, scope)
for _, r := range filesystems {
if r.high() {
flags = append(flags, TriageFlag{
ResourceID: r.hostID, ResourceName: r.hostName, ResourceType: "agent",
Category: "capacity", Severity: "warning", Reason: r.description(),
Metric: "filesystem:" + r.mount, Value: r.percent, Threshold: r.threshold,
})
}
}
}
flags = append(flags, triageThresholdChecksState(snap, scopedSet, thresholds)...)
flags = append(flags, triageAnomalyChecks(intel)...)
flags = append(flags, triageBackupChecksState(snap, scopedSet)...)
@@ -99,6 +115,9 @@ func (p *PatrolService) runDeterministicTriageState(
}
summary := triageBuildSummaryState(snap, flaggedIDs)
if !analyzeHosts {
summary.TotalHosts = 0
}
activeFindings := 0
if p != nil && p.findings != nil {
@@ -106,12 +125,13 @@ func (p *PatrolService) runDeterministicTriageState(
}
return &TriageResult{
Flags: flags,
Summary: summary,
IsQuiet: len(flags) == 0 && activeFindings == 0,
Intel: intel,
GuestIntel: guestIntel,
FlaggedIDs: flaggedIDs,
Flags: flags,
hostFilesystems: filesystems,
Summary: summary,
IsQuiet: len(flags) == 0 && activeFindings == 0,
Intel: intel,
GuestIntel: guestIntel,
FlaggedIDs: flaggedIDs,
unalertedStopKeys: unalertedStopKeys,
}
@@ -642,12 +662,13 @@ func formatTriageOverviewSection(triage *TriageResult) string {
return "# Deterministic Triage Results\nNo triage data available.\n"
}
scanned := triage.Summary.TotalNodes + triage.Summary.TotalGuests + triage.Summary.TotalStorage +
scanned := triage.Summary.TotalHosts + triage.Summary.TotalNodes + triage.Summary.TotalGuests + triage.Summary.TotalStorage +
triage.Summary.TotalDocker + triage.Summary.TotalTrueNAS + triage.Summary.TotalPBS + triage.Summary.TotalPMG
return fmt.Sprintf(
"# Deterministic Triage Results\nScanned %d resources: %d nodes, %d guests, %d storage resources (%d pools, %d physical disks), %d docker hosts, %d TrueNAS systems, %d PBS, %d PMG.\n\n",
scanned,
"# Deterministic Triage Results\nScanned %d %s: %d %s, %d nodes, %d guests, %d storage resources (%d pools, %d physical disks), %d docker hosts, %d TrueNAS systems, %d PBS, %d PMG.\n\n",
scanned, seedCountLabel(scanned, "resource", "resources"),
triage.Summary.TotalHosts, seedCountLabel(triage.Summary.TotalHosts, "host", "hosts"),
triage.Summary.TotalNodes,
triage.Summary.TotalGuests,
triage.Summary.TotalStorage,
@@ -760,11 +781,13 @@ func formatTriageHealthySummarySection(triage *TriageResult) string {
healthyPMG = 0
}
totalHealthy := healthyNodes + healthyGuests + healthyStorage + healthyDocker + healthyTrueNAS + healthyPBS + healthyPMG
healthyHosts := max(0, triage.Summary.TotalHosts-triageUniqueFlaggedByType(triage.Flags, "agent"))
totalHealthy := healthyHosts + healthyNodes + healthyGuests + healthyStorage + healthyDocker + healthyTrueNAS + healthyPBS + healthyPMG
var sb strings.Builder
sb.WriteString(fmt.Sprintf("## Resources without triage flags (%d)\n", totalHealthy))
sb.WriteString("No flag is not proof of health; missing or uncertain readings remain unknown.\n")
sb.WriteString(fmt.Sprintf("Hosts: %d unflagged\n", healthyHosts))
sb.WriteString(fmt.Sprintf("Nodes: %d unflagged\n", healthyNodes))
sb.WriteString(fmt.Sprintf("Guests: %d running, %d stopped\n", triage.Summary.RunningGuests, triage.Summary.StoppedGuests))
sb.WriteString(fmt.Sprintf("Storage: %d resources monitored (%d pools, %d physical disks)\n",
@@ -812,6 +835,7 @@ func triageBuildSummaryState(snap patrolRuntimeState, flaggedIDs map[string]bool
guests := patrolGuestInventoryRows(snap, nil, nil)
summary := TriageSummary{
TotalHosts: counts.hosts,
TotalNodes: len(patrolNodeInventoryRows(snap, nil)),
TotalStoragePools: len(storagePools),
TotalPhysicalDisks: len(physicalDisks),
@@ -1084,6 +1108,8 @@ func triageThresholdsUnset(thresholds PatrolThresholds) bool {
func triageFlagLabel(flag TriageFlag) string {
switch {
case flag.Category == "capacity" && strings.HasPrefix(flag.Metric, "filesystem:"):
return "High filesystem usage"
case flag.Category == "performance" && flag.Metric == "cpu":
return "High CPU"
case flag.Category == "performance" && flag.Metric == "memory":
+1 -1
View File
@@ -765,7 +765,7 @@ func TestFormatTriageBriefing(t *testing.T) {
if !strings.Contains(out, "## Resources without triage flags") {
t.Fatalf("expected healthy summary section, got:\n%s", out)
}
if !strings.Contains(out, "Scanned 7 resources: 1 nodes, 2 guests, 1 storage resources (1 pools, 0 physical disks), 1 docker hosts, 1 TrueNAS systems, 1 PBS, 0 PMG.") {
if !strings.Contains(out, "Scanned 7 resources: 0 hosts, 1 nodes, 2 guests, 1 storage resources (1 pools, 0 physical disks), 1 docker hosts, 1 TrueNAS systems, 1 PBS, 0 PMG.") {
t.Fatalf("expected explicit storage breakdown in scanned summary, got:\n%s", out)
}
if !strings.Contains(out, "Storage: 1 resources monitored (1 pools, 0 physical disks)") {
+25
View File
@@ -203,6 +203,31 @@ func isHostFilesystemResourceID(resourceID string) bool {
return ok && strings.HasPrefix(child, "disk:")
}
// Used only when a caller has no configured alert manager.
var factoryHostFilesystemPolicy = &Manager{config: DefaultAlertConfig()}
// HostFilesystemPolicy returns the resource ID and fill threshold used by CheckHost.
// Reading it does not advance the alert's activation or recovery timers.
func (m *Manager) HostFilesystemPolicy(host models.Host, disk models.Disk) (string, float64) {
if m == nil {
m = factoryHostFilesystemPolicy
}
m.mu.RLock()
defer m.mu.RUnlock()
disabled, _ := m.alertPolicyTypeSwitchesNoLock("agent")
thresholds := m.resolveHostThresholdsNoLock(host.ID, host.LinkedNodeID, host.LinkedVMID, host.LinkedContainerID)
id, _ := hostDiskResourceID(host, disk)
if !m.config.Enabled || disabled || thresholds.Disabled {
return id, 0
}
override, exists := m.hostThresholdOverrideNoLock(host.ID, host.LinkedNodeID, host.LinkedVMID, host.LinkedContainerID)
threshold, _ := m.hostDiskUsageThresholdNoLock(id, disk.Device, thresholds.Disk, exists && override.Disk != nil)
if threshold == nil {
return id, 0
}
return id, threshold.Trigger
}
// hostDiskUsageThresholdNoLock resolves the usage threshold one agent
// filesystem is judged by: the filesystem's own override, then an explicit
// host or inherited disk override, then the fill threshold for its hardware