Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Bound Patrol follow-up execution

rcourtmand435b4c0c637
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 61066e70ea..d2dfc3fd66 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -6292,3 +6292,12 @@ organization binding and carry `settings:read` for export or `settings:write`
for import; tenant browser membership without management authority is denied.
This boundary neither enrolls nor mutates agent identity, tokens, command
sessions, fleet policy, or update state.
+
+### Patrol follow-up manifests do not confer agent authority
+
+`internal/api/chat_service_adapter.go` now forwards a structured tool-name
+allowlist for bounded Patrol continuations. This list is AI-runtime metadata
+that can only reduce the already projected detection manifest. It does not
+enroll an agent, select an agent identity, enable commands, grant a command
+session, alter fleet policy, or bypass agent-side preflight and action
+admission. Agent lifecycle and command authority remain unchanged.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index d0560aef1b..d2eba7a7a5 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -7153,3 +7153,32 @@ recovers and breaches again.
Changing the retained brief, optional context, or resource scope disables the
installed observer and clears its lease; coverage cannot survive a semantic
change to the intent it was designed to protect.
+
+### Patrol follow-up passes are exact-scope, least-manifest continuations
+
+Patrol's main Watch pass retains the full governed detection-profile manifest
+so the selected model owns evidence gathering and diagnosis. Bounded
+continuations do not repeat that broad manifest: the unmatched-signal
+evaluation pass receives only `patrol_report_finding` after the main pass has
+established one complete, unfiltered `patrol_get_findings` snapshot; when no
+complete snapshot exists it receives only `patrol_get_findings` plus
+`patrol_report_finding`. The assessment-completion sweep receives only
+`patrol_assess_finding`. These are structured call-site allowlists applied
+after profile projection and may only reduce authority. An unavailable or
+unknown requested tool fails closed. Prompt text never selects the manifest.
+
+An explicitly scoped Watch may carry related hosts or dependencies in its
+effective runtime snapshot as model evidence, but active, dismissed, and
+snoozed finding lifecycle context is seeded from the exact caller-requested
+resource identities. A dependency finding cannot therefore be refreshed or
+forced into an assessment merely because its resource helped explain the
+target. Deleted-resource reconciliation still uses the full current global
+state, and the synthetic Patrol runtime finding retains its existing special
+handling.
+
+Every provider tool call from the main pass, evaluation pass, and assessment
+sweep is merged into the one durable Patrol run trace, including raw provider
+arguments, failed calls, and bounded outputs. Qualification and operator
+forensics therefore see the complete model-owned decision path; a follow-up
+cannot hide a duplicate findings read or a failed lifecycle write in an
+ephemeral callback.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 29b117d07d..16f406582f 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -9465,3 +9465,14 @@ the canonical and shipped API references describe the same scope and tenant
rules. `config_transfer_authorization_test.go`, the contract ratchet in
`contract_test.go`, and the shipped-doc assertions in `docsLinks.test.ts` pin
the boundary and its published shape.
+
+### Internal Patrol bridge preserves bounded follow-up authority
+
+`internal/api/chat_service_adapter.go` forwards the AI runtime's structured
+`allowed_tool_names` field across the internal Patrol-to-chat boundary without
+deriving it from prompts or widening it. The chat service applies the list only
+after the Patrol detection profile has projected its canonical tool manifest;
+the list can remove tools but cannot add one, and unknown names fail closed.
+This is an internal execution contract, not a new HTTP field or client-granted
+capability. Existing Patrol routes, authorization, tenant binding, payloads,
+and action approval semantics are unchanged.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 2671e6e23a..c2d32252a4 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -5236,3 +5236,11 @@ transactional rollback, metadata replacement, and successful reload semantics
remain unchanged behind this boundary. The config-transfer router matrix and
existing archive compatibility/rollback tests jointly pin denial-before-access
and authorized recovery behavior.
+
+### Patrol follow-up manifests do not confer storage authority
+
+The structured bounded-tool allowlist forwarded by
+`internal/api/chat_service_adapter.go` is an AI-runtime authority reduction.
+It adds no storage, backup, snapshot, restore, retention, or recovery tool and
+cannot turn a detection pass into a mutation path. Storage and recovery state,
+evidence freshness, persistence, and admission contracts remain unchanged.
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 578ad0f958..07620ff904 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -2783,12 +2783,13 @@ func (s *Service) hydrateHandoffResources(sessionID string, handoffResources []H
// PatrolRequest represents a patrol execution request within the chat service
type PatrolRequest struct {
- Prompt string `json:"prompt"`
- SystemPrompt string `json:"system_prompt"`
- SessionID string `json:"session_id,omitempty"`
- ExecutionID string `json:"execution_id,omitempty"`
- UseCase string `json:"use_case"`
- MaxTurns int `json:"max_turns,omitempty"`
+ Prompt string `json:"prompt"`
+ SystemPrompt string `json:"system_prompt"`
+ SessionID string `json:"session_id,omitempty"`
+ ExecutionID string `json:"execution_id,omitempty"`
+ UseCase string `json:"use_case"`
+ MaxTurns int `json:"max_turns,omitempty"`
+ AllowedToolNames []string `json:"allowed_tool_names,omitempty"`
}
// PatrolResponse contains the results of a patrol execution
@@ -2928,6 +2929,10 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
// Get governed tools for the Patrol run, projected from the same
// effective executor that will run them under the detection profile.
filteredTools := s.toolsForExecutor(executor, false)
+ filteredTools, err = restrictPatrolProviderTools(filteredTools, req.AllowedToolNames)
+ if err != nil {
+ return nil, err
+ }
// Run the agentic loop
resultMessages, err := tempLoop.ExecuteWithTools(ctx, session.ID, messages, filteredTools, callback)
@@ -2992,6 +2997,42 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
}, nil
}
+// restrictPatrolProviderTools applies a structured, call-site-owned authority
+// reduction after the Patrol execution profile has projected its governed
+// manifest. It can never add authority, and an unknown requested tool fails
+// closed rather than silently producing an incomplete follow-up pass.
+func restrictPatrolProviderTools(providerTools []providers.Tool, allowedNames []string) ([]providers.Tool, error) {
+ if len(allowedNames) == 0 {
+ return providerTools, nil
+ }
+
+ allowed := make(map[string]bool, len(allowedNames))
+ for _, name := range allowedNames {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return nil, fmt.Errorf("patrol allowed tool name must not be empty")
+ }
+ allowed[name] = true
+ }
+
+ filtered := make([]providers.Tool, 0, len(allowed))
+ for _, tool := range providerTools {
+ if allowed[tool.Name] {
+ filtered = append(filtered, tool)
+ delete(allowed, tool.Name)
+ }
+ }
+ if len(allowed) > 0 {
+ missing := make([]string, 0, len(allowed))
+ for name := range allowed {
+ missing = append(missing, name)
+ }
+ sort.Strings(missing)
+ return nil, fmt.Errorf("patrol allowed tools unavailable after profile projection: %s", strings.Join(missing, ", "))
+ }
+ return filtered, nil
+}
+
// createProviderForModel creates a streaming provider for a specific model string (provider:model format).
func (s *Service) createProviderForModel(modelStr string) (providers.StreamingProvider, error) {
if s.providerFactory != nil {
diff --git a/internal/ai/chat/service_patrol_additional_test.go b/internal/ai/chat/service_patrol_additional_test.go
index 18df3c2d6c..3c1b318dfb 100644
--- a/internal/ai/chat/service_patrol_additional_test.go
+++ b/internal/ai/chat/service_patrol_additional_test.go
@@ -242,6 +242,23 @@ func TestService_ExecutePatrolStream_Success(t *testing.T) {
}
}
+func TestRestrictPatrolProviderToolsFailsClosed(t *testing.T) {
+ available := []providers.Tool{
+ {Name: agentcapabilities.PatrolGetFindingsToolName},
+ {Name: agentcapabilities.PatrolReportFindingToolName},
+ }
+ filtered, err := restrictPatrolProviderTools(available, []string{agentcapabilities.PatrolReportFindingToolName})
+ if err != nil || len(filtered) != 1 || filtered[0].Name != agentcapabilities.PatrolReportFindingToolName {
+ t.Fatalf("restricted tools = %+v, err=%v; want report-finding only", filtered, err)
+ }
+ if _, err := restrictPatrolProviderTools(available, []string{"not-a-profile-tool"}); err == nil || !strings.Contains(err.Error(), "not-a-profile-tool") {
+ t.Fatalf("expected unavailable allowed tool to fail closed, got %v", err)
+ }
+ if _, err := restrictPatrolProviderTools(available, []string{""}); err == nil {
+ t.Fatal("expected blank allowed tool to fail closed")
+ }
+}
+
func TestServiceExecutePatrolStreamReturnsPartialTokenCountsOnError(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
if err != nil {
diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.go
index 3ea05c9dbd..5c7c69eb28 100644
--- a/internal/ai/patrol_ai.go
+++ b/internal/ai/patrol_ai.go
@@ -16,6 +16,7 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/correlation"
@@ -930,11 +931,14 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRunti
Msg("AI Patrol: Unmatched signals found, running evaluation pass")
evalResp, evalErr := p.runEvaluationPass(ctx, adapter, unmatchedSignals, executionID)
+ if evalResp != nil {
+ inputTokens += evalResp.InputTokens
+ outputTokens += evalResp.OutputTokens
+ collectedToolCalls = append(collectedToolCalls, evalResp.ToolCalls...)
+ }
if evalErr != nil {
log.Warn().Err(evalErr).Msg("AI Patrol: Evaluation pass failed")
} else if evalResp != nil {
- inputTokens += evalResp.InputTokens
- outputTokens += evalResp.OutputTokens
log.Info().
Int("eval_input_tokens", evalResp.InputTokens).
Int("eval_output_tokens", evalResp.OutputTokens).
@@ -967,11 +971,14 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRunti
Msg("AI Patrol: Verdicts missing after main pass, running assessment sweep")
sweepResp, sweepErr := p.runAssessmentSweep(ctx, missing, executionID)
+ if sweepResp != nil {
+ inputTokens += sweepResp.InputTokens
+ outputTokens += sweepResp.OutputTokens
+ collectedToolCalls = append(collectedToolCalls, sweepResp.ToolCalls...)
+ }
if sweepErr != nil {
log.Warn().Err(sweepErr).Msg("AI Patrol: Assessment sweep failed")
} else if sweepResp != nil {
- inputTokens += sweepResp.InputTokens
- outputTokens += sweepResp.OutputTokens
remaining := patrolMissingAssessmentIDs(buildAnalysisResult(finalContent, collectedToolCalls, inputTokens, outputTokens))
log.Info().
Int("swept", len(missing)-len(remaining)).
@@ -1060,6 +1067,136 @@ func triageFlagsToDetectedSignals(flags []TriageFlag) []DetectedSignal {
return signals
}
+// patrolFollowupTraceCollector captures the same provider tool lifecycle used
+// by the main pass for bounded evaluation and assessment calls. Keeping these
+// calls in the parent run record makes qualification and operator forensics
+// reflect the entire model-owned decision path, including failed calls.
+type patrolFollowupTraceCollector struct {
+ mu sync.Mutex
+ prefix string
+ pending map[string]ToolCallRecord
+ pendingOrder []string
+ completed []ToolCallRecord
+ anonCounter int
+}
+
+func newPatrolFollowupTraceCollector(prefix string) *patrolFollowupTraceCollector {
+ return &patrolFollowupTraceCollector{
+ prefix: strings.Trim(strings.TrimSpace(prefix), "/"),
+ pending: make(map[string]ToolCallRecord),
+ }
+}
+
+func (c *patrolFollowupTraceCollector) scopedID(id string) string {
+ id = strings.TrimSpace(id)
+ if c == nil || c.prefix == "" || id == "" {
+ return id
+ }
+ return c.prefix + "/" + id
+}
+
+func (c *patrolFollowupTraceCollector) callback(event ChatStreamEvent) {
+ if c == nil || (event.Type != "tool_start" && event.Type != "tool_end") {
+ return
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ switch event.Type {
+ case "tool_start":
+ var data struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input string `json:"input"`
+ RawInput string `json:"raw_input"`
+ }
+ if json.Unmarshal(event.Data, &data) != nil {
+ return
+ }
+ if data.ID == "" {
+ c.anonCounter++
+ data.ID = fmt.Sprintf("anon-%d", c.anonCounter)
+ }
+ data.ID = c.scopedID(data.ID)
+ input := data.Input
+ if data.RawInput != "" {
+ input = data.RawInput
+ }
+ c.pendingOrder = append(c.pendingOrder, data.ID)
+ c.pending[data.ID] = ToolCallRecord{
+ ID: data.ID,
+ ToolName: data.Name,
+ Input: truncateString(input, MaxToolInputSize),
+ StartTime: time.Now().UnixMilli(),
+ }
+ case "tool_end":
+ var data struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input string `json:"input"`
+ RawInput string `json:"raw_input"`
+ Output string `json:"output"`
+ Success bool `json:"success"`
+ }
+ if json.Unmarshal(event.Data, &data) != nil {
+ return
+ }
+ if data.ID == "" {
+ if len(c.pendingOrder) > 0 {
+ data.ID = c.pendingOrder[0]
+ c.pendingOrder = c.pendingOrder[1:]
+ } else {
+ c.anonCounter++
+ data.ID = c.scopedID(fmt.Sprintf("anon-end-%d", c.anonCounter))
+ }
+ } else {
+ data.ID = c.scopedID(data.ID)
+ for i, id := range c.pendingOrder {
+ if id == data.ID {
+ c.pendingOrder = append(c.pendingOrder[:i], c.pendingOrder[i+1:]...)
+ break
+ }
+ }
+ }
+
+ now := time.Now().UnixMilli()
+ input := data.Input
+ if data.RawInput != "" {
+ input = data.RawInput
+ }
+ if call, ok := c.pending[data.ID]; ok {
+ if input != "" {
+ call.Input = truncateString(input, MaxToolInputSize)
+ }
+ call.Output = truncateString(data.Output, MaxToolOutputSize)
+ call.Success = data.Success
+ call.EndTime = now
+ call.Duration = now - call.StartTime
+ c.completed = append(c.completed, call)
+ delete(c.pending, data.ID)
+ return
+ }
+ c.completed = append(c.completed, ToolCallRecord{
+ ID: data.ID,
+ ToolName: data.Name,
+ Input: truncateString(input, MaxToolInputSize),
+ Output: truncateString(data.Output, MaxToolOutputSize),
+ Success: data.Success,
+ StartTime: now,
+ EndTime: now,
+ })
+ }
+}
+
+func (c *patrolFollowupTraceCollector) records() []ToolCallRecord {
+ if c == nil {
+ return nil
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]ToolCallRecord(nil), c.completed...)
+}
+
// runAssessmentSweep runs a bounded follow-up model pass that files the
// patrol_assess_finding verdicts the main pass left missing. Uncertain is an
// accepted verdict, so the pass asks for an honest call on the presented
@@ -1089,6 +1226,7 @@ func (p *PatrolService) runAssessmentSweep(ctx context.Context, missingIDs []str
maxTurns = 12
}
+ trace := newPatrolFollowupTraceCollector("assessment")
resp, err := cs.ExecutePatrolStream(ctx, PatrolExecuteRequest{
Prompt: buildAssessmentSweepUserPrompt(pending),
SystemPrompt: buildAssessmentSweepSystemPrompt(),
@@ -1096,11 +1234,13 @@ func (p *PatrolService) runAssessmentSweep(ctx context.Context, missingIDs []str
ExecutionID: executionID,
UseCase: "patrol",
MaxTurns: maxTurns,
- }, func(event ChatStreamEvent) {
- // Not streamed to the frontend — verdicts land via the adapter.
- })
+ AllowedToolNames: []string{
+ agentcapabilities.PatrolAssessFindingToolName,
+ },
+ }, trace.callback)
if resp != nil {
+ resp.ToolCalls = trace.records()
p.recordPatrolUsage(resp.InputTokens, resp.OutputTokens)
}
if err != nil {
@@ -1204,31 +1344,43 @@ func (p *PatrolService) runEvaluationPass(ctx context.Context, adapter *patrolFi
return nil, fmt.Errorf("patrol evaluation skipped: %w", err)
}
- systemPrompt := buildEvalSystemPrompt()
- userPrompt := buildEvalUserPrompt(unmatchedSignals)
+ findingsSnapshotEstablished := adapter != nil && adapter.HasCompleteFindingSnapshot()
+ var queriedFindings []tools.PatrolFindingInfo
+ allowedToolNames := []string{
+ agentcapabilities.PatrolGetFindingsToolName,
+ agentcapabilities.PatrolReportFindingToolName,
+ }
+ if findingsSnapshotEstablished {
+ queriedFindings = adapter.getQueriedFindings()
+ allowedToolNames = []string{agentcapabilities.PatrolReportFindingToolName}
+ }
+ systemPrompt := buildEvalSystemPrompt(findingsSnapshotEstablished)
+ userPrompt := buildEvalUserPrompt(unmatchedSignals, queriedFindings)
log.Info().
Int("unmatched_signals", len(unmatchedSignals)).
Msg("AI Patrol: Running evaluation pass for unmatched signals")
+ trace := newPatrolFollowupTraceCollector("evaluation")
resp, err := cs.ExecutePatrolStream(ctx, PatrolExecuteRequest{
- Prompt: userPrompt,
- SystemPrompt: systemPrompt,
- SessionID: "patrol-eval",
- ExecutionID: executionID,
- UseCase: "patrol",
- MaxTurns: 5,
- }, func(event ChatStreamEvent) {
- // Minimal callback — we don't stream eval pass to the frontend
- // but findings are still created via the adapter
- })
+ Prompt: userPrompt,
+ SystemPrompt: systemPrompt,
+ SessionID: "patrol-eval",
+ ExecutionID: executionID,
+ UseCase: "patrol",
+ MaxTurns: 5,
+ AllowedToolNames: allowedToolNames,
+ }, trace.callback)
+ if resp != nil {
+ resp.ToolCalls = trace.records()
+ }
if err != nil {
if resp != nil {
p.recordPatrolUsage(resp.InputTokens, resp.OutputTokens)
}
log.Warn().Err(err).Msg("AI Patrol: Evaluation pass failed")
- return nil, err
+ return resp, err
}
log.Info().
@@ -1285,7 +1437,23 @@ func (p *PatrolService) recordPatrolUsage(inputTokens, outputTokens int) {
}
// buildEvalSystemPrompt returns the system prompt for the evaluation pass.
-func buildEvalSystemPrompt() string {
+func buildEvalSystemPrompt(findingsSnapshotEstablished bool) string {
+ if findingsSnapshotEstablished {
+ return `You are a patrol evaluation agent reviewing infrastructure signals that were
+detected but not reported as findings.
+
+Tool: patrol_report_finding
+
+The active-finding snapshot from this run is already included below. Reuse it; do not request another findings read.
+
+Instructions:
+1. For each signal below, determine if it is a genuine issue requiring attention.
+2. If yes and not already covered by the supplied snapshot, call patrol_report_finding with complete details.
+3. If not actionable or already covered by an existing finding, skip it.
+4. Do NOT investigate further — use only the evidence provided below.
+
+When reporting, set ` + "`impact`" + ` to the concrete consequence-if-ignored — name the affected workloads, jobs, or recovery windows. Leave it empty rather than fabricating one if the consequence is genuinely unknown.`
+ }
return `You are a patrol evaluation agent reviewing infrastructure signals that were
detected but not reported as findings.
@@ -1302,10 +1470,22 @@ When reporting, set ` + "`impact`" + ` to the concrete consequence-if-ignored
}
// buildEvalUserPrompt formats the unmatched signals into a user prompt for the evaluation pass.
-func buildEvalUserPrompt(signals []DetectedSignal) string {
+func buildEvalUserPrompt(signals []DetectedSignal, existingFindings []tools.PatrolFindingInfo) string {
var sb strings.Builder
sb.WriteString("The following infrastructure signals were detected during patrol but were not reported as findings.\n")
sb.WriteString("Review each one and report genuine issues using patrol_report_finding.\n\n")
+ if existingFindings != nil {
+ sb.WriteString("# Active-finding snapshot already read in this patrol run\n")
+ if len(existingFindings) == 0 {
+ sb.WriteString("No active findings were returned for the exact caller scope.\n\n")
+ } else {
+ for _, finding := range existingFindings {
+ sb.WriteString(fmt.Sprintf("- [%s] %s on %s (resource ID: %s, severity: %s, category: %s)\n",
+ finding.ID, finding.Title, finding.ResourceName, finding.ResourceID, finding.Severity, finding.Category))
+ }
+ sb.WriteString("\n")
+ }
+ }
for i, s := range signals {
sb.WriteString(fmt.Sprintf("## Signal %d: %s\n", i+1, s.SignalType))
@@ -4111,6 +4291,21 @@ func (p *PatrolService) seedFindingsAndContextState(scope *PatrolScope, snap pat
scopedResources := patrolRuntimeKnownResources(snap)
stateHasScopedResources := len(scopedResources) > 0
+ // The effective runtime snapshot intentionally includes dependency context
+ // (for example a workload's host). Finding lifecycle is narrower: an
+ // explicitly scoped run may refresh only the caller-requested identities.
+ // Dependency resources remain model evidence, but their findings are not
+ // seeded, refreshed, assessed, or injected as dismissed feedback.
+ findingLifecycleResources := scopedResources
+ if scope != nil && len(scope.ResourceIDs) > 0 {
+ findingLifecycleResources = make(map[string]bool, len(scope.ResourceIDs))
+ for _, resourceID := range scope.ResourceIDs {
+ if resourceID = strings.TrimSpace(resourceID); resourceID != "" {
+ findingLifecycleResources[resourceID] = true
+ }
+ }
+ stateHasScopedResources = true
+ }
globalResources := scopedResources
current := p.currentPatrolRuntimeState()
globalResources = patrolRuntimeKnownResources(current)
@@ -4124,7 +4319,7 @@ func (p *PatrolService) seedFindingsAndContextState(scope *PatrolScope, snap pat
sb.WriteString("Verify whether these findings are still valid. Resolve any that are no longer issues.\n\n")
for _, f := range activeFindings {
usesSyntheticRuntimeResource := patrolFindingUsesSyntheticRuntimeResource(f)
- inScopedState := usesSyntheticRuntimeResource || !stateHasScopedResources || scopedResources[f.ResourceID] || scopedResources[f.ResourceName]
+ inScopedState := usesSyntheticRuntimeResource || !stateHasScopedResources || findingLifecycleResources[f.ResourceID] || findingLifecycleResources[f.ResourceName]
inGlobalState := usesSyntheticRuntimeResource || !stateHasGlobalResources || globalResources[f.ResourceID] || globalResources[f.ResourceName]
// Auto-resolve findings only when the resource is gone from the full current state.
@@ -4161,7 +4356,7 @@ func (p *PatrolService) seedFindingsAndContextState(scope *PatrolScope, snap pat
}
// --- Dismissed/Snoozed Findings ---
- feedbackContext := p.findings.GetDismissedForContextForResources(scopedResources)
+ feedbackContext := p.findings.GetDismissedForContextForResources(findingLifecycleResources)
if feedbackContext != "" {
sb.WriteString("# User Feedback on Previous Findings\n")
sb.WriteString("Do NOT re-raise findings the user has dismissed or snoozed.\n\n")
diff --git a/internal/ai/patrol_ai_eval_additional_test.go b/internal/ai/patrol_ai_eval_additional_test.go
index 11ca045ba8..5afcd6842c 100644
--- a/internal/ai/patrol_ai_eval_additional_test.go
+++ b/internal/ai/patrol_ai_eval_additional_test.go
@@ -2,17 +2,20 @@ package ai
import (
"context"
+ "encoding/json"
"errors"
"fmt"
+ "reflect"
"strings"
"testing"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
func TestEvalPromptBuilders(t *testing.T) {
- systemPrompt := buildEvalSystemPrompt()
+ systemPrompt := buildEvalSystemPrompt(false)
if !strings.Contains(systemPrompt, "patrol_report_finding") || !strings.Contains(systemPrompt, "patrol_get_findings") {
t.Fatalf("expected eval system prompt to include tool instructions")
}
@@ -33,7 +36,7 @@ func TestEvalPromptBuilders(t *testing.T) {
Evidence: "cpu=99%",
},
}
- userPrompt := buildEvalUserPrompt(signals)
+ userPrompt := buildEvalUserPrompt(signals, nil)
if !strings.Contains(userPrompt, "Signal 1") || !strings.Contains(userPrompt, "CPU high") || !strings.Contains(userPrompt, "cpu=99%") {
t.Fatalf("unexpected eval user prompt: %s", userPrompt)
}
@@ -105,8 +108,10 @@ func TestRunEvaluationPass(t *testing.T) {
persistence := config.NewConfigPersistence(t.TempDir())
svc := NewService(persistence, nil)
+ var captured PatrolExecuteRequest
mockCS := &patrolMockChatService{
executePatrolStreamFunc: func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {
+ captured = req
return &PatrolStreamResponse{Content: "ok", InputTokens: 10, OutputTokens: 20}, nil
},
}
@@ -120,6 +125,37 @@ func TestRunEvaluationPass(t *testing.T) {
if resp == nil || resp.InputTokens != 10 || resp.OutputTokens != 20 {
t.Fatalf("unexpected evaluation response: %+v", resp)
}
+ wantTools := []string{agentcapabilities.PatrolGetFindingsToolName, agentcapabilities.PatrolReportFindingToolName}
+ if !reflect.DeepEqual(captured.AllowedToolNames, wantTools) {
+ t.Fatalf("evaluation tools = %v, want %v", captured.AllowedToolNames, wantTools)
+ }
+}
+
+func TestRunEvaluationPassReusesEstablishedFindingSnapshot(t *testing.T) {
+ persistence := config.NewConfigPersistence(t.TempDir())
+ svc := NewService(persistence, nil)
+ var captured PatrolExecuteRequest
+ svc.SetChatService(&patrolMockChatService{
+ executePatrolStreamFunc: func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {
+ captured = req
+ return &PatrolStreamResponse{}, nil
+ },
+ })
+ adapter := &patrolFindingCreatorAdapter{
+ checkedFindings: true,
+ completeFindingSnapshot: true,
+ queriedFindings: []tools.PatrolFindingInfo{{ID: "finding-1", Title: "Existing", ResourceID: "node-1"}},
+ }
+ ps := NewPatrolService(svc, nil)
+ if _, err := ps.runEvaluationPass(context.Background(), adapter, []DetectedSignal{{SignalType: SignalHighCPU}}, "patrol-run-eval"); err != nil {
+ t.Fatalf("run evaluation: %v", err)
+ }
+ if !reflect.DeepEqual(captured.AllowedToolNames, []string{agentcapabilities.PatrolReportFindingToolName}) {
+ t.Fatalf("evaluation tools = %v, want report only", captured.AllowedToolNames)
+ }
+ if !strings.Contains(captured.Prompt, "finding-1") || !strings.Contains(captured.SystemPrompt, "already included") {
+ t.Fatalf("evaluation did not reuse established snapshot: system=%q prompt=%q", captured.SystemPrompt, captured.Prompt)
+ }
}
func TestRunEvaluationPassRecordsPartialUsageOnStreamError(t *testing.T) {
@@ -138,8 +174,8 @@ func TestRunEvaluationPassRecordsPartialUsageOnStreamError(t *testing.T) {
if err == nil {
t.Fatal("expected evaluation error")
}
- if resp != nil {
- t.Fatalf("expected no response on evaluation error, got %+v", resp)
+ if resp == nil || resp.InputTokens != 11 || resp.OutputTokens != 7 {
+ t.Fatalf("expected partial response on evaluation error, got %+v", resp)
}
events := svc.ListCostEvents(1)
if len(events) != 1 {
@@ -149,3 +185,21 @@ func TestRunEvaluationPassRecordsPartialUsageOnStreamError(t *testing.T) {
t.Fatalf("unexpected partial usage event: %+v", events[0])
}
}
+
+func TestPatrolFollowupTraceCollectorCapturesRawInputAndFailures(t *testing.T) {
+ collector := newPatrolFollowupTraceCollector("evaluation")
+ start, _ := json.Marshal(map[string]any{
+ "id": "call-1", "name": agentcapabilities.PatrolReportFindingToolName,
+ "input": "normalized", "raw_input": `{"resource_id":"node-1"}`,
+ })
+ end, _ := json.Marshal(map[string]any{
+ "id": "call-1", "name": agentcapabilities.PatrolReportFindingToolName,
+ "output": "rejected", "success": false,
+ })
+ collector.callback(ChatStreamEvent{Type: "tool_start", Data: start})
+ collector.callback(ChatStreamEvent{Type: "tool_end", Data: end})
+ records := collector.records()
+ if len(records) != 1 || records[0].ID != "evaluation/call-1" || records[0].Input != `{"resource_id":"node-1"}` || records[0].Output != "rejected" || records[0].Success {
+ t.Fatalf("unexpected follow-up trace: %+v", records)
+ }
+}
diff --git a/internal/ai/patrol_ai_intelligence_test.go b/internal/ai/patrol_ai_intelligence_test.go
index c5dee93ab7..1de5c92866 100644
--- a/internal/ai/patrol_ai_intelligence_test.go
+++ b/internal/ai/patrol_ai_intelligence_test.go
@@ -755,6 +755,51 @@ func TestSeedFindingsAndContext_ScopedPatrolSkipsOutOfScopeFindingsWithoutResolv
}
}
+func TestSeedFindingsAndContext_DependencyEvidenceDoesNotJoinExactFindingLifecycle(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ now := time.Now().Add(-time.Hour)
+ workload := &Finding{
+ ID: "workload-finding", ResourceID: "workload-1", ResourceName: "workload-1",
+ Title: "Workload unhealthy", Severity: FindingSeverityWarning, Category: FindingCategoryReliability,
+ DetectedAt: now, LastSeenAt: now,
+ }
+ host := &Finding{
+ ID: "host-finding", ResourceID: "host-1", ResourceName: "host-1",
+ Title: "Host packages pending", Severity: FindingSeverityWarning, Category: FindingCategoryGeneral,
+ DetectedAt: now, LastSeenAt: now,
+ }
+ dismissedHost := &Finding{
+ ID: "dismissed-host-finding", ResourceID: "host-1", ResourceName: "host-1",
+ Title: "Dismissed host issue", Severity: FindingSeverityWatch, Category: FindingCategoryGeneral,
+ DetectedAt: now, LastSeenAt: now,
+ }
+ ps.findings.Add(workload)
+ ps.findings.Add(host)
+ ps.findings.Add(dismissedHost)
+ ps.findings.Dismiss(dismissedHost.ID, "expected_behavior", "dependency-only feedback")
+
+ workloadView := ur.NewNodeView(&ur.Resource{ID: "workload-1", Name: "workload-1"})
+ hostView := ur.NewNodeView(&ur.Resource{ID: "host-1", Name: "host-1"})
+ state := &mockReadState{nodes: []*ur.NodeView{&workloadView, &hostView}}
+ ps.SetReadState(state)
+ effective := newPatrolRuntimeState(models.StateSnapshot{Nodes: []models.Node{
+ {ID: "workload-1", Name: "workload-1"},
+ {ID: "host-1", Name: "host-1"},
+ }})
+ effective.readState = state
+
+ output, seeded := ps.seedFindingsAndContextState(&PatrolScope{ResourceIDs: []string{"workload-1"}}, effective)
+ if len(seeded) != 1 || seeded[0] != workload.ID {
+ t.Fatalf("seeded findings = %v, want exact caller-scope finding only", seeded)
+ }
+ if !strings.Contains(output, workload.Title) || strings.Contains(output, host.Title) || strings.Contains(output, dismissedHost.Title) {
+ t.Fatalf("dependency finding lifecycle leaked into exact scope: %s", output)
+ }
+ if host.ResolvedAt != nil {
+ t.Fatalf("dependency finding was incorrectly resolved: %v", host.ResolvedAt)
+ }
+}
+
func TestSeedFindingsAndContext_KeepsSyntheticPatrolServiceFindings(t *testing.T) {
ps := NewPatrolService(nil, nil)
diff --git a/internal/ai/patrol_assessment_sweep_test.go b/internal/ai/patrol_assessment_sweep_test.go
index 8d9929fe55..f4a9b293ee 100644
--- a/internal/ai/patrol_assessment_sweep_test.go
+++ b/internal/ai/patrol_assessment_sweep_test.go
@@ -2,9 +2,11 @@ package ai
import (
"context"
+ "reflect"
"strings"
"testing"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
@@ -79,6 +81,9 @@ func TestRunAssessmentSweepFilesRequest(t *testing.T) {
if captured.MaxTurns != 3 {
t.Fatalf("expected maxTurns len(pending)+2=3, got %d", captured.MaxTurns)
}
+ if !reflect.DeepEqual(captured.AllowedToolNames, []string{agentcapabilities.PatrolAssessFindingToolName}) {
+ t.Fatalf("assessment tools = %v, want assess only", captured.AllowedToolNames)
+ }
if !strings.Contains(captured.Prompt, "0e7c5dbb86bdebe9") {
t.Fatalf("expected prompt to list the missing finding id")
}
diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.go
index 964aa80a0d..d19e469c65 100644
--- a/internal/ai/patrol_findings.go
+++ b/internal/ai/patrol_findings.go
@@ -511,14 +511,16 @@ type patrolFindingCreatorAdapter struct {
// resources must not silently join the finding lifecycle. A targeted Watch
// of one workload should not refresh an unrelated host finding merely
// because Pulse supplied the host as supporting evidence.
- findingScope map[string]bool
- findingsMu sync.Mutex
- findings []*Finding
- assessments []PatrolFindingAssessment
- queriedFindingIDs []string
- resolvedIDs []string
- rejectedCount int
- checkedFindings bool
+ findingScope map[string]bool
+ findingsMu sync.Mutex
+ findings []*Finding
+ assessments []PatrolFindingAssessment
+ queriedFindingIDs []string
+ queriedFindings []tools.PatrolFindingInfo
+ resolvedIDs []string
+ rejectedCount int
+ checkedFindings bool
+ completeFindingSnapshot bool
}
func (a *patrolFindingCreatorAdapter) setFindingScope(resourceIDs []string) {
@@ -1031,6 +1033,12 @@ func (a *patrolFindingCreatorAdapter) ResolveFinding(findingID, reason string) e
func (a *patrolFindingCreatorAdapter) GetActiveFindings(resourceID, minSeverity string) []tools.PatrolFindingInfo {
a.findingsMu.Lock()
a.checkedFindings = true
+ if strings.TrimSpace(resourceID) == "" {
+ minimum := strings.ToLower(strings.TrimSpace(minSeverity))
+ if minimum == "" || minimum == "info" {
+ a.completeFindingSnapshot = true
+ }
+ }
a.findingsMu.Unlock()
var minSev FindingSeverity
@@ -1054,7 +1062,7 @@ func (a *patrolFindingCreatorAdapter) GetActiveFindings(resourceID, minSeverity
if !a.findingInCurrentScope(f) {
continue
}
- result = append(result, tools.PatrolFindingInfo{
+ info := tools.PatrolFindingInfo{
ID: f.ID,
Key: f.Key,
Severity: string(f.Severity),
@@ -1065,7 +1073,8 @@ func (a *patrolFindingCreatorAdapter) GetActiveFindings(resourceID, minSeverity
Title: f.Title,
Description: f.Description,
DetectedAt: f.DetectedAt.Format("2006-01-02 15:04"),
- })
+ }
+ result = append(result, info)
a.findingsMu.Lock()
seen := false
for _, findingID := range a.queriedFindingIDs {
@@ -1076,6 +1085,7 @@ func (a *patrolFindingCreatorAdapter) GetActiveFindings(resourceID, minSeverity
}
if !seen {
a.queriedFindingIDs = append(a.queriedFindingIDs, f.ID)
+ a.queriedFindings = append(a.queriedFindings, info)
}
a.findingsMu.Unlock()
}
@@ -1088,6 +1098,15 @@ func (a *patrolFindingCreatorAdapter) HasCheckedFindings() bool {
return a.checkedFindings
}
+func (a *patrolFindingCreatorAdapter) HasCompleteFindingSnapshot() bool {
+ if a == nil {
+ return false
+ }
+ a.findingsMu.Lock()
+ defer a.findingsMu.Unlock()
+ return a.completeFindingSnapshot
+}
+
// getCollectedFindings returns all findings created during this patrol run.
func (a *patrolFindingCreatorAdapter) getCollectedFindings() []*Finding {
a.findingsMu.Lock()
@@ -1150,6 +1169,17 @@ func (a *patrolFindingCreatorAdapter) getQueriedFindingIDs() []string {
return result
}
+func (a *patrolFindingCreatorAdapter) getQueriedFindings() []tools.PatrolFindingInfo {
+ if a == nil {
+ return nil
+ }
+ a.findingsMu.Lock()
+ defer a.findingsMu.Unlock()
+ result := make([]tools.PatrolFindingInfo, len(a.queriedFindings))
+ copy(result, a.queriedFindings)
+ return result
+}
+
// dispatchPatrolInvestigations advances model-reported findings from the
// completed Watch stage into Pro investigation. It must be called only after
// the Watch run record is durable and run-scoped executor state has unwound.
diff --git a/internal/ai/patrol_findings_additional_test.go b/internal/ai/patrol_findings_additional_test.go
index 4597d7e9b7..70f82bb423 100644
--- a/internal/ai/patrol_findings_additional_test.go
+++ b/internal/ai/patrol_findings_additional_test.go
@@ -1020,6 +1020,13 @@ func TestPatrolFindingCreatorAdapter_ResolveFindingAndChecks(t *testing.T) {
if !adapter.HasCheckedFindings() {
t.Fatal("expected HasCheckedFindings to be true after GetActiveFindings")
}
+ if adapter.HasCompleteFindingSnapshot() {
+ t.Fatal("expected severity-filtered finding read not to count as a complete snapshot")
+ }
+ _ = adapter.GetActiveFindings("", "")
+ if !adapter.HasCompleteFindingSnapshot() {
+ t.Fatal("expected unfiltered finding read to establish the complete snapshot")
+ }
}
func TestPatrolFindingCreatorAdapter_GetActiveFindings_UsesScopedRuntimeState(t *testing.T) {
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 28cc252e18..8c45f21d77 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -200,12 +200,13 @@ type ChatToolResult = agentcapabilities.ProviderToolResult
// PatrolExecuteRequest represents a patrol execution request via the chat service
type PatrolExecuteRequest struct {
- Prompt string `json:"prompt"`
- SystemPrompt string `json:"system_prompt"`
- SessionID string `json:"session_id,omitempty"`
- ExecutionID string `json:"execution_id,omitempty"`
- UseCase string `json:"use_case"` // "patrol" — for model selection
- MaxTurns int `json:"max_turns,omitempty"`
+ Prompt string `json:"prompt"`
+ SystemPrompt string `json:"system_prompt"`
+ SessionID string `json:"session_id,omitempty"`
+ ExecutionID string `json:"execution_id,omitempty"`
+ UseCase string `json:"use_case"` // "patrol" — for model selection
+ MaxTurns int `json:"max_turns,omitempty"`
+ AllowedToolNames []string `json:"allowed_tool_names,omitempty"`
}
// QuickAnalysisRequest represents a lightweight single-turn analysis request.
@@ -226,6 +227,9 @@ type PatrolStreamResponse struct {
Content string `json:"content"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
+ // ToolCalls carries calls observed by bounded Patrol follow-up passes so
+ // the parent run's durable audit contains every provider action.
+ ToolCalls []ToolCallRecord `json:"tool_calls,omitempty"`
}
// Service orchestrates AI interactions
diff --git a/internal/api/chat_service_adapter.go b/internal/api/chat_service_adapter.go
index 184705210e..2e48a8f57a 100644
--- a/internal/api/chat_service_adapter.go
+++ b/internal/api/chat_service_adapter.go
@@ -34,14 +34,7 @@ func (a *chatServiceAdapter) ExecuteStream(ctx context.Context, req ai.ChatExecu
}
func (a *chatServiceAdapter) ExecutePatrolStream(ctx context.Context, req ai.PatrolExecuteRequest, callback ai.ChatStreamCallback) (*ai.PatrolStreamResponse, error) {
- resp, err := a.svc.ExecutePatrolStream(ctx, chat.PatrolRequest{
- Prompt: req.Prompt,
- SystemPrompt: req.SystemPrompt,
- SessionID: req.SessionID,
- ExecutionID: req.ExecutionID,
- UseCase: req.UseCase,
- MaxTurns: req.MaxTurns,
- }, adaptCallback(callback))
+ resp, err := a.svc.ExecutePatrolStream(ctx, adaptPatrolExecuteRequest(req), adaptCallback(callback))
if err != nil {
if resp != nil {
return &ai.PatrolStreamResponse{
@@ -59,6 +52,18 @@ func (a *chatServiceAdapter) ExecutePatrolStream(ctx context.Context, req ai.Pat
}, nil
}
+func adaptPatrolExecuteRequest(req ai.PatrolExecuteRequest) chat.PatrolRequest {
+ return chat.PatrolRequest{
+ Prompt: req.Prompt,
+ SystemPrompt: req.SystemPrompt,
+ SessionID: req.SessionID,
+ ExecutionID: req.ExecutionID,
+ UseCase: req.UseCase,
+ MaxTurns: req.MaxTurns,
+ AllowedToolNames: append([]string(nil), req.AllowedToolNames...),
+ }
+}
+
//nolint:dupl // mirrors orchestratorChatAdapter.GetMessages: same source messages mapped onto a deliberately separate output contract that may diverge
func (a *chatServiceAdapter) GetMessages(ctx context.Context, sessionID string) ([]ai.ChatMessage, error) {
messages, err := a.svc.GetMessages(ctx, sessionID)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 158c0e6868..58369851c5 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -67,6 +67,32 @@ import (
tmock "github.com/stretchr/testify/mock"
)
+func TestContractPatrolInternalBridgePreservesBoundedToolAuthority(t *testing.T) {
+ allowed := []string{
+ agentcapabilities.PatrolGetFindingsToolName,
+ agentcapabilities.PatrolReportFindingToolName,
+ }
+ got := adaptPatrolExecuteRequest(ai.PatrolExecuteRequest{
+ Prompt: "evaluate",
+ SystemPrompt: "bounded",
+ SessionID: "patrol-eval",
+ ExecutionID: "run-1",
+ UseCase: "patrol",
+ MaxTurns: 5,
+ AllowedToolNames: allowed,
+ })
+ if got.Prompt != "evaluate" || got.SystemPrompt != "bounded" || got.SessionID != "patrol-eval" || got.ExecutionID != "run-1" || got.UseCase != "patrol" || got.MaxTurns != 5 {
+ t.Fatalf("Patrol bridge lost execution metadata: %+v", got)
+ }
+ if !reflect.DeepEqual(got.AllowedToolNames, allowed) {
+ t.Fatalf("Patrol bridge allowed tools = %v, want %v", got.AllowedToolNames, allowed)
+ }
+ allowed[0] = "mutated-after-adaptation"
+ if got.AllowedToolNames[0] != agentcapabilities.PatrolGetFindingsToolName {
+ t.Fatalf("Patrol bridge retained caller-owned allowlist storage: %v", got.AllowedToolNames)
+ }
+}
+
func TestContract_ConfigTransferRoutesUseCanonicalPreHandlerAuthorization(t *testing.T) {
routesSource, err := os.ReadFile(filepath.Clean("router_routes_registration.go"))
if err != nil {