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.

fix(ai): pass autonomous mode per-request instead of mutating shared state

rcourtman78cd64338a48
diff --git a/internal/ai/investigation/chat_adapter.go b/internal/ai/investigation/chat_adapter.go
index 7247d190b8..74817b70d1 100644
--- a/internal/ai/investigation/chat_adapter.go
+++ b/internal/ai/investigation/chat_adapter.go
@@ -46,9 +46,10 @@ func (a *ChatServiceAdapter) ExecuteStream(ctx context.Context, req ExecuteReque
}
chatReq := chat.ExecuteRequest{
- Prompt: req.Prompt,
- SessionID: req.SessionID,
- MaxTurns: req.MaxTurns,
+ Prompt: req.Prompt,
+ SessionID: req.SessionID,
+ MaxTurns: req.MaxTurns,
+ AutonomousMode: req.AutonomousMode,
}
log.Debug().
diff --git a/internal/ai/investigation/orchestrator.go b/internal/ai/investigation/orchestrator.go
index 27c89a00de..3da2e05b1b 100644
--- a/internal/ai/investigation/orchestrator.go
+++ b/internal/ai/investigation/orchestrator.go
@@ -42,9 +42,10 @@ type Session struct {
// ExecuteRequest represents a chat execution request
type ExecuteRequest struct {
- Prompt string `json:"prompt"`
- SessionID string `json:"session_id,omitempty"`
- MaxTurns int `json:"max_turns,omitempty"` // Override max agentic turns (0 = use default)
+ Prompt string `json:"prompt"`
+ SessionID string `json:"session_id,omitempty"`
+ MaxTurns int `json:"max_turns,omitempty"` // Override max agentic turns (0 = use default)
+ AutonomousMode *bool `json:"autonomous_mode,omitempty"` // Per-request autonomous override (nil = use service default)
}
// StreamCallback is called for each streaming event
@@ -205,6 +206,18 @@ func NewOrchestrator(
}
}
+// GetStore returns the investigation store for external cleanup/maintenance.
+func (o *Orchestrator) GetStore() *Store {
+ return o.store
+}
+
+// CleanupInvestigationStore runs periodic maintenance on the investigation store:
+// removes old/stuck sessions and enforces a size limit.
+func (o *Orchestrator) CleanupInvestigationStore(maxAge time.Duration, maxSessions int) {
+ o.store.Cleanup(maxAge)
+ o.store.EnforceSizeLimit(maxSessions)
+}
+
// SetConfig updates the orchestrator configuration
func (o *Orchestrator) SetConfig(config InvestigationConfig) {
o.mu.Lock()
@@ -353,9 +366,11 @@ func (o *Orchestrator) InvestigateFinding(ctx context.Context, finding *Finding,
// For all other levels, write commands (pulse_control, pulse_file_edit)
// must go through the normal approval gate. The investigation AI should
// propose fixes via PROPOSED_FIX markers, not execute them directly.
+ //
+ // NOTE: We pass autonomous mode via the ExecuteRequest rather than
+ // mutating shared chatService state, which is unsafe under concurrent
+ // investigations.
useAutonomous := autonomyLevel == "full"
- o.chatService.SetAutonomousMode(useAutonomous)
- defer o.chatService.SetAutonomousMode(false)
// Create chat session
session, err := o.chatService.CreateSession(ctx)
@@ -392,7 +407,7 @@ func (o *Orchestrator) InvestigateFinding(ctx context.Context, finding *Finding,
Msg("Starting investigation")
// Execute with timeout and turn limit
- err = o.executeWithLimits(ctx, investigation, prompt)
+ err = o.executeWithLimits(ctx, investigation, prompt, useAutonomous)
if err != nil {
// Mark as failed
o.store.Fail(investigation.ID, err.Error())
@@ -521,7 +536,7 @@ func formatOptional(label, value string) string {
}
// executeWithLimits runs the investigation with turn and timeout limits
-func (o *Orchestrator) executeWithLimits(ctx context.Context, investigation *InvestigationSession, prompt string) error {
+func (o *Orchestrator) executeWithLimits(ctx context.Context, investigation *InvestigationSession, prompt string, autonomousMode bool) error {
// Create context with timeout. The passed-in ctx is already shutdown-aware
// (derived via context.AfterFunc in InvestigateFinding), so the timeout
// context inherits both the caller's deadline and the shutdown signal.
@@ -548,9 +563,10 @@ func (o *Orchestrator) executeWithLimits(ctx context.Context, investigation *Inv
// Execute the prompt with investigation-specific turn limit
req := ExecuteRequest{
- Prompt: prompt,
- SessionID: investigation.SessionID,
- MaxTurns: maxTurns,
+ Prompt: prompt,
+ SessionID: investigation.SessionID,
+ MaxTurns: maxTurns,
+ AutonomousMode: &autonomousMode,
}
log.Debug().
@@ -652,6 +668,14 @@ func (o *Orchestrator) processResult(ctx context.Context, investigation *Investi
finding.LastInvestigatedAt = &now
if fix != nil {
+ // Guard: investigation produced a fix with no commands — nothing to execute
+ if len(fix.Commands) == 0 {
+ log.Warn().Str("finding_id", finding.ID).Msg("Investigation fix has no commands, marking needs_attention")
+ finding.InvestigationOutcome = string(OutcomeNeedsAttention)
+ finding.LastInvestigatedAt = &now
+ return nil
+ }
+
// Re-check current autonomy level before deciding on fix execution
// This handles cases where user changed autonomy during investigation
currentLevel := autonomyLevel
diff --git a/internal/ai/investigation/orchestrator_additional_test.go b/internal/ai/investigation/orchestrator_additional_test.go
index 8700b5b7c0..7cfc8ee2d8 100644
--- a/internal/ai/investigation/orchestrator_additional_test.go
+++ b/internal/ai/investigation/orchestrator_additional_test.go
@@ -108,7 +108,7 @@ func TestOrchestrator_ExecuteWithLimits_Success(t *testing.T) {
orchestrator := NewOrchestrator(chatService, store, nil, nil, DefaultConfig())
investigation := store.Create("finding-1", "session-1")
- if err := orchestrator.executeWithLimits(context.Background(), investigation, "prompt"); err != nil {
+ if err := orchestrator.executeWithLimits(context.Background(), investigation, "prompt", false); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if investigation.Summary == "" {
@@ -128,7 +128,7 @@ func TestOrchestrator_ExecuteWithLimits_StreamError(t *testing.T) {
orchestrator := NewOrchestrator(chatService, store, nil, nil, DefaultConfig())
investigation := store.Create("finding-1", "session-1")
- if err := orchestrator.executeWithLimits(context.Background(), investigation, "prompt"); err == nil {
+ if err := orchestrator.executeWithLimits(context.Background(), investigation, "prompt", false); err == nil {
t.Fatalf("expected stream error")
}
}
diff --git a/internal/ai/investigation/orchestrator_autonomy_test.go b/internal/ai/investigation/orchestrator_autonomy_test.go
index aaac931755..1f8d6aeb8f 100644
--- a/internal/ai/investigation/orchestrator_autonomy_test.go
+++ b/internal/ai/investigation/orchestrator_autonomy_test.go
@@ -8,16 +8,26 @@ import (
"github.com/stretchr/testify/require"
)
-// capturingChatService records the boolean passed to SetAutonomousMode.
+// capturingChatService records the AutonomousMode passed via ExecuteRequest
+// and tracks any direct SetAutonomousMode calls.
type capturingChatService struct {
stubChatService
- autonomousCalls []bool
+ autonomousCalls []bool // direct SetAutonomousMode calls
+ capturedRequests []ExecuteRequest // requests passed to ExecuteStream
}
func (c *capturingChatService) SetAutonomousMode(enabled bool) {
c.autonomousCalls = append(c.autonomousCalls, enabled)
}
+func (c *capturingChatService) ExecuteStream(ctx context.Context, req ExecuteRequest, callback StreamCallback) error {
+ c.capturedRequests = append(c.capturedRequests, req)
+ if c.execute != nil {
+ return c.execute(callback)
+ }
+ return nil
+}
+
func newCapturingChat() *capturingChatService {
cs := &capturingChatService{}
cs.execute = func(cb StreamCallback) error {
@@ -37,10 +47,13 @@ func TestInvestigateFinding_AutonomousMode_Full(t *testing.T) {
err := o.InvestigateFinding(context.Background(), findings.finding, "full")
require.NoError(t, err)
- // First call should be SetAutonomousMode(true), then deferred false
- require.Len(t, chat.autonomousCalls, 2, "expected two SetAutonomousMode calls (set + deferred reset)")
- assert.True(t, chat.autonomousCalls[0], "full autonomy should set autonomous mode to true")
- assert.False(t, chat.autonomousCalls[1], "deferred reset should set autonomous mode to false")
+ // Autonomous mode should be passed via the request, not via SetAutonomousMode
+ require.Len(t, chat.capturedRequests, 1)
+ require.NotNil(t, chat.capturedRequests[0].AutonomousMode)
+ assert.True(t, *chat.capturedRequests[0].AutonomousMode, "full autonomy should set autonomous mode to true in request")
+
+ // SetAutonomousMode should NOT be called on the chat service
+ assert.Empty(t, chat.autonomousCalls, "should not mutate shared chat service autonomous mode")
}
func TestInvestigateFinding_AutonomousMode_Approval(t *testing.T) {
@@ -52,9 +65,10 @@ func TestInvestigateFinding_AutonomousMode_Approval(t *testing.T) {
err := o.InvestigateFinding(context.Background(), findings.finding, "approval")
require.NoError(t, err)
- require.Len(t, chat.autonomousCalls, 2)
- assert.False(t, chat.autonomousCalls[0], "approval mode should set autonomous mode to false")
- assert.False(t, chat.autonomousCalls[1], "deferred reset should set autonomous mode to false")
+ require.Len(t, chat.capturedRequests, 1)
+ require.NotNil(t, chat.capturedRequests[0].AutonomousMode)
+ assert.False(t, *chat.capturedRequests[0].AutonomousMode, "approval mode should set autonomous mode to false in request")
+ assert.Empty(t, chat.autonomousCalls)
}
func TestInvestigateFinding_AutonomousMode_Assisted(t *testing.T) {
@@ -66,14 +80,13 @@ func TestInvestigateFinding_AutonomousMode_Assisted(t *testing.T) {
err := o.InvestigateFinding(context.Background(), findings.finding, "assisted")
require.NoError(t, err)
- require.Len(t, chat.autonomousCalls, 2)
- assert.False(t, chat.autonomousCalls[0], "assisted mode should set autonomous mode to false")
- assert.False(t, chat.autonomousCalls[1])
+ require.Len(t, chat.capturedRequests, 1)
+ require.NotNil(t, chat.capturedRequests[0].AutonomousMode)
+ assert.False(t, *chat.capturedRequests[0].AutonomousMode, "assisted mode should set autonomous mode to false in request")
+ assert.Empty(t, chat.autonomousCalls)
}
func TestInvestigateFinding_AutonomousMode_Monitor(t *testing.T) {
- // Monitor mode normally wouldn't reach InvestigateFinding (blocked by ShouldInvestigate),
- // but if called directly, it should still set autonomous mode to false.
chat := newCapturingChat()
store := NewStore("")
findings := &stubFindingsStore{finding: &Finding{ID: "f1", Severity: "warning"}}
@@ -82,9 +95,10 @@ func TestInvestigateFinding_AutonomousMode_Monitor(t *testing.T) {
err := o.InvestigateFinding(context.Background(), findings.finding, "monitor")
require.NoError(t, err)
- require.Len(t, chat.autonomousCalls, 2)
- assert.False(t, chat.autonomousCalls[0], "monitor mode should set autonomous mode to false")
- assert.False(t, chat.autonomousCalls[1])
+ require.Len(t, chat.capturedRequests, 1)
+ require.NotNil(t, chat.capturedRequests[0].AutonomousMode)
+ assert.False(t, *chat.capturedRequests[0].AutonomousMode, "monitor mode should set autonomous mode to false in request")
+ assert.Empty(t, chat.autonomousCalls)
}
func TestInvestigateFinding_AutonomousMode_Empty(t *testing.T) {
@@ -96,7 +110,8 @@ func TestInvestigateFinding_AutonomousMode_Empty(t *testing.T) {
err := o.InvestigateFinding(context.Background(), findings.finding, "")
require.NoError(t, err)
- require.Len(t, chat.autonomousCalls, 2)
- assert.False(t, chat.autonomousCalls[0], "empty autonomy level should set autonomous mode to false")
- assert.False(t, chat.autonomousCalls[1])
+ require.Len(t, chat.capturedRequests, 1)
+ require.NotNil(t, chat.capturedRequests[0].AutonomousMode)
+ assert.False(t, *chat.capturedRequests[0].AutonomousMode, "empty autonomy level should set autonomous mode to false in request")
+ assert.Empty(t, chat.autonomousCalls)
}
diff --git a/internal/ai/investigation/store.go b/internal/ai/investigation/store.go
index 17032a7159..78b5113140 100644
--- a/internal/ai/investigation/store.go
+++ b/internal/ai/investigation/store.go
@@ -404,12 +404,15 @@ func (s *Store) CountFixed() int {
return count
}
-// Cleanup removes old completed/failed investigations
+// Cleanup removes old completed/failed investigations and stuck sessions.
+// A session is considered stuck if it has no CompletedAt and StartedAt is
+// older than 20 minutes (2x the 10-minute investigation timeout).
func (s *Store) Cleanup(maxAge time.Duration) int {
s.mu.Lock()
defer s.mu.Unlock()
cutoff := time.Now().Add(-maxAge)
+ stuckCutoff := time.Now().Add(-20 * time.Minute)
removed := 0
for id, session := range s.sessions {
@@ -420,6 +423,11 @@ func (s *Store) Cleanup(maxAge time.Duration) int {
shouldRemove = true
}
+ // Remove stuck sessions (no CompletedAt and started more than 20min ago)
+ if session.CompletedAt == nil && session.StartedAt.Before(stuckCutoff) {
+ shouldRemove = true
+ }
+
if shouldRemove {
delete(s.sessions, id)
// Clean up byFinding index
@@ -434,6 +442,70 @@ func (s *Store) Cleanup(maxAge time.Duration) int {
}
}
+ // Clean up orphaned empty slices in byFinding
+ for findingID, sessionIDs := range s.byFinding {
+ if len(sessionIDs) == 0 {
+ delete(s.byFinding, findingID)
+ }
+ }
+
+ if removed > 0 {
+ s.scheduleSaveLocked()
+ }
+
+ return removed
+}
+
+// EnforceSizeLimit removes the oldest completed sessions when the store
+// exceeds maxSessions. Running/pending sessions are never evicted.
+func (s *Store) EnforceSizeLimit(maxSessions int) int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if len(s.sessions) <= maxSessions {
+ return 0
+ }
+
+ // Collect completed sessions sorted by CompletedAt (oldest first)
+ type entry struct {
+ id string
+ completedAt time.Time
+ }
+ var completed []entry
+ for id, session := range s.sessions {
+ if session.CompletedAt != nil {
+ completed = append(completed, entry{id: id, completedAt: *session.CompletedAt})
+ }
+ }
+
+ // Sort oldest first
+ for i := 0; i < len(completed)-1; i++ {
+ for j := i + 1; j < len(completed); j++ {
+ if completed[j].completedAt.Before(completed[i].completedAt) {
+ completed[i], completed[j] = completed[j], completed[i]
+ }
+ }
+ }
+
+ toRemove := len(s.sessions) - maxSessions
+ removed := 0
+ for _, e := range completed {
+ if removed >= toRemove {
+ break
+ }
+ session := s.sessions[e.id]
+ delete(s.sessions, e.id)
+ // Clean up byFinding index
+ findingIDs := s.byFinding[session.FindingID]
+ for i, sid := range findingIDs {
+ if sid == e.id {
+ s.byFinding[session.FindingID] = append(findingIDs[:i], findingIDs[i+1:]...)
+ break
+ }
+ }
+ removed++
+ }
+
if removed > 0 {
s.scheduleSaveLocked()
}