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.

Update investigation orchestrator for improved guardrails

rcourtman7be3ab2c1a28
diff --git a/internal/ai/investigation/chat_adapter.go b/internal/ai/investigation/chat_adapter.go
index b475567e24..4ac11556dc 100644
--- a/internal/ai/investigation/chat_adapter.go
+++ b/internal/ai/investigation/chat_adapter.go
@@ -104,6 +104,14 @@ func (a *ChatServiceAdapter) DeleteSession(ctx context.Context, sessionID string
return a.service.DeleteSession(ctx, sessionID)
}
+// ListAvailableTools returns tool names available for the given prompt.
+func (a *ChatServiceAdapter) ListAvailableTools(ctx context.Context, prompt string) []string {
+ if a.service == nil {
+ return nil
+ }
+ return a.service.ListAvailableTools(ctx, prompt)
+}
+
// IsRunning checks if the chat service is running
func (a *ChatServiceAdapter) IsRunning() bool {
return a.service != nil && a.service.IsRunning()
diff --git a/internal/ai/investigation/guardrails.go b/internal/ai/investigation/guardrails.go
index 0d7a938470..f9e4f96cf8 100644
--- a/internal/ai/investigation/guardrails.go
+++ b/internal/ai/investigation/guardrails.go
@@ -43,14 +43,13 @@ func (g *Guardrails) IsDestructiveAction(command string) bool {
// RequiresApproval determines if an action requires user approval
// based on finding severity, autonomy level, and whether the command is destructive
-func (g *Guardrails) RequiresApproval(findingSeverity, autonomyLevel, command string, criticalRequireApproval bool) bool {
- // Autonomous mode - user explicitly opted into full autonomy, no approvals needed
- // This is like "auto-accept" mode in Claude Code - user accepts all risk
- if autonomyLevel == "autonomous" {
+func (g *Guardrails) RequiresApproval(findingSeverity, autonomyLevel, command string) bool {
+ // Full mode - user explicitly opted into full autonomy, no approvals needed
+ if autonomyLevel == "full" {
return false
}
- // Destructive actions ALWAYS require approval (except in autonomous mode above)
+ // Destructive actions ALWAYS require approval (except in full mode above)
if g.IsDestructiveAction(command) {
return true
}
@@ -60,17 +59,15 @@ func (g *Guardrails) RequiresApproval(findingSeverity, autonomyLevel, command st
return true
}
- // Critical findings require approval if configured (default: true)
- if findingSeverity == "critical" && criticalRequireApproval {
- return true
- }
-
- // In full autonomy mode, non-destructive warning fixes can proceed
- if autonomyLevel == "full" && findingSeverity == "warning" {
- return false
+ // In assisted mode: auto-fix warnings, critical needs approval
+ if autonomyLevel == "assisted" {
+ if findingSeverity == "warning" {
+ return false
+ }
+ return true // critical findings need approval
}
- // Default to requiring approval
+ // Default to requiring approval (covers monitor mode and unknown levels)
return true
}
diff --git a/internal/ai/investigation/guardrails_test.go b/internal/ai/investigation/guardrails_test.go
index b6d36f055c..5108183f2f 100644
--- a/internal/ai/investigation/guardrails_test.go
+++ b/internal/ai/investigation/guardrails_test.go
@@ -22,28 +22,39 @@ func TestGuardrails_DestructiveAndCustomPatterns(t *testing.T) {
func TestGuardrails_RequiresApproval(t *testing.T) {
g := NewGuardrails()
- if !g.RequiresApproval("warning", "approval", "echo ok", true) {
+
+ // Approval mode: everything needs approval
+ if !g.RequiresApproval("warning", "approval", "echo ok") {
t.Fatalf("expected approval mode to require approval")
}
- if !g.RequiresApproval("critical", "full", "echo ok", true) {
- t.Fatalf("expected critical to require approval")
- }
- if g.RequiresApproval("warning", "full", "echo ok", true) {
- t.Fatalf("expected full autonomy warning to skip approval")
+
+ // Assisted mode: warnings auto-fix, critical needs approval
+ if g.RequiresApproval("warning", "assisted", "echo ok") {
+ t.Fatalf("expected assisted mode warning to skip approval")
}
- if !g.RequiresApproval("warning", "controlled", "echo ok", true) {
- t.Fatalf("expected default to require approval")
+ if !g.RequiresApproval("critical", "assisted", "echo ok") {
+ t.Fatalf("expected assisted mode critical to require approval")
}
- // Autonomous mode bypasses ALL approvals
- if g.RequiresApproval("warning", "autonomous", "echo ok", true) {
- t.Fatalf("expected autonomous mode to skip approval for safe commands")
+ // Full mode: everything auto-fixes (user accepts risk)
+ if g.RequiresApproval("warning", "full", "echo ok") {
+ t.Fatalf("expected full mode to skip approval for warnings")
+ }
+ if g.RequiresApproval("critical", "full", "echo ok") {
+ t.Fatalf("expected full mode to skip approval for critical")
}
- if g.RequiresApproval("critical", "autonomous", "echo ok", true) {
- t.Fatalf("expected autonomous mode to skip approval for critical findings")
+ if g.RequiresApproval("critical", "full", "rm -rf /tmp/test") {
+ t.Fatalf("expected full mode to skip approval even for destructive commands")
}
- if g.RequiresApproval("critical", "autonomous", "rm -rf /tmp/test", true) {
- t.Fatalf("expected autonomous mode to skip approval even for destructive commands")
+
+ // Unknown/default mode: requires approval
+ if !g.RequiresApproval("warning", "unknown", "echo ok") {
+ t.Fatalf("expected unknown mode to require approval")
+ }
+
+ // Destructive commands require approval in all modes except full
+ if !g.RequiresApproval("warning", "assisted", "rm -rf /tmp/test") {
+ t.Fatalf("expected destructive command to require approval in assisted mode")
}
}
diff --git a/internal/ai/investigation/orchestrator.go b/internal/ai/investigation/orchestrator.go
index a93d17ed49..d84122be00 100644
--- a/internal/ai/investigation/orchestrator.go
+++ b/internal/ai/investigation/orchestrator.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "strings"
"sync"
"time"
@@ -17,6 +18,7 @@ type ChatService interface {
ExecuteStream(ctx context.Context, req ExecuteRequest, callback StreamCallback) error
GetMessages(ctx context.Context, sessionID string) ([]Message, error)
DeleteSession(ctx context.Context, sessionID string) error
+ ListAvailableTools(ctx context.Context, prompt string) []string
SetAutonomousMode(enabled bool)
}
@@ -107,6 +109,12 @@ type InfrastructureContextProvider interface {
GetInfrastructureContext() string
}
+// AutonomyLevelProvider provides the current autonomy level (for re-checking before fix execution)
+type AutonomyLevelProvider interface {
+ GetCurrentAutonomyLevel() string
+ IsFullModeUnlocked() bool
+}
+
// Orchestrator manages the investigation lifecycle
type Orchestrator struct {
mu sync.RWMutex
@@ -122,6 +130,9 @@ type Orchestrator struct {
// Infrastructure context provider for CLI access information
infraContextProvider InfrastructureContextProvider
+ // Autonomy level provider for re-checking before fix execution
+ autonomyProvider AutonomyLevelProvider
+
// Track running investigations
runningCount int
runningMu sync.Mutex
@@ -168,6 +179,14 @@ func (o *Orchestrator) SetInfrastructureContextProvider(provider InfrastructureC
o.infraContextProvider = provider
}
+// SetAutonomyLevelProvider sets the provider for fetching current autonomy level
+// This enables re-checking autonomy level before fix execution
+func (o *Orchestrator) SetAutonomyLevelProvider(provider AutonomyLevelProvider) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.autonomyProvider = provider
+}
+
// GetConfig returns the current configuration
func (o *Orchestrator) GetConfig() InvestigationConfig {
o.mu.RLock()
@@ -227,6 +246,12 @@ func (o *Orchestrator) InvestigateFinding(ctx context.Context, finding *Finding,
// Build the investigation prompt
prompt := o.buildInvestigationPrompt(finding)
+ toolsAvailable := o.chatService.ListAvailableTools(ctx, prompt)
+ if len(toolsAvailable) > 0 {
+ investigation.ToolsAvailable = toolsAvailable
+ o.store.Update(investigation)
+ }
+
log.Info().
Str("finding_id", finding.ID).
Str("session_id", session.ID).
@@ -278,11 +303,23 @@ func (o *Orchestrator) buildInvestigationPrompt(finding *Finding) string {
`, infraContext)
}
+ // Add targeted guidance to reduce ambiguous fixes
+ var extraGuidance string
+ if strings.EqualFold(finding.ResourceType, "storage") {
+ extraGuidance = `
+## Storage Verification
+- Confirm the storage is actually required by the affected workload before proposing a fix.
+- Verify storage scope (node membership) and guest mounts or data paths using available tools.
+- If dependency cannot be confirmed, respond with NEEDS_ATTENTION and state what evidence is missing.
+`
+ }
+
return fmt.Sprintf(`You are investigating a finding from Pulse Patrol. Your goal is to:
1. Understand the issue using available tools
2. Determine if it can be automatically fixed
3. If fixable, propose a specific remediation command
%s
+%s
## Finding Details
- **Title**: %s
- **Severity**: %s
@@ -327,6 +364,7 @@ Remember:
- Never propose destructive commands (they'll be blocked anyway)
- Focus on the specific resource mentioned in the finding`,
infraSection,
+ extraGuidance,
finding.Title,
finding.Severity,
finding.Category,
@@ -365,6 +403,10 @@ func (o *Orchestrator) executeWithLimits(ctx context.Context, investigation *Inv
var lastContent string
var streamErr error
+ var toolsUsed []string
+ var evidenceIDs []string
+ toolsUsedSet := make(map[string]bool)
+ evidenceSet := make(map[string]bool)
// Execute the prompt
req := ExecuteRequest{
@@ -386,7 +428,36 @@ func (o *Orchestrator) executeWithLimits(ctx context.Context, investigation *Inv
if err := json.Unmarshal(event.Data, &data); err == nil {
lastContent += data.Text
}
+ case "tool_start":
+ var data struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ }
+ if err := json.Unmarshal(event.Data, &data); err == nil {
+ if data.Name != "" && !toolsUsedSet[data.Name] {
+ toolsUsedSet[data.Name] = true
+ toolsUsed = append(toolsUsed, data.Name)
+ }
+ if data.ID != "" && !evidenceSet[data.ID] {
+ evidenceSet[data.ID] = true
+ evidenceIDs = append(evidenceIDs, data.ID)
+ }
+ }
case "tool_end":
+ var data struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ }
+ if err := json.Unmarshal(event.Data, &data); err == nil {
+ if data.Name != "" && !toolsUsedSet[data.Name] {
+ toolsUsedSet[data.Name] = true
+ toolsUsed = append(toolsUsed, data.Name)
+ }
+ if data.ID != "" && !evidenceSet[data.ID] {
+ evidenceSet[data.ID] = true
+ evidenceIDs = append(evidenceIDs, data.ID)
+ }
+ }
// Each tool call counts as a turn
turnCount++
o.store.IncrementTurnCount(investigation.ID)
@@ -410,14 +481,22 @@ func (o *Orchestrator) executeWithLimits(ctx context.Context, investigation *Inv
})
if err != nil {
+ investigation.ToolsUsed = toolsUsed
+ investigation.EvidenceIDs = evidenceIDs
+ o.store.Update(investigation)
return err
}
if streamErr != nil {
+ investigation.ToolsUsed = toolsUsed
+ investigation.EvidenceIDs = evidenceIDs
+ o.store.Update(investigation)
return streamErr
}
// Store the summary
investigation.Summary = lastContent
+ investigation.ToolsUsed = toolsUsed
+ investigation.EvidenceIDs = evidenceIDs
o.store.Update(investigation)
return nil
@@ -434,12 +513,22 @@ func (o *Orchestrator) processResult(ctx context.Context, investigation *Investi
finding.LastInvestigatedAt = &now
if fix != nil {
- // Check if fix requires approval
+ // Re-check current autonomy level before deciding on fix execution
+ // This handles cases where user changed autonomy during investigation
+ currentLevel := autonomyLevel
+ if o.autonomyProvider != nil {
+ currentLevel = o.autonomyProvider.GetCurrentAutonomyLevel()
+ // Also check if full mode is still unlocked
+ if currentLevel == "full" && !o.autonomyProvider.IsFullModeUnlocked() {
+ currentLevel = "assisted" // Downgrade if full mode was locked
+ }
+ }
+
+ // Check if fix requires approval based on current autonomy level
requiresApproval := o.guardrails.RequiresApproval(
finding.Severity,
- autonomyLevel,
+ currentLevel,
fix.Commands[0],
- o.config.CriticalRequireApproval,
)
fix.RiskLevel = o.guardrails.ClassifyRisk(fix.Commands[0])
diff --git a/internal/ai/investigation/orchestrator_additional_test.go b/internal/ai/investigation/orchestrator_additional_test.go
index f61706fac0..8700b5b7c0 100644
--- a/internal/ai/investigation/orchestrator_additional_test.go
+++ b/internal/ai/investigation/orchestrator_additional_test.go
@@ -33,6 +33,10 @@ func (s *stubChatService) DeleteSession(ctx context.Context, sessionID string) e
return nil
}
+func (s *stubChatService) ListAvailableTools(ctx context.Context, prompt string) []string {
+ return nil
+}
+
func (s *stubChatService) SetAutonomousMode(enabled bool) {}
type stubCommandExecutor struct {
diff --git a/internal/ai/investigation/orchestrator_test.go b/internal/ai/investigation/orchestrator_test.go
index d28e30a557..195cded1b1 100644
--- a/internal/ai/investigation/orchestrator_test.go
+++ b/internal/ai/investigation/orchestrator_test.go
@@ -34,6 +34,9 @@ func (m *MockChatService) GetMessages(ctx context.Context, sessionID string) ([]
func (m *MockChatService) DeleteSession(ctx context.Context, sessionID string) error {
return nil
}
+func (m *MockChatService) ListAvailableTools(ctx context.Context, prompt string) []string {
+ return nil
+}
func (m *MockChatService) SetAutonomousMode(enabled bool) {}
type MockFindingsStore struct {
diff --git a/internal/ai/investigation/types.go b/internal/ai/investigation/types.go
index 3b148a62e5..8ea1dd3c09 100644
--- a/internal/ai/investigation/types.go
+++ b/internal/ai/investigation/types.go
@@ -7,18 +7,21 @@ import (
// InvestigationSession represents an AI investigation of a finding
type InvestigationSession struct {
- ID string `json:"id"`
- FindingID string `json:"finding_id"`
- SessionID string `json:"session_id"` // Chat session ID
- Status Status `json:"status"`
- StartedAt time.Time `json:"started_at"`
- CompletedAt *time.Time `json:"completed_at,omitempty"`
- TurnCount int `json:"turn_count"` // Number of agentic turns used
- Outcome Outcome `json:"outcome,omitempty"` // Result of investigation
- ProposedFix *Fix `json:"proposed_fix,omitempty"`
- ApprovalID string `json:"approval_id,omitempty"` // If fix is queued for approval
- Summary string `json:"summary,omitempty"` // AI-generated summary
- Error string `json:"error,omitempty"` // Error message if failed
+ ID string `json:"id"`
+ FindingID string `json:"finding_id"`
+ SessionID string `json:"session_id"` // Chat session ID
+ Status Status `json:"status"`
+ StartedAt time.Time `json:"started_at"`
+ CompletedAt *time.Time `json:"completed_at,omitempty"`
+ TurnCount int `json:"turn_count"` // Number of agentic turns used
+ Outcome Outcome `json:"outcome,omitempty"` // Result of investigation
+ ProposedFix *Fix `json:"proposed_fix,omitempty"`
+ ApprovalID string `json:"approval_id,omitempty"` // If fix is queued for approval
+ ToolsAvailable []string `json:"tools_available,omitempty"`
+ ToolsUsed []string `json:"tools_used,omitempty"`
+ EvidenceIDs []string `json:"evidence_ids,omitempty"`
+ Summary string `json:"summary,omitempty"` // AI-generated summary
+ Error string `json:"error,omitempty"` // Error message if failed
}
// Status represents the current state of an investigation
@@ -99,23 +102,21 @@ var DestructivePatterns = []string{
// InvestigationConfig holds configuration for investigations
type InvestigationConfig struct {
- MaxTurns int // Maximum agentic turns per investigation
- Timeout time.Duration // Maximum duration per investigation
- MaxConcurrent int // Maximum concurrent investigations
- MaxAttemptsPerFinding int // Maximum investigation attempts per finding
- CooldownDuration time.Duration // Cooldown before re-investigating
- CriticalRequireApproval bool // Critical findings always require approval
+ MaxTurns int // Maximum agentic turns per investigation
+ Timeout time.Duration // Maximum duration per investigation
+ MaxConcurrent int // Maximum concurrent investigations
+ MaxAttemptsPerFinding int // Maximum investigation attempts per finding
+ CooldownDuration time.Duration // Cooldown before re-investigating
}
// DefaultConfig returns the default investigation configuration
func DefaultConfig() InvestigationConfig {
return InvestigationConfig{
- MaxTurns: 15,
- Timeout: 5 * time.Minute,
- MaxConcurrent: 3,
- MaxAttemptsPerFinding: 3,
- CooldownDuration: 1 * time.Hour,
- CriticalRequireApproval: true,
+ MaxTurns: 15,
+ Timeout: 5 * time.Minute,
+ MaxConcurrent: 3,
+ MaxAttemptsPerFinding: 3,
+ CooldownDuration: 1 * time.Hour,
}
}
diff --git a/internal/ai/investigation/types_test.go b/internal/ai/investigation/types_test.go
index 6e00c994ed..2f29212d8d 100644
--- a/internal/ai/investigation/types_test.go
+++ b/internal/ai/investigation/types_test.go
@@ -7,9 +7,6 @@ func TestDefaultConfig(t *testing.T) {
if cfg.MaxTurns == 0 || cfg.Timeout == 0 || cfg.MaxConcurrent == 0 {
t.Fatalf("expected non-zero defaults")
}
- if !cfg.CriticalRequireApproval {
- t.Fatalf("expected critical approval default")
- }
}
func TestIsDestructiveAndHelpers(t *testing.T) {