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.

feat(ai): parallelize tool execution and refine knowledge extraction

rcourtman81ec5c525abc
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index bca711ae76..9eb96ab677 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -15,6 +15,15 @@ import (
"github.com/rs/zerolog/log"
)
+// parallelToolResult holds the result of a single tool execution during
+// parallel tool execution in the agentic loop. Defined at package level
+// because the executeWithTools function's `tools` parameter shadows the
+// tools package import, preventing inline type references.
+type parallelToolResult struct {
+ Result tools.CallToolResult
+ Err error
+}
+
// AgenticLoop handles the tool-calling loop with streaming
type AgenticLoop struct {
provider providers.StreamingProvider
@@ -111,6 +120,10 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
singleToolRequested := isSingleToolRequest(providerMessages)
singleToolEnforced := false
+ // 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)
+
// Loop detection: track identical tool calls (name + serialized input).
// After maxIdenticalCalls identical invocations, the next one is blocked.
const maxIdenticalCalls = 3
@@ -521,27 +534,38 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
return resultMessages, nil
}
- // Execute tool calls
+ // === Execute tool calls (three-phase pipeline) ===
+ // Phase 1: Pre-check (sequential) — FSM, loop detection, knowledge gate
+ // Phase 2: Execute (parallel) — actual tool calls via goroutines
+ // Phase 3: Post-process (sequential) — streaming, FSM transitions, KA extraction
if len(toolCalls) > 0 && preferredToolName != "" {
// Clear preferred tool once the model has used any tool.
preferredToolName = ""
}
firstToolResultText := ""
budgetBlockedThisTurn := 0
- for _, tc := range toolCalls {
- // Check for abort
- a.mu.Lock()
- if a.aborted[sessionID] {
- a.mu.Unlock()
- return resultMessages, fmt.Errorf("session aborted")
- }
- fsm := a.sessionFSM
+
+ // --- Phase 1: Pre-check all tool calls sequentially ---
+ // Pre-checks share mutable state (FSM, loop counts) so must be sequential.
+ a.mu.Lock()
+ if a.aborted[sessionID] {
a.mu.Unlock()
+ return resultMessages, fmt.Errorf("session aborted")
+ }
+ fsm := a.sessionFSM
+ a.mu.Unlock()
+
+ type pendingToolExec struct {
+ tc providers.ToolCall
+ toolKind ToolKind
+ }
+ var pendingExec []pendingToolExec
+ for _, tc := range toolCalls {
log.Debug().
Str("tool", tc.Name).
Str("id", tc.ID).
- Msg("Executing tool")
+ Msg("Pre-checking tool call")
// === FSM ENFORCEMENT GATE 1: Check if tool is allowed in current state ===
toolKind := ClassifyToolCall(tc.Name, tc.Input)
@@ -655,7 +679,8 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
// === KNOWLEDGE GATE: Return cached facts for redundant tool calls ===
- if a.knowledgeAccumulator != nil {
+ // 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 {
@@ -714,8 +739,49 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
}
- // Execute the tool
- result, err := a.executor.ExecuteTool(ctx, tc.Name, tc.Input)
+ // Tool passed all pre-checks — queue for execution
+ pendingExec = append(pendingExec, pendingToolExec{tc: tc, toolKind: toolKind})
+ }
+
+ // --- Phase 2: Execute pending tools (parallel if multiple) ---
+ // Tool execution is stateless I/O — safe to parallelize.
+ // Cap concurrency at 4 to avoid overwhelming infrastructure.
+ execResults := make([]parallelToolResult, len(pendingExec))
+
+ if len(pendingExec) > 1 {
+ log.Info().
+ Int("tool_count", len(pendingExec)).
+ Str("session_id", sessionID).
+ Msg("[AgenticLoop] Executing multiple tools in parallel")
+
+ var wg sync.WaitGroup
+ sem := make(chan struct{}, 4)
+
+ for j, pe := range pendingExec {
+ wg.Add(1)
+ go func(idx int, tc providers.ToolCall) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ r, e := a.executor.ExecuteTool(ctx, tc.Name, tc.Input)
+ execResults[idx] = parallelToolResult{Result: r, Err: e}
+ }(j, pe.tc)
+ }
+ wg.Wait()
+ } else if len(pendingExec) == 1 {
+ r, e := a.executor.ExecuteTool(ctx, pendingExec[0].tc.Name, pendingExec[0].tc.Input)
+ execResults[0] = parallelToolResult{Result: r, Err: e}
+ }
+
+ // --- Phase 3: Post-process results in original order (sequential) ---
+ // Streaming events, FSM transitions, KA extraction, approval flow
+ // must all be sequential and in the original tool call order.
+ for j, pe := range pendingExec {
+ tc := pe.tc
+ toolKind := pe.toolKind
+
+ result := execResults[j].Result
+ err := execResults[j].Err
var resultText string
var isError bool
@@ -749,13 +815,10 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
// to prevent the gate from re-executing the same tool call.
if len(facts) == 0 && !isError {
if predictedKeys := PredictFactKeys(tc.Name, tc.Input); len(predictedKeys) > 0 {
+ summary := summarizeForNegativeMarker(resultText)
for _, key := range predictedKeys {
if _, found := a.knowledgeAccumulator.Lookup(key); !found {
cat := categoryForPredictedKey(key)
- summary := resultText
- if len(summary) > 120 {
- summary = summary[:120]
- }
a.knowledgeAccumulator.AddFactForTool(tc.ID, cat, key, fmt.Sprintf("checked: %s", summary))
log.Debug().
Str("tool", tc.Name).
@@ -878,7 +941,6 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
Str("approval_id", approvalData.ApprovalID).
Str("command", approvalData.Command).
Msg("[AgenticLoop] Autonomous mode: returning approval request without waiting")
- // Return special message indicating fix is queued for approval
resultText = fmt.Sprintf("FIX_QUEUED: This action requires user approval. The fix has been queued for review. Approval ID: %s, Command: %s", approvalData.ApprovalID, approvalData.Command)
isError = false
} else {
@@ -1270,6 +1332,102 @@ func (a *AgenticLoop) ResetTokenCounts() {
// 1. Concrete system metrics/values (CPU %, memory usage, etc.)
// 2. Infrastructure state that requires live queries (running/stopped)
// 3. Fake tool call formatting
+// summarizeForNegativeMarker creates a concise summary of a tool result for
+// use in negative markers. Tries to extract meaningful context from JSON
+// responses rather than blindly truncating.
+func summarizeForNegativeMarker(resultText string) string {
+ if len(resultText) == 0 {
+ return "empty response"
+ }
+
+ // Try to parse as JSON and extract key indicators
+ var obj map[string]interface{}
+ if err := json.Unmarshal([]byte(resultText), &obj); err == nil {
+ var indicators []string
+
+ // Check for common empty-result patterns
+ for _, arrayKey := range []string{"points", "pools", "disks", "alerts", "findings", "jobs", "tasks", "snapshots", "resources", "containers", "vms", "nodes", "updates"} {
+ if arr, ok := obj[arrayKey]; ok {
+ if slice, ok := arr.([]interface{}); ok {
+ indicators = append(indicators, fmt.Sprintf("%s: %d items", arrayKey, len(slice)))
+ }
+ }
+ }
+
+ // Check for total field
+ if total, ok := obj["total"]; ok {
+ indicators = append(indicators, fmt.Sprintf("total=%v", total))
+ }
+
+ // Check for period/resource_id context
+ if rid, ok := obj["resource_id"]; ok {
+ indicators = append(indicators, fmt.Sprintf("resource=%v", rid))
+ }
+ if period, ok := obj["period"]; ok {
+ indicators = append(indicators, fmt.Sprintf("period=%v", period))
+ }
+
+ // Check for error field
+ if errVal, ok := obj["error"]; ok {
+ indicators = append(indicators, fmt.Sprintf("error=%v", errVal))
+ }
+
+ if len(indicators) > 0 {
+ result := strings.Join(indicators, ", ")
+ if len(result) > 200 {
+ result = result[:200]
+ }
+ return result
+ }
+ }
+
+ // Try JSON array
+ var arr []interface{}
+ if err := json.Unmarshal([]byte(resultText), &arr); err == nil {
+ return fmt.Sprintf("array with %d items", len(arr))
+ }
+
+ // Fall back to truncated text
+ summary := resultText
+ if len(summary) > 200 {
+ summary = summary[:200] + "..."
+ }
+ return summary
+}
+
+// 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
+}
+
func hasPhantomExecution(content string) bool {
if content == "" {
return false
diff --git a/internal/ai/chat/agentic_test.go b/internal/ai/chat/agentic_test.go
index d713d15469..2aec37428e 100644
--- a/internal/ai/chat/agentic_test.go
+++ b/internal/ai/chat/agentic_test.go
@@ -634,3 +634,272 @@ func TestTruncateForLog(t *testing.T) {
})
}
}
+
+func TestSummarizeForNegativeMarker(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ contains []string
+ }{
+ {
+ name: "empty response",
+ input: "",
+ contains: []string{"empty response"},
+ },
+ {
+ name: "JSON with empty array",
+ input: `{"resource_id":"105","period":"24h","points":[]}`,
+ contains: []string{"points: 0 items", "resource=105", "period=24h"},
+ },
+ {
+ name: "JSON with populated array",
+ input: `{"pools":[{"name":"a"},{"name":"b"}],"total":2}`,
+ contains: []string{"pools: 2 items", "total=2"},
+ },
+ {
+ name: "JSON with error",
+ input: `{"error":"not_found","resource_id":"999"}`,
+ contains: []string{"error=not_found", "resource=999"},
+ },
+ {
+ name: "JSON array",
+ input: `[{"a":1},{"b":2},{"c":3}]`,
+ contains: []string{"array with 3 items"},
+ },
+ {
+ name: "plain text",
+ input: "No data available for this resource",
+ contains: []string{"No data available"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := summarizeForNegativeMarker(tt.input)
+ for _, c := range tt.contains {
+ assert.Contains(t, result, c, "expected %q to contain %q", result, c)
+ }
+ })
+ }
+}
+
+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{})
+
+ t.Run("MultipleToolCallsExecuteAndReturnInOrder", func(t *testing.T) {
+ mockProvider := &MockProvider{}
+ loop := NewAgenticLoop(mockProvider, executor, "You are a helper")
+ ctx := context.Background()
+ sessionID := "parallel-session"
+ messages := []Message{{Role: "user", Content: "Check three things"}}
+
+ // Turn 1: provider returns 3 tool calls at once
+ mockProvider.On("ChatStream", mock.Anything, mock.MatchedBy(func(req providers.ChatRequest) bool {
+ return len(req.Messages) == 1
+ }), mock.Anything).Return(nil).Run(func(args mock.Arguments) {
+ callback := args.Get(2).(providers.StreamCallback)
+ // Emit tool_start events for each tool
+ for _, id := range []string{"call_a", "call_b", "call_c"} {
+ callback(providers.StreamEvent{
+ Type: "tool_start",
+ Data: providers.ToolStartEvent{ID: id, Name: "pulse_query"},
+ })
+ }
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{
+ ToolCalls: []providers.ToolCall{
+ {ID: "call_a", Name: "pulse_query", Input: map[string]interface{}{
+ "action": "get", "resource_type": "vm", "resource_id": "100",
+ }},
+ {ID: "call_b", Name: "pulse_query", Input: map[string]interface{}{
+ "action": "get", "resource_type": "vm", "resource_id": "200",
+ }},
+ {ID: "call_c", Name: "pulse_query", Input: map[string]interface{}{
+ "action": "get", "resource_type": "lxc", "resource_id": "300",
+ }},
+ },
+ },
+ })
+ }).Once()
+
+ // Turn 2: provider sees the 3 tool results and gives final answer
+ // Messages: 1 user + 1 assistant (with 3 tool calls) + 3 tool results = 5
+ mockProvider.On("ChatStream", mock.Anything, mock.MatchedBy(func(req providers.ChatRequest) bool {
+ return len(req.Messages) >= 5
+ }), mock.Anything).Return(nil).Run(func(args mock.Arguments) {
+ callback := args.Get(2).(providers.StreamCallback)
+ callback(providers.StreamEvent{
+ Type: "content",
+ Data: providers.ContentEvent{Text: "All three checks completed."},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{},
+ })
+ }).Once()
+
+ var toolEndEvents []ToolEndData
+ results, err := loop.Execute(ctx, sessionID, messages, func(event StreamEvent) {
+ if event.Type == "tool_end" {
+ var data ToolEndData
+ json.Unmarshal(event.Data, &data)
+ toolEndEvents = append(toolEndEvents, data)
+ }
+ })
+
+ assert.NoError(t, err)
+
+ // Verify we got 3 tool_end events in the original order
+ require.Len(t, toolEndEvents, 3, "expected 3 tool_end events")
+ assert.Equal(t, "call_a", toolEndEvents[0].ID)
+ assert.Equal(t, "call_b", toolEndEvents[1].ID)
+ assert.Equal(t, "call_c", toolEndEvents[2].ID)
+
+ // Verify result messages contain: assistant (with tool calls) + 3 tool results + final answer
+ require.GreaterOrEqual(t, len(results), 5, "expected at least 5 result messages")
+
+ // Verify tool results are in order by checking ToolUseIDs
+ toolResultIDs := []string{}
+ for _, msg := range results {
+ if msg.ToolResult != nil {
+ toolResultIDs = append(toolResultIDs, msg.ToolResult.ToolUseID)
+ }
+ }
+ require.Len(t, toolResultIDs, 3, "expected 3 tool result messages")
+ assert.Equal(t, "call_a", toolResultIDs[0])
+ assert.Equal(t, "call_b", toolResultIDs[1])
+ assert.Equal(t, "call_c", toolResultIDs[2])
+
+ // Verify final response
+ lastMsg := results[len(results)-1]
+ assert.Equal(t, "assistant", lastMsg.Role)
+ assert.Equal(t, "All three checks completed.", lastMsg.Content)
+
+ mockProvider.AssertExpectations(t)
+ })
+
+ t.Run("SingleToolCallNoGoroutineOverhead", func(t *testing.T) {
+ // Ensure single tool calls still work correctly (no regression)
+ mockProvider := &MockProvider{}
+ loop := NewAgenticLoop(mockProvider, executor, "You are a helper")
+ ctx := context.Background()
+ sessionID := "single-tool-session"
+ messages := []Message{{Role: "user", Content: "Check one thing"}}
+
+ mockProvider.On("ChatStream", mock.Anything, mock.MatchedBy(func(req providers.ChatRequest) bool {
+ return len(req.Messages) == 1
+ }), mock.Anything).Return(nil).Run(func(args mock.Arguments) {
+ callback := args.Get(2).(providers.StreamCallback)
+ callback(providers.StreamEvent{
+ Type: "tool_start",
+ Data: providers.ToolStartEvent{ID: "call_single", Name: "pulse_query"},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{
+ ToolCalls: []providers.ToolCall{
+ {ID: "call_single", Name: "pulse_query", Input: map[string]interface{}{
+ "action": "get", "resource_type": "vm", "resource_id": "100",
+ }},
+ },
+ },
+ })
+ }).Once()
+
+ mockProvider.On("ChatStream", mock.Anything, mock.MatchedBy(func(req providers.ChatRequest) bool {
+ return len(req.Messages) >= 3
+ }), mock.Anything).Return(nil).Run(func(args mock.Arguments) {
+ callback := args.Get(2).(providers.StreamCallback)
+ callback(providers.StreamEvent{
+ Type: "content",
+ Data: providers.ContentEvent{Text: "Done."},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{},
+ })
+ }).Once()
+
+ var toolEndCount int
+ results, err := loop.Execute(ctx, sessionID, messages, func(event StreamEvent) {
+ if event.Type == "tool_end" {
+ toolEndCount++
+ }
+ })
+
+ assert.NoError(t, err)
+ assert.Equal(t, 1, toolEndCount, "expected 1 tool_end event")
+
+ // Verify final response
+ lastMsg := results[len(results)-1]
+ assert.Equal(t, "Done.", lastMsg.Content)
+
+ mockProvider.AssertExpectations(t)
+ })
+}
diff --git a/internal/ai/chat/knowledge_extractor.go b/internal/ai/chat/knowledge_extractor.go
index b564d336df..29e539be62 100644
--- a/internal/ai/chat/knowledge_extractor.go
+++ b/internal/ai/chat/knowledge_extractor.go
@@ -874,6 +874,13 @@ func extractMetricsPerformanceFacts(input map[string]interface{}, resultText str
}
var resp struct {
+ ResourceID string `json:"resource_id"`
+ Period string `json:"period"`
+ Points []struct {
+ CPU float64 `json:"cpu"`
+ Memory float64 `json:"memory"`
+ Disk float64 `json:"disk"`
+ } `json:"points"`
Summary map[string]struct {
AvgCPU float64 `json:"avg_cpu"`
MaxCPU float64 `json:"max_cpu"`
@@ -886,18 +893,42 @@ func extractMetricsPerformanceFacts(input map[string]interface{}, resultText str
return nil
}
- var avgCPU, maxCPU float64
+ var avgCPU, maxCPU, avgMem, maxMem float64
var trend string
- if s, ok := resp.Summary[resourceID]; ok {
- avgCPU = s.AvgCPU
- maxCPU = s.MaxCPU
- trend = s.Trend
- } else {
- for _, s := range resp.Summary {
+
+ // Single-resource queries return Points array; compute summary from points
+ if len(resp.Points) > 0 {
+ var sumCPU, sumMem float64
+ for _, p := range resp.Points {
+ sumCPU += p.CPU
+ sumMem += p.Memory
+ if p.CPU > maxCPU {
+ maxCPU = p.CPU
+ }
+ if p.Memory > maxMem {
+ maxMem = p.Memory
+ }
+ }
+ n := float64(len(resp.Points))
+ avgCPU = sumCPU / n
+ avgMem = sumMem / n
+ } else if len(resp.Summary) > 0 {
+ // Multi-resource queries return Summary map
+ if s, ok := resp.Summary[resourceID]; ok {
avgCPU = s.AvgCPU
maxCPU = s.MaxCPU
+ avgMem = s.AvgMemory
+ maxMem = s.MaxMemory
trend = s.Trend
- break
+ } else {
+ for _, s := range resp.Summary {
+ avgCPU = s.AvgCPU
+ maxCPU = s.MaxCPU
+ avgMem = s.AvgMemory
+ maxMem = s.MaxMemory
+ trend = s.Trend
+ break
+ }
}
}
@@ -906,7 +937,13 @@ func extractMetricsPerformanceFacts(input map[string]interface{}, resultText str
parts = append(parts, fmt.Sprintf("avg_cpu=%.1f%%", avgCPU))
}
if maxCPU > 0 {
- parts = append(parts, fmt.Sprintf("max=%.1f%%", maxCPU))
+ parts = append(parts, fmt.Sprintf("max_cpu=%.1f%%", maxCPU))
+ }
+ if avgMem > 0 {
+ parts = append(parts, fmt.Sprintf("avg_mem=%.1f%%", avgMem))
+ }
+ if maxMem > 0 {
+ parts = append(parts, fmt.Sprintf("max_mem=%.1f%%", maxMem))
}
if trend != "" {
parts = append(parts, "trend="+trend)
@@ -2663,23 +2700,31 @@ func extractResourceDisksFacts(resultText string) []FactEntry {
// MarkerExpansions maps marker fact keys to the prefix used to find related per-resource facts.
// Used by the gate to enrich marker-based cache hits with actual data.
var MarkerExpansions = map[string]string{
- "storage:pools:queried": "storage:",
- "disk_health:queried": "disk_health:",
- "baselines:queried": "baseline:",
- "physical_disks:queried": "physical_disks:",
- "temperatures:queried": "temperatures:",
- "raid:queried": "raid:",
- "backups:queried": "backups:",
- "ceph:queried": "ceph:",
- "ceph_details:queried": "ceph_details:",
- "snapshots:queried": "snapshots:",
- "replication:queried": "replication:",
- "pbs_jobs:queried": "pbs_jobs:",
- "resource_disks:queried": "resource_disks:",
- "backup_tasks:queried": "backup:",
+ // Storage markers
+ "storage:pools:queried": "storage:",
+ "disk_health:queried": "disk_health:",
+ "raid:queried": "raid:",
+ "backups:queried": "backups:",
+ "ceph:queried": "ceph:",
+ "ceph_details:queried": "ceph_details:",
+ "snapshots:queried": "snapshots:",
+ "replication:queried": "replication:",
+ "pbs_jobs:queried": "pbs_jobs:",
+ "resource_disks:queried": "resource_disks:",
+ "backup_tasks:queried": "backup:",
+ // Metrics markers
+ "baselines:queried": "baseline:",
+ "physical_disks:queried": "physical_disks:",
+ "temperatures:queried": "temperatures:",
+ // Docker markers
"docker_services:queried": "docker_services:",
- "k8s_clusters:queried": "k8s_cluster:",
- "pmg:queried": "pmg:",
+ // Kubernetes markers
+ "k8s_clusters:queried": "k8s_cluster:",
+ // PMG markers
+ "pmg:queried": "pmg:",
+ // Alert & finding markers → expand to per-item facts
+ "alerts:overview": "alert:",
+ "findings:overview": "finding:",
"patrol_findings:queried": "patrol_findings:",
}
diff --git a/internal/ai/chat/knowledge_extractor_test.go b/internal/ai/chat/knowledge_extractor_test.go
index fae16ab1fe..f6c7c1a281 100644
--- a/internal/ai/chat/knowledge_extractor_test.go
+++ b/internal/ai/chat/knowledge_extractor_test.go
@@ -229,7 +229,9 @@ func TestExtractFacts_Metrics(t *testing.T) {
assert.Equal(t, FactCategoryMetrics, f.Category)
assert.Equal(t, "metrics:vm101", f.Key)
assert.Contains(t, f.Value, "avg_cpu=12.3%")
- assert.Contains(t, f.Value, "max=78.5%")
+ assert.Contains(t, f.Value, "max_cpu=78.5%")
+ assert.Contains(t, f.Value, "avg_mem=65.0%")
+ assert.Contains(t, f.Value, "max_mem=89.0%")
assert.Contains(t, f.Value, "trend=growing")
}
@@ -241,6 +243,35 @@ func TestExtractFacts_Metrics_EmptySummary(t *testing.T) {
assert.Empty(t, facts)
}
+func TestExtractFacts_Metrics_Points(t *testing.T) {
+ input := map[string]interface{}{"action": "performance", "resource_id": "vm101"}
+ // Single-resource query returns Points array, no Summary
+ result := `{"resource_id":"vm101","period":"1h","points":[` +
+ `{"timestamp":"2025-01-01T00:00:00Z","cpu":10.0,"memory":40.0,"disk":0},` +
+ `{"timestamp":"2025-01-01T00:05:00Z","cpu":30.0,"memory":60.0,"disk":0},` +
+ `{"timestamp":"2025-01-01T00:10:00Z","cpu":20.0,"memory":80.0,"disk":0}` +
+ `]}`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ require.Len(t, facts, 1)
+
+ f := facts[0]
+ assert.Equal(t, FactCategoryMetrics, f.Category)
+ assert.Equal(t, "metrics:vm101", f.Key)
+ assert.Contains(t, f.Value, "avg_cpu=20.0%") // (10+30+20)/3
+ assert.Contains(t, f.Value, "max_cpu=30.0%") // max of 10,30,20
+ assert.Contains(t, f.Value, "avg_mem=60.0%") // (40+60+80)/3
+ assert.Contains(t, f.Value, "max_mem=80.0%") // max of 40,60,80
+}
+
+func TestExtractFacts_Metrics_Points_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "performance", "resource_id": "vm101"}
+ result := `{"resource_id":"vm101","period":"1h","points":[]}`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ assert.Empty(t, facts)
+}
+
func TestExtractFacts_Finding(t *testing.T) {
input := map[string]interface{}{
"key": "high-cpu-vm101",
@@ -1728,8 +1759,10 @@ func TestPredictExtractRoundtrip(t *testing.T) {
`{"jobs":[{"id":"j1","type":"backup","status":"ok"}],"total":1}`},
{"storage:resource_disks", "pulse_storage", map[string]interface{}{"action": "resource_disks"},
`{"resources":[{"vmid":100,"name":"test","disks":[{"mountpoint":"/","usage_percent":50}]}],"total":1}`},
- {"metrics:performance", "pulse_metrics", map[string]interface{}{"action": "performance", "resource_id": "vm101"},
+ {"metrics:performance:summary", "pulse_metrics", map[string]interface{}{"action": "performance", "resource_id": "vm101"},
`{"summary":{"vm101":{"avg_cpu":10,"max_cpu":50,"trend":"stable"}}}`},
+ {"metrics:performance:points", "pulse_metrics", map[string]interface{}{"action": "performance", "resource_id": "vm101"},
+ `{"resource_id":"vm101","period":"1h","points":[{"timestamp":"2025-01-01T00:00:00Z","cpu":10,"memory":50}]}`},
{"metrics:baselines", "pulse_metrics", map[string]interface{}{"action": "baselines"},
`{"baselines":{"n1":{"n1:100:cpu":{"mean":5,"std_dev":2,"min":0,"max":20}}}}`},
{"metrics:disks", "pulse_metrics", map[string]interface{}{"action": "disks"},
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
index ded9083dcb..db02fa1dc8 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"sort"
"strings"
+ "sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
@@ -320,6 +321,9 @@ const (
//
// This type implements tools.ResolvedContextProvider interface.
type ResolvedContext struct {
+ // mu protects all map fields from concurrent access during parallel tool execution.
+ mu sync.RWMutex `json:"-"`
+
SessionID string `json:"session_id"`
// Resources maps resource names to their resolved information
@@ -491,6 +495,8 @@ func (rc *ResolvedContext) removeByID(resourceID string) {
// PinResource marks a resource as pinned (won't be evicted)
func (rc *ResolvedContext) PinResource(resourceID string) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
if rc.pinned == nil {
rc.pinned = make(map[string]bool)
}
@@ -499,16 +505,22 @@ func (rc *ResolvedContext) PinResource(resourceID string) {
// UnpinResource removes the pinned status from a resource
func (rc *ResolvedContext) UnpinResource(resourceID string) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
delete(rc.pinned, resourceID)
}
// IsPinned returns whether a resource is pinned
func (rc *ResolvedContext) IsPinned(resourceID string) bool {
+ rc.mu.RLock()
+ defer rc.mu.RUnlock()
return rc.pinned[resourceID]
}
// Clear removes all resources from the context (respects pinned)
func (rc *ResolvedContext) Clear(keepPinned bool) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
if !keepPinned {
rc.Resources = make(map[string]*ResolvedResource)
rc.ResourcesByID = make(map[string]*ResolvedResource)
@@ -551,6 +563,8 @@ func (rc *ResolvedContext) Clear(keepPinned bool) {
// Stats returns statistics about the context
func (rc *ResolvedContext) Stats() ResolvedContextStats {
+ rc.mu.RLock()
+ defer rc.mu.RUnlock()
uniqueCount := len(rc.ResourcesByID)
pinnedCount := 0
for _, isPinned := range rc.pinned {
@@ -580,6 +594,8 @@ type ResolvedContextStats struct {
// HasAnyResources implements tools.ResolvedContextProvider interface.
// Returns true if at least one resource has been discovered in this session.
func (rc *ResolvedContext) HasAnyResources() bool {
+ rc.mu.RLock()
+ defer rc.mu.RUnlock()
return len(rc.ResourcesByID) > 0
}
@@ -591,6 +607,8 @@ func (rc *ResolvedContext) HasAnyResources() bool {
// - Bulk discovery adds resources (sets lastAccessed) but should NOT trigger routing blocks
// - Explicit get/select sets explicitlyAccessed, indicating user intent to target that resource
func (rc *ResolvedContext) WasRecentlyAccessed(resourceID string, window time.Duration) bool {
+ rc.mu.RLock()
+ defer rc.mu.RUnlock()
if rc.explicitlyAccessed == nil {
return false
}
@@ -605,6 +623,8 @@ func (rc *ResolvedContext) WasRecentlyAccessed(resourceID string, window time.Du
// Uses explicitlyAccessed (not lastAccessed) to avoid false positives from bulk discovery.
// Returns a slice of resource IDs.
func (rc *ResolvedContext) GetRecentlyAccessedResources(window time.Duration) []string {
+ rc.mu.RLock()
+ defer rc.mu.RUnlock()
if rc.explicitlyAccessed == nil {
return nil
}
@@ -621,6 +641,8 @@ func (rc *ResolvedContext) GetRecentlyAccessedResources(window time.Duration) []
// GetRecentlyAccessedResourcesSorted returns recently accessed resources ordered by most recent access.
// If max <= 0, all recent resources are returned.
func (rc *ResolvedContext) GetRecentlyAccessedResourcesSorted(window time.Duration, max int) []string {
+ rc.mu.RLock()
+ defer rc.mu.RUnlock()
if rc.explicitlyAccessed == nil {
return nil
}
@@ -660,12 +682,16 @@ func (rc *ResolvedContext) GetRecentlyAccessedResourcesSorted(window time.Durati
// Use MarkExplicitAccess() when the user explicitly selects/queries a single resource.
// This separation prevents bulk discovery operations from poisoning routing validation.
func (rc *ResolvedContext) AddResource(name string, res *ResolvedResource) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
rc.addResourceInternal(name, res, false)
}
// AddResourceWithExplicitAccess adds a resource AND marks it as recently accessed.
// Use this for single-resource operations where user intent is clear (e.g., pulse_query get).
func (rc *ResolvedContext) AddResourceWithExplicitAccess(name string, res *ResolvedResource) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
rc.addResourceInternal(name, res, true)
}
@@ -745,6 +771,8 @@ func (rc *ResolvedContext) addResourceInternal(name string, res *ResolvedResourc
// If this is called incorrectly from bulk operations, routing validation will produce
// false positives, blocking legitimate host operations.
func (rc *ResolvedContext) MarkExplicitAccess(resourceID string) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
if rc.explicitlyAccessed == nil {
rc.explicitlyAccessed = make(map[string]time.Time)
}
@@ -754,6 +782,8 @@ func (rc *ResolvedContext) MarkExplicitAccess(resourceID string) {
// AddResolvedResource implements tools.ResolvedContextProvider interface.
// Called by query/discovery tools to register discovered resources.
func (rc *ResolvedContext) AddResolvedResource(reg tools.ResourceRegistration) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
// Build the canonical resource ID with scope for global uniqueness.
// Format: {kind}:{host}:{provider_uid} for scoped resources
// {kind}:{provider_uid} for global resources (nodes, clusters)
@@ -885,12 +915,19 @@ func (rc *ResolvedContext) AddResolvedResource(reg tools.ResourceRegistration) {
// Timestamps
ResolvedAt: time.Now(),
}
- rc.AddResource(reg.Name, res)
+ rc.addResourceInternal(reg.Name, res, false)
}
// GetResource retrieves a resource by name (case-insensitive)
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResource(name string) (*ResolvedResource, bool) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
+ return rc.getResourceInternal(name)
+}
+
+// getResourceInternal is the lock-free implementation of GetResource.
+func (rc *ResolvedContext) getResourceInternal(name string) (*ResolvedResource, bool) {
// Evict expired on access
rc.evictExpired()
@@ -910,6 +947,13 @@ func (rc *ResolvedContext) GetResource(name string) (*ResolvedResource, bool) {
// GetResourceByID retrieves a resource by its canonical ResourceID (internal use)
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResourceByID(resourceID string) (*ResolvedResource, bool) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
+ return rc.getResourceByIDInternal(resourceID)
+}
+
+// getResourceByIDInternal is the lock-free implementation of GetResourceByID.
+func (rc *ResolvedContext) getResourceByIDInternal(resourceID string) (*ResolvedResource, bool) {
// Evict expired on access
rc.evictExpired()
@@ -923,6 +967,9 @@ func (rc *ResolvedContext) GetResourceByID(resourceID string) (*ResolvedResource
// GetResolvedResourceByID implements tools.ResolvedContextProvider interface.
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResolvedResourceByID(resourceID string) (tools.ResolvedResourceInfo, bool) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
+
// Evict expired on access
rc.evictExpired()
@@ -938,6 +985,9 @@ func (rc *ResolvedContext) GetResolvedResourceByID(resourceID string) (tools.Res
// Retrieves a resource by any of its aliases (case-insensitive).
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResolvedResourceByAlias(alias string) (tools.ResolvedResourceInfo, bool) {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
+
// Evict expired on access
rc.evictExpired()
@@ -952,7 +1002,14 @@ func (rc *ResolvedContext) GetResolvedResourceByAlias(alias string) (tools.Resol
// ValidateResourceID checks if a resource ID exists in this context
// and returns the resource if valid
func (rc *ResolvedContext) ValidateResourceID(resourceID string) (*ResolvedResource, error) {
- res, ok := rc.GetResourceByID(resourceID)
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
+ return rc.validateResourceIDInternal(resourceID)
+}
+
+// validateResourceIDInternal is the lock-free implementation of ValidateResourceID.
+func (rc *ResolvedContext) validateResourceIDInternal(resourceID string) (*ResolvedResource, error) {
+ res, ok := rc.getResourceByIDInternal(resourceID)
if !ok {
return nil, &ResourceNotResolvedError{ResourceID: resourceID}
}
@@ -961,7 +1018,14 @@ func (rc *ResolvedContext) ValidateResourceID(resourceID string) (*ResolvedResou
// ValidateAction checks if an action is allowed for a resource (internal use)
func (rc *ResolvedContext) ValidateAction(resourceID, action string) error {
- res, err := rc.ValidateResourceID(resourceID)
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
+ return rc.validateActionInternal(resourceID, action)
+}
+
+// validateActionInternal is the lock-free implementation of ValidateAction.
+func (rc *ResolvedContext) validateActionInternal(resourceID, action string) error {
+ res, err := rc.validateResourceIDInternal(resourceID)
if err != nil {
return err
}
@@ -987,10 +1051,12 @@ func (rc *ResolvedContext) ValidateAction(resourceID, action string) error {
// ValidateResourceForAction implements tools.ResolvedContextProvider interface.
// Returns the resource if valid, error if not found or action not allowed.
func (rc *ResolvedContext) ValidateResourceForAction(resourceID, action string) (tools.ResolvedResourceInfo, error) {
- if err := rc.ValidateAction(resourceID, action); err != nil {
+ rc.mu.Lock()
+ defer rc.mu.Unlock()
+ if err := rc.validateActionInternal(resourceID, action); err != nil {
return nil, err
}
- res, _ := rc.GetResourceByID(resourceID)
+ res, _ := rc.getResourceByIDInternal(resourceID)
return res, nil
}
diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.go
index 4ca6b57c43..0a039ebb5f 100644
--- a/internal/ai/tools/tools_query.go
+++ b/internal/ai/tools/tools_query.go
@@ -2212,7 +2212,7 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args ma
Status: vm.Status,
Node: vm.Node,
CPU: vm.CPU * 100,
- Memory: vm.Memory.Usage * 100,
+ Memory: vm.Memory.Usage, // Already 0-100 from safePercentage
})
count++
}
@@ -2242,7 +2242,7 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args ma
Status: ct.Status,
Node: ct.Node,
CPU: ct.CPU * 100,
- Memory: ct.Memory.Usage * 100,
+ Memory: ct.Memory.Usage, // Already 0-100 from safePercentage
})
count++
}
@@ -2449,7 +2449,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
Name: vm.Name,
Status: vm.Status,
CPU: vm.CPU * 100,
- Memory: vm.Memory.Usage * 100,
+ Memory: vm.Memory.Usage, // Already 0-100 from safePercentage
OS: vm.OSName,
Tags: vm.Tags,
})
@@ -2474,7 +2474,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
Name: ct.Name,
Status: ct.Status,
CPU: ct.CPU * 100,
- Memory: ct.Memory.Usage * 100,
+ Memory: ct.Memory.Usage, // Already 0-100 from safePercentage
OS: ct.OSName,
Tags: ct.Tags,
HasDocker: ct.HasDocker,
@@ -2575,7 +2575,7 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
Cores: vm.CPUs,
},
Memory: ResourceMemory{
- Percent: vm.Memory.Usage * 100,
+ Percent: vm.Memory.Usage, // Already 0-100 from safePercentage
UsedGB: float64(vm.Memory.Used) / (1024 * 1024 * 1024),
TotalGB: float64(vm.Memory.Total) / (1024 * 1024 * 1024),
},
@@ -2632,7 +2632,7 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
Cores: ct.CPUs,
},
Memory: ResourceMemory{
- Percent: ct.Memory.Usage * 100,
+ Percent: ct.Memory.Usage, // Already 0-100 from safePercentage
UsedGB: float64(ct.Memory.Used) / (1024 * 1024 * 1024),
TotalGB: float64(ct.Memory.Total) / (1024 * 1024 * 1024),
},