Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Repair resource evidence for Patrol and Assistant

rcourtmanb7f546f81a5d
diff --git a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
index f36eef0836..395cc4a78e 100644
--- a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
+++ b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
@@ -171,3 +171,76 @@ A final identical readiness retry again received the provider policy refusal.
The normal manual Patrol trigger returned HTTP 409 `patrol_readiness_not_ready`.
No Patrol run or infrastructure action was accepted. Actual Patrol evaluation
with this model remains blocked on a working supported provider path.
+
+
+## Resource evidence continuation, 2026-09-05
+
+The next real read-only run exposed independent model-facing contract defects.
+A canonical resource or hostname was passed directly to the in-memory metrics
+store, while `pulse_summarize` already resolved the registry's metrics target.
+Physical disk queries used the operation selector `type=disks` as a hardware
+format filter. The advertised `node` get type was rejected. Canonical agent
+projection also dropped Proxmox CPU topology. These defects are repaired in the
+shared tools, with ambiguous identity rejected and canonical response IDs kept.
+
+The first repaired performance query returned only post-restart observations.
+The production tool adapter now receives the current monitor's retained SQLite
+store. Resource-scoped reads use that store and return errors rather than
+silently substituting shorter in-memory history. A close/reopen regression
+covers Proxmox nodes, agents, VMs and system containers. Merged points are
+chronological before the existing output-size limit is applied. Unscoped
+summaries and baselines retain their existing providers and remain a
+modernization residual.
+
+A subsequent live Opus 5 response retrieved pre-restart observations and the
+correct delly2 NVMe disk, whose SMART assessment passed at 33 degrees Celsius.
+It correctly identified that the retained series covered about 31 minutes,
+not the requested full day. More retained data cannot be invented. The model
+still inferred a probable wear-related reason for a warning without the risk
+record, and the tool omitted explicit wear units. Disk risk explanation and
+coverage reconciliation remain unqualified.
+
+The corrected incomplete-readiness projection is browser-tested using the
+backend regression result, explicitly as presentation proof rather than a new
+provider qualification. No provider refusal was bypassed or repeatedly retried.
+The real manual Patrol endpoint remains blocked with HTTP 409. The existing
+provider policy refusal still prevents a qualified autonomous Patrol run.
+
+
+The named-resource repeat also misused `current_resource` from the Patrol
+page, then asked which machine was intended despite `delly2` being named.
+The shared boundary error had instructed the model to ask the user before any
+further targeted read. It now distinguishes the unattached shortcut from an
+explicit name and directs name resolution through canonical query search.
+The shortcut remains blocked until attached context exists.
+
+Live gate testing exposed an execution defect while correcting the saved
+readiness verdict: both runtime and API paths treated an unassessed mode as an
+executable warning. One manual read-only test run started unexpectedly and
+reassessed an existing finding before the development backend was restarted to
+stop it. No infrastructure mutation was performed. It is not a qualified
+Patrol outcome. The runtime now blocks a provider-failed unassessed Watch result
+for every selected mode, and the API consumes that execution verdict instead
+of authorizing from display warnings. Operator cancellation retains its
+existing non-failure behavior. The repaired live endpoint returned HTTP 409,
+and the actual saved result displays latency and Watch-only as not assessed.
+No new provider probe was needed to correct that persisted result.
+
+
+The final named-resource retest completed without clarification in 110 seconds.
+It resolved delly2 to the correct canonical agent, reported 12 CPU cores,
+retrieved chronological pre-restart metrics, and attributed the KIOXIA NVMe
+SMART PASSED result to the correct host. It identified the 31-minute retained
+window and roughly 44-minute age of its newest point, and did not claim that
+unchecked alerts were absent. Reasoning remains imperfect: child resources
+were later described as guests without workload enumeration, and coincident
+metric changes were treated as a probable workload start without attribution.
+This is a bounded evidence-path pass, not full diagnosis qualification.
+
+Final browser verification used `/patrol` and
+`/settings/pulse-intelligence/patrol` at 1440x1000 and 390x1000. It exercised
+Assistant submission and completion, keyboard/pointer tool-result expansion
+and collapse, output scrolling, final-answer pixels, Escape, session history
+and reload. The actual cached readiness result and actual HTTP 409 gate were
+verified after the final source changes. Local receipts bind source hashes,
+transcripts and screenshots under the homelab resource-browser artifact set.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index ce9006c6fa..1fdda90384 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -10201,7 +10201,7 @@
},
{
"id": "patrol-assistant-customer-outcome-qualification",
- "summary": "The 2026-09-05 product review found that Explain with Assistant opened a blank generic conversation and the attention workbench discarded richer canonical finding context. The explicit explanation dispatcher and canonical handoff repair address that frontend break, with scripted browser proof and regression tests. They do not qualify model reasoning, real infrastructure actions, or repeated customer value. Latest-report, monitoring-active, multi-ping telemetry excluding dev and deployment proof contained 127 paid installs, 71 with Patrol enabled and 23 with Assistant calls. Fourteen reported verified resolutions were concentrated in one install. Paid includes all non-free tiers, and activity cooccurrence is not a linked successful journey. Schema 17 outcome/provider/cost fields had no adoption in that review. Three real jobs remain to qualify across named provider/model/version configurations: unhealthy service diagnosis, backup or capacity risk, and supported VM/LXC plan, approval and verified result. Repeatability must be established across independent paid customer environments without pooling free-tier or ineligible installs. The same-day real maintainer homelab evaluation with Claude Opus 5 exposed missing Proxmox temperature-tool evidence, contradictory summary health, incomplete visible prose, alert-count confusion and an inaccurately classified provider refusal during Patrol readiness. The shared temperature projection and premature within-window evidence compaction are repaired, while the documented reasoning, completion, readiness and end-to-end outcome failures remain unqualified.",
+ "summary": "The 2026-09-05 product review found that Explain with Assistant opened a blank generic conversation and the attention workbench discarded richer canonical finding context. The explicit explanation dispatcher and canonical handoff repair address that frontend break, with scripted browser proof and regression tests. They do not qualify model reasoning, real infrastructure actions, or repeated customer value. Latest-report, monitoring-active, multi-ping telemetry excluding dev and deployment proof contained 127 paid installs, 71 with Patrol enabled and 23 with Assistant calls. Fourteen reported verified resolutions were concentrated in one install. Paid includes all non-free tiers, and activity cooccurrence is not a linked successful journey. Schema 17 outcome/provider/cost fields had no adoption in that review. Three real jobs remain to qualify across named provider/model/version configurations: unhealthy service diagnosis, backup or capacity risk, and supported VM/LXC plan, approval and verified result. Repeatability must be established across independent paid customer environments without pooling free-tier or ineligible installs. The same-day real maintainer homelab evaluation with Claude Opus 5 exposed missing Proxmox temperature-tool evidence, contradictory summary health, incomplete visible prose, alert-count confusion and an inaccurately classified provider refusal during Patrol readiness. The shared temperature projection and premature within-window evidence compaction are repaired, while the documented reasoning, completion, readiness and end-to-end outcome failures remain unqualified. The continuation repaired canonical resource lookup, operation-versus-disk filtering, Proxmox CPU topology and retained resource-scoped history across backend restarts. Unscoped summary/baseline modernization, wear semantics, disk risk explanation and complete retained-window coverage remain open. A named-resource repeat exposed overly restrictive current_resource recovery guidance, now corrected without weakening the attachment boundary. Live testing also exposed warning-based API execution after an incomplete provider check. Runtime and API now enforce the selected-mode verdict, including saved incomplete results, and the repaired live endpoint returns HTTP 409. One read-only test run started before the gate correction and was stopped, so it is not qualification evidence.",
"owner": "project-owner",
"status": "planned",
"recorded_at": "2026-09-05",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8dd94d00a0..0844c2db22 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -15,6 +15,11 @@
## Purpose
+Assistant historical metric wiring uses the current monitor's retained store
+and registry metrics coordinates. Historical reads do not alter enrollment,
+agent ownership, or command capabilities. Proxmox-only canonical agent details
+retain CPU topology without requiring an installed collector.
+
Unraid collection preserves optional nonnegative `mdNumDisks` as `numDisks` through the host report. Explicit zero survives JSON encoding; absent, negative, or malformed source counts remain unknown. This telemetry does not change enrollment or command authority; older agents retain unknown-count behaviour.
### Portable installer lifecycle ownership
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 5fca86eabd..aec97c384d 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -19,6 +19,40 @@
## Purpose
+The manual Patrol API consumes the service's selected-mode runtime verdict as
+an execution check. Dimension-level presentation warnings cannot authorize a
+run after a provider failure leaves Watch-only readiness unassessed. Operator
+cancellation retains its existing non-failure advisory semantics. Higher-mode canary guidance
+retains its existing advisory behavior only after Watch has been verified.
+
+The unavailable `current_resource` tool result describes an unattached shortcut,
+not an unresolved explicit name. Its recovery guidance directs named resources
+through canonical query search. The attachment guard remains enforced and
+never invents a selected resource or grants execution authority.
+
+Resource-scoped `pulse_metrics` performance reads resolve canonical identity
+and unambiguous lookup aliases through the unified registry, then query its
+metrics target. The retained SQLite metrics store supplies the requested window
+across backend restarts. An available store error remains an error, with no
+silent downgrade to a shorter in-memory history. The in-memory-only adapter
+remains a compatibility boundary for installations without a retained store.
+The unscoped summary and baseline paths still use their existing providers and
+are a modernization residual, not proof of retained-history coverage.
+`TestPerformanceMetricsRetainedAcrossRestart` verifies native store coordinates,
+canonical response identity, node/agent/guest families, restart retention and
+store failure. The `node` get alias resolves to canonical `agent`, whose CPU
+count retains Proxmox topology when no agent count is available. Physical disk
+metrics use the advertised `disk_type` filter independently of `type=disks`,
+and share canonical disk host projection with resource queries.
+
+An incomplete streaming readiness evaluation leaves latency and Watch-only
+suitability unassessed. Completed tool/context evidence remains available, and
+an explicit provider-error guard prevents authorizing Patrol. Provider errors
+remain distinct from measured latency failures. The exact legacy unfinished-probe latency verdict is corrected when persisted
+evidence is decoded, preserving its timestamp, provider cause and completed
+checks without a new provider request or granting a verified mode. Provider refusal taxonomy and
+supported subscription readiness remain unresolved qualification work.
+
Within an active investigation, tool observations are preserved across provider
turns while the full request fits the model context window. Turn age is not a
compaction trigger and does not prove evidence has been understood or retained.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 729ff2fd82..80d6a302af 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -20,6 +20,20 @@
## Purpose
+The manual Patrol API consumes the service's selected-mode runtime verdict as
+an execution check. Dimension-level presentation warnings cannot authorize a
+run after a provider failure leaves Watch-only readiness unassessed. Operator
+cancellation retains its existing non-failure advisory semantics. Higher-mode canary guidance
+retains its existing advisory behavior only after Watch has been verified.
+
+The Assistant tool-provider wiring passes the current monitor's retained
+metrics store to the historical metrics adapter. Resource-scoped performance
+queries use canonical registry coordinates and retain history across process
+restarts. Store failures are returned to the caller rather than hidden behind
+an in-memory fallback. This is an internal read-provider extension and adds no
+route or external write authority. The restart proof is
+`internal/ai/tools/retained_metrics_test.go`.
+
The public `PBSBackup` projection keeps `inProgress` as the compatibility field
for an incomplete, manifestless snapshot. Optional
`writeActivityObserved: true` says the collector obtained a complete bounded
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index b838e5b897..f25d3f1b7c 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -15,6 +15,12 @@
## Purpose
+Resource-scoped Assistant performance reads query retained CPU, memory and
+disk series using the registry target, then retain the existing 120-point
+output limit. A backend restart does not define the requested history window.
+Store errors cannot silently substitute a shorter in-memory series. Unscoped
+summary modernization remains tracked by the AI runtime contract.
+
Own measurable performance budgets, query-plan guarantees, and hot-path
regression protection.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 8bb09f60f4..7a8dfe7f1d 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -18,6 +18,11 @@
## Purpose
+Assistant retained-history wiring uses the store belonging to its current
+monitor and read-only metric queries. Canonical identity resolution precedes
+store lookup, and ambiguous names fail with a request for canonical identity.
+This provider extension grants no infrastructure execution or write authority.
+
API-token rename is an authenticated token-management mutation: blank labels
fail closed, successful changes are persisted and audited as `token_renamed`,
and neither the plaintext credential nor its stored hash is exposed or
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 1194cc4d85..b8bd11e2c0 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -21,6 +21,12 @@
## Purpose
+Assistant physical-disk metrics use the canonical disk host projection and
+separate the disk format filter from the metrics operation selector. Missing
+SMART observations remain missing coverage, not disk failure or recovery
+readiness. Retained performance history is operational evidence and does not
+establish backup coverage or restorability.
+
Provider incident nativeSeverity is evidence, not a storage recovery result or identity component. TrueNAS NOTICE remains actionable while INFO remains resource evidence; both retain canonical monitor risk. This distinction must not alter pool health assessment, recovery confirmation counts, or storage action authority.
TrueNAS replication state `FINISHED` is successful completion evidence when a
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index cc1d60b07e..8fb69ec62e 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -162,7 +162,7 @@ func currentResourceUnavailableToolResult(err error) string {
reason = strings.TrimSpace(err.Error())
}
return fmt.Sprintf(
- "CURRENT_RESOURCE_UNAVAILABLE: %s. Ask which host, VM, container, app, or storage resource the user means before calling resource-targeted tools. Do not retry this tool with %s until the user provides or opens a specific resource context.",
+ "CURRENT_RESOURCE_UNAVAILABLE: %s. The %s shortcut requires an attached resource. For a resource named in the user request, use pulse_query search to resolve its canonical ID and use that ID in subsequent tools. Ask the user only if the intended resource remains unspecified or ambiguous.",
reason,
agentcapabilities.CurrentResourceHandle,
)
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index a9ef20aa3e..53e86ba86d 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -3046,7 +3046,7 @@ func TestAgenticLoop_CancelsUnavailableCurrentResourcePendingToolCall(t *testing
if !strings.Contains(toolResult.Content, "CURRENT_RESOURCE_UNAVAILABLE") {
t.Fatalf("expected current resource block marker, got %q", toolResult.Content)
}
- if !strings.Contains(toolResult.Content, "Ask which host, VM, container, app, or storage resource") {
+ if !strings.Contains(toolResult.Content, "use pulse_query search to resolve its canonical ID") {
t.Fatalf("expected model-facing recovery instruction, got %q", toolResult.Content)
}
callback(providers.StreamEvent{
diff --git a/internal/ai/patrol_model_readiness.go b/internal/ai/patrol_model_readiness.go
index 74cdfdcd79..5b6f8d8c0f 100644
--- a/internal/ai/patrol_model_readiness.go
+++ b/internal/ai/patrol_model_readiness.go
@@ -319,6 +319,18 @@ func (s *Service) loadPatrolModelReadiness() {
if persisted.Result.ProbeVersion != PatrolModelReadinessProbeVersion || persisted.RecordedAt.IsZero() {
return
}
+ // Older v1 writers marked this exact unfinished-probe outcome as a
+ // latency failure. Correct its presentation on decode without rerunning the
+ // provider, changing the recorded evidence, or granting a verified mode.
+ if persisted.Result.Dimensions.Latency.Status == PatrolModelReadinessFail &&
+ persisted.Result.Dimensions.Latency.Summary == "Latency could not be measured because the streaming probe did not complete." {
+ persisted.Result.Dimensions.Latency.Status = PatrolModelReadinessNotAssessed
+ persisted.Result.Dimensions.Latency.Summary = "Latency was not fully measured because the provider did not complete the evaluation."
+ persisted.Result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeNotAssessed, Summary: "Watch-only readiness was not established because the provider did not complete the evaluation."}
+ persisted.Result.Success = false
+ persisted.Result.PatrolCapable = false
+ persisted.Result.MaxVerifiedMode = ""
+ }
persisted.Result.CacheKey = persisted.CacheKey
s.patrolModelReadinessCache.result = clonePatrolModelReadinessResult(&persisted.Result)
s.patrolModelReadinessCache.recordedAt = persisted.RecordedAt
@@ -830,8 +842,8 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
latencyStatus = PatrolModelReadinessNotAssessed
latencySummary = "Latency was not fully measured because the evaluation was interrupted."
} else if len(durations) == 0 || probeErr != nil {
- latencyStatus = PatrolModelReadinessFail
- latencySummary = "Latency could not be measured because the streaming probe did not complete."
+ latencyStatus = PatrolModelReadinessNotAssessed
+ latencySummary = "Latency was not fully measured because the provider did not complete the evaluation."
} else if projectedWatch > patrolReadinessWatchEnvelope {
latencyStatus = PatrolModelReadinessWarning
latencySummary = fmt.Sprintf("Projected 8-turn Watch-only loop is %s, above the four-minute readiness envelope.", formatReadinessDuration(projectedWatch))
@@ -846,10 +858,12 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
ProjectedApprovalMs: projectedApproval.Milliseconds(),
}
- watchVerified := toolStatus == PatrolModelReadinessPass && contextStatus == PatrolModelReadinessPass && latencyStatus == PatrolModelReadinessPass
+ watchVerified := probeErr == nil && toolStatus == PatrolModelReadinessPass && contextStatus == PatrolModelReadinessPass && latencyStatus == PatrolModelReadinessPass
approvalVerified := watchVerified && continuationObserved && projectedApproval <= cfg.GetPatrolInvestigationTimeout()
if watchVerified {
result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeVerified, Summary: "Verified for Watch only on this provider, model, and runtime."}
+ } else if probeErr != nil {
+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeNotAssessed, Summary: "Watch-only readiness was not established because the provider did not complete the evaluation."}
} else if latencyStatus == PatrolModelReadinessWarning {
result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeWarning, Summary: "Core protocol passed, but projected Watch-only latency exceeds the readiness envelope."}
} else {
diff --git a/internal/ai/patrol_model_readiness_test.go b/internal/ai/patrol_model_readiness_test.go
index 4a1dabe9b4..f8fdcc12a5 100644
--- a/internal/ai/patrol_model_readiness_test.go
+++ b/internal/ai/patrol_model_readiness_test.go
@@ -19,6 +19,7 @@ import (
type scriptedReadinessProvider struct {
connectionErr error
+ continuationErr error
wrongProtocol bool
wrongContext bool
skipContinuation bool
@@ -73,6 +74,9 @@ func (p *scriptedReadinessProvider) ChatStream(ctx context.Context, req provider
last := req.Messages[len(req.Messages)-1]
if last.ToolResult != nil {
+ if p.continuationErr != nil {
+ return p.continuationErr
+ }
if p.skipContinuation {
callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{StopReason: "end_turn", InputTokens: 100, OutputTokens: 10}})
return nil
@@ -411,3 +415,62 @@ func TestPatrolRuntimeReadinessUsesAdvisorForSelectedAutonomyMode(t *testing.T)
t.Fatalf("unassessed higher autonomy should remain advisory in the MVP: %+v", readiness)
}
}
+
+func TestRunPatrolModelReadinessWithProvider_IncompleteContinuationIsNotLatencyFailure(t *testing.T) {
+ provider := &scriptedReadinessProvider{contextWindow: 32768, continuationErr: errors.New("provider rejected continuation request")}
+ result := runPatrolModelReadinessWithProvider(context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider)
+ encoded, err := json.Marshal(result)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("readiness evidence: %s", encoded)
+
+ if result.Success || result.PatrolCapable || result.MaxVerifiedMode != "" {
+ t.Fatalf("incomplete provider evaluation must not authorize Patrol: %+v", result)
+ }
+ if result.Dimensions.Latency.Status != PatrolModelReadinessNotAssessed {
+ t.Fatalf("unfinished evaluation is not measured latency failure: %+v", result.Dimensions.Latency)
+ }
+ if result.Dimensions.ToolProtocol.Passed != 3 || result.Dimensions.ContextQuality.Passed != 2 {
+ t.Fatalf("completed evidence must survive: %+v", result.Dimensions)
+ }
+ if result.Modes.Monitor.Status != PatrolModeNotAssessed || result.Cause != PatrolFailureCauseProviderConnection {
+ t.Fatalf("preserve provider failure without asserting model incapability: %+v", result)
+ }
+}
+
+func TestPatrolReadinessCacheCorrectsLegacyIncompleteLatency(t *testing.T) {
+ persistence := config.NewConfigPersistence(t.TempDir())
+ cfg := readinessTestConfig()
+ service := NewService(persistence, nil)
+ service.cfg = cfg
+ result := runPatrolModelReadinessWithProvider(context.Background(), cfg, config.AIProviderOllama, "test-model", "ollama:test-model", &scriptedReadinessProvider{contextWindow: 32768, continuationErr: errors.New("provider rejected continuation request")})
+ result.Dimensions.Latency = PatrolModelReadinessDimension{Status: PatrolModelReadinessFail, Summary: "Latency could not be measured because the streaming probe did not complete."}
+ result.Modes.Monitor.Status = PatrolModeNotSuitable
+ result.CacheKey = service.patrolModelReadinessCacheKey(cfg, result.Provider, result.Model)
+ at := time.Now()
+ service.recordPatrolModelReadiness(result, at)
+ reloaded := NewService(persistence, nil)
+ reloaded.cfg = cfg
+ cached, recordedAt := reloaded.CachedPatrolModelReadiness()
+ if cached == nil {
+ t.Fatal("expected retained evidence")
+ }
+ if cached.Success || cached.PatrolCapable || cached.MaxVerifiedMode != "" {
+ t.Fatalf("cache correction must not authorize Patrol: %+v", cached)
+ }
+ if cached.Dimensions.Latency.Status != PatrolModelReadinessNotAssessed || cached.Modes.Monitor.Status != PatrolModeNotAssessed {
+ t.Fatalf("legacy incomplete probe still misclassified: %+v", cached)
+ }
+ for _, mode := range []string{config.PatrolAutonomyMonitor, config.PatrolAutonomyApproval, config.PatrolAutonomyAssisted, config.PatrolAutonomyFull} {
+ cfg.PatrolAutonomyLevel = mode
+ cached.CacheKey = reloaded.patrolModelReadinessCacheKey(cfg, cached.Provider, cached.Model)
+ reloaded.recordPatrolModelReadiness(*cached, at.Add(time.Second))
+ if readiness := reloaded.PatrolRuntimeReadiness(); readiness.Ready {
+ t.Fatalf("unassessed Watch must block %s, got %+v", mode, readiness)
+ }
+ }
+ if !recordedAt.Equal(at) || cached.Cause != result.Cause || cached.Dimensions.ToolProtocol.Passed != 3 || cached.Dimensions.ContextQuality.Passed != 2 {
+ t.Fatalf("recorded evidence changed: %+v", cached)
+ }
+}
diff --git a/internal/ai/patrol_readiness.go b/internal/ai/patrol_readiness.go
index 34d4646e3e..48d88242af 100644
--- a/internal/ai/patrol_readiness.go
+++ b/internal/ai/patrol_readiness.go
@@ -230,15 +230,21 @@ func (s *Service) PatrolRuntimeReadiness() PatrolConfigReadiness {
switch suitability.Status {
case PatrolModeVerified:
return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessReady, PatrolFailureCauseNone, suitability.Summary)
- case PatrolModeWarning, PatrolModeNotAssessed:
+ case PatrolModeWarning:
return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessWarning, advisor.Cause, suitability.Summary)
- default:
- cause := advisor.Cause
- if cause == PatrolFailureCauseNone || cause == "" {
- cause = PatrolFailureCauseModelToolSupportUnverified
+ case PatrolModeNotAssessed:
+ // Preserve operator-cancellation semantics and higher-mode canary
+ // guidance after verified Watch. A failed provider evaluation with
+ // unassessed Watch cannot authorize a run through a warning status.
+ if advisor.Modes.Monitor.Status == PatrolModeVerified || advisor.Cause == PatrolFailureCauseInterrupted {
+ return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessWarning, advisor.Cause, suitability.Summary)
}
- return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessNotReady, cause, suitability.Summary)
}
+ cause := advisor.Cause
+ if cause == PatrolFailureCauseNone || cause == "" {
+ cause = PatrolFailureCauseModelToolSupportUnverified
+ }
+ return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessNotReady, cause, suitability.Summary)
}
func patrolPreflightReadinessSummary(result *PatrolPreflightResult) string {
diff --git a/internal/ai/tools/adapters.go b/internal/ai/tools/adapters.go
index 62d5c5ec7b..f8d9c101ac 100644
--- a/internal/ai/tools/adapters.go
+++ b/internal/ai/tools/adapters.go
@@ -3,6 +3,7 @@ package tools
import (
"context"
"fmt"
+ "sort"
"strings"
"time"
@@ -11,6 +12,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/recovery"
recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
)
// AlertManagerToolAdapter adapts alerts.Manager to AlertProvider interface
@@ -246,19 +248,25 @@ type MetricsSource interface {
// MetricsHistoryToolAdapter adapts the metrics history to MetricsHistoryProvider interface
type MetricsHistoryToolAdapter struct {
- readState unifiedresources.ReadState
- metricsSource MetricsSource
+ readState unifiedresources.ReadState
+ metricsSource MetricsSource
+ retainedMetrics *metrics.Store
}
// NewMetricsHistoryToolAdapter creates a new adapter for metrics history.
// readState is required for iterating VMs/Containers/Nodes in GetAllMetricsSummary.
-func NewMetricsHistoryToolAdapter(metricsSource MetricsSource, readState unifiedresources.ReadState) *MetricsHistoryToolAdapter {
+func NewMetricsHistoryToolAdapter(metricsSource MetricsSource, readState unifiedresources.ReadState, retained ...*metrics.Store) *MetricsHistoryToolAdapter {
if metricsSource == nil || readState == nil {
return nil
}
+ var store *metrics.Store
+ if len(retained) > 0 {
+ store = retained[0]
+ }
return &MetricsHistoryToolAdapter{
- readState: readState,
- metricsSource: metricsSource,
+ retainedMetrics: store,
+ readState: readState,
+ metricsSource: metricsSource,
}
}
@@ -385,6 +393,8 @@ func mergeMetricsByTimestamp(allMetrics map[string][]RawMetricPoint) []MetricPoi
result = append(result, *p)
}
+ sort.Slice(result, func(i, j int) bool { return result[i].Timestamp.Before(result[j].Timestamp) })
+
return result
}
diff --git a/internal/ai/tools/infrastructure_low_coverage_test.go b/internal/ai/tools/infrastructure_low_coverage_test.go
index f51e9b8dd5..7b5e4c85d4 100644
--- a/internal/ai/tools/infrastructure_low_coverage_test.go
+++ b/internal/ai/tools/infrastructure_low_coverage_test.go
@@ -652,7 +652,7 @@ func TestExecuteListPhysicalDisks(t *testing.T) {
UnifiedResourceProvider: diskProvider,
})
result, err := exec.executeListPhysicalDisks(ctx, map[string]interface{}{
- "type": "sata",
+ "disk_type": "sata",
})
require.NoError(t, err)
diff --git a/internal/ai/tools/resource_metrics.go b/internal/ai/tools/resource_metrics.go
new file mode 100644
index 0000000000..6efb8d9c64
--- /dev/null
+++ b/internal/ai/tools/resource_metrics.go
@@ -0,0 +1,62 @@
+package tools
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// resourceMetricsTargetResolver is the optional capability the unified
+// resource provider exposes for translating canonical resource IDs into
+// metrics-store query targets. The production provider (the monitor's
+// unified adapter) implements it; lightweight fixtures may not.
+type resourceMetricsTargetResolver interface {
+ MetricsTargetForResource(resourceID string) *unifiedresources.MetricsTarget
+}
+
+// resourceMetricsTarget resolves the metrics-store target for a unified
+// resource, asking the provider's on-demand resolver first (registry targets
+// are computed lazily; the struct field is only populated by fixtures).
+func (e *PulseToolExecutor) resourceMetricsTarget(res unifiedresources.Resource) *unifiedresources.MetricsTarget {
+ if resolver, ok := e.unifiedResourceProvider.(resourceMetricsTargetResolver); ok && resolver != nil {
+ if target := resolver.MetricsTargetForResource(res.ID); target != nil {
+ return target
+ }
+ }
+ return res.MetricsTarget
+}
+
+// resolvePerformanceResource keeps canonical identity separate from metrics-store
+// coordinates. Names and provider IDs are accepted only when unambiguous.
+func (e *PulseToolExecutor) resolvePerformanceResource(reference, kind string) (unifiedresources.Resource, error) {
+ reference = strings.TrimSpace(reference)
+ var matches []unifiedresources.Resource
+ for _, resourceType := range []unifiedresources.ResourceType{
+ unifiedresources.ResourceTypeAgent, unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeSystemContainer,
+ } {
+ if kind != "" && canonicalQueryResourceType(kind) != string(resourceType) {
+ continue
+ }
+ for _, resource := range e.unifiedResourceProvider.GetByType(resourceType) {
+ if resource.ID == reference {
+ return resource, nil
+ }
+ candidates := []string{resource.Name, resourceDisplayName(resource), canonicalGuestManagedID(resource)}
+ candidates = append(candidates, resource.Identity.Hostnames...)
+ if target := e.resourceMetricsTarget(resource); target != nil {
+ candidates = append(candidates, target.ResourceID)
+ }
+ if matchesCanonicalResourceReference(resource, reference, candidates...) {
+ matches = append(matches, resource)
+ }
+ }
+ }
+ if len(matches) == 1 {
+ return matches[0], nil
+ }
+ if len(matches) > 1 {
+ return unifiedresources.Resource{}, fmt.Errorf("resource reference %q is ambiguous; use a canonical resource ID from pulse_query", reference)
+ }
+ return unifiedresources.Resource{}, fmt.Errorf("resource %q was not found for performance metrics; use pulse_query to find its canonical ID", reference)
+}
diff --git a/internal/ai/tools/resource_metrics_test.go b/internal/ai/tools/resource_metrics_test.go
new file mode 100644
index 0000000000..3ab8aee7e2
--- /dev/null
+++ b/internal/ai/tools/resource_metrics_test.go
@@ -0,0 +1,74 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/stretchr/testify/require"
+)
+
+func TestPerformanceMetricsCanonicalIdentity(t *testing.T) {
+ provider := newSummarizeStubProvider()
+ history := &mockMetricsHistoryProvider{}
+ history.On("GetResourceMetrics", "delly-node-id", 24*time.Hour).Return([]MetricPoint{{CPU: 23, Memory: 41}}, nil)
+ executor := NewPulseToolExecutor(ExecutorConfig{StateProvider: &mockStateProvider{}})
+ executor.unifiedResourceProvider = provider
+ executor.metricsHistory = history
+ for _, ref := range []string{"host-abc123", "delly", "delly-node-id"} {
+ for _, kind := range []string{"agent", "node", ""} {
+ result, err := executor.ExecuteTool(context.Background(), agentcapabilities.PulseMetricsToolName, map[string]interface{}{"type": "performance", "resource_id": ref, "resource_type": kind})
+ require.NoError(t, err)
+ require.False(t, result.IsError, "%+v", result)
+ var response MetricsResponse
+ require.NoError(t, json.Unmarshal([]byte(result.Content[0].Text), &response))
+ require.Equal(t, "host-abc123", response.ResourceID)
+ require.Len(t, response.Points, 1)
+ require.Equal(t, 23.0, response.Points[0].CPU)
+ }
+ }
+ history.AssertNumberOfCalls(t, "GetResourceMetrics", 9)
+ provider.byType[unifiedresources.ResourceTypeAgent] = append(provider.byType[unifiedresources.ResourceTypeAgent], unifiedresources.Resource{ID: "agent-second", Type: unifiedresources.ResourceTypeAgent, Name: "delly"})
+ for _, ref := range []string{"delly", "absent-resource"} {
+ result, err := executor.executeGetMetrics(context.Background(), map[string]interface{}{"resource_id": ref})
+ require.NoError(t, err)
+ require.True(t, result.IsError)
+ }
+ history.AssertNumberOfCalls(t, "GetResourceMetrics", 9)
+ history.AssertExpectations(t)
+}
+
+func TestDiskMetricsRoutingPreservesFilters(t *testing.T) {
+ provider := newSummarizeStubProvider()
+ provider.byType[unifiedresources.ResourceTypePhysicalDisk] = []unifiedresources.Resource{
+ {ID: "disk-nvme", Type: unifiedresources.ResourceTypePhysicalDisk, ParentName: "Friendly host", Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"delly"}}, PhysicalDisk: &unifiedresources.PhysicalDiskMeta{DiskType: "nvme", Health: "PASSED", Temperature: 39}},
+ {ID: "disk-sata", Type: unifiedresources.ResourceTypePhysicalDisk, ParentName: "Friendly host", Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"delly"}}, PhysicalDisk: &unifiedresources.PhysicalDiskMeta{DiskType: "sata", Health: "FAILED", Temperature: 52}},
+ }
+ executor := NewPulseToolExecutor(ExecutorConfig{StateProvider: &mockStateProvider{}})
+ executor.unifiedResourceProvider = provider
+ for _, tc := range []struct {
+ format string
+ count int
+ }{{"", 2}, {"nvme", 1}, {"sas", 0}} {
+ result, err := executor.ExecuteTool(context.Background(), agentcapabilities.PulseMetricsToolName, map[string]interface{}{"type": "disks", "node": "delly", "disk_type": tc.format})
+ require.NoError(t, err)
+ require.False(t, result.IsError)
+ var response PhysicalDisksResponse
+ require.NoError(t, json.Unmarshal([]byte(result.Content[0].Text), &response))
+ require.Len(t, response.Disks, tc.count)
+ require.Equal(t, tc.count, response.Filtered)
+ }
+}
+
+func TestQueryNodeAliasReturnsCanonicalAgent(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{StateProvider: &mockStateProvider{}})
+ executor.unifiedResourceProvider = newSummarizeStubProvider()
+ result, err := executor.ExecuteTool(context.Background(), agentcapabilities.PulseQueryToolName, map[string]interface{}{"action": "get", "resource_type": "node", "resource_id": "delly"})
+ require.NoError(t, err)
+ require.False(t, result.IsError, "%+v", result)
+ require.Contains(t, result.Content[0].Text, "host-abc123")
+ require.Contains(t, result.Content[0].Text, `"type":"agent"`)
+}
diff --git a/internal/ai/tools/retained_metrics.go b/internal/ai/tools/retained_metrics.go
new file mode 100644
index 0000000000..75510dddaf
--- /dev/null
+++ b/internal/ai/tools/retained_metrics.go
@@ -0,0 +1,46 @@
+package tools
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// GetResourceMetricsForTarget reads the retained store using the registry's
+// metrics coordinates. A process restart must not shorten a requested history
+// window. The in-memory source remains available on installations without a store.
+func (a *MetricsHistoryToolAdapter) GetResourceMetricsForTarget(target unifiedresources.MetricsTarget, period time.Duration) ([]MetricPoint, error) {
+ if a.retainedMetrics == nil {
+ return a.GetResourceMetrics(target.ResourceID, period)
+ }
+ var storeTypes []string
+ switch target.ResourceType {
+ case "agent":
+ storeTypes = []string{"agent", "node"}
+ case "node", "vm":
+ storeTypes = []string{target.ResourceType}
+ case "system-container", "container":
+ storeTypes = []string{"container"}
+ default:
+ return nil, fmt.Errorf("unsupported metrics target type %q", target.ResourceType)
+ }
+ end := time.Now()
+ start := end.Add(-period)
+ for _, storeType := range storeTypes {
+ observations := make(map[string][]RawMetricPoint)
+ for _, metric := range []string{"cpu", "memory", "disk"} {
+ points, err := a.retainedMetrics.Query(storeType, target.ResourceID, metric, start, end, 0)
+ if err != nil {
+ return nil, err
+ }
+ for _, point := range points {
+ observations[metric] = append(observations[metric], RawMetricPoint{Timestamp: point.Timestamp, Value: point.Value})
+ }
+ }
+ if len(observations) > 0 {
+ return mergeMetricsByTimestamp(observations), nil
+ }
+ }
+ return nil, nil
+}
diff --git a/internal/ai/tools/retained_metrics_test.go b/internal/ai/tools/retained_metrics_test.go
new file mode 100644
index 0000000000..176661cc9f
--- /dev/null
+++ b/internal/ai/tools/retained_metrics_test.go
@@ -0,0 +1,72 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
+ "github.com/stretchr/testify/require"
+)
+
+func TestPerformanceMetricsRetainedAcrossRestart(t *testing.T) {
+ cfg := metrics.DefaultConfig(t.TempDir())
+ cfg.RetentionRaw = 8 * 24 * time.Hour
+ store, err := metrics.NewStore(cfg)
+ require.NoError(t, err)
+ at := time.Now().Add(-6 * time.Hour).Truncate(time.Second)
+ for _, family := range []string{"node", "agent", "vm", "container"} {
+ store.Write(family, family+"-native", "cpu", 37, at)
+ store.Write(family, family+"-native", "memory", 62, at)
+ }
+ require.NoError(t, store.Close())
+ store, err = metrics.NewStore(cfg)
+ require.NoError(t, err)
+ defer store.Close()
+ adapter := NewMetricsHistoryToolAdapter(&fakeMetricsSource{}, &fakeReadState{}, store)
+ for _, tc := range []struct{ kind, family string }{{"agent", "node"}, {"agent", "agent"}, {"vm", "vm"}, {"system-container", "container"}} {
+ t.Run(tc.family, func(t *testing.T) {
+ resource := unifiedresources.Resource{ID: "canonical-" + tc.family, Type: unifiedresources.ResourceType(tc.kind), Name: "machine-" + tc.family, MetricsTarget: &unifiedresources.MetricsTarget{ResourceType: tc.kind, ResourceID: tc.family + "-native"}}
+ executor := NewPulseToolExecutor(ExecutorConfig{StateProvider: &mockStateProvider{}, MetricsHistory: adapter, UnifiedResourceProvider: &stubUnifiedResourceProvider{resources: []unifiedresources.Resource{resource}}})
+ result, err := executor.executeGetMetrics(context.Background(), map[string]interface{}{"resource_id": resource.ID, "period": "24h"})
+ require.NoError(t, err)
+ require.False(t, result.IsError)
+ var response MetricsResponse
+ require.NoError(t, json.Unmarshal([]byte(result.Content[0].Text), &response))
+ require.Equal(t, resource.ID, response.ResourceID)
+ require.Len(t, response.Points, 1)
+ require.Equal(t, at.Unix(), response.Points[0].Timestamp.Unix())
+ require.Equal(t, 37.0, response.Points[0].CPU)
+ require.Equal(t, 62.0, response.Points[0].Memory)
+ })
+ }
+ // A store failure must not become a successful empty history or fall back to
+ // shorter in-memory history, which could change the operator's conclusion.
+ require.NoError(t, store.Close())
+ _, err = adapter.GetResourceMetricsForTarget(unifiedresources.MetricsTarget{ResourceType: "agent", ResourceID: "node-native"}, 24*time.Hour)
+ require.Error(t, err)
+}
+
+func TestCanonicalAgentCPUCountUsesAvailableSource(t *testing.T) {
+ resource := unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent, Proxmox: &unifiedresources.ProxmoxData{CPUs: 12}}
+ require.Equal(t, 12, canonicalAgentResponse(resource, nil).CPU.Cores)
+ resource.Proxmox.CPUInfo = &unifiedresources.CPUInfo{Cores: 6, Sockets: 2}
+ resource.Proxmox.CPUs = 0
+ require.Equal(t, 12, canonicalAgentResponse(resource, nil).CPU.Cores)
+ resource.Agent = &unifiedresources.AgentData{}
+ require.Equal(t, 12, canonicalAgentResponse(resource, nil).CPU.Cores)
+ resource.Agent.CPUCount = 16
+ require.Equal(t, 16, canonicalAgentResponse(resource, nil).CPU.Cores)
+}
+
+func TestMergedMetricsAreChronological(t *testing.T) {
+ start := time.Now().Add(-time.Hour).Truncate(time.Second)
+ points := mergeMetricsByTimestamp(map[string][]RawMetricPoint{"cpu": {{Value: 3, Timestamp: start.Add(2 * time.Minute)}, {Value: 1, Timestamp: start}, {Value: 2, Timestamp: start.Add(time.Minute)}}})
+ require.Len(t, points, 3)
+ for i, point := range points {
+ require.Equal(t, float64(i+1), point.CPU)
+ require.Equal(t, start.Add(time.Duration(i)*time.Minute), point.Timestamp)
+ }
+}
diff --git a/internal/ai/tools/tools_metrics.go b/internal/ai/tools/tools_metrics.go
index 0287a9f508..810426106a 100644
--- a/internal/ai/tools/tools_metrics.go
+++ b/internal/ai/tools/tools_metrics.go
@@ -47,7 +47,7 @@ Examples:
},
"resource_type": {
Type: "string",
- Description: "Filter by canonical v6 resource type: vm, system-container, node (for performance, baselines)",
+ Description: "Filter by resource type: agent, vm, system-container (performance). The node alias is also accepted. Baselines accept vm, system-container, node.",
},
"host": {
Type: "string",
@@ -136,12 +136,12 @@ func (e *PulseToolExecutor) executeGetMetrics(_ context.Context, args map[string
resourceType = strings.ToLower(strings.TrimSpace(resourceType))
if resourceType != "" {
if isLegacyMetricsResourceTypeInput(resourceType) {
- return NewErrorResult(fmt.Errorf("invalid resource_type: %s. Use vm, system-container, or node", resourceType)), nil
+ return NewErrorResult(fmt.Errorf("invalid resource_type: %s. Use agent, vm, or system-container (node is an alias)", resourceType)), nil
}
resourceType = canonicalMetricsResourceType(resourceType)
- validTypes := map[string]bool{"vm": true, "system-container": true, "node": true}
+ validTypes := map[string]bool{"agent": true, "vm": true, "system-container": true, "node": true}
if !validTypes[resourceType] {
- return NewErrorResult(fmt.Errorf("invalid resource_type: %s. Use vm, system-container, or node", resourceType)), nil
+ return NewErrorResult(fmt.Errorf("invalid resource_type: %s. Use agent, vm, or system-container (node is an alias)", resourceType)), nil
}
}
@@ -165,7 +165,30 @@ func (e *PulseToolExecutor) executeGetMetrics(_ context.Context, args map[string
if resourceID != "" {
response.ResourceID = resourceID
- metrics, err := e.metricsHistory.GetResourceMetrics(resourceID, duration)
+ metricsID := resourceID
+ var metricsTarget *unifiedresources.MetricsTarget
+ if e.unifiedResourceProvider != nil {
+ resource, err := e.resolvePerformanceResource(resourceID, resourceType)
+ if err != nil {
+ return NewErrorResult(err), nil
+ }
+ response.ResourceID = resource.ID
+ target := e.resourceMetricsTarget(resource)
+ if target == nil || strings.TrimSpace(target.ResourceID) == "" {
+ return NewTextResult(fmt.Sprintf("No metrics target is available for resource %s.", resource.ID)), nil
+ }
+ metricsID = target.ResourceID
+ metricsTarget = target
+ }
+ var metrics []MetricPoint
+ var err error
+ if retained, ok := e.metricsHistory.(interface {
+ GetResourceMetricsForTarget(unifiedresources.MetricsTarget, time.Duration) ([]MetricPoint, error)
+ }); ok && metricsTarget != nil {
+ metrics, err = retained.GetResourceMetricsForTarget(*metricsTarget, duration)
+ } else {
+ metrics, err = e.metricsHistory.GetResourceMetrics(metricsID, duration)
+ }
if err != nil {
return NewErrorResult(err), nil
}
@@ -189,7 +212,7 @@ func (e *PulseToolExecutor) executeGetMetrics(_ context.Context, args map[string
keys := make([]string, 0, len(summary))
for id, metric := range summary {
metricType := canonicalMetricsResourceType(metric.ResourceType)
- if resourceType != "" && metricType != resourceType {
+ if resourceType != "" && canonicalQueryResourceType(metricType) != canonicalQueryResourceType(resourceType) {
continue
}
keys = append(keys, id)
@@ -688,7 +711,7 @@ func (e *PulseToolExecutor) executeListPhysicalDisks(_ context.Context, args map
instanceFilter, _ := args["instance"].(string)
nodeFilter, _ := args["node"].(string)
healthFilter, _ := args["health"].(string)
- typeFilter, _ := args["type"].(string)
+ typeFilter, _ := args["disk_type"].(string)
limit := intArg(args, "limit", 100)
// Prefer unified resources when available
@@ -707,10 +730,7 @@ func (e *PulseToolExecutor) executeListPhysicalDisks(_ context.Context, args map
continue
}
- node := r.ParentName
- if node == "" && len(r.Identity.Hostnames) > 0 {
- node = r.Identity.Hostnames[0]
- }
+ node := canonicalPhysicalDiskHost(r)
// Apply filters
if instanceFilter != "" {
diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.go
index 290991832f..1950524279 100644
--- a/internal/ai/tools/tools_query.go
+++ b/internal/ai/tools/tools_query.go
@@ -2166,7 +2166,7 @@ func (e *PulseToolExecutor) registerQueryTools() {
},
"resource_type": {
Type: "string",
- Description: "Resource type. For get/search, prefer canonical values: 'agent', 'vm', 'system-container', 'app-container', 'storage', 'physical-disk', 'node', and 'docker-host'. Compatibility aliases 'system' and 'storage-pool' are still accepted. For config: 'vm', 'system-container', or supported API-backed 'app-container'.",
+ Description: "Resource type. For get/search, prefer canonical values: 'agent', 'vm', 'system-container', 'app-container', 'storage', 'physical-disk', and 'docker-host'. For get, 'node' resolves to 'agent'. For search, 'node' filters Proxmox nodes. Compatibility aliases 'system' and 'storage-pool' are still accepted. For config: 'vm', 'system-container', or supported API-backed 'app-container'.",
Enum: []string{"agent", "system", "vm", "system-container", "app-container", "node", "docker-host", "storage", "storage-pool", "physical-disk"},
},
"resource_id": {
@@ -2261,7 +2261,7 @@ func (e *PulseToolExecutor) registerQueryTools() {
func canonicalQueryResourceType(resourceType string) string {
switch strings.ToLower(strings.TrimSpace(resourceType)) {
- case "system":
+ case "system", "node":
return "agent"
case "storage-pool":
return "storage"
@@ -3319,9 +3319,15 @@ func canonicalAgentResponse(resource unifiedresources.Resource, governance *gove
}
}
response.Tags = append([]string{}, resource.Tags...)
+ if resource.Proxmox != nil {
+ response.CPU.Cores = unifiedresources.NewNodeView(&resource).CPUs()
+ }
+
if resource.Agent != nil {
response.OS = strings.TrimSpace(resource.Agent.OSName)
- response.CPU.Cores = resource.Agent.CPUCount
+ if resource.Agent.CPUCount > 0 {
+ response.CPU.Cores = resource.Agent.CPUCount
+ }
}
if response.Host == "" && resource.TrueNAS != nil {
response.Host = strings.TrimSpace(resource.TrueNAS.Hostname)
diff --git a/internal/ai/tools/tools_summarize.go b/internal/ai/tools/tools_summarize.go
index db2681a0f4..49219c5340 100644
--- a/internal/ai/tools/tools_summarize.go
+++ b/internal/ai/tools/tools_summarize.go
@@ -249,14 +249,6 @@ type summarizeFleetEntry struct {
Name string `json:"name,omitempty"`
}
-// summarizeMetricsTargetResolver is the optional capability the unified
-// resource provider exposes for translating canonical resource IDs into
-// metrics-store query targets. The production provider (the monitor's
-// unified adapter) implements it; lightweight fixtures may not.
-type summarizeMetricsTargetResolver interface {
- MetricsTargetForResource(resourceID string) *unifiedresources.MetricsTarget
-}
-
// summarizeFleetCandidate is a unified resource resolved into the reporting
// engine's request shape: a reporting resource type, the canonical resource
// ID (which keys Patrol findings and recovery points), and the metrics-store
@@ -325,18 +317,6 @@ func summarizeReportTypeForResource(res unifiedresources.Resource) string {
}
}
-// summarizeMetricsTarget resolves the metrics-store target for a unified
-// resource, asking the provider's on-demand resolver first (registry targets
-// are computed lazily; the struct field is only populated by fixtures).
-func (e *PulseToolExecutor) summarizeMetricsTarget(res unifiedresources.Resource) *unifiedresources.MetricsTarget {
- if resolver, ok := e.unifiedResourceProvider.(summarizeMetricsTargetResolver); ok && resolver != nil {
- if target := resolver.MetricsTargetForResource(res.ID); target != nil {
- return target
- }
- }
- return res.MetricsTarget
-}
-
// summarizeFleetCandidateFor projects a unified resource into a fleet
// candidate, mirroring the API report path's resolveReportSubject: the
// canonical ID stays the request ResourceID (findings and recovery points key
@@ -358,7 +338,7 @@ func (e *PulseToolExecutor) summarizeFleetCandidateFor(res unifiedresources.Reso
name: strings.TrimSpace(res.Name),
status: string(res.Status),
}
- if target := e.summarizeMetricsTarget(res); target != nil {
+ if target := e.resourceMetricsTarget(res); target != nil {
cand.metricsID = strings.TrimSpace(target.ResourceID)
if reportType != "node" {
if canonical := reporting.CanonicalResourceType(target.ResourceType); canonical != "" {
diff --git a/internal/ai/tools/tools_summarize_test.go b/internal/ai/tools/tools_summarize_test.go
index 66b9f9bf15..79555ee861 100644
--- a/internal/ai/tools/tools_summarize_test.go
+++ b/internal/ai/tools/tools_summarize_test.go
@@ -377,7 +377,7 @@ func TestSummarizeTool_FleetUsesFleetNarratorWhenConfigured(t *testing.T) {
// The production unified provider (the monitor adapter) must satisfy the
// on-demand metrics-target resolver, or fleet enumeration silently degrades
// to fixture-populated targets only.
-var _ summarizeMetricsTargetResolver = (*unifiedresources.MonitorAdapter)(nil)
+var _ resourceMetricsTargetResolver = (*unifiedresources.MonitorAdapter)(nil)
// stubSummarizeResourceProvider implements UnifiedResourceProvider plus the
// on-demand metrics-target resolver the production monitor adapter exposes.
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 2dc5cc7455..2a89407cda 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -5253,6 +5253,13 @@ func (h *AISettingsHandler) buildPatrolReadiness(ctx context.Context, aiService
}
addCheck("model", patrolReadinessReady, ai.PatrolFailureCauseNone, "Patrol model", "Patrol has a model selected from a configured provider.", "")
+ // Execution authority comes from the runtime's selected-mode verdict.
+ // Display-only dimension warnings must not turn an incomplete evaluation
+ // into permission to launch a manual run.
+ if runtime := aiService.PatrolRuntimeReadiness(); !runtime.Ready {
+ addCheck("runtime", patrolReadinessNotReady, runtime.Cause, "Patrol execution", runtime.Summary, "open_provider_settings")
+ }
+
toolStatus, toolCause, toolMessage, toolAction := resolvePatrolToolsCheck(aiService, provider, model)
addCheck("tools", toolStatus, toolCause, "Patrol tools", toolMessage, toolAction)
if advisor, recordedAt := aiService.CachedPatrolModelReadiness(); advisor != nil && !recordedAt.IsZero() {
diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.go
index 86e7fbfeca..8a0eaa4422 100644
--- a/internal/api/ai_handlers_patrol_actions_additional_test.go
+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go
@@ -2,9 +2,12 @@ package api
import (
"bytes"
+ "context"
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -1101,6 +1104,82 @@ func TestHandleForcePatrol_BlocksNotReadyPatrolModel(t *testing.T) {
}
}
+func TestHandleForcePatrol_BlocksIncompleteContinuationDespitePassingDimensions(t *testing.T) {
+ provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "provider unavailable", http.StatusServiceUnavailable)
+ }))
+ defer provider.Close()
+
+ tmp := t.TempDir()
+ cfg := &config.Config{DataPath: tmp}
+ persistence := config.NewConfigPersistence(tmp)
+ aiCfg := config.NewDefaultAIConfig()
+ aiCfg.Enabled = true
+ aiCfg.Model = "ollama:test-model"
+ aiCfg.PatrolModel = aiCfg.Model
+ aiCfg.OllamaBaseURL = provider.URL
+ if err := persistence.SaveAIConfig(*aiCfg); err != nil {
+ t.Fatal(err)
+ }
+ handler := newTestAISettingsHandler(cfg, persistence, nil)
+ // Obtain the production cache identity against a local provider, then
+ // reproduce a saved evaluation whose continuation failed after its probes.
+ result := handler.defaultAIService.RunPatrolModelReadiness(context.Background(), config.AIProviderOllama, "test-model")
+ if result.CacheKey == "" {
+ t.Fatal("expected a persisted evaluation identity")
+ }
+ result.Success = false
+ result.PatrolCapable = false
+ result.TransportHealthy = true
+ result.Status = ai.PatrolModelReadinessWarning
+ result.Cause = ai.PatrolFailureCauseProviderConnection
+ result.MaxVerifiedMode = ""
+ result.Summary = "Provider stopped before continuation completed."
+ result.Dimensions.Connectivity = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessPass}
+ result.Dimensions.ToolProtocol = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessPass, Attempts: 3, Passed: 3}
+ result.Dimensions.ContextQuality = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessPass, Attempts: 2, Passed: 2}
+ result.Dimensions.Latency = ai.PatrolModelReadinessDimension{Status: ai.PatrolModelReadinessNotAssessed}
+ result.Modes.Monitor = ai.PatrolModeSuitability{Status: ai.PatrolModeNotAssessed, Summary: result.Summary}
+ result.Modes.Approval = ai.PatrolModeSuitability{Status: ai.PatrolModeNotSuitable}
+ payload, err := json.Marshal(struct {
+ Result ai.PatrolModelReadinessResult `json:"result"`
+ CacheKey string `json:"cache_key"`
+ RecordedAt time.Time `json:"recorded_at"`
+ }{result, result.CacheKey, time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(tmp, "ai_patrol_model_readiness.json"), payload, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ handler = newTestAISettingsHandler(cfg, persistence, nil)
+ handler.defaultAIService.SetStateProvider(&stubStateProvider{})
+ if cached, _ := handler.defaultAIService.CachedPatrolModelReadiness(); cached == nil {
+ t.Fatal("expected the saved evaluation to survive restart")
+ }
+ readiness := handler.buildPatrolReadiness(context.Background(), handler.defaultAIService, true)
+ for _, id := range []string{"tools", "context_quality", "latency"} {
+ if check := requirePatrolReadinessCheck(t, readiness, id); check.Status == patrolReadinessNotReady {
+ t.Fatalf("display dimension %s unexpectedly blocks the fixture: %+v", id, check)
+ }
+ }
+ if check := requirePatrolReadinessCheck(t, readiness, "runtime"); check.Status != patrolReadinessNotReady {
+ t.Fatalf("execution check = %+v, want not ready", check)
+ }
+ rec := httptest.NewRecorder()
+ handler.HandleForcePatrol(rec, newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil))
+ if rec.Code != http.StatusConflict {
+ t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())
+ }
+ var response APIError
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code != "patrol_readiness_not_ready" {
+ t.Fatalf("code = %q, want patrol_readiness_not_ready", response.Code)
+ }
+}
+
func TestHandleForcePatrol_CommunityTierIgnoresRecentScopedActivityForFullPatrolRateLimit(t *testing.T) {
handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
seedReadyAnthropicPatrolRuntime(t, handler)
diff --git a/internal/api/router.go b/internal/api/router.go
index d81c243e36..6b7157532a 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -3294,6 +3294,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A
metricsAdapter := tools.NewMetricsHistoryToolAdapter(
&metricsSourceWrapper{history: metricsHistory},
monitor.GetUnifiedReadState(),
+ monitor.GetMetricsStore(),
)
if metricsAdapter != nil {
service.SetMetricsHistory(metricsAdapter)