Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Remove Assistant and Patrol tool-routing heuristics
rcourtman0561a1b5fa7d
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 0062d39ddc..58969ea9f3 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -2790,6 +2790,17 @@"TestSessionStore_List|TestService_ExecuteStream_AttachesModelOnlyHandoffContext"]},+ {+ "id": "patrol-model-owned-probe-runtime-tests",+ "run": [+ "go",+ "test",+ "./internal/ai",+ "-run",+ "TestRunAIAnalysis_TriageQuietStillCallsLLM|TestRunEvaluationPass",+ "-count=1"+ ]+ },{"id": "patrol-model-owned-remediation-runtime-tests","run": [@@ -2799,6 +2810,15 @@"-run","TestPatrolService_RecordFindingDoesNotGenerateTemplateRemediationPlan|TestShouldResolveAlert|TestReviewAndResolveAlerts"]+ },+ {+ "id": "patrol-unified-finding-no-auto-remediation-tests",+ "run": [+ "go",+ "test",+ "./internal/ai/unified",+ "-count=1"+ ]}],"evidence": [@@ -2902,6 +2922,11 @@"path": "internal/ai/chat/types.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/ai/patrol_ai.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/ai/patrol_findings.go",@@ -2911,6 +2936,21 @@"repo": "pulse","path": "internal/ai/patrol_run.go","kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/patrol_triage_integration_test.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/unified/integration.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/unified/integration_test.go",+ "kind": "file"}]},@@ -2950,6 +2990,28 @@"--run","src/components/AI/Chat/__tests__/useChat.test.ts"]+ },+ {+ "id": "assistant-no-automatic-tool-retry-tests",+ "run": [+ "go",+ "test",+ "./internal/ai/chat",+ "-run",+ "TestAgenticLoop_DoesNotAutoRecoverStructuredToolCall|TestEnsureFinalTextResponse|TestCommandExtraction",+ "-count=1"+ ]+ },+ {+ "id": "assistant-tool-policy-facts-tests",+ "run": [+ "go",+ "test",+ "./internal/ai/tools",+ "-run",+ "TestExecuteReadLogs|TestRoutingMismatch|TestWriteExecutionContext|TestExecutionIntent|TestReadExec|TestStrictResolution",+ "-count=1"+ ]}],"evidence": [@@ -2978,6 +3040,16 @@"path": "internal/ai/chat/agentic.go","kind": "file"},+ {+ "repo": "pulse",+ "path": "internal/ai/chat/agentic_additional_test.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/chat/agentic_final.go",+ "kind": "file"+ },{"repo": "pulse","path": "internal/ai/chat/service.go",@@ -2992,6 +3064,26 @@"repo": "pulse","path": "internal/ai/chat/service_tooling_test.go","kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/tools/tools_file.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/tools/tools_query.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/tools/tools_read.go",+ "kind": "file"+ },+ {+ "repo": "pulse",+ "path": "internal/ai/tools/tools_read_test.go",+ "kind": "file"}]}diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 0a56cfe072..60b91be464 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -121,7 +121,7 @@ runtime cost control, and shared AI transport surfaces.1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as OpenAI-compatible `tool_choice` handling, runtime-failure classification splits (for example separating tool-choice request rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier either still detects the failure signal **or returns an inconclusive result** — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate). The fail-closed-on-inconclusive policy treats verifier errors (timeouts, executor unavailability, transport faults) as "we don't know" rather than "go ahead": resolution of an event/persistent finding is effectively permanent (next detection registers as a regression and inflates counters), so the safe default is to refuse and require either a successful re-verification or operator action, the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data, and the patrol-session-bound contract where `ExecutePatrolStream` calls `SessionStore.TrimMessages` after persisting each run's messages to cap the patrol-main session at 200 messages (roughly two recent runs' worth) — without the bound the file grew unbounded at every scheduled run, reaching 16 MB and 3,593 messages within a month and making every `AddMessage` rewrite linearly more expensive; the canonical Patrol forensic log is the `PatrolRunRecord` history surfaced at `/api/ai/patrol/runs`, not the chat-session-shaped file2. Keep AI runtime and shared API proof routing aligned in `registry.json`-3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changes+3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changes. Interactive Assistant and Patrol tool selection must remain model-owned: Pulse may provide governed context, tools, approval state, resource-resolution facts, and safety policy, but it must not add prompt-keyword routers, expected-tool retries, auto-recovery tool calls, or Pulse-authored remediation/finding fallbacks that choose the next investigative or corrective action for the model.Patrol runtime failures are part of that runtime contract: provider, model,tool-calling, auth, quota, rate-limit, context-window, and connectivityfailures must be classified in `internal/ai/` before they reach operators,@@ -1725,9 +1725,9 @@ of dropping the last chunk or leaving tool calls unfinalized on clean close.That same provider-transport boundary owns OpenAI-compatible tool protocoladaptation. Pulse must keep normal tool selection automatic/model-owned forOpenAI-compatible providers, including direct DeepSeek paths. Text-only-`tool_choice=none` remains allowed only as a safety brake when Pulse is-ending a turn after loop, budget, or verification gates; it must not be used-as an intent classifier.+turns reached through loop, budget, or verification gates should omit tools+entirely instead of sending provider-specific `tool_choice=none`; that transport+setting must not be used as an intent classifier.Reasoning-backed provider turns that return tool calls with `reasoning_content`must preserve that reasoning state on the following tool-result turn when theprovider requires it, so Assistant and Patrol can complete multi-turn tool usediff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex e1255ea658..5b79e7e6cd 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -184,7 +184,14 @@ Patrol-specific presentation helpers.is the diagnostic and remediation-reasoning owner. Patrol handoff prompts mayprovide system context, resource posture, action posture, and governed tools,but must not force active tool use, name a required tool path, or present a- Patrol-authored remediation answer for the LLM to execute. Visible Patrol+ Patrol-authored remediation answer for the LLM to execute. Patrol+ runs must still call the configured model when deterministic triage is quiet,+ and unmatched deterministic signals may be returned as context for another+ model pass but must not be converted into Pulse-authored findings after the+ model declines to report them. Legacy unified AI-finding integration must+ likewise store model-reported findings as evidence and must not auto-generate+ remediation plans from finding metadata.+ Visible PatrolAssistant handoffs must not make the operator think Pulse has alreadyproduced the correct fix. The visible Assistant drawer briefing opened from a Patrolfinding must be compact and source-named: current status/risk, one primarydiff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.goindex 0558215a90..6b148ce4af 100644--- a/internal/ai/chat/agentic.go+++ b/internal/ai/chat/agentic.go@@ -257,13 +257,8 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mevar resultMessages []Messageturn := 0- toolsSucceededThisEpisode := false // Track if any tool executed successfully this episode- writeCompletedLastTurn := false // When true, force text-only response on next turn- toolBlockedLastTurn := false // When true, force text-only response after budget/loop block-- // Fresh-data intent: if the user's latest message indicates they want- // fresh/updated data, bypass the knowledge gate so tools re-execute.- userWantsFresh := detectFreshDataIntent(messages)+ writeCompletedLastTurn := false // When true, request final text without offering tools+ toolBlockedLastTurn := false // When true, request final text after budget/loop block// Loop detection: track identical tool calls (name + serialized input).// After maxIdenticalCalls identical invocations, the next one is blocked.@@ -334,39 +329,38 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meExecutionID: a.executionID,}- // Tool selection is model-owned. Pulse exposes the governed tool manifest- // and only applies text-only brakes for loop/budget/FSM safety.+ // Tool selection is model-owned. Pulse normally exposes the governed tool+ // manifest unchanged. When a run must stop for safety or budget reasons,+ // omit tools entirely rather than sending provider-specific tool_choice.textOnlySafetyBrake := falseif turn >= maxTurns-1 {- // Last turn before hitting the limit — force a text-only response so- // the model summarizes its findings instead of silently stopping.- req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceNone}+ // Last turn before hitting the limit: ask the model to summarize with+ // the context already gathered.+ req.Tools = niltextOnlySafetyBrake = truelog.Warn().Int("turn", turn).Int("max_turns", maxTurns).Str("session_id", sessionID).- Msg("[AgenticLoop] Approaching max turns — forcing text-only response for summary")+ Msg("[AgenticLoop] Approaching max turns — omitting tools for final response")} else if writeCompletedLastTurn {// A write action completed successfully on the previous turn.- // Force text-only response so the model summarizes the result instead of- // making more tool calls (which often return stale cached data and cause loops).- req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceNone}+ // Ask for the final response with the execution result already in context.+ req.Tools = niltextOnlySafetyBrake = truewriteCompletedLastTurn = falselog.Debug().Str("session_id", sessionID).- Msg("[AgenticLoop] Write completed last turn — forcing text-only response")+ Msg("[AgenticLoop] Write completed last turn — omitting tools for final response")} else if toolBlockedLastTurn {// Tool calls were blocked last turn (budget exceeded or loop detected).- // The model already has the data it gathered — force it to produce a text- // response instead of continuing to call tools that will just be blocked again.- req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceNone}+ // Ask for a response using the data already gathered.+ req.Tools = niltextOnlySafetyBrake = truetoolBlockedLastTurn = falselog.Debug().Str("session_id", sessionID).- Msg("[AgenticLoop] Tool calls blocked last turn — forcing text-only response")+ Msg("[AgenticLoop] Tool calls blocked last turn — omitting tools for final response")}// Pre-request context validation: catch overflow from message history growth.@@ -394,8 +388,12 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me// Re-build request with compacted messagesreq.Messages = providerMessages- // Re-estimate after compaction- estimatedTokens = EstimateTokens(req.System) + EstimateMessagesTokens(req.Messages) + cachedToolTokens+ // Re-estimate after compaction.+ toolTokensForRequest := cachedToolTokens+ if req.Tools == nil {+ toolTokensForRequest = 0+ }+ estimatedTokens = EstimateTokens(req.System) + EstimateMessagesTokens(req.Messages) + toolTokensForRequestif estimatedTokens > contextLimit {log.Warn().Int("estimated_tokens", estimatedTokens).@@ -404,7 +402,6 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meMsg("[AgenticLoop] Still over limit after compaction - dropping tools for this turn")req.Tools = nil- req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceNone}textOnlySafetyBrake = true// Final check: if system + messages alone still exceed limit,@@ -614,15 +611,14 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mereturn resultMessages, fmt.Errorf("provider error: %w", err)}- // Guard: if a safety brake requested text-only but the model still returned tool calls- // (some providers like Gemini can hallucinate function calls from conversation- // history even when tools are not offered in the request), strip them so the- // model's text content is treated as the final response.+ // Guard: if a safety brake omitted tools but the model still returned tool+ // calls from conversation history, strip them so the model's text content+ // is treated as the final response.if textOnlySafetyBrake && len(toolCalls) > 0 {log.Warn().Str("session_id", sessionID).Int("stripped_tool_calls", len(toolCalls)).- Msg("[AgenticLoop] Model returned tool calls despite ToolChoiceNone — stripping them")+ Msg("[AgenticLoop] Model returned tool calls after tools were omitted — stripping them")toolCalls = nil}@@ -740,49 +736,13 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me}}- // Detect phantom execution: model claims to have done something without tool calls.- // IMPORTANT: Skip this check if tools already succeeded this episode - the model is- // legitimately summarizing tool results, not hallucinating.- log.Debug().- Bool("toolsSucceededThisEpisode", toolsSucceededThisEpisode).- Bool("hasPhantomExecution", hasPhantomExecution(assistantMsg.Content)).- Str("content_preview", truncateForLog(assistantMsg.Content, 200)).- Msg("[AgenticLoop] Phantom detection check")- if !toolsSucceededThisEpisode && hasPhantomExecution(assistantMsg.Content) {- log.Warn().- Str("session_id", sessionID).- Str("content_preview", truncateForLog(assistantMsg.Content, 200)).- Msg("[AgenticLoop] Phantom execution detected - model claims action without tool call")-- // Record telemetry for phantom detection- if metrics := GetAIMetrics(); metrics != nil {- metrics.RecordPhantomDetected(providerName, modelName)- }-- // Replace the response with a safe failure message- safeResponse := "I apologize, but I wasn't able to access the infrastructure tools needed to complete that request. This can happen when:\n\n" +- "1. The tools aren't available right now\n" +- "2. There was a connection issue\n" +- "3. The model I'm running on doesn't support function calling\n\n" +- "Please try again, or let me know if you have a question I can answer without checking live infrastructure."-- // Update the last result message- if len(resultMessages) > 0 {- resultMessages[len(resultMessages)-1].Content = safeResponse- }-- // Send corrected content to callback- jsonData, _ := json.Marshal(ContentData{Text: "\n\n---\n" + safeResponse})- callback(StreamEvent{Type: "content", Data: jsonData})- }-log.Debug().Msg("agentic loop complete - no tool calls")resultMessages = a.ensureFinalTextResponse(ctx, sessionID, resultMessages, providerMessages, callback)return resultMessages, nil}// === Execute tool calls (three-phase pipeline) ===- // Phase 1: Pre-check (sequential) — FSM, loop detection, knowledge gate+ // Phase 1: Pre-check (sequential) — FSM, loop detection, budget checks// Phase 2: Execute (parallel) — actual tool calls via goroutines// Phase 3: Post-process (sequential) — streaming, FSM transitions, KA extractionfirstToolResultText := ""@@ -1030,7 +990,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meif ok && fsmBlockedErr.Recoverable {// Track pending recovery for success correlationfsm.TrackPendingRecovery("FSM_BLOCKED", tc.Name)- // Record auto-recovery attempt (model gets a chance to self-correct)+ // Record that the model received a recoverable policy block.if metrics := GetAIMetrics(); metrics != nil {metrics.RecordAutoRecoveryAttempt("FSM_BLOCKED", tc.Name)}@@ -1118,68 +1078,6 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mecontinue}- // === KNOWLEDGE GATE: Return cached facts for redundant tool calls ===- // Skip gate on first turn if the user explicitly asked for fresh data.- if a.knowledgeAccumulator != nil && !(userWantsFresh && turn == 0) {- if keys := PredictFactKeys(tc.Name, tc.Input); len(keys) > 0 {- var cachedParts []string- for _, key := range keys {- if value, found := a.knowledgeAccumulator.Lookup(key); found {- cachedParts = append(cachedParts, value)- }- }- if len(cachedParts) > 0 {- // Enrich marker-based cache hits with related per-resource facts- for _, key := range keys {- if prefix, ok := MarkerExpansions[key]; ok {- if related := a.knowledgeAccumulator.RelatedFacts(prefix); related != "" {- cachedParts = append(cachedParts, related)- }- }- }- cachedResult := fmt.Sprintf("Already known (from earlier investigation): %s. If you need fresh data, use a different query or approach.", strings.Join(cachedParts, "; "))- anyToolSucceededThisTurn = true-- log.Info().- Str("tool", tc.Name).- Str("session_id", sessionID).- Strs("matched_keys", keys).- Int("cached_parts", len(cachedParts)).- Msg("[AgenticLoop] Knowledge gate: returning cached fact instead of re-executing tool")-- jsonData, _ := json.Marshal(ToolEndData{- ID: tc.ID,- Name: tc.Name,- Input: "",- Output: cachedResult,- Success: true,- })- callback(StreamEvent{Type: "tool_end", Data: jsonData})-- toolResultMsg := Message{- ID: uuid.New().String(),- Role: "user",- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: cachedResult,- IsError: false,- },- }- resultMessages = append(resultMessages, toolResultMsg)- providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: cachedResult,- IsError: false,- },- })- continue- }- }- }-// Tool passed all pre-checks — queue for executionpendingExec = append(pendingExec, pendingToolExec{tc: tc, toolKind: toolKind})}@@ -1246,12 +1144,6 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me} else {resultText = FormatToolResult(result)isError = result.IsError- if !isError {- toolsSucceededThisEpisode = true // Tool executed successfully- log.Debug().- Str("tool", tc.Name).- Msg("[AgenticLoop] Tool succeeded - toolsSucceededThisEpisode set to true")- }// Extract and accumulate knowledge facts from both success and structured error responsesif a.knowledgeAccumulator != nil {a.knowledgeAccumulator.SetTurn(turn)@@ -1298,54 +1190,6 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meMsg("[AgenticLoop] Tracking pending recovery for strict resolution block")}- // === AUTO-RECOVERY FOR STRUCTURED BLOCKS ===- // If a tool returns a blocked response with auto_recoverable=true and a- // governed recovery plan, automatically apply that plan and retry once.- // Note: err == nil means executor didn't throw, isError means the tool result indicates error/block- if err == nil && isError && strings.Contains(resultText, `"auto_recoverable":true`) {- // Result is a blocked response (not a hard error)- if recoveryPlan, recoveryAttempted := tryAutoRecovery(result, tc, a.executor, ctx); recoveryPlan != nil && !recoveryAttempted {- // This is a fresh recoverable block - attempt auto-recovery- log.Info().- Str("tool", tc.Name).- Str("recovery_tool", recoveryPlan.ToolName).- Interface("recovery_input", recoveryPlan.Input).- Msg("[AgenticLoop] Attempting structured auto-recovery")-- // Record auto-recovery attempt- if metrics := GetAIMetrics(); metrics != nil {- metrics.RecordAutoRecoveryAttempt(recoveryPlan.ErrorCode, tc.Name)- }-- retryResult, retryErr := a.executeToolSafely(ctx, recoveryPlan.ToolName, recoveryPlan.Input)- if retryErr != nil {- log.Warn().- Err(retryErr).- Str("tool", tc.Name).- Msg("[AgenticLoop] Auto-recovery retry failed with error")- } else if !retryResult.IsError {- // Recovery succeeded!- log.Info().- Str("tool", tc.Name).- Msg("[AgenticLoop] Auto-recovery succeeded")- if metrics := GetAIMetrics(); metrics != nil {- metrics.RecordAutoRecoverySuccess(recoveryPlan.ErrorCode, tc.Name)- }- // Use the successful result- result = retryResult- resultText = FormatToolResult(result)- isError = false- } else {- log.Warn().- Str("tool", tc.Name).- Str("retry_error", FormatToolResult(retryResult)).- Msg("[AgenticLoop] Auto-recovery retry still blocked")- // Keep original error but note the failed recovery attempt- resultText = resultText + "\n\n[Auto-recovery attempted but failed. Follow the recovery hint manually.]"- }- }- }-// Check if this is an approval requestif strings.HasPrefix(resultText, "APPROVAL_REQUIRED:") {// Parse approval request@@ -1524,13 +1368,13 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meBool("read_after_write", fsm.ReadAfterWrite).Msg("[AgenticLoop] FSM state transition after tool success")- // Check if this success resolves a pending recovery+ // Check if this success resolves a pending policy block.if pr := fsm.CheckRecoverySuccess(tc.Name); pr != nil {log.Info().Str("tool", tc.Name).Str("error_code", pr.ErrorCode).Str("recovery_id", pr.RecoveryID).- Msg("[AgenticLoop] Auto-recovery succeeded")+ Msg("[AgenticLoop] model self-correction after policy block succeeded")if metrics := GetAIMetrics(); metrics != nil {metrics.RecordAutoRecoverySuccess(pr.ErrorCode, pr.Tool)}@@ -1578,7 +1422,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meInt("consecutive_all_error_turns", consecutiveAllErrorTurns).Int("turn", turn).Str("session_id", sessionID).- Msg("[AgenticLoop] All tool calls failed for 3 consecutive turns — forcing text-only response")+ Msg("[AgenticLoop] All tool calls failed for 3 consecutive turns — next turn omits tools")}}}@@ -1593,7 +1437,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meInt("total_calls", len(toolCalls)).Int("turn", turn).Str("session_id", sessionID).- Msg("[AgenticLoop] Tool calls blocked this turn — will force text-only next turn")+ Msg("[AgenticLoop] Tool calls blocked this turn — next turn omits tools")}// Guardrail: in interactive chat mode, force wrap-up after repeated@@ -1607,7 +1451,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meInt("consecutive_tool_only_turns", consecutiveToolOnlyTurns).Int("turn", turn).Str("session_id", sessionID).- Msg("[AgenticLoop] Consecutive tool-only turns exceeded threshold — forcing text-only response")+ Msg("[AgenticLoop] Consecutive tool-only turns exceeded threshold — next turn omits tools")}// Track cumulative tool calls and inject wrap-up nudge/escalation if threshold exceededdiff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.goindex f7d14c010c..0f4ab2bdad 100644--- a/internal/ai/chat/agentic_additional_test.go+++ b/internal/ai/chat/agentic_additional_test.go@@ -141,8 +141,8 @@ func TestEnsureFinalTextResponse(t *testing.T) {if len(result) != 2 {t.Fatalf("expected summary message to be appended")}- if provider.lastRequest.ToolChoice == nil || provider.lastRequest.ToolChoice.Type != providers.ToolChoiceNone {- t.Fatalf("expected summary call to use the text-only safety brake")+ if provider.lastRequest.ToolChoice != nil || len(provider.lastRequest.Tools) != 0 {+ t.Fatalf("expected summary call to omit tools and tool_choice, got tools=%d choice=%+v", len(provider.lastRequest.Tools), provider.lastRequest.ToolChoice)}provider.chatStream = func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {@@ -419,54 +419,7 @@ func TestAgenticLoop_DoesNotRetryErrorEventAfterVisibleOutput(t *testing.T) {}}-func TestTryAutoRecoveryAndCommandExtraction(t *testing.T) {- result := tools.CallToolResult{- Content: []tools.Content{{Type: "text", Text: `{"error":{"code":"READ_ONLY_VIOLATION","details":{"auto_recoverable":true,"suggested_rewrite":"uptime","category":"strict"}}}`}},- IsError: true,- }- plan, attempted := tryAutoRecovery(result, providers.ToolCall{- Name: "pulse_read",- Input: map[string]interface{}{"action": "exec"},- }, nil, context.Background())- if attempted || plan == nil {- t.Fatalf("expected recovery plan and no prior attempt")- }- if plan.ToolName != "pulse_read" || plan.Input["command"] != "uptime" {- t.Fatalf("unexpected legacy recovery plan: %+v", plan)- }- if plan.ErrorCode != "READ_ONLY_VIOLATION" {- t.Fatalf("expected READ_ONLY_VIOLATION error code, got %+v", plan)- }-- structured := tools.CallToolResult{- Content: []tools.Content{{Type: "text", Text: `{"error":{"code":"ACTION_NOT_ALLOWED","details":{"auto_recoverable":true,"suggested_tool":"pulse_query","suggested_arguments":{"action":"get","resource_type":"vm","resource_id":"app-01"}}}}`}},- IsError: true,- }- plan, _ = tryAutoRecovery(structured, providers.ToolCall{Input: map[string]interface{}{}}, nil, context.Background())- if plan == nil {- t.Fatalf("expected structured recovery plan")- }- if plan.ToolName != "pulse_query" || plan.Input["action"] != "get" || plan.Input["resource_id"] != "app-01" {- t.Fatalf("unexpected structured recovery plan: %+v", plan)- }- if plan.ErrorCode != "ACTION_NOT_ALLOWED" {- t.Fatalf("expected ACTION_NOT_ALLOWED error code, got %+v", plan)- }-- retryTool := tools.CallToolResult{- Content: []tools.Content{{Type: "text", Text: `{"error":5,"auto_recoverable":true,"suggested_tool":"pulse_query","suggested_arguments":{"action":"list"}}`}},- IsError: true,- }- plan, _ = tryAutoRecovery(retryTool, providers.ToolCall{Input: map[string]interface{}{}}, nil, context.Background())- if plan == nil || plan.ToolName != "pulse_query" || plan.Input["action"] != "list" {- t.Fatalf("expected alternate-format structured recovery plan, got %+v", plan)- }-- plan, attempted = tryAutoRecovery(result, providers.ToolCall{Input: map[string]interface{}{"_auto_recovery_attempt": true}}, nil, context.Background())- if !attempted || plan != nil {- t.Fatalf("expected auto recovery to be skipped when already attempted")- }-+func TestCommandExtraction(t *testing.T) {if cmd := getCommandFromInput(map[string]interface{}{"command": "ls"}); cmd != "ls" {t.Fatalf("expected command to be extracted")}@@ -475,7 +428,7 @@ func TestTryAutoRecoveryAndCommandExtraction(t *testing.T) {}}-func TestAgenticLoop_AutoRecoveryExecutesStructuredToolCall(t *testing.T) {+func TestAgenticLoop_DoesNotAutoRecoverStructuredToolCall(t *testing.T) {executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})failCalls := 0recoveryCalls := 0@@ -494,11 +447,7 @@ func TestAgenticLoop_AutoRecoveryExecutesStructuredToolCall(t *testing.T) {tools.ErrCodeActionNotAllowed,"blocked",map[string]interface{}{- "auto_recoverable": true,- "suggested_tool": "recovery_tool",- "suggested_arguments": map[string]interface{}{- "value": "recovered through query",- },+ "policy_boundary": "resource requires model-selected follow-up context",},)), nil},@@ -545,15 +494,15 @@ func TestAgenticLoop_AutoRecoveryExecutesStructuredToolCall(t *testing.T) {if len(req.Messages) != 3 {t.Fatalf("expected assistant tool call plus tool result, got %d messages", len(req.Messages))}- if req.Messages[2].ToolResult == nil || req.Messages[2].ToolResult.IsError {- t.Fatalf("expected recovered tool result, got %+v", req.Messages[2].ToolResult)+ if req.Messages[2].ToolResult == nil || !req.Messages[2].ToolResult.IsError {+ t.Fatalf("expected original blocked tool result, got %+v", req.Messages[2].ToolResult)}- if !strings.Contains(req.Messages[2].ToolResult.Content, "recovered through query") {- t.Fatalf("expected recovered output in provider follow-up, got %+v", req.Messages[2].ToolResult)+ if strings.Contains(req.Messages[2].ToolResult.Content, "recovered through query") {+ t.Fatalf("blocked result should not be replaced by auto-recovery output: %+v", req.Messages[2].ToolResult)}callback(providers.StreamEvent{Type: "content",- Data: providers.ContentEvent{Text: "Recovered."},+ Data: providers.ContentEvent{Text: "The tool was blocked; I need to decide the next step."},})callback(providers.StreamEvent{Type: "done",@@ -565,20 +514,20 @@ func TestAgenticLoop_AutoRecoveryExecutesStructuredToolCall(t *testing.T) {return nil}- results, err := loop.Execute(context.Background(), "structured-auto-recovery", []Message{{Role: "user", Content: "help"}}, func(event StreamEvent) {})+ results, err := loop.Execute(context.Background(), "structured-model-owned-recovery", []Message{{Role: "user", Content: "help"}}, func(event StreamEvent) {})if err != nil {- t.Fatalf("expected successful auto-recovery, got %v", err)+ t.Fatalf("expected model-owned recovery turn to continue, got %v", err)}- if failCalls != 1 || recoveryCalls != 1 {- t.Fatalf("expected one fail call and one recovery call, got fail=%d recovery=%d", failCalls, recoveryCalls)+ if failCalls != 1 || recoveryCalls != 0 {+ t.Fatalf("expected only the model-selected failing call to execute, got fail=%d recovery=%d", failCalls, recoveryCalls)}if len(results) != 3 {- t.Fatalf("expected assistant tool call, recovered tool result, and final response, got %+v", results)+ t.Fatalf("expected assistant tool call, blocked tool result, and final response, got %+v", results)}- if results[1].ToolResult == nil || !strings.Contains(results[1].ToolResult.Content, "recovered through query") {- t.Fatalf("expected recovered tool result in transcript, got %+v", results[1])+ if results[1].ToolResult == nil || !results[1].ToolResult.IsError {+ t.Fatalf("expected blocked tool result in transcript, got %+v", results[1])}- if results[2].Content != "Recovered." {+ if results[2].Content != "The tool was blocked; I need to decide the next step." {t.Fatalf("unexpected final response: %+v", results[2])}}diff --git a/internal/ai/chat/agentic_final.go b/internal/ai/chat/agentic_final.goindex 446f6ccb63..d727c5909f 100644--- a/internal/ai/chat/agentic_final.go+++ b/internal/ai/chat/agentic_final.go@@ -14,7 +14,8 @@ import ()// ensureFinalTextResponse checks if the result messages contain any assistant text.-// If not, it makes one last text-only LLM call to force the model to summarize its findings.+// If not, it makes one last LLM call without tools so the model can summarize+// its findings.// This prevents the loop from exiting silently after making tool calls without answering.//// cost-recording-exempt: any tokens this final summary turn consumes@@ -62,8 +63,8 @@ func (a *AgenticLoop) ensureFinalTextResponse(Messages: cleanMessages,System: a.getSystemPrompt(),ExecutionID: a.executionID,- ToolChoice: &providers.ToolChoice{Type: providers.ToolChoiceNone},- // No Tools field — completely omit tools to prevent hallucinated function calls+ // No Tools field: this is a final narrative turn, and Pulse avoids+ // provider-specific tool_choice transport fields.}a.mu.Lock()requestSanitizer := a.requestSanitizerdiff --git a/internal/ai/chat/agentic_intent.go b/internal/ai/chat/agentic_intent.godeleted file mode 100644index 64b72acf07..0000000000--- a/internal/ai/chat/agentic_intent.go+++ /dev/null@@ -1,119 +0,0 @@-package chat--import "strings"--// detectFreshDataIntent returns true when the user's latest message explicitly-// requests updated/fresh data (e.g. "check again", "refresh", "what's the-// latest status"). This bypasses the knowledge gate for the first turn so-// tools re-execute instead of returning cached results.-func detectFreshDataIntent(messages []Message) bool {- // Walk backwards to find the last user message- var lastUserContent string- for i := len(messages) - 1; i >= 0; i-- {- if messages[i].Role == "user" && messages[i].Content != "" {- lastUserContent = strings.ToLower(messages[i].Content)- break- }- }- if lastUserContent == "" {- return false- }-- // Strong refresh signals — these clearly indicate the user wants re-execution- strongPatterns := []string{- "check again", "look again", "try again", "run again",- "refresh", "re-check", "recheck", "re check",- "fresh data", "fresh look", "latest data",- "has it changed", "did it change", "any changes",- "what's happening now", "what is happening now",- }- for _, p := range strongPatterns {- if strings.Contains(lastUserContent, p) {- return true- }- }- return false-}--// hasPhantomExecution detects when the model claims to have executed something-// but no actual tool calls were made. This catches models that "hallucinate"-// tool execution by writing about it instead of calling tools.-//-// We're intentionally conservative here to avoid false positives like:-// - "I checked the docs..." (not a tool)-// - "I ran through the logic..." (not a command)-//-// We only trigger when the model asserts:-// 1. Concrete system metrics/values (CPU %, memory usage, etc.)-// 2. Infrastructure state that requires live queries (running/stopped)-// 3. Fake tool call formatting-func hasPhantomExecution(content string) bool {- if content == "" {- return false- }-- lower := strings.ToLower(content)-- // Category 1: Concrete metrics/values that MUST come from tools- // These are specific enough that they can't be "general knowledge"- metricsPatterns := []string{- "cpu usage is ", "cpu is at ", "cpu at ",- "memory usage is ", "memory is at ", "memory at ",- "disk usage is ", "disk is at ", "storage at ",- "using % ", "% cpu", "% memory", "% disk",- "mb of ram", "gb of ram", "mb of memory", "gb of memory",- }-- for _, pattern := range metricsPatterns {- if strings.Contains(lower, pattern) {- return true- }- }-- // Category 2: Claims of infrastructure state that require live queries- // Must be specific claims about current state, not general discussion- statePatterns := []string{- "is currently running", "is currently stopped", "is currently down",- "is now running", "is now stopped", "is now restarted",- "the service is running", "the container is running",- "the service is stopped", "the container is stopped",- "the logs show", "the output shows", "the result shows",- "according to the logs", "according to the output",- }-- for _, pattern := range statePatterns {- if strings.Contains(lower, pattern) {- return true- }- }-- // Category 3: Fake tool call formatting (definite hallucination)- fakeToolPatterns := []string{- "```tool", "```json\n{\"tool", "tool_result:",- "function_call:", "<tool_call>", "</tool_call>",- "pulse_query(", "pulse_run_command(", "pulse_control(",- }-- for _, pattern := range fakeToolPatterns {- if strings.Contains(lower, pattern) {- return true- }- }-- // Category 4: Past tense claims of SPECIFIC infrastructure actions- // Only trigger if followed by concrete results (not "I checked and...")- actionResultPatterns := []string{- "i restarted the", "i stopped the", "i started the",- "i killed the", "i terminated the",- "successfully restarted", "successfully stopped", "successfully started",- "has been restarted", "has been stopped", "has been started",- }-- for _, pattern := range actionResultPatterns {- if strings.Contains(lower, pattern) {- return true- }- }-- return false-}diff --git a/internal/ai/chat/agentic_recovery.go b/internal/ai/chat/agentic_recovery.godeleted file mode 100644index 249c12c263..0000000000--- a/internal/ai/chat/agentic_recovery.go+++ /dev/null@@ -1,151 +0,0 @@-package chat--import (- "context"- "encoding/json"- "strings"-- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"- "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"-)--type autoRecoveryPlan struct {- ErrorCode string- ToolName string- Input map[string]interface{}-}--type autoRecoveryDetails struct {- AutoRecoverable bool `json:"auto_recoverable"`- SuggestedRewrite string `json:"suggested_rewrite"`- SuggestedTool string `json:"suggested_tool"`- SuggestedArgument map[string]interface{} `json:"suggested_arguments"`-}--// tryAutoRecovery checks if a tool result is auto-recoverable and returns a retry plan.-// Returns (plan, alreadyAttempted) where:-// - plan is nil when no auto-recovery should be attempted-// - alreadyAttempted is true if auto-recovery was already attempted for this call-func tryAutoRecovery(result tools.CallToolResult, tc providers.ToolCall, executor *tools.PulseToolExecutor, ctx context.Context) (*autoRecoveryPlan, bool) {- // Check if this is already a recovery attempt- if _, ok := tc.Input["_auto_recovery_attempt"]; ok {- return nil, true // Already attempted, don't retry again- }-- // Parse the result to check for auto_recoverable flag- resultStr := FormatToolResult(result)-- // Look for the structured error response pattern- // The result should contain JSON with auto_recoverable and suggested_rewrite- if !strings.Contains(resultStr, `"auto_recoverable"`) {- return nil, false- }-- // Extract the JSON portion from the result- // Results are formatted as "Error: {json}" or just "{json}"- jsonStart := strings.Index(resultStr, "{")- if jsonStart == -1 {- return nil, false- }-- var parsed struct {- Error struct {- Code string `json:"code"`- Details struct {- AutoRecoverable bool `json:"auto_recoverable"`- SuggestedRewrite string `json:"suggested_rewrite"`- SuggestedTool string `json:"suggested_tool"`- SuggestedArgument map[string]interface{} `json:"suggested_arguments"`- Category string `json:"category"`- } `json:"details"`- } `json:"error"`- AutoRecoverable bool `json:"auto_recoverable"`- SuggestedRewrite string `json:"suggested_rewrite"`- SuggestedTool string `json:"suggested_tool"`- SuggestedArgument map[string]interface{} `json:"suggested_arguments"`- }-- if err := json.Unmarshal([]byte(resultStr[jsonStart:]), &parsed); err != nil {- // Try alternative format where details are at top level- var altParsed struct {- ErrorCode string `json:"error_code"`- AutoRecoverable bool `json:"auto_recoverable"`- SuggestedRewrite string `json:"suggested_rewrite"`- SuggestedTool string `json:"suggested_tool"`- SuggestedArguments map[string]interface{} `json:"suggested_arguments"`- }- if err2 := json.Unmarshal([]byte(resultStr[jsonStart:]), &altParsed); err2 != nil {- return nil, false- }- return buildAutoRecoveryPlan(tc, altParsed.ErrorCode, autoRecoveryDetails{- AutoRecoverable: altParsed.AutoRecoverable,- SuggestedRewrite: altParsed.SuggestedRewrite,- SuggestedTool: altParsed.SuggestedTool,- SuggestedArgument: altParsed.SuggestedArguments,- }), false- }-- if plan := buildAutoRecoveryPlan(tc, parsed.Error.Code, autoRecoveryDetails{- AutoRecoverable: parsed.Error.Details.AutoRecoverable,- SuggestedRewrite: parsed.Error.Details.SuggestedRewrite,- SuggestedTool: parsed.Error.Details.SuggestedTool,- SuggestedArgument: parsed.Error.Details.SuggestedArgument,- }); plan != nil {- return plan, false- }-- return buildAutoRecoveryPlan(tc, parsed.Error.Code, autoRecoveryDetails{- AutoRecoverable: parsed.AutoRecoverable,- SuggestedRewrite: parsed.SuggestedRewrite,- SuggestedTool: parsed.SuggestedTool,- SuggestedArgument: parsed.SuggestedArgument,- }), false-}--func buildAutoRecoveryPlan(tc providers.ToolCall, errorCode string, details autoRecoveryDetails) *autoRecoveryPlan {- if !details.AutoRecoverable {- return nil- }-- if suggestedTool := strings.TrimSpace(details.SuggestedTool); suggestedTool != "" {- input := cloneAutoRecoveryInput(details.SuggestedArgument)- input["_auto_recovery_attempt"] = true- return &autoRecoveryPlan{- ErrorCode: firstNonEmptyAutoRecoveryCode(errorCode),- ToolName: suggestedTool,- Input: input,- }- }-- if suggestedRewrite := strings.TrimSpace(details.SuggestedRewrite); suggestedRewrite != "" {- input := cloneAutoRecoveryInput(tc.Input)- input["command"] = suggestedRewrite- input["_auto_recovery_attempt"] = true- return &autoRecoveryPlan{- ErrorCode: firstNonEmptyAutoRecoveryCode(errorCode),- ToolName: tc.Name,- Input: input,- }- }-- return nil-}--func cloneAutoRecoveryInput(input map[string]interface{}) map[string]interface{} {- if len(input) == 0 {- return map[string]interface{}{}- }- cloned := make(map[string]interface{}, len(input)+1)- for key, value := range input {- cloned[key] = value- }- return cloned-}--func firstNonEmptyAutoRecoveryCode(code string) string {- code = strings.TrimSpace(code)- if code == "" {- return "AUTO_RECOVERY"- }- return code-}diff --git a/internal/ai/chat/agentic_test.go b/internal/ai/chat/agentic_test.goindex 45beb147c2..34aab0d4e9 100644--- a/internal/ai/chat/agentic_test.go+++ b/internal/ai/chat/agentic_test.go@@ -353,56 +353,6 @@ func TestWaitForApprovalDecision(t *testing.T) {})}-func TestHasPhantomExecution(t *testing.T) {- tests := []struct {- name string- content string- expected bool- }{- // Phantom execution patterns - concrete metrics- {"cpu percentage", "The CPU usage is at 85%", true},- {"memory usage", "Memory usage is 4.2GB", true},- {"disk at", "Disk is at 92% capacity", true},-- // Phantom execution patterns - state claims- {"currently running", "The service is currently running", true},- {"currently stopped", "The container is currently stopped", true},- {"logs show", "The logs show several errors", true},- {"output shows", "The output shows the service failed", true},-- // Phantom execution patterns - fake tool formatting- {"fake tool block", "```tool\npulse_query\n```", true},- {"fake function call", "pulse_query({\"type\": \"nodes\"})", true},-- // Phantom execution patterns - action claims- {"restarted the", "I restarted the nginx service", true},- {"successfully restarted", "The service was successfully restarted", true},- {"has been stopped", "The container has been stopped", true},-- // NOT phantom execution - these are safe- {"suggestion", "You should check the logs", false},- {"question", "Would you like me to restart it?", false},- {"explanation", "Docker containers run in isolated environments", false},- {"future tense", "I will check the status for you", false},- {"empty", "", false},- {"general info", "Proxmox uses LXC for containers", false},-- // NOT phantom - these used to false-positive- {"checked docs", "I checked the documentation and found...", false},- {"ran through logic", "I ran through the logic and it seems...", false},- {"looked at code", "I looked at the configuration options", false},- {"verified understanding", "I verified my understanding of the issue", false},- {"found that general", "I found that Docker networking is complex", false},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := hasPhantomExecution(tt.content)- assert.Equal(t, tt.expected, result, "content: %q", tt.content)- })- }-}-func TestToolCallKey(t *testing.T) {t.Run("same name and input produce same key", func(t *testing.T) {input := map[string]interface{}{"action": "get", "resource_type": "lxc", "target_id": "node1"}@@ -631,71 +581,6 @@ func TestSummarizeForNegativeMarker(t *testing.T) {}}-func TestDetectFreshDataIntent(t *testing.T) {- tests := []struct {- name string- messages []Message- want bool- }{- {- name: "empty messages",- messages: nil,- want: false,- },- {- name: "normal question",- messages: []Message{- {Role: "user", Content: "What containers are running?"},- },- want: false,- },- {- name: "check again",- messages: []Message{- {Role: "user", Content: "Check again please"},- },- want: true,- },- {- name: "refresh",- messages: []Message{- {Role: "user", Content: "Can you refresh the data?"},- },- want: true,- },- {- name: "has it changed",- messages: []Message{- {Role: "user", Content: "Has it changed since last time?"},- },- want: true,- },- {- name: "latest data",- messages: []Message{- {Role: "user", Content: "Show me the latest data for frigate"},- },- want: true,- },- {- name: "uses last user message only",- messages: []Message{- {Role: "user", Content: "Check again"},- {Role: "assistant", Content: "OK, checking..."},- {Role: "user", Content: "What is the CPU usage?"},- },- want: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := detectFreshDataIntent(tt.messages)- assert.Equal(t, tt.want, got)- })- }-}-func TestParallelToolExecution(t *testing.T) {executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})diff --git a/internal/ai/chat/metrics.go b/internal/ai/chat/metrics.goindex b76146ff40..db1f641e0b 100644--- a/internal/ai/chat/metrics.go+++ b/internal/ai/chat/metrics.go@@ -41,7 +41,7 @@ type AIMetrics struct {// Phantom detection - tracks hallucinated tool execution claimsphantomDetected *prometheus.CounterVec- // Auto-recovery - tracks self-healing attempts and outcomes+ // Policy-block self-correction - tracks model-owned follow-up after blocked tools.autoRecoveryAttempt *prometheus.CounterVecautoRecoverySuccess *prometheus.CounterVec@@ -115,7 +115,7 @@ func newAIMetrics() *AIMetrics {Namespace: "pulse",Subsystem: "ai",Name: "auto_recovery_attempt_total",- Help: "Total auto-recovery attempts by error code and tool",+ Help: "Total model self-correction opportunities after policy blocks by error code and tool",},[]string{"error_code", "tool"},),@@ -124,7 +124,7 @@ func newAIMetrics() *AIMetrics {Namespace: "pulse",Subsystem: "ai",Name: "auto_recovery_success_total",- Help: "Total successful auto-recoveries by error code and tool",+ Help: "Total successful model-owned follow-ups after policy blocks by error code and tool",},[]string{"error_code", "tool"},),@@ -183,14 +183,14 @@ func (m *AIMetrics) RecordPhantomDetected(provider, model string) {m.phantomDetected.WithLabelValues(sanitizeLabel(provider), sanitizeLabel(model)).Inc()}-// RecordAutoRecoveryAttempt records an auto-recovery attempt.-// Definition: "we returned a recoverable error that the model can self-correct"+// RecordAutoRecoveryAttempt records when the model receives a recoverable policy block.+// Definition: "we returned policy facts and the model may decide the next step"func (m *AIMetrics) RecordAutoRecoveryAttempt(errorCode, tool string) {m.autoRecoveryAttempt.WithLabelValues(sanitizeLabel(errorCode), sanitizeLabel(tool)).Inc()}-// RecordAutoRecoverySuccess records a successful auto-recovery.-// Definition: "a previously blocked operation succeeded on retry after discovery"+// RecordAutoRecoverySuccess records a successful model-owned follow-up after a policy block.+// Definition: "a previously blocked operation later succeeded without Pulse forcing a tool retry"func (m *AIMetrics) RecordAutoRecoverySuccess(errorCode, tool string) {m.autoRecoverySuccess.WithLabelValues(sanitizeLabel(errorCode), sanitizeLabel(tool)).Inc()}@@ -218,7 +218,7 @@ func NewAIMetricsTelemetryCallback() *AIMetricsTelemetryCallback {func (c *AIMetricsTelemetryCallback) RecordStrictResolutionBlock(tool, action string) {if c.metrics != nil {c.metrics.RecordStrictResolutionBlock(tool, action)- // Strict resolution blocks are recoverable (model can discover then retry)+ // Strict resolution returns policy facts; the model owns any follow-up.c.metrics.RecordAutoRecoveryAttempt("STRICT_RESOLUTION", tool)}}@@ -241,7 +241,7 @@ func (c *AIMetricsTelemetryCallback) RecordAutoRecoverySuccess(errorCode, tool sfunc (c *AIMetricsTelemetryCallback) RecordRoutingMismatchBlock(tool, targetKind, childKind string) {if c.metrics != nil {c.metrics.RecordRoutingMismatchBlock(tool, targetKind, childKind)- // Routing mismatch blocks are recoverable (model can retry with correct target)+ // Routing mismatch returns policy facts; the model owns any follow-up.c.metrics.RecordAutoRecoveryAttempt("ROUTING_MISMATCH", tool)}}diff --git a/internal/ai/chat/routing_contract_test.go b/internal/ai/chat/routing_contract_test.goindex 08f59c6fb4..2a17c2491a 100644--- a/internal/ai/chat/routing_contract_test.go+++ b/internal/ai/chat/routing_contract_test.go@@ -17,14 +17,14 @@ import (// TestContract_MentionTriggersRoutingMismatchBlock verifies that:// 1. @mention resolution marks resources as explicitly accessed// 2. Tool execution targeting the parent host gets blocked-// 3. The error response includes target_resource_id for auto-recovery+// 3. The error response includes routing facts without choosing the next tool call//// This is the core contract for Invariant 7: routing validation.func TestContract_MentionTriggersRoutingMismatchBlock(t *testing.T) {// Simulate: User message contains "@homepage-docker"// Prefetch resolves it to system-container:pve-node:141 and marks explicit access// Tool call attempts to write with target_host="pve-node"- // Assert: ROUTING_MISMATCH with target_resource_id suggestion+ // Assert: ROUTING_MISMATCH with factual child-resource context// Step 1: Create resolved context (simulating session creation)resolvedCtx := NewResolvedContext("test-session")@@ -112,16 +112,17 @@ func TestContract_MentionTriggersRoutingMismatchBlock(t *testing.T) {t.Error("Expected Blocked=true for routing mismatch")}- // Verify auto-recovery hints+ // Verify policy facts without Pulse-authored retry instructions.details := response.Error.Details- if details["auto_recoverable"] != true {- t.Error("Expected auto_recoverable=true in response")+ if details["auto_recoverable"] != nil {+ t.Error("Expected auto_recoverable to be absent")}- if details["target_resource_id"] != "system-container:pve-node:141" {- t.Errorf("Expected target_resource_id='system-container:pve-node:141', got %v", details["target_resource_id"])+ ids, ok := details["more_specific_resource_ids"].([]string)+ if !ok || len(ids) != 1 || ids[0] != "system-container:pve-node:141" {+ t.Errorf("Expected more_specific_resource_ids=['system-container:pve-node:141'], got %v", details["more_specific_resource_ids"])}- if details["recovery_hint"] == nil {- t.Error("Expected recovery_hint in response")+ if details["policy_boundary"] == nil {+ t.Error("Expected policy_boundary in response")}t.Log("✓ @mention → explicit access → routing mismatch block contract verified")diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 9a83798783..2f116c4d9d 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -2654,7 +2654,7 @@ func (s *Service) applyChatContextSettings() {//// Philosophy: This prompt provides identity, context, and tool policy. Tool// selection remains model-owned; Pulse enforces safety after a model choice via-// tool policy, approvals, FSM verification gates, and phantom execution checks.+// tool policy, approvals, and FSM verification gates.func (s *Service) buildSystemPrompt() string {return `You are Pulse AI, a knowledgeable infrastructure assistant. You pair-program with the user on their homelab and infrastructure tasks.@@ -2697,7 +2697,7 @@ You are like a colleague doing pair programming on infrastructure tasks. Tool ca## TASK COMPLETION- After successful control actions, the system auto-verifies. Once verified, stop making tool calls and respond.- If a tool call is BLOCKED, read the error message carefully and follow its instructions exactly.-- If told to call pulse_query or pulse_read first, you MUST do that before retrying the blocked action.`+- If a tool call is BLOCKED, use the returned facts and policy boundary to decide whether more read context, a different governed tool call, or user clarification is needed.`}func (s *Service) buildToolGovernancePromptSection() string {diff --git a/internal/ai/eval/scenarios.go b/internal/ai/eval/scenarios.goindex b668b6d7ca..f9cb09520d 100644--- a/internal/ai/eval/scenarios.go+++ b/internal/ai/eval/scenarios.go@@ -1292,10 +1292,9 @@ func GuestControlNaturalLanguageScenario() Scenario {// GuestControlMultiMentionScenario tests querying multiple resources via mentions.// Each step queries one resource with a structured mention.//-// KNOWN LIMITATION: The model loops on read-only queries because tool_choice=none-// forcing only applies after writes. The model calls pulse_query repeatedly until-// budget-exhausted, often producing 0 content. Assertions are relaxed to document-// this behavior — tighten them once read-looping is fixed.+// KNOWN LIMITATION: Some models loop on read-only queries until budget-exhausted,+// often producing 0 content. Assertions are relaxed to document this behavior;+// tighten them once read-looping is fixed without Pulse-owned tool forcing.func GuestControlMultiMentionScenario() Scenario {t := loadEvalTargets()mention1 := StepMention{@@ -1401,8 +1400,8 @@ func ReadOnlyModelChoiceScenario() Scenario {}// ReadLoopRecoveryScenario tests that the model produces text output even when-// tool calls are budget-blocked or loop-detected. This validates the toolBlockedLastTurn-// fix: after blocked calls, tool_choice=none forces a text response.+// tool calls are budget-blocked or loop-detected. After blocked calls, Pulse+// omits tools on the follow-up turn so the selected model can produce text.//// The scenario asks a broad question that may trigger multiple tool calls. The key// assertion is that the model always produces meaningful content — it should neverdiff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex 2399f35cd0..3f23737c66 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -146,7 +146,7 @@ type PatrolRunRecord struct {ErrorDetail string `json:"error_detail,omitempty"`// Triage statsTriageFlags int `json:"triage_flags"` // Number of deterministic flags found- TriageSkippedLLM bool `json:"triage_skipped_llm,omitempty"` // True if LLM was skipped (quiet infra)+ TriageSkippedLLM bool `json:"triage_skipped_llm,omitempty"` // Legacy: true for older quiet-triage runs// AI Analysis detailsAIAnalysis string `json:"ai_analysis,omitempty"` // The AI's raw response/analysisInputTokens int `json:"input_tokens,omitempty"` // Tokens sent to AIdiff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex 4ed8418c54..bb6ff5aa35 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -33,7 +33,7 @@ type AIAnalysisResult struct {Findings []*Finding // Parsed findings from the responseRejectedFindings int // Findings rejected by threshold validationTriageFlags int // Number of deterministic triage flags- TriageSkippedLLM bool // True if LLM was skipped due to quiet triage+ TriageSkippedLLM bool // Legacy: true for older records where quiet triage skipped LLMInputTokens intOutputTokens intToolCalls []ToolCallRecord // Tool invocations during this analysis@@ -244,14 +244,10 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntimetrics.RecordTriageQuiet()}- // Quiet infrastructure: skip LLM entirely+ // Quiet infrastructure still goes through the configured model. Triage is+ // context, not a replacement for model-owned assessment.if triageResult.IsQuiet {- log.Info().Msg("AI Patrol: Infrastructure quiet, skipping LLM analysis")- return &AIAnalysisResult{- Response: "Infrastructure healthy — deterministic triage found no issues.",- TriageFlags: 0,- TriageSkippedLLM: true,- }, nil+ log.Info().Msg("AI Patrol: Infrastructure quiet, continuing with model-owned analysis")}// Phase 2: Build focused seed context from triage results@@ -557,10 +553,8 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntiInt("findings_resolved", adapter.getResolvedCount()).Msg("AI Patrol: Agentic patrol analysis complete")- var toolCallsMu sync.MutexcompletedToolCalls := append([]ToolCallRecord(nil), attempt.toolCalls...)rawToolOutputs := append([]string(nil), attempt.rawToolOutputs...)- p.ensureInvestigationToolCall(ctx, executor, &toolCallsMu, &completedToolCalls, &rawToolOutputs, noStream)// Broadcast completionif !noStream {@@ -572,7 +566,6 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRunti}// Collect completed tool calls- toolCallsMu.Lock()collectedToolCalls := completedToolCallssignalToolCalls := make([]ToolCallRecord, len(collectedToolCalls))for i, tc := range collectedToolCalls {@@ -581,7 +574,6 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntisignalToolCalls[i].Output = rawToolOutputs[i]}}- toolCallsMu.Unlock()// --- Deterministic signal detection + evaluation pass ---// Build signal thresholds from user config so detection aligns with alert settings@@ -618,16 +610,11 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntiMsg("AI Patrol: Evaluation pass completed")}- // Deterministic fallback: if unmatched signals remain, create findings directly.remaining := UnmatchedSignals(detectedSignals, adapter.getCollectedFindings())if len(remaining) > 0 {- created := p.createFindingsFromSignals(adapter, remaining)- if created > 0 {- log.Info().- Int("created", created).- Int("remaining", len(remaining)).- Msg("AI Patrol: Created deterministic findings for unmatched signals")- }+ log.Info().+ Int("remaining", len(remaining)).+ Msg("AI Patrol: Unmatched signals remain after model evaluation; not creating Pulse-authored findings")}} else {log.Debug().@@ -698,96 +685,6 @@ func computeTriageMaxTurns(flagCount int, scope *PatrolScope) int {return turns}-func (p *PatrolService) ensureInvestigationToolCall(- ctx context.Context,- executor *tools.PulseToolExecutor,- toolCallsMu *sync.Mutex,- completedToolCalls *[]ToolCallRecord,- rawToolOutputs *[]string,- noStream bool,-) {- if executor == nil {- return- }-- toolCallsMu.Lock()- needsInvestigation := true- for _, tc := range *completedToolCalls {- if isInvestigationTool(tc.ToolName) {- needsInvestigation = false- break- }- }- toolCallsMu.Unlock()-- if !needsInvestigation {- return- }-- fallbackName := "pulse_query"- args := map[string]interface{}{"action": "health"}- inputBytes, _ := json.Marshal(args)- inputStr := string(inputBytes)- fallbackID := fmt.Sprintf("patrol-fallback-%d", time.Now().UnixNano())-- start := time.Now().UnixMilli()- if !noStream {- p.broadcast(PatrolStreamEvent{- Type: "tool_start",- ToolID: fallbackID,- ToolName: fallbackName,- ToolInput: inputStr,- ToolRawInput: inputStr,- })- }-- result, err := executor.ExecuteTool(ctx, fallbackName, args)- output := ""- success := false- if err != nil {- output = err.Error()- } else {- output = formatToolResult(result)- success = !result.IsError- }-- end := time.Now().UnixMilli()- if !noStream {- p.broadcast(PatrolStreamEvent{- Type: "tool_end",- ToolID: fallbackID,- ToolName: fallbackName,- ToolInput: inputStr,- ToolRawInput: inputStr,- ToolOutput: output,- ToolSuccess: &success,- })- }-- toolCallsMu.Lock()- *completedToolCalls = append(*completedToolCalls, ToolCallRecord{- ID: fallbackID,- ToolName: fallbackName,- Input: truncateString(inputStr, MaxToolInputSize),- Output: truncateString(output, MaxToolOutputSize),- Success: success,- StartTime: start,- EndTime: end,- Duration: end - start,- })- *rawToolOutputs = append(*rawToolOutputs, output)- toolCallsMu.Unlock()-}--func isInvestigationTool(name string) bool {- switch name {- case "pulse_query", "pulse_metrics", "pulse_storage", "pulse_read":- return true- default:- return false- }-}-func formatToolResult(result tools.CallToolResult) string {if len(result.Content) == 0 {return ""@@ -929,122 +826,6 @@ func buildEvalUserPrompt(signals []DetectedSignal) string {return sb.String()}-func (p *PatrolService) createFindingsFromSignals(adapter *patrolFindingCreatorAdapter, signals []DetectedSignal) int {- if adapter == nil || len(signals) == 0 {- return 0- }- created := 0- for _, s := range signals {- input := signalToFindingInput(s)- if input.ResourceName == "" {- input.ResourceName = input.ResourceID- }- if input.ResourceType == "" {- input.ResourceType = inferFindingResourceType(input.ResourceID, input.ResourceName)- }- if input.Category == "" {- input.Category = "general"- }- if input.Severity == "" {- input.Severity = "warning"- }- if input.Recommendation == "" {- input.Recommendation = defaultRecommendationForSignal(s)- }- if input.Title == "" {- input.Title = s.Summary- }- if input.Description == "" {- input.Description = s.Summary- }-- if _, _, err := adapter.CreateFinding(input); err == nil {- created++- }- }- return created-}--func signalToFindingInput(s DetectedSignal) tools.PatrolFindingInput {- key := signalKey(s)- category := s.Category- severity := s.SuggestedSeverity- return tools.PatrolFindingInput{- Key: key,- Severity: severity,- Category: category,- ResourceID: s.ResourceID,- ResourceName: s.ResourceName,- ResourceType: s.ResourceType,- Title: signalTitle(s),- Description: s.Summary,- Evidence: s.Evidence,- }-}--func signalKey(s DetectedSignal) string {- switch s.SignalType {- case SignalSMARTFailure:- return "smart-failure"- case SignalHighCPU:- return "cpu-high"- case SignalHighMemory:- return "memory-high"- case SignalHighDisk:- return "disk-high"- case SignalBackupFailed:- return "backup-failed"- case SignalBackupStale:- return "backup-stale"- case SignalGuestUnreachable:- return "guest-unreachable"- default:- return "deterministic-signal"- }-}--func signalTitle(s DetectedSignal) string {- switch s.SignalType {- case SignalSMARTFailure:- return "SMART health check failed"- case SignalHighCPU:- return "High CPU usage detected"- case SignalHighMemory:- return "High memory usage detected"- case SignalHighDisk:- return "Storage usage is high"- case SignalBackupFailed:- return "Backup failed"- case SignalBackupStale:- return "Backup is stale"- case SignalGuestUnreachable:- return fmt.Sprintf("Guest unreachable: %s", s.ResourceName)- default:- return "Infrastructure signal detected"- }-}--func defaultRecommendationForSignal(s DetectedSignal) string {- switch s.SignalType {- case SignalSMARTFailure:- return "Inspect the disk for errors and consider replacing it if SMART failures persist."- case SignalHighCPU:- return "Identify processes causing high CPU usage and optimize or scale resources."- case SignalHighMemory:- return "Identify memory-heavy processes and consider increasing memory or tuning workloads."- case SignalHighDisk:- return "Investigate disk usage growth and clean up or expand storage as needed."- case SignalBackupFailed:- return "Review backup logs and fix the underlying error, then rerun the backup."- case SignalBackupStale:- return "Ensure backups are scheduled and completing successfully; run a new backup."- case SignalGuestUnreachable:- return "Investigate why this guest is not responding to ping. Check network configuration, firewall rules, or whether the guest has crashed."- default:- return "Investigate the signal and take corrective action if needed."- }-}-// getPatrolSystemPrompt returns the system prompt for AI patrol analysis.// The new agentic prompt instructs the LLM to use investigation tools and// report findings via the patrol_report_finding tool instead of text blocks.diff --git a/internal/ai/patrol_ai_eval_additional_test.go b/internal/ai/patrol_ai_eval_additional_test.goindex 9a7a0e4d7e..27b129dda6 100644--- a/internal/ai/patrol_ai_eval_additional_test.go+++ b/internal/ai/patrol_ai_eval_additional_test.go@@ -7,18 +7,8 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/tools""github.com/rcourtman/pulse-go-rewrite/internal/config"- "github.com/rcourtman/pulse-go-rewrite/internal/models")-func TestIsInvestigationTool(t *testing.T) {- if !isInvestigationTool("pulse_query") || !isInvestigationTool("pulse_metrics") || !isInvestigationTool("pulse_storage") || !isInvestigationTool("pulse_read") {- t.Fatal("expected investigation tools to be recognized")- }- if isInvestigationTool("pulse_control") {- t.Fatal("expected non-investigation tool to be false")- }-}-func TestFormatToolResult(t *testing.T) {result := tools.CallToolResult{Content: []tools.Content{@@ -60,67 +50,6 @@ func TestEvalPromptBuilders(t *testing.T) {}}-func TestSignalHelpersAndFindingsFromSignals(t *testing.T) {- cases := []struct {- signal DetectedSignal- wantKey string- wantTitle string- recSubstring string- }{- {signal: DetectedSignal{SignalType: SignalSMARTFailure}, wantKey: "smart-failure", wantTitle: "SMART health check failed", recSubstring: "disk"},- {signal: DetectedSignal{SignalType: SignalHighCPU}, wantKey: "cpu-high", wantTitle: "High CPU usage detected", recSubstring: "CPU"},- {signal: DetectedSignal{SignalType: SignalHighMemory}, wantKey: "memory-high", wantTitle: "High memory usage detected", recSubstring: "memory"},- {signal: DetectedSignal{SignalType: SignalHighDisk}, wantKey: "disk-high", wantTitle: "Storage usage is high", recSubstring: "storage"},- {signal: DetectedSignal{SignalType: SignalBackupFailed}, wantKey: "backup-failed", wantTitle: "Backup failed", recSubstring: "backup"},- {signal: DetectedSignal{SignalType: SignalBackupStale}, wantKey: "backup-stale", wantTitle: "Backup is stale", recSubstring: "backup"},- {signal: DetectedSignal{SignalType: SignalGuestUnreachable, ResourceName: "db-server"}, wantKey: "guest-unreachable", wantTitle: "Guest unreachable: db-server", recSubstring: "ping"},- {signal: DetectedSignal{SignalType: SignalType("unknown")}, wantKey: "deterministic-signal", wantTitle: "Infrastructure signal detected", recSubstring: "Investigate"},- }-- for _, c := range cases {- if got := signalKey(c.signal); got != c.wantKey {- t.Fatalf("signalKey(%s) = %s, want %s", c.signal.SignalType, got, c.wantKey)- }- if got := signalTitle(c.signal); got != c.wantTitle {- t.Fatalf("signalTitle(%s) = %s, want %s", c.signal.SignalType, got, c.wantTitle)- }- if !strings.Contains(defaultRecommendationForSignal(c.signal), c.recSubstring) {- t.Fatalf("unexpected recommendation for %s: %s", c.signal.SignalType, defaultRecommendationForSignal(c.signal))- }- }-- ps := NewPatrolService(nil, nil)- adapter := newPatrolFindingCreatorAdapterState(ps, patrolRuntimeStateForTest(ps, models.StateSnapshot{}))-- signals := []DetectedSignal{- {- SignalType: SignalHighCPU,- ResourceID: "node-1",- ResourceName: "",- ResourceType: "",- SuggestedSeverity: "",- Category: "",- Summary: "CPU high",- Evidence: "cpu=99%",- },- {- SignalType: SignalBackupFailed,- ResourceID: "vm-101",- ResourceName: "vm-101",- ResourceType: "vm",- SuggestedSeverity: "warning",- Category: "backup",- Summary: "Backup failed",- Evidence: "job failed",- },- }-- created := ps.createFindingsFromSignals(adapter, signals)- if created != len(signals) {- t.Fatalf("expected %d findings created, got %d", len(signals), created)- }-}-func TestRunEvaluationPass(t *testing.T) {ps := NewPatrolService(&Service{}, nil)_, err := ps.runEvaluationPass(context.Background(), nil, []DetectedSignal{{SignalType: SignalHighCPU}}, "patrol-run-eval")diff --git a/internal/ai/patrol_ai_more_test.go b/internal/ai/patrol_ai_more_test.goindex ae04d0161b..f5b195b13e 100644--- a/internal/ai/patrol_ai_more_test.go+++ b/internal/ai/patrol_ai_more_test.go@@ -6,7 +6,6 @@ import ("fmt""reflect""strings"- "sync""testing""time"@@ -170,25 +169,6 @@ func TestComputePatrolMaxTurns(t *testing.T) {}}-func TestEnsureInvestigationToolCall_NoOp(t *testing.T) {- ps := NewPatrolService(nil, nil)- ctx := context.Background()-- var mu sync.Mutex- completed := []ToolCallRecord{{ToolName: "pulse_query"}}- raw := []string{"existing"}-- ps.ensureInvestigationToolCall(ctx, &tools.PulseToolExecutor{}, &mu, &completed, &raw, true)- if len(completed) != 1 || len(raw) != 1 {- t.Fatalf("expected no changes when investigation tool already present")- }-- ps.ensureInvestigationToolCall(ctx, nil, &mu, &completed, &raw, true)- if len(completed) != 1 || len(raw) != 1 {- t.Fatalf("expected no changes when executor is nil")- }-}-func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {svc := &Service{cfg: &config.AIConfig{PatrolAutoFix: true}}ps := NewPatrolService(svc, nil)diff --git a/internal/ai/patrol_assistant_handoff.go b/internal/ai/patrol_assistant_handoff.goindex a0523abefa..70f993d9eb 100644--- a/internal/ai/patrol_assistant_handoff.go+++ b/internal/ai/patrol_assistant_handoff.go@@ -314,7 +314,7 @@ func patrolRunEffortSummary(run PatrolRunRecord) string {countPatrolRunSingularFact(run.TriageFlags, "triage flag"),}if run.TriageSkippedLLM {- parts = append(parts, "LLM skipped for deterministic triage")+ parts = append(parts, "legacy quiet-triage run skipped LLM")}if tokenCount > 0 {parts = append(parts, fmt.Sprintf("%d tokens", tokenCount))diff --git a/internal/ai/patrol_init.go b/internal/ai/patrol_init.goindex 79af89719d..2160755e43 100644--- a/internal/ai/patrol_init.go+++ b/internal/ai/patrol_init.go@@ -216,7 +216,7 @@ func (p *PatrolService) SetCircuitBreaker(breaker *circuit.Breaker) {log.Info().Msg("circuit breaker configured for patrol")}-// SetRemediationEngine sets the remediation engine for generating fix plans from findings.+// SetRemediationEngine sets the governed plan store/executor for model-proposed fixes.func (p *PatrolService) SetRemediationEngine(engine aicontracts.RemediationEngine) {p.mu.Lock()defer p.mu.Unlock()diff --git a/internal/ai/patrol_metrics.go b/internal/ai/patrol_metrics.goindex 2be3ca6594..461da275f2 100644--- a/internal/ai/patrol_metrics.go+++ b/internal/ai/patrol_metrics.go@@ -222,7 +222,7 @@ func (m *PatrolMetrics) RecordTriageFlags(count int) {m.triageFlags.Observe(float64(count))}-// RecordTriageQuiet records a patrol run that skipped LLM due to quiet infrastructure.+// RecordTriageQuiet records a patrol run whose pre-model triage found no flags.func (m *PatrolMetrics) RecordTriageQuiet() {m.triageQuietTotal.Inc()}diff --git a/internal/ai/patrol_triage_integration_test.go b/internal/ai/patrol_triage_integration_test.goindex 32a77f0d1e..991e95b645 100644--- a/internal/ai/patrol_triage_integration_test.go+++ b/internal/ai/patrol_triage_integration_test.go@@ -6,12 +6,32 @@ import ("strings""testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models")-func TestRunAIAnalysis_TriageQuietSkipsLLM(t *testing.T) {- ps := NewPatrolService(&Service{}, nil)+func TestRunAIAnalysis_TriageQuietStillCallsLLM(t *testing.T) {+ svc := NewService(config.NewConfigPersistence(t.TempDir()), nil)+ svc.cfg = &config.AIConfig{Enabled: true, PatrolModel: "mock:model"}++ calls := 0+ svc.SetChatService(&mockChatService{+ executor: tools.NewPulseToolExecutor(tools.ExecutorConfig{}),+ executePatrolStreamFunc: func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {+ calls+++ if !strings.Contains(req.Prompt, "# Deterministic Triage Results") {+ t.Fatalf("expected quiet triage context in model prompt, got:\n%s", req.Prompt)+ }+ return &PatrolStreamResponse{+ Content: "No issues found after reviewing the provided infrastructure context.",+ InputTokens: 10,+ OutputTokens: 6,+ }, nil+ },+ })++ ps := NewPatrolService(svc, nil)state := models.StateSnapshot{}triage := ps.runDeterministicTriageState(context.Background(), patrolRuntimeStateForTest(ps, state), nil, nil)@@ -29,8 +49,14 @@ func TestRunAIAnalysis_TriageQuietSkipsLLM(t *testing.T) {if res == nil {t.Fatal("expected analysis result")}- if !strings.Contains(res.Response, "Infrastructure healthy") {- t.Fatalf("expected quiet short-circuit response, got: %q", res.Response)+ if calls != 1 {+ t.Fatalf("expected quiet patrol to call the model once, got %d", calls)+ }+ if res.TriageSkippedLLM {+ t.Fatal("quiet patrol should not mark LLM as skipped")+ }+ if !strings.Contains(res.Response, "No issues found") {+ t.Fatalf("expected model response, got: %q", res.Response)}}diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.goindex 4d70fd5502..c953cca147 100644--- a/internal/ai/tools/executor.go+++ b/internal/ai/tools/executor.go@@ -597,9 +597,9 @@ type PulseToolExecutor struct {type TelemetryCallback interface {// RecordStrictResolutionBlock records when strict resolution blocks an actionRecordStrictResolutionBlock(tool, action string)- // RecordAutoRecoveryAttempt records an auto-recovery attempt+ // RecordAutoRecoveryAttempt records when a model receives a recoverable policy block.RecordAutoRecoveryAttempt(errorCode, tool string)- // RecordAutoRecoverySuccess records a successful auto-recovery+ // RecordAutoRecoverySuccess records model-owned follow-up success after a policy block.RecordAutoRecoverySuccess(errorCode, tool string)// RecordRoutingMismatchBlock records when routing validation blocks an operation// that targeted a parent host when a child resource was recently referenced.diff --git a/internal/ai/tools/strict_resolution_test.go b/internal/ai/tools/strict_resolution_test.goindex 149d2fc0f1..1132adc318 100644--- a/internal/ai/tools/strict_resolution_test.go+++ b/internal/ai/tools/strict_resolution_test.go@@ -632,8 +632,11 @@ func TestErrRoutingMismatch(t *testing.T) {if len(resources) != 2 || resources[0] != "homepage-docker" {t.Errorf("Details[more_specific_resources] = %v, want [homepage-docker jellyfin]", resources)}- if response.Error.Details["auto_recoverable"] != true {- t.Error("Details[auto_recoverable] should be true")+ if response.Error.Details["auto_recoverable"] != nil {+ t.Error("Details[auto_recoverable] should not be present")+ }+ if response.Error.Details["policy_boundary"] == nil {+ t.Error("Details[policy_boundary] should be present")}}@@ -689,17 +692,16 @@ func TestRoutingMismatch_RegressionHomepageScenario(t *testing.T) {response := err.ToToolResponse()- // Verify the error response has the right structure for auto-recovery- if response.Error.Details["auto_recoverable"] != true {- t.Error("ROUTING_MISMATCH should be auto_recoverable")+ // Verify the error response gives policy facts without directing a retry.+ if response.Error.Details["auto_recoverable"] != nil {+ t.Error("ROUTING_MISMATCH should not expose auto_recoverable")}-- hint, ok := response.Error.Details["recovery_hint"].(string)+ policy, ok := response.Error.Details["policy_boundary"].(string)if !ok {- t.Fatal("recovery_hint should be a string")+ t.Fatal("policy_boundary should be a string")}- if !containsString(hint, "homepage-docker") {- t.Errorf("recovery_hint should mention the specific resource: %s", hint)+ if !containsString(policy, "more specific child resource") {+ t.Errorf("policy_boundary should explain the routing boundary: %s", policy)}}@@ -1080,8 +1082,11 @@ func TestWriteExecutionContext_BlocksNodeFallbackForLXC(t *testing.T) {if response.Error.Details["resolved_kind"] != "system-container" {t.Errorf("Expected resolved_kind=system-container, got %v", response.Error.Details["resolved_kind"])}- if response.Error.Details["auto_recoverable"] != false {- t.Error("Expected auto_recoverable=false")+ if response.Error.Details["auto_recoverable"] != nil {+ t.Error("Expected auto_recoverable to be absent")+ }+ if response.Error.Details["policy_boundary"] == nil {+ t.Error("Expected policy_boundary")}t.Log("✓ Write to LXC blocked when routing would execute on node (no pct exec)")diff --git a/internal/ai/tools/tools_file.go b/internal/ai/tools/tools_file.goindex f1d546c615..b41ea8260f 100644--- a/internal/ai/tools/tools_file.go+++ b/internal/ai/tools/tools_file.go@@ -161,9 +161,9 @@ func (e *PulseToolExecutor) executeFileRead(ctx context.Context, path, targetHos"SENSITIVE_PATH",fmt.Sprintf("Refusing to read sensitive path '%s' (%s).", path, reason),map[string]interface{}{- "path": path,- "reason": reason,- "recovery_hint": "Avoid reading credential files. If you need a value, provide it manually or scope the request to non-sensitive config/log files.",+ "path": path,+ "reason": reason,+ "policy_boundary": "Credential files cannot be read through AI tools.",},)), nil}@@ -243,9 +243,9 @@ func (e *PulseToolExecutor) executeFileAppend(ctx context.Context, path, content"SENSITIVE_PATH",fmt.Sprintf("Refusing to write sensitive path '%s' (%s).", path, reason),map[string]interface{}{- "path": path,- "reason": reason,- "recovery_hint": "Avoid modifying credential files via AI. Apply this change manually if needed.",+ "path": path,+ "reason": reason,+ "policy_boundary": "Credential files cannot be modified through AI tools.",},)), nil}@@ -396,9 +396,9 @@ func (e *PulseToolExecutor) executeFileWrite(ctx context.Context, path, content,"SENSITIVE_PATH",fmt.Sprintf("Refusing to write sensitive path '%s' (%s).", path, reason),map[string]interface{}{- "path": path,- "reason": reason,- "recovery_hint": "Avoid modifying credential files via AI. Apply this change manually if needed.",+ "path": path,+ "reason": reason,+ "policy_boundary": "Credential files cannot be modified through AI tools.",},)), nil}@@ -636,12 +636,11 @@ func (e *ErrExecutionContextUnavailable) Error() string {func (e *ErrExecutionContextUnavailable) ToToolResponse() ToolResponse {return NewToolBlockedError("EXECUTION_CONTEXT_UNAVAILABLE", e.Message, map[string]interface{}{- "target_host": e.TargetHost,- "resolved_kind": e.ResolvedKind,- "resolved_node": e.ResolvedNode,- "transport": e.Transport,- "auto_recoverable": false,- "recovery_hint": "Cannot write files to this target. The execution context (container/VM) is not reachable via pct exec/qm guest exec. Verify the agent is installed on the host node and the target is running.",+ "target_host": e.TargetHost,+ "resolved_kind": e.ResolvedKind,+ "resolved_node": e.ResolvedNode,+ "transport": e.Transport,+ "policy_boundary": "Cannot write files to this target because the execution context is not reachable through the governed container/VM transport.",})}diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.goindex 580c16aa8c..445ab43235 100644--- a/internal/ai/tools/tools_query.go+++ b/internal/ai/tools/tools_query.go@@ -43,16 +43,15 @@ func (e *ErrStrictResolution) Code() string {}// ToToolResponse returns a consistent ToolResponse for blocked operations.-// This enables the agentic loop to detect and auto-recover (discover then retry).+// The model receives the policy facts and decides any follow-up tool use.func (e *ErrStrictResolution) ToToolResponse() ToolResponse {return NewToolBlockedError(ErrCodeStrictResolution,e.Message,map[string]interface{}{- "resource_id": e.ResourceID,- "action": e.Action,- "recovery_hint": "Resource discovery is required before resource-specific actions.",- "auto_recoverable": true, // Signal to agentic loop that auto-discovery can help+ "resource_id": e.ResourceID,+ "action": e.Action,+ "policy_boundary": "Resource discovery is required before resource-specific actions.",},)}@@ -94,22 +93,15 @@ func (e *ErrRoutingMismatch) ToToolResponse() ToolResponse {details := map[string]interface{}{"target_host": e.TargetHost,"more_specific_resources": e.MoreSpecificResources,- "auto_recoverable": true,}- // Include canonical IDs and prefer ID-based targeting in recovery hint+ // Include canonical IDs as facts for the model. Do not pick one as the+ // next tool target; the selected model owns that decision.if len(e.MoreSpecificIDs) > 0 {details["more_specific_resource_ids"] = e.MoreSpecificIDs- details["target_resource_id"] = e.MoreSpecificIDs[0] // Primary suggestion- // Prefer ID-based targeting; keep name-based targeting as a fallback.- details["recovery_hint"] = fmt.Sprintf(- "Retry with target_resource_id='%s' (preferred) or target_host='%s'",- e.MoreSpecificIDs[0], e.MoreSpecificResources[0])+ details["policy_boundary"] = "A more specific child resource exists on the requested host; choose the intended resource before retrying a scoped action."} else {- // Fallback if no IDs available- details["recovery_hint"] = fmt.Sprintf(- "Use target_host='%s' to target the specific resource, not the parent host node",- e.MoreSpecificResources[0])+ details["policy_boundary"] = "A more specific child resource exists on the requested host; choose the intended resource before retrying a scoped action."}return NewToolBlockedError(@@ -286,7 +278,7 @@ func classifySingleCommand(command string) IntentResult {if niBlock := checkNonInteractiveGuardrails(command, cmdLower); niBlock != nil {return IntentResult{Intent: IntentWriteOrUnknown,- Reason: niBlock.FormatMessage(),+ Reason: niBlock.Message,NonInteractiveBlock: niBlock,}}@@ -378,12 +370,10 @@ func checkMutationCapabilityGuards(command, cmdLower string) string {return ""}-// NonInteractiveBlockResult contains structured information about a NonInteractiveOnly block.+// NonInteractiveBlockResult contains structured policy facts about a NonInteractiveOnly block.type NonInteractiveBlockResult struct {- Category string // telemetry category: tty_flag, pager, unbounded_stream, interactive_repl- Message string // human-readable reason- SuggestedCmd string // drop-in rewrite suggestion (empty if none available)- AutoRecoverable bool // true if the suggested rewrite is safe for auto-recovery+ Category string // telemetry category: tty_flag, pager, unbounded_stream, interactive_repl+ Message string // human-readable reason}// checkNonInteractiveGuardrails enforces the exit-boundedness invariant:@@ -400,228 +390,46 @@ func checkNonInteractiveGuardrails(command, cmdLower string) *NonInteractiveBloc// [tty_flag] Interactive TTY flags allocate a terminalif hasInteractiveTTYFlags(cmdLower) {return &NonInteractiveBlockResult{- Category: "tty_flag",- Message: "[tty_flag] interactive/TTY flags require terminal; use non-interactive form",- SuggestedCmd: suggestNonInteractiveTTY(command),- AutoRecoverable: true,+ Category: "tty_flag",+ Message: "[tty_flag] interactive/TTY flags require terminal; pulse_read requires bounded non-interactive commands",}}// [pager] Pager and editor tools require terminal interactionif isPagerOrEditorTool(cmdLower) {return &NonInteractiveBlockResult{- Category: "pager",- Message: "[pager] pager/editor tools require terminal; use cat, head, or tail instead",- SuggestedCmd: suggestPagerReplacement(command, cmdLower),- AutoRecoverable: true,+ Category: "pager",+ Message: "[pager] pager/editor tools require terminal; pulse_read requires bounded non-interactive commands",}}// [unbounded_stream] Live monitoring tools never terminateif isLiveMonitoringTool(cmdLower) {return &NonInteractiveBlockResult{- Category: "unbounded_stream",- Message: "[unbounded_stream] live monitoring tools run indefinitely; use bounded alternatives",- SuggestedCmd: suggestLiveMonitoringReplacement(command, cmdLower),- AutoRecoverable: true,+ Category: "unbounded_stream",+ Message: "[unbounded_stream] live monitoring tools run indefinitely; pulse_read requires commands that terminate deterministically",}}// [unbounded_stream] Follow mode without explicit boundif isUnboundedStreaming(cmdLower) {return &NonInteractiveBlockResult{- Category: "unbounded_stream",- Message: "[unbounded_stream] follow mode without bound; add --tail/--since or wrap with timeout",- SuggestedCmd: suggestBoundedStreaming(command, cmdLower),- AutoRecoverable: true,+ Category: "unbounded_stream",+ Message: "[unbounded_stream] follow mode without bound; pulse_read requires commands that terminate deterministically",}}// [interactive_repl] Commands that open REPL/interactive sessionif isInteractiveREPL(cmdLower) {return &NonInteractiveBlockResult{- Category: "interactive_repl",- Message: "[interactive_repl] command opens interactive session; add -c/--execute flag or inline command",- SuggestedCmd: suggestNonInteractiveREPL(command, cmdLower),- AutoRecoverable: false, // REPL rewrites need human judgment (what query to run?)+ Category: "interactive_repl",+ Message: "[interactive_repl] command opens interactive session; pulse_read requires bounded non-interactive commands",}}return nil}-// FormatNonInteractiveBlock formats a block result for tool response.-func (r *NonInteractiveBlockResult) FormatMessage() string {- if r.SuggestedCmd != "" {- return fmt.Sprintf("%s\n\nSuggested rewrite:\n %s", r.Message, r.SuggestedCmd)- }- return r.Message-}--// suggestNonInteractiveTTY suggests removing -it flags from docker/kubectl commands.-func suggestNonInteractiveTTY(command string) string {- // Remove -it, -i -t, --interactive, --tty flags- result := command- replacements := []struct{ old, new string }{- {" -it ", " "},- {" -i -t ", " "},- {" -ti ", " "},- {" --interactive --tty ", " "},- {" --tty --interactive ", " "},- {" --interactive ", " "},- {" --tty ", " "},- }- for _, r := range replacements {- result = strings.ReplaceAll(result, r.old, r.new)- }- // Clean up double spaces- for strings.Contains(result, " ") {- result = strings.ReplaceAll(result, " ", " ")- }- if result != command {- return strings.TrimSpace(result)- }- return ""-}--// suggestPagerReplacement suggests cat/head/tail instead of pagers.-func suggestPagerReplacement(command, cmdLower string) string {- parts := strings.Fields(command)- if len(parts) < 2 {- return ""- }- // Extract the file argument (everything after the pager command)- fileArgs := strings.Join(parts[1:], " ")- pager := strings.ToLower(parts[0])-- switch pager {- case "less", "more":- return fmt.Sprintf("cat %s | head -200", fileArgs)- case "vim", "vi", "nano", "emacs", "pico", "ed":- return fmt.Sprintf("cat %s", fileArgs)- }- return ""-}--// suggestLiveMonitoringReplacement suggests bounded alternatives for live tools.-func suggestLiveMonitoringReplacement(command, cmdLower string) string {- parts := strings.Fields(cmdLower)- if len(parts) == 0 {- return ""- }- tool := parts[0]-- switch tool {- case "top", "htop", "atop":- return "ps aux --sort=-%cpu | head -20"- case "iotop":- return "iotop -b -n 1" // batch mode, 1 iteration- case "iftop", "nload":- return "ss -s" // socket statistics summary- case "watch":- // Extract the watched command and suggest running it once- if len(parts) > 1 {- // Skip watch and any flags like -n 1- cmdStart := 1- for i := 1; i < len(parts); i++ {- if strings.HasPrefix(parts[i], "-") {- cmdStart = i + 1- if parts[i] == "-n" && i+1 < len(parts) {- cmdStart = i + 2- }- } else {- break- }- }- if cmdStart < len(parts) {- watchedCmd := strings.Join(strings.Fields(command)[cmdStart:], " ")- return strings.Trim(watchedCmd, "'\"")- }- }- }- return ""-}--// suggestBoundedStreaming adds --tail/--since bounds to streaming commands.-func suggestBoundedStreaming(command, cmdLower string) string {- parts := strings.Fields(command)- if len(parts) == 0 {- return ""- }- tool := strings.ToLower(parts[0])-- switch {- case tool == "tail":- // tail -f /var/log/app.log → tail -n 200 --follow=name /var/log/app.log (or just remove -f)- // Simplest: add -n 200 and keep -f for "recent + follow with bound"- // Or suggest removing -f entirely- result := strings.ReplaceAll(command, " -f", " -n 200")- result = strings.ReplaceAll(result, " --follow", " -n 200")- return result-- case tool == "journalctl":- // journalctl -f → journalctl -n 200 --since "10 min ago"- result := command- if strings.Contains(cmdLower, " -f") {- result = strings.ReplaceAll(result, " -f", ` -n 200 --since "10 min ago"`)- }- if strings.Contains(cmdLower, " --follow") {- result = strings.ReplaceAll(result, " --follow", ` -n 200 --since "10 min ago"`)- }- return result-- case strings.HasPrefix(tool, "docker") && strings.Contains(cmdLower, "logs"):- // docker logs -f container → docker logs --tail=200 container- result := strings.ReplaceAll(command, " -f ", " --tail=200 ")- result = strings.ReplaceAll(result, " -f", " --tail=200")- result = strings.ReplaceAll(result, " --follow ", " --tail=200 ")- result = strings.ReplaceAll(result, " --follow", " --tail=200")- return result-- case strings.HasPrefix(tool, "kubectl") && strings.Contains(cmdLower, "logs"):- // kubectl logs -f pod → kubectl logs --tail=200 --since=10m pod- result := strings.ReplaceAll(command, " -f ", " --tail=200 --since=10m ")- result = strings.ReplaceAll(result, " -f", " --tail=200 --since=10m")- result = strings.ReplaceAll(result, " --follow ", " --tail=200 --since=10m ")- result = strings.ReplaceAll(result, " --follow", " --tail=200 --since=10m")- return result-- case tool == "dmesg":- // dmesg -w → dmesg | tail -200- result := strings.ReplaceAll(command, " -w", "")- result = strings.ReplaceAll(result, " --follow", "")- return result + " | tail -200"- }- return ""-}--// suggestNonInteractiveREPL suggests non-interactive form for REPL commands.-// Returns empty string for cases needing human judgment (what query to run?).-func suggestNonInteractiveREPL(command, cmdLower string) string {- parts := strings.Fields(command)- if len(parts) == 0 {- return ""- }- tool := strings.ToLower(parts[0])-- // For SQL CLIs and REPLs, we can't suggest a specific query- // but we can show the pattern- switch tool {- case "mysql", "mariadb":- return fmt.Sprintf("%s -e \"SELECT ...\"", command)- case "psql":- return fmt.Sprintf("%s -c \"SELECT ...\"", command)- case "sqlite3":- return fmt.Sprintf("%s \"SELECT ...\"", command)- case "redis-cli":- return fmt.Sprintf("%s PING", command)- case "ssh":- // ssh host → ssh host "command"- return fmt.Sprintf("%s \"ls -la\"", command)- }- return ""-}-// hasInteractiveTTYFlags detects flags that request interactive/TTY mode.func hasInteractiveTTYFlags(cmdLower string) bool {// Only check for docker/kubectl commandsdiff --git a/internal/ai/tools/tools_read.go b/internal/ai/tools/tools_read.goindex ac6f42ad36..99dd91214d 100644--- a/internal/ai/tools/tools_read.go+++ b/internal/ai/tools/tools_read.go@@ -129,8 +129,8 @@ func (e *PulseToolExecutor) executeReadExec(ctx context.Context, args map[string"SENSITIVE_COMMAND",fmt.Sprintf("Refusing to run command that touches sensitive paths (%s).", reason),map[string]interface{}{- "reason": reason,- "recovery_hint": "Avoid reading credential files or process env via AI tools. Scope the request to non-sensitive logs/status output instead.",+ "reason": reason,+ "policy_boundary": "Credential files and process environment values cannot be read through AI tools.",},)), nil}@@ -151,15 +151,9 @@ func (e *PulseToolExecutor) executeReadExec(ctx context.Context, args map[string"alternative": alternative,}- // If this is a NonInteractiveOnly block with a suggested rewrite,- // include auto-recovery informationif niBlock := intentResult.NonInteractiveBlock; niBlock != nil {- details["auto_recoverable"] = niBlock.AutoRecoverabledetails["category"] = niBlock.Category- if niBlock.SuggestedCmd != "" {- details["suggested_rewrite"] = niBlock.SuggestedCmd- details["recovery_hint"] = fmt.Sprintf("Retry with: %s", niBlock.SuggestedCmd)- }+ details["policy_boundary"] = "pulse_read only accepts bounded, non-interactive, read-only commands."}return NewToolResponseResult(NewToolBlockedError(@@ -555,20 +549,9 @@ func blockedNativeReadLogsResult(resolved ResolvedResourceInfo, resourceRef, concontainerName = resourceName}if targetHost != "" {- suggestedArgs := map[string]interface{}{- "action": "logs",- "target_host": targetHost,- "container": containerName,- }- if lines > 0 {- suggestedArgs["lines"] = lines- }details["target_host"] = targetHostdetails["container"] = containerName- details["auto_recoverable"] = true- details["suggested_tool"] = "pulse_read"- details["suggested_arguments"] = suggestedArgs- details["recovery_hint"] = fmt.Sprintf(+ details["policy_boundary"] = fmt.Sprintf("App logs on this platform are addressed with target_host=%q and container=%q.",targetHost,containerName,@@ -589,15 +572,9 @@ func blockedNativeReadLogsResult(resolved ResolvedResourceInfo, resourceRef, conif queryResourceID == "" {queryResourceID = resourceRef}- suggestedArgs := map[string]interface{}{- "action": "get",- "resource_type": queryType,- "resource_id": queryResourceID,- }- details["auto_recoverable"] = true- details["suggested_tool"] = "pulse_query"- details["suggested_arguments"] = suggestedArgs- details["recovery_hint"] = fmt.Sprintf(+ details["query_resource_type"] = queryType+ details["query_resource_id"] = queryResourceID+ details["policy_boundary"] = fmt.Sprintf("Status, alerts, activity, and metrics are addressed with resource_type=%q and resource_id=%q.",queryType,queryResourceID,diff --git a/internal/ai/tools/tools_read_test.go b/internal/ai/tools/tools_read_test.goindex dc7916c69e..d013ff650b 100644--- a/internal/ai/tools/tools_read_test.go+++ b/internal/ai/tools/tools_read_test.go@@ -277,18 +277,15 @@ func TestExecuteReadLogs_VMwareResourcesReturnStructuredQueryGuidance(t *testingassert.Contains(t, payload.Error.Message, "does not expose native logs through pulse_read")assert.Equal(t, tc.wantKind, payload.Error.Details["resource_type"])assert.Equal(t, "vmware-vsphere", payload.Error.Details["adapter"])- assert.Equal(t, true, payload.Error.Details["auto_recoverable"])- assert.Equal(t, "pulse_query", payload.Error.Details["suggested_tool"])+ assert.NotContains(t, payload.Error.Details, "auto_recoverable")+ assert.NotContains(t, payload.Error.Details, "suggested_tool")+ assert.NotContains(t, payload.Error.Details, "suggested_arguments")- hint, ok := payload.Error.Details["recovery_hint"].(string)+ policy, ok := payload.Error.Details["policy_boundary"].(string)require.True(t, ok)- assert.Contains(t, hint, `Status, alerts, activity, and metrics are addressed`)- assert.Contains(t, hint, `resource_type="`+tc.wantKind+`"`)-- suggestedArgs, ok := payload.Error.Details["suggested_arguments"].(map[string]interface{})- require.True(t, ok)- assert.Equal(t, "get", suggestedArgs["action"])- assert.Equal(t, tc.wantKind, suggestedArgs["resource_type"])+ assert.Contains(t, policy, `Status, alerts, activity, and metrics are addressed`)+ assert.Contains(t, policy, `resource_type="`+tc.wantKind+`"`)+ assert.Equal(t, tc.wantKind, payload.Error.Details["query_resource_type"])})}}@@ -329,19 +326,14 @@ func TestExecuteReadLogs_NonNativeAppContainersReturnStructuredTargetHostGuidancassert.Equal(t, "app-container", payload.Error.Details["resource_type"])assert.Equal(t, "docker-host", payload.Error.Details["target_host"])assert.Equal(t, "homepage", payload.Error.Details["container"])- assert.Equal(t, true, payload.Error.Details["auto_recoverable"])- assert.Equal(t, "pulse_read", payload.Error.Details["suggested_tool"])-- hint, ok := payload.Error.Details["recovery_hint"].(string)- require.True(t, ok)- assert.Contains(t, hint, `target_host="docker-host"`)- assert.Contains(t, hint, `container="homepage"`)+ assert.NotContains(t, payload.Error.Details, "auto_recoverable")+ assert.NotContains(t, payload.Error.Details, "suggested_tool")+ assert.NotContains(t, payload.Error.Details, "suggested_arguments")- suggestedArgs, ok := payload.Error.Details["suggested_arguments"].(map[string]interface{})+ policy, ok := payload.Error.Details["policy_boundary"].(string)require.True(t, ok)- assert.Equal(t, "logs", suggestedArgs["action"])- assert.Equal(t, "docker-host", suggestedArgs["target_host"])- assert.Equal(t, "homepage", suggestedArgs["container"])+ assert.Contains(t, policy, `target_host="docker-host"`)+ assert.Contains(t, policy, `container="homepage"`)}func decodeToolResponse(t *testing.T, result CallToolResult) ToolResponse {diff --git a/internal/ai/unified/integration.go b/internal/ai/unified/integration.goindex 237fad6d84..85049a42fc 100644--- a/internal/ai/unified/integration.go+++ b/internal/ai/unified/integration.go@@ -16,7 +16,6 @@ type Integration struct {// Component references for cross-feature integrationcorrelationEngine CorrelationEngine- remediationEngine RemediationEnginelearningStore LearningStore}@@ -26,12 +25,6 @@ type CorrelationEngine interface {AnalyzeForFinding(findingID string, resourceID string) (rootCauseID string, correlatedIDs []string, explanation string, err error)}-// RemediationEngine interface for remediation-type RemediationEngine interface {- // GeneratePlanForFinding generates a remediation plan for a finding- GeneratePlanForFinding(finding *UnifiedFinding) (planID string, err error)-}-// LearningStore interface for feedback learningtype LearningStore interface {// RecordFindingFeedback records user feedback on a finding@@ -83,11 +76,6 @@ func (i *Integration) SetCorrelationEngine(engine CorrelationEngine) {})}-// SetRemediationEngine sets the remediation engine-func (i *Integration) SetRemediationEngine(engine RemediationEngine) {- i.remediationEngine = engine-}-// SetLearningStore sets the learning storefunc (i *Integration) SetLearningStore(store LearningStore) {i.learningStore = store@@ -143,15 +131,6 @@ func (i *Integration) AddAIFinding(finding *UnifiedFinding) (*UnifiedFinding, boresult, isNew := i.store.AddFromAI(finding)- // Generate remediation plan for new findings- if isNew && i.remediationEngine != nil {- go func() {- if planID, err := i.remediationEngine.GeneratePlanForFinding(result); err == nil {- i.store.LinkRemediation(result.ID, planID)- }- }()- }-return result, isNew}diff --git a/internal/ai/unified/integration_test.go b/internal/ai/unified/integration_test.goindex 502e7f5a44..2216a84884 100644--- a/internal/ai/unified/integration_test.go+++ b/internal/ai/unified/integration_test.go@@ -20,19 +20,6 @@ func (s *stubCorrelationEngine) AnalyzeForFinding(findingID string, resourceID sreturn s.rootCauseID, s.correlated, s.explanation, s.returnErr}-type stubRemediationEngine struct {- planID string- err error- called chan string-}--func (s *stubRemediationEngine) GeneratePlanForFinding(finding *UnifiedFinding) (string, error) {- if s.called != nil {- s.called <- finding.ID- }- return s.planID, s.err-}-type stubLearningStore struct {suppress boollast string@@ -66,41 +53,6 @@ func TestIntegration_AddAIFinding_Suppressed(t *testing.T) {}}-func TestIntegration_AddAIFinding_Remediation(t *testing.T) {- integration := NewIntegration(DefaultIntegrationConfig(t.TempDir()))- remediation := &stubRemediationEngine{- planID: "plan-1",- called: make(chan string, 1),- }- integration.SetRemediationEngine(remediation)-- finding := &UnifiedFinding{- ID: "ai-1",- Source: SourceAIPatrol,- Severity: SeverityWarning,- Category: CategoryCapacity,- ResourceID: "res-1",- Title: "test",- }- integration.AddAIFinding(finding)-- select {- case <-remediation.called:- case <-time.After(200 * time.Millisecond):- t.Fatalf("expected remediation to be invoked")- }-- deadline := time.Now().Add(200 * time.Millisecond)- for time.Now().Before(deadline) {- stored := integration.store.Get(finding.ID)- if stored != nil && stored.RemediationID == "plan-1" {- return- }- time.Sleep(10 * time.Millisecond)- }- t.Fatalf("expected remediation ID to be linked")-}-func TestIntegration_EnhanceFindingWithCorrelation(t *testing.T) {integration := NewIntegration(DefaultIntegrationConfig(t.TempDir()))engine := &stubCorrelationEngine{