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.

refactor(ai): refine agentic loop compaction and knowledge accumulation

rcourtman82ddeac4546b
diff --git a/cmd/pulse/main.go b/cmd/pulse/main.go
index 3275b4f910..8117fe81fb 100644
--- a/cmd/pulse/main.go
+++ b/cmd/pulse/main.go
@@ -1,7 +1,5 @@
package main
-// rebuild trigger
-
import (
"context"
"fmt"
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index f3be021c13..bca711ae76 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -122,10 +122,17 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
const compactionMinChars = 300 // Only compact results longer than this
currentTurnStartIndex := len(providerMessages) // Initial messages are never compacted
+ // Wrap-up nudge: after this many cumulative tool calls, hint the model to start wrapping up.
+ const wrapUpNudgeAfterCalls = 12
+ const wrapUpEscalateAfterCalls = 18
+ totalToolCalls := 0
+ wrapUpNudgeFired := false
+ wrapUpEscalateFired := false
+
for turn < maxTurns {
// === CONTEXT COMPACTION: Compact old tool results to prevent context blowout ===
if turn > 0 {
- compactOldToolResults(providerMessages, currentTurnStartIndex, compactionKeepTurns, compactionMinChars)
+ compactOldToolResults(providerMessages, currentTurnStartIndex, compactionKeepTurns, compactionMinChars, a.knowledgeAccumulator)
}
// Check if aborted
@@ -657,7 +664,15 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
}
if len(cachedParts) > 0 {
- cachedResult := fmt.Sprintf("Already known (from earlier investigation, matched keys: %s): %s. If you need fresh data, use a different query or approach.", strings.Join(keys, ","), strings.Join(cachedParts, "; "))
+ // Enrich marker-based cache hits with related per-resource facts
+ for _, key := range keys {
+ if prefix, ok := MarkerExpansions[key]; ok {
+ if related := a.knowledgeAccumulator.RelatedFacts(prefix); related != "" {
+ cachedParts = append(cachedParts, related)
+ }
+ }
+ }
+ cachedResult := fmt.Sprintf("Already known (from earlier investigation): %s. If you need fresh data, use a different query or approach.", strings.Join(cachedParts, "; "))
log.Info().
Str("tool", tc.Name).
@@ -716,18 +731,38 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
log.Debug().
Str("tool", tc.Name).
Msg("[AgenticLoop] Tool succeeded - toolsSucceededThisEpisode set to true")
+ }
+ // Extract and accumulate knowledge facts from both success and structured error responses
+ if a.knowledgeAccumulator != nil {
+ a.knowledgeAccumulator.SetTurn(turn)
+ facts := ExtractFacts(tc.Name, tc.Input, resultText)
+ for _, f := range facts {
+ a.knowledgeAccumulator.AddFactForTool(tc.ID, f.Category, f.Key, f.Value)
+ log.Debug().
+ Str("tool", tc.Name).
+ Str("fact_key", f.Key).
+ Int("value_len", len(f.Value)).
+ Msg("[AgenticLoop] Stored knowledge fact")
+ }
- // Extract and accumulate knowledge facts
- if a.knowledgeAccumulator != nil {
- a.knowledgeAccumulator.SetTurn(turn)
- facts := ExtractFacts(tc.Name, tc.Input, resultText)
- for _, f := range facts {
- a.knowledgeAccumulator.AddFact(f.Category, f.Key, f.Value)
- log.Debug().
- Str("tool", tc.Name).
- Str("fact_key", f.Key).
- Int("value_len", len(f.Value)).
- Msg("[AgenticLoop] Stored knowledge fact")
+ // If no facts were extracted but we predicted keys, store negative markers
+ // 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 {
+ 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).
+ Str("fact_key", key).
+ Msg("[AgenticLoop] Stored negative marker (text response)")
+ }
+ }
}
}
}
@@ -1053,6 +1088,16 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
return resultMessages, nil
}
+ // Track cumulative tool calls and inject wrap-up nudge/escalation if threshold exceeded
+ totalToolCalls += len(toolCalls)
+ if !wrapUpNudgeFired && totalToolCalls >= wrapUpNudgeAfterCalls {
+ maybeInjectWrapUpNudge(providerMessages, totalToolCalls, maxTurns, turn, wrapUpNudgeAfterCalls)
+ wrapUpNudgeFired = true
+ } else if wrapUpNudgeFired && !wrapUpEscalateFired && totalToolCalls >= wrapUpEscalateAfterCalls {
+ maybeInjectWrapUpEscalation(providerMessages, totalToolCalls)
+ wrapUpEscalateFired = true
+ }
+
// Mark the start of the next turn's messages for compaction tracking
currentTurnStartIndex = len(providerMessages)
turn++
@@ -1830,7 +1875,7 @@ func convertToProviderMessages(messages []Message) []providers.Message {
//
// The model retains all its assistant messages (reasoning, analysis, findings) in full.
// Only the raw tool result data from older turns gets replaced with a summary line.
-func compactOldToolResults(messages []providers.Message, currentTurnStartIndex, keepTurns, minChars int) {
+func compactOldToolResults(messages []providers.Message, currentTurnStartIndex, keepTurns, minChars int, ka *KnowledgeAccumulator) {
if currentTurnStartIndex <= 0 || keepTurns < 0 {
return
}
@@ -1902,7 +1947,7 @@ func compactOldToolResults(messages []providers.Message, currentTurnStartIndex,
toolInput = info.Input
}
- summary := buildCompactSummary(toolName, toolInput, content)
+ summary := buildCompactSummary(toolName, toolInput, content, ka, msg.ToolResult.ToolUseID)
savedChars += len(content) - len(summary)
msg.ToolResult.Content = summary
compacted++
@@ -1919,12 +1964,35 @@ func compactOldToolResults(messages []providers.Message, currentTurnStartIndex,
}
// buildCompactSummary creates a short summary line for a compacted tool result.
-func buildCompactSummary(toolName string, toolInput map[string]interface{}, originalContent string) string {
+// When a KnowledgeAccumulator is provided and has facts for this tool_use_id,
+// the summary includes those facts so the model knows what it learned.
+func buildCompactSummary(toolName string, toolInput map[string]interface{}, originalContent string, ka *KnowledgeAccumulator, toolUseID string) string {
params := formatKeyParams(toolInput)
- // Count lines and try to extract a count hint (e.g., number of items returned)
- lineCount := strings.Count(originalContent, "\n") + 1
charCount := len(originalContent)
+ // Try to include KA facts for this specific tool call
+ if ka != nil && toolUseID != "" {
+ if factSummary := ka.FactSummaryForTool(toolUseID); factSummary != "" {
+ var summary string
+ if params != "" {
+ summary = fmt.Sprintf("[Compacted: %s(%s) — Key facts: %s]",
+ toolName, params, factSummary)
+ } else {
+ summary = fmt.Sprintf("[Compacted: %s — Key facts: %s]",
+ toolName, factSummary)
+ }
+ log.Info().
+ Str("tool", toolName).
+ Str("tool_use_id", toolUseID).
+ Int("original_chars", charCount).
+ Int("summary_chars", len(summary)).
+ Msg("[SmartCompaction] Used KA facts for compacted summary")
+ return summary
+ }
+ }
+
+ // Fallback: generic format when no KA facts available
+ lineCount := strings.Count(originalContent, "\n") + 1
if params != "" {
return fmt.Sprintf("[Tool result compacted: %s(%s) — %d chars, %d lines. Full data was provided to the model in an earlier turn and has already been processed.]",
toolName, params, charCount, lineCount)
@@ -1933,6 +2001,54 @@ func buildCompactSummary(toolName string, toolInput map[string]interface{}, orig
toolName, charCount, lineCount)
}
+// maybeInjectWrapUpNudge appends a system hint to the last non-error tool result in
+// providerMessages when totalCalls exceeds the threshold. This nudges the model to
+// start wrapping up without forcing text-only mode.
+// Returns true if a nudge was injected.
+func maybeInjectWrapUpNudge(messages []providers.Message, totalCalls, maxTurns, currentTurn, threshold int) bool {
+ if totalCalls < threshold {
+ return false
+ }
+
+ turnsRemaining := maxTurns - currentTurn - 1
+ nudge := fmt.Sprintf("\n\n[System: You have made %d tool calls (%d turns remaining). You likely have enough data to answer. Start forming your response. You may make 1-2 more targeted calls if critical information is missing, but avoid exploratory calls.]",
+ totalCalls, turnsRemaining)
+
+ // Find the last non-error tool result in messages and append the nudge
+ for i := len(messages) - 1; i >= 0; i-- {
+ if messages[i].ToolResult != nil && !messages[i].ToolResult.IsError {
+ messages[i].ToolResult.Content += nudge
+ log.Info().
+ Int("total_calls", totalCalls).
+ Int("turns_remaining", turnsRemaining).
+ Int("message_index", i).
+ Msg("[WrapUpNudge] Injected wrap-up nudge into tool result")
+ return true
+ }
+ }
+ return false
+}
+
+// maybeInjectWrapUpEscalation appends a strong wrap-up directive to the last non-error
+// tool result. Called once when the model ignores the initial nudge and reaches 18+ calls.
+// Returns true if an escalation was injected.
+func maybeInjectWrapUpEscalation(messages []providers.Message, totalCalls int) bool {
+ escalation := fmt.Sprintf("\n\n[System: WRAP UP NOW. You have made %d tool calls — well past the recommended limit. You MUST respond with your findings on this turn. Do NOT make any more tool calls.]",
+ totalCalls)
+
+ for i := len(messages) - 1; i >= 0; i-- {
+ if messages[i].ToolResult != nil && !messages[i].ToolResult.IsError {
+ messages[i].ToolResult.Content += escalation
+ log.Info().
+ Int("total_calls", totalCalls).
+ Int("message_index", i).
+ Msg("[WrapUpEscalation] Injected wrap-up escalation into tool result")
+ return true
+ }
+ }
+ return false
+}
+
// formatKeyParams extracts the most important parameters from tool input for display.
func formatKeyParams(input map[string]interface{}) string {
if len(input) == 0 {
diff --git a/internal/ai/chat/compaction_test.go b/internal/ai/chat/compaction_test.go
index a8cb0d72ba..e156fdfc91 100644
--- a/internal/ai/chat/compaction_test.go
+++ b/internal/ai/chat/compaction_test.go
@@ -41,7 +41,7 @@ func TestCompactOldToolResults_NoCompactionOnFirstTurn(t *testing.T) {
{Role: "user", Content: "check my infra"},
}
original := msgs[0].Content
- compactOldToolResults(msgs, len(msgs), 3, 500)
+ compactOldToolResults(msgs, len(msgs), 3, 500, nil)
assert.Equal(t, original, msgs[0].Content, "user message should not be modified")
}
@@ -56,7 +56,7 @@ func TestCompactOldToolResults_DoesNotCompactCurrentTurn(t *testing.T) {
}
// currentTurnStartIndex = 3 means all messages are from the current turn
- compactOldToolResults(msgs, 3, 3, 500)
+ compactOldToolResults(msgs, 3, 3, 500, nil)
assert.Equal(t, bigResult, msgs[2].ToolResult.Content, "current turn results should not be compacted")
}
@@ -101,7 +101,7 @@ func TestCompactOldToolResults_CompactsOldTurns(t *testing.T) {
keepTurns := 2
minChars := 500
- compactOldToolResults(msgs, currentTurnStart, keepTurns, minChars)
+ compactOldToolResults(msgs, currentTurnStart, keepTurns, minChars, nil)
// With keepTurns=2, we walk back from currentTurnStart=9:
// index 7 (turn 2 assistant): turnsFound=1
@@ -144,7 +144,7 @@ func TestCompactOldToolResults_DoesNotCompactErrors(t *testing.T) {
makeToolResultMessage("tc2", bigContent(1000), false),
}
- compactOldToolResults(msgs, 3, 0, 500) // keepTurns=0 means compact everything before currentTurnStart
+ compactOldToolResults(msgs, 3, 0, 500, nil) // keepTurns=0 means compact everything before currentTurnStart
assert.Equal(t, errorContent, msgs[2].ToolResult.Content, "error results should never be compacted")
}
@@ -165,15 +165,15 @@ func TestCompactOldToolResults_KeepTurnsZero(t *testing.T) {
makeToolResultMessage("tc2", bigContent(3000), false),
}
- compactOldToolResults(msgs, 3, 0, 500)
+ compactOldToolResults(msgs, 3, 0, 500, nil)
assert.Contains(t, msgs[2].ToolResult.Content, "[Tool result compacted:", "should compact with keepTurns=0")
}
func TestCompactOldToolResults_EmptyMessages(t *testing.T) {
// Edge case: empty or nil-ish slices should not panic
- compactOldToolResults(nil, 0, 3, 500)
- compactOldToolResults([]providers.Message{}, 0, 3, 500)
- compactOldToolResults([]providers.Message{{Role: "user", Content: "hi"}}, 0, 3, 500)
+ compactOldToolResults(nil, 0, 3, 500, nil)
+ compactOldToolResults([]providers.Message{}, 0, 3, 500, nil)
+ compactOldToolResults([]providers.Message{{Role: "user", Content: "hi"}}, 0, 3, 500, nil)
}
func TestCompactOldToolResults_ContextSavings(t *testing.T) {
@@ -202,7 +202,7 @@ func TestCompactOldToolResults_ContextSavings(t *testing.T) {
}
}
- compactOldToolResults(msgs, currentTurnStart, 3, 500)
+ compactOldToolResults(msgs, currentTurnStart, 3, 500, nil)
// Measure after
charsAfter := 0
@@ -267,7 +267,7 @@ func TestBuildCompactSummary(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- result := buildCompactSummary(tt.toolName, tt.toolInput, tt.content)
+ result := buildCompactSummary(tt.toolName, tt.toolInput, tt.content, nil, "")
for _, part := range tt.wantParts {
assert.Contains(t, result, part)
}
@@ -341,7 +341,7 @@ func TestCompactOldToolResults_PreservesToolCallInfo(t *testing.T) {
makeToolResultMessage("tc3", bigContent(1000), false),
}
- compactOldToolResults(msgs, 4, 0, 500) // compact everything before index 4
+ compactOldToolResults(msgs, 4, 0, 500, nil) // compact everything before index 4
require.Contains(t, msgs[2].ToolResult.Content, "pulse_storage")
require.Contains(t, msgs[2].ToolResult.Content, "type=pools")
@@ -350,6 +350,149 @@ func TestCompactOldToolResults_PreservesToolCallInfo(t *testing.T) {
require.Contains(t, msgs[3].ToolResult.Content, "period=7d")
}
+func TestBuildCompactSummary_WithKAFacts(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+ ka.AddFactForTool("tc-abc", FactCategoryStorage, "storage:delly+minipc:pbs-minipc", "PBS, available, active on delly+minipc, 42.7% used, 573GB free")
+
+ result := buildCompactSummary("pulse_storage", map[string]interface{}{"type": "pools"}, bigContent(2847), ka, "tc-abc")
+ assert.Contains(t, result, "[Compacted:")
+ assert.Contains(t, result, "pulse_storage")
+ assert.Contains(t, result, "Key facts:")
+ assert.Contains(t, result, "PBS")
+ assert.Contains(t, result, "42.7% used")
+ assert.NotContains(t, result, "already been processed", "should use KA format, not generic format")
+}
+
+func TestBuildCompactSummary_WithKAFacts_NoFacts(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+ // No facts added for this tool ID — should fall back to generic format
+ result := buildCompactSummary("pulse_query", map[string]interface{}{"type": "topology"}, bigContent(5000), ka, "tc-unknown")
+ assert.Contains(t, result, "[Tool result compacted:")
+ assert.Contains(t, result, "already been processed")
+ assert.NotContains(t, result, "Key facts:")
+}
+
+func TestCompactOldToolResults_WithKAFacts(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+ ka.AddFactForTool("tc1", FactCategoryStorage, "storage:delly:local-lvm", "dir, available, 80% used, 20GB free")
+
+ msgs := []providers.Message{
+ {Role: "user", Content: "check storage"},
+ makeAssistantMessageWithToolCalls("",
+ providers.ToolCall{ID: "tc1", Name: "pulse_storage", Input: map[string]interface{}{"type": "pools"}},
+ ),
+ makeToolResultMessage("tc1", bigContent(3000), false),
+ // Current turn
+ makeAssistantMessageWithToolCalls("",
+ providers.ToolCall{ID: "tc2", Name: "pulse_read", Input: map[string]interface{}{}},
+ ),
+ makeToolResultMessage("tc2", bigContent(1000), false),
+ }
+
+ compactOldToolResults(msgs, 3, 0, 500, ka)
+
+ assert.Contains(t, msgs[2].ToolResult.Content, "[Compacted:")
+ assert.Contains(t, msgs[2].ToolResult.Content, "Key facts:")
+ assert.Contains(t, msgs[2].ToolResult.Content, "80% used")
+}
+
+func TestMaybeInjectWrapUpNudge(t *testing.T) {
+ msgs := []providers.Message{
+ {Role: "user", Content: "check everything"},
+ makeAssistantMessageWithToolCalls("",
+ providers.ToolCall{ID: "tc1", Name: "pulse_query", Input: map[string]interface{}{"type": "topology"}},
+ ),
+ makeToolResultMessage("tc1", "some result data", false),
+ }
+
+ // Above threshold: should inject nudge
+ injected := maybeInjectWrapUpNudge(msgs, 13, 20, 5, 12)
+ assert.True(t, injected)
+ assert.Contains(t, msgs[2].ToolResult.Content, "[System: You have made 13 tool calls")
+ assert.Contains(t, msgs[2].ToolResult.Content, "14 turns remaining")
+ assert.Contains(t, msgs[2].ToolResult.Content, "Start forming your response")
+}
+
+func TestMaybeInjectWrapUpNudge_NotInjectedBelowThreshold(t *testing.T) {
+ msgs := []providers.Message{
+ {Role: "user", Content: "check something"},
+ makeAssistantMessageWithToolCalls("",
+ providers.ToolCall{ID: "tc1", Name: "pulse_query", Input: map[string]interface{}{}},
+ ),
+ makeToolResultMessage("tc1", "result", false),
+ }
+
+ originalContent := msgs[2].ToolResult.Content
+ injected := maybeInjectWrapUpNudge(msgs, 5, 20, 2, 12)
+ assert.False(t, injected)
+ assert.Equal(t, originalContent, msgs[2].ToolResult.Content, "content should not be modified below threshold")
+}
+
+func TestMaybeInjectWrapUpNudge_SkipsErrorResults(t *testing.T) {
+ msgs := []providers.Message{
+ makeToolResultMessage("tc1", "good result", false),
+ makeToolResultMessage("tc2", "error result", true), // Last result is an error
+ }
+
+ injected := maybeInjectWrapUpNudge(msgs, 15, 20, 5, 12)
+ assert.True(t, injected)
+ // Should inject into tc1 (the last non-error result), not tc2
+ assert.Contains(t, msgs[0].ToolResult.Content, "[System:")
+ assert.NotContains(t, msgs[1].ToolResult.Content, "[System:")
+}
+
+func TestWrapUpNudge_FiresOnce(t *testing.T) {
+ // Simulate calling maybeInjectWrapUpNudge twice above threshold.
+ // Only the first call should inject text (caller gates with wrapUpNudgeFired).
+ msgs := []providers.Message{
+ makeToolResultMessage("tc1", "result data", false),
+ }
+
+ // First call: should inject
+ injected := maybeInjectWrapUpNudge(msgs, 13, 20, 5, 12)
+ assert.True(t, injected)
+ assert.Contains(t, msgs[0].ToolResult.Content, "[System: You have made 13 tool calls")
+
+ // Record content after first injection
+ contentAfterFirst := msgs[0].ToolResult.Content
+
+ // Second call: the function itself always injects if above threshold,
+ // but the agentic loop gates it with wrapUpNudgeFired. Verify that
+ // calling it again would add a second nudge (showing why the gate matters).
+ injected2 := maybeInjectWrapUpNudge(msgs, 15, 20, 7, 12)
+ assert.True(t, injected2)
+ // Content changed — this proves the agentic loop gate is necessary
+ assert.NotEqual(t, contentAfterFirst, msgs[0].ToolResult.Content)
+}
+
+func TestWrapUpNudge_Escalation(t *testing.T) {
+ // Verify escalation fires at 18+ calls with stronger text.
+ msgs := []providers.Message{
+ makeToolResultMessage("tc1", "some data", false),
+ }
+
+ // Escalation should NOT fire below 18 (it's gated in the loop, but test the function)
+ injected := maybeInjectWrapUpEscalation(msgs, 18)
+ assert.True(t, injected)
+ assert.Contains(t, msgs[0].ToolResult.Content, "WRAP UP NOW")
+ assert.Contains(t, msgs[0].ToolResult.Content, "18 tool calls")
+ assert.Contains(t, msgs[0].ToolResult.Content, "MUST respond")
+ assert.Contains(t, msgs[0].ToolResult.Content, "Do NOT make any more tool calls")
+}
+
+func TestWrapUpEscalation_SkipsErrorResults(t *testing.T) {
+ msgs := []providers.Message{
+ makeToolResultMessage("tc1", "good result", false),
+ makeToolResultMessage("tc2", "error result", true),
+ }
+
+ injected := maybeInjectWrapUpEscalation(msgs, 20)
+ assert.True(t, injected)
+ // Should inject into tc1 (last non-error), not tc2
+ assert.Contains(t, msgs[0].ToolResult.Content, "WRAP UP NOW")
+ assert.NotContains(t, msgs[1].ToolResult.Content, "WRAP UP NOW")
+}
+
func TestTruncateToolResultForModel_ReducedLimit(t *testing.T) {
// Verify the limit is now 16000
assert.Equal(t, 16000, MaxToolResultCharsLimit, "MaxToolResultCharsLimit should be 16000")
diff --git a/internal/ai/chat/knowledge_accumulator.go b/internal/ai/chat/knowledge_accumulator.go
index 94ff2c6ccc..735babf898 100644
--- a/internal/ai/chat/knowledge_accumulator.go
+++ b/internal/ai/chat/knowledge_accumulator.go
@@ -13,12 +13,20 @@ type FactCategory string
const (
FactCategoryResource FactCategory = "resource"
FactCategoryStorage FactCategory = "storage"
+ FactCategoryAlert FactCategory = "alert"
FactCategoryDiscovery FactCategory = "discovery"
FactCategoryExec FactCategory = "exec"
FactCategoryMetrics FactCategory = "metrics"
FactCategoryFinding FactCategory = "finding"
)
+// isMarkerKey returns true if the fact key is a marker (ends with ":queried").
+// Markers exist only for gate matching and should not appear in rendered output
+// or count toward the character budget.
+func isMarkerKey(key string) bool {
+ return strings.HasSuffix(key, ":queried")
+}
+
// Fact is a single extracted knowledge entry.
type Fact struct {
Category FactCategory
@@ -39,8 +47,9 @@ const (
// Thread-safe: all methods are protected by a mutex.
type KnowledgeAccumulator struct {
mu sync.Mutex
- facts map[string]*Fact // key -> fact (upsert: same key updates value)
- order []string // insertion order for LRU eviction
+ facts map[string]*Fact // key -> fact (upsert: same key updates value)
+ order []string // insertion order for LRU eviction
+ toolFacts map[string][]string // tool_use_id -> fact keys extracted from that tool call
totalChars int
maxEntries int
maxChars int
@@ -51,6 +60,7 @@ type KnowledgeAccumulator struct {
func NewKnowledgeAccumulator() *KnowledgeAccumulator {
return &KnowledgeAccumulator{
facts: make(map[string]*Fact),
+ toolFacts: make(map[string][]string),
maxEntries: defaultMaxEntries,
maxChars: defaultMaxChars,
}
@@ -73,6 +83,47 @@ func (ka *KnowledgeAccumulator) AddFact(category FactCategory, key, value string
ka.mu.Lock()
defer ka.mu.Unlock()
+ ka.addFactLocked(category, key, value)
+}
+
+// AddFactForTool upserts a fact and records the association with a specific tool_use_id.
+// This allows FactSummaryForTool to later retrieve what facts were extracted from a given tool call.
+func (ka *KnowledgeAccumulator) AddFactForTool(toolUseID string, category FactCategory, key, value string) {
+ if key == "" || value == "" {
+ return
+ }
+
+ ka.mu.Lock()
+ defer ka.mu.Unlock()
+
+ ka.addFactLocked(category, key, value)
+ if toolUseID != "" {
+ ka.toolFacts[toolUseID] = append(ka.toolFacts[toolUseID], key)
+ }
+}
+
+// FactSummaryForTool returns a joined summary of fact values extracted from the given tool call.
+// Returns empty string if no facts were recorded for this tool_use_id.
+func (ka *KnowledgeAccumulator) FactSummaryForTool(toolUseID string) string {
+ ka.mu.Lock()
+ defer ka.mu.Unlock()
+
+ keys, ok := ka.toolFacts[toolUseID]
+ if !ok || len(keys) == 0 {
+ return ""
+ }
+
+ var parts []string
+ for _, key := range keys {
+ if fact, ok := ka.facts[key]; ok {
+ parts = append(parts, fmt.Sprintf("%s = %s", key, fact.Value))
+ }
+ }
+ return strings.Join(parts, "; ")
+}
+
+// addFactLocked is the internal implementation of AddFact. Caller must hold ka.mu.
+func (ka *KnowledgeAccumulator) addFactLocked(category FactCategory, key, value string) {
// Truncate value
if len(value) > maxValueLen {
value = value[:maxValueLen]
@@ -80,14 +131,20 @@ func (ka *KnowledgeAccumulator) AddFact(category FactCategory, key, value string
now := time.Now()
+ marker := isMarkerKey(key)
+
if existing, ok := ka.facts[key]; ok {
// Upsert: update existing fact
- ka.totalChars -= len(existing.Value)
+ if !marker {
+ ka.totalChars -= len(existing.Value)
+ }
existing.Value = value
existing.Category = category
existing.ObservedAt = now
existing.Turn = ka.currentTurn
- ka.totalChars += len(value)
+ if !marker {
+ ka.totalChars += len(value)
+ }
} else {
// New fact
fact := &Fact{
@@ -99,7 +156,9 @@ func (ka *KnowledgeAccumulator) AddFact(category FactCategory, key, value string
}
ka.facts[key] = fact
ka.order = append(ka.order, key)
- ka.totalChars += len(value)
+ if !marker {
+ ka.totalChars += len(value)
+ }
}
// Evict until within budget
@@ -125,7 +184,9 @@ func (ka *KnowledgeAccumulator) evict() {
continue
}
// Evict this fact
- ka.totalChars -= len(fact.Value)
+ if !isMarkerKey(key) {
+ ka.totalChars -= len(fact.Value)
+ }
delete(ka.facts, key)
ka.order = append(ka.order[:i], ka.order[i+1:]...)
evicted = true
@@ -162,6 +223,25 @@ func (ka *KnowledgeAccumulator) Lookup(key string) (string, bool) {
return "", false
}
+// RelatedFacts returns a semicolon-joined summary of non-marker facts
+// whose keys start with the given prefix. Used by the gate to enrich
+// marker-based cache hits with actual per-resource data.
+func (ka *KnowledgeAccumulator) RelatedFacts(prefix string) string {
+ ka.mu.Lock()
+ defer ka.mu.Unlock()
+
+ var parts []string
+ for _, key := range ka.order {
+ if isMarkerKey(key) || !strings.HasPrefix(key, prefix) {
+ continue
+ }
+ if fact, ok := ka.facts[key]; ok {
+ parts = append(parts, fmt.Sprintf("%s = %s", key, fact.Value))
+ }
+ }
+ return strings.Join(parts, "; ")
+}
+
// Render produces the system prompt section with grouped facts.
func (ka *KnowledgeAccumulator) Render() string {
ka.mu.Lock()
@@ -175,6 +255,7 @@ func (ka *KnowledgeAccumulator) Render() string {
categoryOrder := []FactCategory{
FactCategoryResource,
FactCategoryStorage,
+ FactCategoryAlert,
FactCategoryDiscovery,
FactCategoryExec,
FactCategoryMetrics,
@@ -184,6 +265,7 @@ func (ka *KnowledgeAccumulator) Render() string {
categoryLabels := map[FactCategory]string{
FactCategoryResource: "Resources",
FactCategoryStorage: "Storage",
+ FactCategoryAlert: "Alerts",
FactCategoryDiscovery: "Discovery",
FactCategoryExec: "Exec",
FactCategoryMetrics: "Metrics",
@@ -192,6 +274,9 @@ func (ka *KnowledgeAccumulator) Render() string {
grouped := make(map[FactCategory][]*Fact)
for _, key := range ka.order {
+ if isMarkerKey(key) {
+ continue
+ }
if fact, ok := ka.facts[key]; ok {
grouped[fact.Category] = append(grouped[fact.Category], fact)
}
@@ -208,7 +293,7 @@ func (ka *KnowledgeAccumulator) Render() string {
label := categoryLabels[cat]
sb.WriteString(fmt.Sprintf("\n%s:", label))
for _, fact := range facts {
- sb.WriteString(fmt.Sprintf("\n- %s", fact.Value))
+ sb.WriteString(fmt.Sprintf("\n- [%s] %s", fact.Key, fact.Value))
}
}
diff --git a/internal/ai/chat/knowledge_accumulator_test.go b/internal/ai/chat/knowledge_accumulator_test.go
index a3dc2ab3e6..fb52d5fd21 100644
--- a/internal/ai/chat/knowledge_accumulator_test.go
+++ b/internal/ai/chat/knowledge_accumulator_test.go
@@ -19,7 +19,7 @@ func TestKnowledgeAccumulator_Basic(t *testing.T) {
rendered := ka.Render()
assert.Contains(t, rendered, "Known Facts")
assert.Contains(t, rendered, "Resources:")
- assert.Contains(t, rendered, "running, Postfix")
+ assert.Contains(t, rendered, "[lxc:delly:106:status] running, Postfix")
}
func TestKnowledgeAccumulator_Upsert(t *testing.T) {
@@ -117,6 +117,7 @@ func TestKnowledgeAccumulator_CategoryGrouping(t *testing.T) {
ka.AddFact(FactCategoryResource, "res1", "LXC 106 running")
ka.AddFact(FactCategoryStorage, "stor1", "PBS available, 42% used")
+ ka.AddFact(FactCategoryAlert, "alert1", "2 active alerts")
ka.AddFact(FactCategoryExec, "exec1", "exit=0, service active")
ka.AddFact(FactCategoryFinding, "find1", "warning: high CPU on vm101")
@@ -125,16 +126,31 @@ func TestKnowledgeAccumulator_CategoryGrouping(t *testing.T) {
// Verify category headers appear
assert.Contains(t, rendered, "Resources:")
assert.Contains(t, rendered, "Storage:")
+ assert.Contains(t, rendered, "Alerts:")
assert.Contains(t, rendered, "Exec:")
assert.Contains(t, rendered, "Findings:")
// Verify values appear
assert.Contains(t, rendered, "LXC 106 running")
assert.Contains(t, rendered, "PBS available, 42% used")
+ assert.Contains(t, rendered, "2 active alerts")
assert.Contains(t, rendered, "exit=0, service active")
assert.Contains(t, rendered, "warning: high CPU on vm101")
}
+func TestKnowledgeAccumulator_AlertCategoryOrder(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ ka.AddFact(FactCategoryAlert, "a1", "alert data")
+ ka.AddFact(FactCategoryStorage, "s1", "storage data")
+
+ rendered := ka.Render()
+ // Alerts should appear after Storage in the render order
+ storIdx := strings.Index(rendered, "Storage:")
+ alertIdx := strings.Index(rendered, "Alerts:")
+ assert.Greater(t, alertIdx, storIdx, "Alerts should come after Storage")
+}
+
func TestKnowledgeAccumulator_RenderOrder(t *testing.T) {
ka := NewKnowledgeAccumulator()
@@ -174,6 +190,109 @@ func TestKnowledgeAccumulator_SetTurn(t *testing.T) {
assert.Equal(t, 3, fact.Turn)
}
+func TestKnowledgeAccumulator_FactSummaryForTool(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ // Add facts associated with a tool call
+ ka.AddFactForTool("tc-abc", FactCategoryStorage, "storage:delly:pbs-minipc", "PBS, available, 42.7% used, 573GB free")
+ ka.AddFactForTool("tc-abc", FactCategoryStorage, "storage:delly:local-lvm", "dir, available, 80% used, 20GB free")
+
+ // Add a fact for a different tool call
+ ka.AddFactForTool("tc-xyz", FactCategoryResource, "lxc:delly:106:status", "running, Postfix")
+
+ // FactSummaryForTool should return "key = value" pairs joined with semicolons
+ summary := ka.FactSummaryForTool("tc-abc")
+ assert.Contains(t, summary, "storage:delly:pbs-minipc = PBS")
+ assert.Contains(t, summary, "42.7% used")
+ assert.Contains(t, summary, "storage:delly:local-lvm = dir")
+ assert.Contains(t, summary, "80% used")
+ assert.Contains(t, summary, "; ") // Joined with semicolons
+
+ // tc-xyz should only have its own fact
+ summary2 := ka.FactSummaryForTool("tc-xyz")
+ assert.Contains(t, summary2, "lxc:delly:106:status = running, Postfix")
+ assert.NotContains(t, summary2, "PBS")
+
+ // Unknown tool ID returns empty
+ assert.Equal(t, "", ka.FactSummaryForTool("tc-unknown"))
+}
+
+func TestKnowledgeAccumulator_AddFactForTool_EmptyToolID(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ // Empty tool ID should still add the fact (just not track the association)
+ ka.AddFactForTool("", FactCategoryResource, "key1", "value1")
+ assert.Equal(t, 1, ka.Len())
+ assert.Equal(t, "", ka.FactSummaryForTool(""))
+}
+
+func TestKnowledgeAccumulator_MarkerFactsHiddenFromRender(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ ka.AddFact(FactCategoryStorage, "storage:pools:queried", "11 pools extracted")
+ ka.AddFact(FactCategoryStorage, "storage:delly:local-lvm", "dir, 80% used")
+
+ rendered := ka.Render()
+ assert.NotContains(t, rendered, "storage:pools:queried")
+ assert.NotContains(t, rendered, "11 pools extracted")
+ assert.Contains(t, rendered, "[storage:delly:local-lvm] dir, 80% used")
+}
+
+func TestKnowledgeAccumulator_MarkerFactsDontCountChars(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ ka.AddFact(FactCategoryStorage, "storage:pools:queried", "11 pools extracted")
+ assert.Equal(t, 0, ka.TotalChars(), "marker fact chars should not count toward budget")
+
+ ka.AddFact(FactCategoryStorage, "storage:delly:local-lvm", "dir, 80% used")
+ assert.Equal(t, len("dir, 80% used"), ka.TotalChars(), "only non-marker chars should count")
+}
+
+func TestKnowledgeAccumulator_MarkerFactsStillLookupable(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ ka.AddFact(FactCategoryStorage, "storage:pools:queried", "11 pools extracted")
+
+ val, found := ka.Lookup("storage:pools:queried")
+ assert.True(t, found, "marker facts should still be lookupable by the gate")
+ assert.Equal(t, "11 pools extracted", val)
+}
+
+func TestRelatedFacts_StoragePools(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ ka.AddFact(FactCategoryStorage, "storage:pools:queried", "3 pools extracted")
+ ka.AddFact(FactCategoryStorage, "storage:delly:local-lvm", "dir, 80% used")
+ ka.AddFact(FactCategoryStorage, "storage:delly:pbs-minipc", "PBS, 42% used")
+ ka.AddFact(FactCategoryStorage, "storage:minipc:local", "dir, 50% used")
+
+ related := ka.RelatedFacts("storage:")
+ assert.Contains(t, related, "storage:delly:local-lvm = dir, 80% used")
+ assert.Contains(t, related, "storage:delly:pbs-minipc = PBS, 42% used")
+ assert.Contains(t, related, "storage:minipc:local = dir, 50% used")
+ assert.NotContains(t, related, "pools:queried", "marker should be excluded")
+}
+
+func TestRelatedFacts_ExcludesMarkers(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ ka.AddFact(FactCategoryStorage, "disk_health:queried", "2 hosts extracted")
+ ka.AddFact(FactCategoryStorage, "disk_health:delly", "2 disks all PASSED")
+
+ related := ka.RelatedFacts("disk_health:")
+ assert.Contains(t, related, "disk_health:delly = 2 disks all PASSED")
+ assert.NotContains(t, related, "queried")
+}
+
+func TestRelatedFacts_EmptyPrefix(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ ka.AddFact(FactCategoryStorage, "storage:delly:local", "dir, 80% used")
+
+ related := ka.RelatedFacts("nonexistent:")
+ assert.Equal(t, "", related)
+}
+
func keyForIndex(i int) string {
return strings.Repeat("k", i+1)
}
diff --git a/internal/ai/chat/knowledge_extractor.go b/internal/ai/chat/knowledge_extractor.go
index e69ea22cd6..a134ed82e0 100644
--- a/internal/ai/chat/knowledge_extractor.go
+++ b/internal/ai/chat/knowledge_extractor.go
@@ -4,6 +4,8 @@ import (
"encoding/json"
"fmt"
"strings"
+
+ "github.com/rs/zerolog/log"
)
// FactEntry is the output of ExtractFacts — ready to feed into KnowledgeAccumulator.AddFact.
@@ -31,9 +33,12 @@ func ExtractFacts(toolName string, toolInput map[string]interface{}, resultText
return extractExecFacts(toolInput, resultText)
case "pulse_metrics":
return extractMetricsFacts(toolInput, resultText)
+ case "pulse_alerts":
+ return extractAlertsFacts(toolInput, resultText)
case "patrol_report_finding":
return extractFindingFacts(toolInput, resultText)
default:
+ log.Debug().Str("tool", toolName).Msg("[KnowledgeExtractor] No extractor for tool")
return nil
}
}
@@ -51,7 +56,17 @@ func extractQueryFacts(input map[string]interface{}, resultText string) []FactEn
return extractQueryGetFacts(input, resultText)
case "search":
return extractQuerySearchFacts(input, resultText)
+ case "topology":
+ return extractQueryTopologyFacts(resultText)
+ case "health":
+ return extractQueryHealthFacts(resultText)
+ case "list":
+ return extractQueryListFacts(resultText)
+ case "config":
+ return extractQueryConfigFacts(input, resultText)
default:
+ log.Debug().Str("tool", "pulse_query").Str("action", action).
+ Msg("[KnowledgeExtractor] No extractor for action")
return nil
}
}
@@ -80,9 +95,17 @@ func extractQueryGetFacts(input map[string]interface{}, resultText string) []Fac
return nil
}
- // Skip error/not-found responses
+ // Return negative fact for error/not-found responses
if resource.Error != "" {
- return nil
+ resourceID := strFromMap(input, "resource_id")
+ if resourceID == "" {
+ return nil
+ }
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: fmt.Sprintf("query:get:%s:error", resourceID),
+ Value: fmt.Sprintf("not found: %s", resource.Error),
+ }}
}
if resource.Name == "" && resource.ID == "" {
return nil
@@ -178,6 +201,308 @@ func extractQuerySearchFacts(input map[string]interface{}, resultText string) []
}}
}
+func extractQueryTopologyFacts(resultText string) []FactEntry {
+ // TopologyResponse — direct JSON. Has summary + proxmox.nodes array.
+ // Real format: nodes are under "proxmox.nodes", LXC count is "total_lxc_containers".
+ var resp struct {
+ Summary struct {
+ TotalNodes int `json:"total_nodes"`
+ TotalVMs int `json:"total_vms"`
+ RunningVMs int `json:"running_vms"`
+ TotalLXCContainers int `json:"total_lxc_containers"`
+ RunningLXC int `json:"running_lxc"`
+ TotalDockerHost int `json:"total_docker_hosts"`
+ } `json:"summary"`
+ Proxmox struct {
+ Nodes []struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ } `json:"nodes"`
+ } `json:"proxmox"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ s := resp.Summary
+
+ // Build node list
+ var nodeDescs []string
+ for _, n := range resp.Proxmox.Nodes {
+ status := n.Status
+ if status == "" {
+ status = "unknown"
+ }
+ nodeDescs = append(nodeDescs, fmt.Sprintf("%s=%s", n.Name, status))
+ }
+
+ var parts []string
+ if s.TotalNodes > 0 || len(resp.Proxmox.Nodes) > 0 {
+ nodeCount := s.TotalNodes
+ if nodeCount == 0 {
+ nodeCount = len(resp.Proxmox.Nodes)
+ }
+ nodeStr := fmt.Sprintf("%d nodes", nodeCount)
+ if len(nodeDescs) > 0 {
+ nodeStr += " (" + strings.Join(nodeDescs, ", ") + ")"
+ }
+ parts = append(parts, nodeStr)
+ }
+ if s.TotalVMs > 0 {
+ parts = append(parts, fmt.Sprintf("%d VMs (%d running)", s.TotalVMs, s.RunningVMs))
+ }
+ if s.TotalLXCContainers > 0 {
+ parts = append(parts, fmt.Sprintf("%d LXC (%d running)", s.TotalLXCContainers, s.RunningLXC))
+ }
+ if s.TotalDockerHost > 0 {
+ parts = append(parts, fmt.Sprintf("%d docker host", s.TotalDockerHost))
+ }
+
+ if len(parts) == 0 {
+ return nil
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "topology:summary",
+ Value: truncateValue(strings.Join(parts, ", ")),
+ }}
+}
+
+func extractQueryHealthFacts(resultText string) []FactEntry {
+ // ConnectionHealthResponse — direct JSON.
+ // Real format uses "instance_id" as the identifier field.
+ var resp struct {
+ Connections []struct {
+ InstanceID string `json:"instance_id"`
+ Name string `json:"name"`
+ Instance string `json:"instance"`
+ Connected bool `json:"connected"`
+ Status string `json:"status"`
+ } `json:"connections"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+ if len(resp.Connections) == 0 {
+ return nil
+ }
+
+ total := len(resp.Connections)
+ connected := 0
+ var disconnected []string
+ for _, c := range resp.Connections {
+ if c.Connected {
+ connected++
+ } else {
+ name := c.InstanceID
+ if name == "" {
+ name = c.Name
+ }
+ if name == "" {
+ name = c.Instance
+ }
+ if name != "" {
+ disconnected = append(disconnected, name)
+ }
+ }
+ }
+
+ value := fmt.Sprintf("%d/%d connected", connected, total)
+ if len(disconnected) > 0 {
+ value += ", disconnected: " + strings.Join(disconnected, ", ")
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "health:connections",
+ Value: truncateValue(value),
+ }}
+}
+
+func extractQueryListFacts(resultText string) []FactEntry {
+ var resp struct {
+ Nodes []struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ } `json:"nodes"`
+ VMs []struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ } `json:"vms"`
+ Containers []struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ } `json:"containers"`
+ DockerHosts []struct {
+ Hostname string `json:"hostname"`
+ DisplayName string `json:"display_name"`
+ ContainerCount int `json:"container_count"`
+ } `json:"docker_hosts"`
+ Total struct {
+ Nodes int `json:"nodes"`
+ VMs int `json:"vms"`
+ Containers int `json:"containers"`
+ DockerHosts int `json:"docker_hosts"`
+ } `json:"total"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ // Count running resources
+ runningVMs := 0
+ for _, vm := range resp.VMs {
+ if vm.Status == "running" {
+ runningVMs++
+ }
+ }
+ runningLXC := 0
+ for _, ct := range resp.Containers {
+ if ct.Status == "running" {
+ runningLXC++
+ }
+ }
+
+ var parts []string
+ nodeCount := resp.Total.Nodes
+ if nodeCount == 0 {
+ nodeCount = len(resp.Nodes)
+ }
+ vmCount := resp.Total.VMs
+ if vmCount == 0 {
+ vmCount = len(resp.VMs)
+ }
+ ctCount := resp.Total.Containers
+ if ctCount == 0 {
+ ctCount = len(resp.Containers)
+ }
+
+ if nodeCount > 0 {
+ parts = append(parts, fmt.Sprintf("%d nodes", nodeCount))
+ }
+ if vmCount > 0 {
+ parts = append(parts, fmt.Sprintf("%d VMs (%d running)", vmCount, runningVMs))
+ }
+ if ctCount > 0 {
+ parts = append(parts, fmt.Sprintf("%d LXC (%d running)", ctCount, runningLXC))
+ }
+ dockerCount := resp.Total.DockerHosts
+ if dockerCount == 0 {
+ dockerCount = len(resp.DockerHosts)
+ }
+ if dockerCount > 0 {
+ totalContainers := 0
+ for _, dh := range resp.DockerHosts {
+ totalContainers += dh.ContainerCount
+ }
+ parts = append(parts, fmt.Sprintf("%d docker hosts (%d containers)", dockerCount, totalContainers))
+ }
+
+ if len(parts) == 0 {
+ return nil
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: "inventory:summary",
+ Value: truncateValue(strings.Join(parts, ", ")),
+ }}
+}
+
+func extractQueryConfigFacts(input map[string]interface{}, resultText string) []FactEntry {
+ var resp struct {
+ GuestType string `json:"guest_type"`
+ VMID int `json:"vmid"`
+ Name string `json:"name"`
+ Node string `json:"node"`
+ Hostname string `json:"hostname"`
+ OSType string `json:"os_type"`
+ Onboot *bool `json:"onboot"`
+ Mounts []struct {
+ Key string `json:"key"`
+ Mountpoint string `json:"mountpoint"`
+ } `json:"mounts"`
+ Disks []struct {
+ Key string `json:"key"`
+ } `json:"disks"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ if resp.VMID == 0 && resp.Name == "" {
+ return nil
+ }
+
+ id := fmt.Sprintf("%d", resp.VMID)
+ if id == "0" {
+ id = resp.Name
+ }
+
+ var parts []string
+ if resp.GuestType != "" {
+ parts = append(parts, resp.GuestType)
+ }
+ if resp.Hostname != "" {
+ parts = append(parts, "hostname="+resp.Hostname)
+ }
+ if resp.OSType != "" {
+ parts = append(parts, "os="+resp.OSType)
+ }
+ if resp.Onboot != nil {
+ if *resp.Onboot {
+ parts = append(parts, "onboot=yes")
+ } else {
+ parts = append(parts, "onboot=no")
+ }
+ }
+ if len(resp.Mounts) > 0 {
+ parts = append(parts, fmt.Sprintf("%d mounts", len(resp.Mounts)))
+ }
+ if len(resp.Disks) > 0 {
+ parts = append(parts, fmt.Sprintf("%d disks", len(resp.Disks)))
+ }
+
+ if len(parts) == 0 {
+ return nil
+ }
+
+ return []FactEntry{{
+ Category: FactCategoryResource,
+ Key: fmt.Sprintf("config:%s:%s", resp.Node, id),
+ Value: truncateValue(strings.Join(parts, ", ")),
+ }}
+}
+
+// categoryForPredictedKey infers the FactCategory from a predicted key prefix.
+// Used when storing negative markers for text/error responses.
+func categoryForPredictedKey(key string) FactCategory {
+ switch {
+ case strings.HasPrefix(key, "storage:") || strings.HasPrefix(key, "disk_health:") ||
+ strings.HasPrefix(key, "raid:") || strings.HasPrefix(key, "backups:") ||
+ strings.HasPrefix(key, "physical_disks:"):
+ return FactCategoryStorage
+ case strings.HasPrefix(key, "metrics:") || strings.HasPrefix(key, "baseline:") ||
+ strings.HasPrefix(key, "baselines:") || strings.HasPrefix(key, "temperatures:"):
+ return FactCategoryMetrics
+ case strings.HasPrefix(key, "exec:"):
+ return FactCategoryExec
+ case strings.HasPrefix(key, "discovery:"):
+ return FactCategoryDiscovery
+ case strings.HasPrefix(key, "topology:") || strings.HasPrefix(key, "health:") ||
+ strings.HasPrefix(key, "search:") || strings.HasPrefix(key, "query:") ||
+ strings.HasPrefix(key, "inventory:") || strings.HasPrefix(key, "config:"):
+ return FactCategoryResource
+ case strings.HasPrefix(key, "finding:") || strings.HasPrefix(key, "findings:"):
+ return FactCategoryFinding
+ case strings.HasPrefix(key, "alert:") || strings.HasPrefix(key, "alerts:"):
+ return FactCategoryAlert
+ default:
+ return FactCategoryResource
+ }
+}
+
// --- pulse_storage ---
func extractStorageFacts(input map[string]interface{}, resultText string) []FactEntry {
@@ -191,7 +516,15 @@ func extractStorageFacts(input map[string]interface{}, resultText string) []Fact
return extractStoragePoolFacts(resultText)
case "backup_tasks":
return extractBackupTaskFacts(resultText)
+ case "disk_health":
+ return extractDiskHealthFacts(resultText)
+ case "raid":
+ return extractStorageRAIDFacts(resultText)
+ case "backups":
+ return extractStorageBackupsFacts(resultText)
default:
+ log.Debug().Str("tool", "pulse_storage").Str("action", action).
+ Msg("[KnowledgeExtractor] No extractor for action")
return nil
}
}
@@ -215,7 +548,14 @@ func extractStoragePoolFacts(resultText string) []FactEntry {
return nil
}
+ // Emit marker fact so PredictFactKeys can gate repeat calls
var facts []FactEntry
+ facts = append(facts, FactEntry{
+ Category: FactCategoryStorage,
+ Key: "storage:pools:queried",
+ Value: fmt.Sprintf("%d pools extracted", len(resp.Pools)),
+ })
+
for _, pool := range resp.Pools {
node := pool.Node
if node == "" && len(pool.Nodes) > 0 {
@@ -339,31 +679,48 @@ func extractDiscoveryFacts(input map[string]interface{}, resultText string) []Fa
// --- pulse_read / pulse_run_command ---
-func extractExecFacts(input map[string]interface{}, resultText string) []FactEntry {
- host := strFromMap(input, "target_host")
- if host == "" {
- host = strFromMap(input, "host")
- }
+// buildExecKeyCmd derives the command portion of the KA fact key from tool input.
+// Shared by extractExecFacts and PredictFactKeys to ensure consistent key generation.
+// Returns empty string if no distinguishing command/action can be determined.
+func buildExecKeyCmd(input map[string]interface{}) string {
cmd := strFromMap(input, "command")
if cmd == "" {
- // For pulse_read file/tail/find actions, use action+path to distinguish
- // different file reads on the same host.
action := strFromMap(input, "action")
path := strFromMap(input, "path")
if action != "" && path != "" {
cmd = action + ":" + path
+ } else if action == "logs" {
+ // For log queries, include distinguishing params to avoid key collisions.
+ // Different since/grep/source/unit combos must produce different keys.
+ var parts []string
+ parts = append(parts, "logs")
+ for _, param := range []string{"since", "grep", "source", "unit"} {
+ if v := strFromMap(input, param); v != "" {
+ parts = append(parts, param+"="+v)
+ }
+ }
+ cmd = strings.Join(parts, ":")
} else if action != "" {
cmd = action
}
}
if cmd == "" {
- return nil
+ return ""
+ }
+ if len(cmd) > 60 {
+ cmd = cmd[:60]
}
+ return cmd
+}
- // Use first 60 chars of command as key prefix (longer to accommodate path)
- cmdPrefix := cmd
- if len(cmdPrefix) > 60 {
- cmdPrefix = cmdPrefix[:60]
+func extractExecFacts(input map[string]interface{}, resultText string) []FactEntry {
+ host := strFromMap(input, "target_host")
+ if host == "" {
+ host = strFromMap(input, "host")
+ }
+ cmdPrefix := buildExecKeyCmd(input)
+ if cmdPrefix == "" {
+ return nil
}
// Try to parse as CommandResponse (direct JSON, no wrapper)
@@ -410,17 +767,28 @@ func extractMetricsFacts(input map[string]interface{}, resultText string) []Fact
action = strFromMap(input, "type")
}
- if action != "performance" {
+ switch action {
+ case "performance":
+ return extractMetricsPerformanceFacts(input, resultText)
+ case "baselines":
+ return extractMetricsBaselinesFacts(resultText)
+ case "disks":
+ return extractMetricsDisksFacts(resultText)
+ case "temperatures":
+ return extractMetricsTemperaturesFacts(resultText)
+ default:
+ log.Debug().Str("tool", "pulse_metrics").Str("action", action).
+ Msg("[KnowledgeExtractor] No extractor for action")
return nil
}
+}
+func extractMetricsPerformanceFacts(input map[string]interface{}, resultText string) []FactEntry {
resourceID := strFromMap(input, "resource_id")
if resourceID == "" {
return nil
}
- // MetricsResponse — direct JSON, no wrapper.
- // Summary is map[string]ResourceMetricsSummary keyed by resource ID.
var resp struct {
Summary map[string]struct {
AvgCPU float64 `json:"avg_cpu"`
@@ -434,7 +802,6 @@ func extractMetricsFacts(input map[string]interface{}, resultText string) []Fact
return nil
}
- // Look up the summary for this resource (or take the first entry)
var avgCPU, maxCPU float64
var trend string
if s, ok := resp.Summary[resourceID]; ok {
@@ -442,7 +809,6 @@ func extractMetricsFacts(input map[string]interface{}, resultText string) []Fact
maxCPU = s.MaxCPU
trend = s.Trend
} else {
- // Take first entry if resource ID doesn't match exactly
for _, s := range resp.Summary {
avgCPU = s.AvgCPU
maxCPU = s.MaxCPU
@@ -473,6 +839,397 @@ func extractMetricsFacts(input map[string]interface{}, resultText string) []Fact
}}
}
+func extractMetricsBaselinesFacts(resultText string) []FactEntry {
+ // BaselinesResponse — real format is nested: baselines.{nodeName}.{resourceKey:metricType}
+ // where each metric entry has mean/std_dev/min/max.
+ // Example: baselines.delly."delly:101:cpu" = {mean: 0.9, std_dev: 0.5, min: -0.2, max: 2.1}
+ // Node-level metrics use just "cpu"/"memory" as keys.
+ var resp struct {
+ Baselines map[string]map[string]struct {
+ Mean float64 `json:"mean"`
+ StdDev float64 `json:"std_dev"`
+ Min float64 `json:"min"`
+ Max float64 `json:"max"`
+ } `json:"baselines"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ // Emit marker fact so PredictFactKeys can gate repeat calls (even for empty results)
+ markerFact := FactEntry{
+ Category: FactCategoryMetrics,
+ Key: "baselines:queried",
+ Value: fmt.Sprintf("%d nodes extracted", len(resp.Baselines)),
+ }
+
+ if len(resp.Baselines) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ // Aggregate per-node: collect cpu and memory stats for each node
+ facts := []FactEntry{markerFact}
+ count := 0
+ for nodeName, metrics := range resp.Baselines {
+ if count >= 10 {
+ break
+ }
+
+ // Separate node-level metrics from resource-level metrics
+ var cpuMeans, memMeans []float64
+ var cpuMax, memMax float64
+ for metricKey, stat := range metrics {
+ // Keys are like "delly:101:cpu", "delly:101:memory", or bare "cpu", "memory"
+ if strings.HasSuffix(metricKey, ":cpu") || metricKey == "cpu" {
+ cpuMeans = append(cpuMeans, stat.Mean)
+ if stat.Max > cpuMax {
+ cpuMax = stat.Max
+ }
+ }
+ if strings.HasSuffix(metricKey, ":memory") || metricKey == "memory" {
+ memMeans = append(memMeans, stat.Mean)
+ if stat.Max > memMax {
+ memMax = stat.Max
+ }
+ }
+ }
+
+ var parts []string
+ if len(cpuMeans) > 0 {
+ avgCPU := average(cpuMeans)
+ parts = append(parts, fmt.Sprintf("cpu: avg=%.1f%% max=%.1f%%", avgCPU, cpuMax))
+ }
+ if len(memMeans) > 0 {
+ avgMem := average(memMeans)
+ parts = append(parts, fmt.Sprintf("memory: avg=%.1f%% max=%.1f%%", avgMem, memMax))
+ }
+ if len(parts) == 0 {
+ parts = append(parts, fmt.Sprintf("%d metrics tracked", len(metrics)))
+ }
+
+ facts = append(facts, FactEntry{
+ Category: FactCategoryMetrics,
+ Key: fmt.Sprintf("baseline:%s", nodeName),
+ Value: truncateValue(strings.Join(parts, ", ")),
+ })
+ count++
+ }
+ return facts
+}
+
+func average(vals []float64) float64 {
+ if len(vals) == 0 {
+ return 0
+ }
+ sum := 0.0
+ for _, v := range vals {
+ sum += v
+ }
+ return sum / float64(len(vals))
+}
+
+func extractMetricsDisksFacts(resultText string) []FactEntry {
+ // PhysicalDisksResponse
+ var resp struct {
+ Disks []struct {
+ Host string `json:"host"`
+ Device string `json:"device"`
+ Model string `json:"model"`
+ Health string `json:"health"`
+ Status string `json:"status"`
+ } `json:"disks"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ // Emit marker fact so PredictFactKeys can gate repeat calls (even for empty results)
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "physical_disks:queried",
+ Value: "summary extracted",
+ }
+
+ if len(resp.Disks) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ total := len(resp.Disks)
+ failed := 0
+ var failedDescs []string
+ for _, d := range resp.Disks {
+ health := strings.ToUpper(d.Health)
+ if health == "" {
+ health = strings.ToUpper(d.Status)
+ }
+ if health != "PASSED" && health != "OK" && health != "" {
+ failed++
+ desc := d.Host + " " + d.Device
+ if d.Model != "" {
+ desc += " " + d.Model
+ }
+ failedDescs = append(failedDescs, desc)
+ }
+ }
+
+ var value string
+ if failed == 0 {
+ value = fmt.Sprintf("%d disks total, all PASSED", total)
+ } else {
+ value = fmt.Sprintf("%d disks, %d FAILED: %s", total, failed, strings.Join(failedDescs, "; "))
+ }
+
+ return []FactEntry{markerFact, {
+ Category: FactCategoryStorage,
+ Key: "physical_disks:summary",
+ Value: truncateValue(value),
+ }}
+}
+
+// --- pulse_storage: disk_health ---
+
+func extractDiskHealthFacts(resultText string) []FactEntry {
+ // DiskHealthResponse — per-host SMART data.
+ // Real format uses "smart" array, not "disks". Try both for robustness.
+ var resp struct {
+ Hosts []struct {
+ Hostname string `json:"hostname"`
+ Host string `json:"host"`
+ Smart []struct {
+ Device string `json:"device"`
+ Model string `json:"model"`
+ Health string `json:"health"`
+ Status string `json:"status"`
+ } `json:"smart"`
+ Disks []struct {
+ Device string `json:"device"`
+ Model string `json:"model"`
+ Health string `json:"health"`
+ Status string `json:"status"`
+ } `json:"disks"`
+ } `json:"hosts"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ // Emit marker fact so PredictFactKeys can gate repeat calls (even for empty results)
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "disk_health:queried",
+ Value: fmt.Sprintf("%d hosts extracted", len(resp.Hosts)),
+ }
+
+ if len(resp.Hosts) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+
+ for _, host := range resp.Hosts {
+ hostname := host.Hostname
+ if hostname == "" {
+ hostname = host.Host
+ }
+ if hostname == "" {
+ continue
+ }
+
+ // Prefer "smart" field (real format), fall back to "disks" (test compat)
+ disks := host.Smart
+ if len(disks) == 0 {
+ disks = host.Disks
+ }
+ total := len(disks)
+ passed := 0
+ failed := 0
+ var failedDescs []string
+ for _, d := range disks {
+ health := strings.ToUpper(d.Health)
+ if health == "" {
+ health = strings.ToUpper(d.Status)
+ }
+ if health == "PASSED" || health == "OK" {
+ passed++
+ } else if health != "" {
+ failed++
+ desc := d.Device
+ if d.Model != "" {
+ desc += " " + d.Model
+ }
+ failedDescs = append(failedDescs, desc)
+ } else {
+ passed++ // Unknown treated as passed
+ }
+ }
+
+ var value string
+ if failed == 0 {
+ value = fmt.Sprintf("%d disks all PASSED", total)
+ } else {
+ value = fmt.Sprintf("%d SMART disks: %d PASSED, %d FAILED (%s)", total, passed, failed, strings.Join(failedDescs, ", "))
+ }
+
+ facts = append(facts, FactEntry{
+ Category: FactCategoryStorage,
+ Key: fmt.Sprintf("disk_health:%s", hostname),
+ Value: truncateValue(value),
+ })
+ }
+ return facts
+}
+
+// --- pulse_alerts ---
+
+func extractAlertsFacts(input map[string]interface{}, resultText string) []FactEntry {
+ action := strFromMap(input, "action")
+ if action == "" {
+ action = strFromMap(input, "type")
+ }
+
+ switch action {
+ case "findings":
+ return extractAlertsFindingsFacts(resultText)
+ case "list":
+ return extractAlertsListFacts(resultText)
+ default:
+ log.Debug().Str("tool", "pulse_alerts").Str("action", action).
+ Msg("[KnowledgeExtractor] No extractor for action")
+ return nil
+ }
+}
+
+func extractAlertsFindingsFacts(resultText string) []FactEntry {
+ var resp struct {
+ Findings []struct {
+ Key string `json:"key"`
+ Severity string `json:"severity"`
+ Title string `json:"title"`
+ Status string `json:"status"`
+ ResourceID string `json:"resource_id"`
+ } `json:"findings"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ if len(resp.Findings) == 0 {
+ return nil
+ }
+
+ // Count by status
+ active := 0
+ dismissed := 0
+ for _, f := range resp.Findings {
+ switch strings.ToLower(f.Status) {
+ case "dismissed", "resolved":
+ dismissed++
+ default:
+ active++
+ }
+ }
+
+ var facts []FactEntry
+ facts = append(facts, FactEntry{
+ Category: FactCategoryFinding,
+ Key: "findings:overview",
+ Value: fmt.Sprintf("%d active, %d dismissed", active, dismissed),
+ })
+
+ // Per-finding facts (cap at 5)
+ limit := 5
+ if len(resp.Findings) < limit {
+ limit = len(resp.Findings)
+ }
+ for _, f := range resp.Findings[:limit] {
+ if f.Key == "" {
+ continue
+ }
+ var parts []string
+ if f.Severity != "" {
+ parts = append(parts, f.Severity)
+ }
+ if f.Title != "" {
+ parts = append(parts, f.Title)
+ }
+ if f.ResourceID != "" {
+ parts = append(parts, "(resource="+f.ResourceID+")")
+ }
+ if len(parts) > 0 {
+ facts = append(facts, FactEntry{
+ Category: FactCategoryFinding,
+ Key: fmt.Sprintf("finding:%s", f.Key),
+ Value: truncateValue(strings.Join(parts, ": ")),
+ })
+ }
+ }
+
+ return facts
+}
+
+func extractAlertsListFacts(resultText string) []FactEntry {
+ var resp struct {
+ Alerts []struct {
+ ResourceName string `json:"resource_name"`
+ Type string `json:"type"`
+ Severity string `json:"severity"`
+ Value float64 `json:"value"`
+ Threshold float64 `json:"threshold"`
+ Status string `json:"status"`
+ } `json:"alerts"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ if len(resp.Alerts) == 0 {
+ return nil
+ }
+
+ // Count active
+ active := 0
+ for _, a := range resp.Alerts {
+ if strings.ToLower(a.Status) != "resolved" {
+ active++
+ }
+ }
+
+ var facts []FactEntry
+ facts = append(facts, FactEntry{
+ Category: FactCategoryAlert,
+ Key: "alerts:overview",
+ Value: fmt.Sprintf("%d active alerts", active),
+ })
+
+ // Per-alert facts (cap at 5)
+ limit := 5
+ if len(resp.Alerts) < limit {
+ limit = len(resp.Alerts)
+ }
+ for _, a := range resp.Alerts[:limit] {
+ if a.ResourceName == "" && a.Type == "" {
+ continue
+ }
+ var parts []string
+ if a.Severity != "" {
+ parts = append(parts, a.Severity)
+ }
+ if a.Value > 0 && a.Threshold > 0 {
+ parts = append(parts, fmt.Sprintf("%.1f%% (threshold %.0f%%)", a.Value, a.Threshold))
+ }
+ key := fmt.Sprintf("alert:%s:%s", a.ResourceName, a.Type)
+ if len(parts) > 0 {
+ facts = append(facts, FactEntry{
+ Category: FactCategoryAlert,
+ Key: key,
+ Value: truncateValue(strings.Join(parts, ": ")),
+ })
+ }
+ }
+
+ return facts
+}
+
// --- patrol_report_finding ---
func extractFindingFacts(input map[string]interface{}, resultText string) []FactEntry {
@@ -510,6 +1267,37 @@ func extractFindingFacts(input map[string]interface{}, resultText string) []Fact
// Returns nil if the key can't be predicted from input alone.
func PredictFactKeys(toolName string, toolInput map[string]interface{}) []string {
switch toolName {
+ case "pulse_query":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "topology":
+ return []string{"topology:summary"}
+ case "health":
+ return []string{"health:connections"}
+ case "get":
+ // Can't predict: success key depends on response (type:node:id:status)
+ // Negative facts (not-found) are stored by the extractor directly.
+ return nil
+ case "search":
+ query := strFromMap(toolInput, "query")
+ if query == "" {
+ query = strFromMap(toolInput, "search")
+ }
+ if query != "" {
+ return []string{fmt.Sprintf("search:%s:summary", query)}
+ }
+ case "list":
+ return []string{"inventory:summary"}
+ case "config":
+ resourceID := strFromMap(toolInput, "resource_id")
+ node := strFromMap(toolInput, "node")
+ if resourceID != "" && node != "" {
+ return []string{fmt.Sprintf("config:%s:%s", node, resourceID)}
+ }
+ }
case "pulse_discovery":
host := strFromMap(toolInput, "host_id")
if host == "" {
@@ -524,39 +1312,241 @@ func PredictFactKeys(toolName string, toolInput map[string]interface{}) []string
if host == "" {
host = strFromMap(toolInput, "host")
}
- cmd := strFromMap(toolInput, "command")
- if cmd == "" {
- // For file/tail/find actions, include path to distinguish different file reads
- action := strFromMap(toolInput, "action")
- path := strFromMap(toolInput, "path")
- if action != "" && path != "" {
- cmd = action + ":" + path
- } else if action != "" {
- cmd = action
- }
- }
- if host != "" && cmd != "" {
- cmdPrefix := cmd
- if len(cmdPrefix) > 60 {
- cmdPrefix = cmdPrefix[:60]
- }
+ cmdPrefix := buildExecKeyCmd(toolInput)
+ if host != "" && cmdPrefix != "" {
return []string{fmt.Sprintf("exec:%s:%s", host, cmdPrefix)}
}
+ case "pulse_storage":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "pools":
+ return []string{"storage:pools:queried"}
+ case "disk_health":
+ return []string{"disk_health:queried"}
+ case "raid":
+ return []string{"raid:queried"}
+ case "backups":
+ return []string{"backups:queried"}
+ }
case "pulse_metrics":
action := strFromMap(toolInput, "action")
if action == "" {
action = strFromMap(toolInput, "type")
}
- resourceID := strFromMap(toolInput, "resource_id")
- if action == "performance" && resourceID != "" {
- return []string{fmt.Sprintf("metrics:%s", resourceID)}
+ switch action {
+ case "performance":
+ resourceID := strFromMap(toolInput, "resource_id")
+ if resourceID != "" {
+ return []string{fmt.Sprintf("metrics:%s", resourceID)}
+ }
+ case "baselines":
+ resourceID := strFromMap(toolInput, "resource_id")
+ if resourceID != "" {
+ return []string{fmt.Sprintf("baseline:%s", resourceID)}
+ }
+ return []string{"baselines:queried"}
+ case "disks":
+ return []string{"physical_disks:queried"}
+ case "temperatures":
+ return []string{"temperatures:queried"}
+ }
+ case "pulse_alerts":
+ action := strFromMap(toolInput, "action")
+ if action == "" {
+ action = strFromMap(toolInput, "type")
+ }
+ switch action {
+ case "findings":
+ return []string{"findings:overview"}
+ case "list":
+ return []string{"alerts:overview"}
}
}
- // pulse_query get/search and pulse_storage: keys depend on result data,
- // can't predict from input alone. Return nil — these calls won't be gated.
return nil
}
+// --- pulse_metrics: temperatures ---
+
+func extractMetricsTemperaturesFacts(resultText string) []FactEntry {
+ var hosts []struct {
+ Hostname string `json:"hostname"`
+ CPUTemps map[string]float64 `json:"cpu_temps"`
+ DiskTemps map[string]float64 `json:"disk_temps"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &hosts); err != nil {
+ return nil
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryMetrics,
+ Key: "temperatures:queried",
+ Value: fmt.Sprintf("%d hosts", len(hosts)),
+ }
+ if len(hosts) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ for _, h := range hosts {
+ if h.Hostname == "" {
+ continue
+ }
+ var maxCPU float64
+ for _, t := range h.CPUTemps {
+ if t > maxCPU {
+ maxCPU = t
+ }
+ }
+ var maxDisk float64
+ for _, t := range h.DiskTemps {
+ if t > maxDisk {
+ maxDisk = t
+ }
+ }
+ var parts []string
+ if maxCPU > 0 {
+ parts = append(parts, fmt.Sprintf("cpu_max=%.0f°C", maxCPU))
+ }
+ if maxDisk > 0 {
+ parts = append(parts, fmt.Sprintf("disk_max=%.0f°C", maxDisk))
+ }
+ if len(parts) == 0 {
+ continue
+ }
+ facts = append(facts, FactEntry{
+ Category: FactCategoryMetrics,
+ Key: fmt.Sprintf("temperatures:%s", h.Hostname),
+ Value: truncateValue(strings.Join(parts, ", ")),
+ })
+ }
+ return facts
+}
+
+// --- pulse_storage: raid ---
+
+func extractStorageRAIDFacts(resultText string) []FactEntry {
+ var resp struct {
+ Hosts []struct {
+ Hostname string `json:"hostname"`
+ Arrays []struct {
+ Device string `json:"device"`
+ Level string `json:"level"`
+ State string `json:"state"`
+ FailedDevices int `json:"failed_devices"`
+ TotalDevices int `json:"total_devices"`
+ } `json:"arrays"`
+ } `json:"hosts"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "raid:queried",
+ Value: fmt.Sprintf("%d hosts", len(resp.Hosts)),
+ }
+ if len(resp.Hosts) == 0 {
+ return []FactEntry{markerFact}
+ }
+
+ facts := []FactEntry{markerFact}
+ for _, h := range resp.Hosts {
+ if h.Hostname == "" {
+ continue
+ }
+ totalArrays := len(h.Arrays)
+ degraded := 0
+ for _, a := range h.Arrays {
+ if (a.State != "clean" && a.State != "active") || a.FailedDevices > 0 {
+ degraded++
+ }
+ }
+ var value string
+ if degraded == 0 {
+ value = fmt.Sprintf("%d arrays, all clean", totalArrays)
+ } else {
+ value = fmt.Sprintf("%d arrays, %d degraded/failed", totalArrays, degraded)
+ }
+ facts = append(facts, FactEntry{
+ Category: FactCategoryStorage,
+ Key: fmt.Sprintf("raid:%s", h.Hostname),
+ Value: truncateValue(value),
+ })
+ }
+ return facts
+}
+
+// --- pulse_storage: backups ---
+
+func extractStorageBackupsFacts(resultText string) []FactEntry {
+ var resp struct {
+ PBS []json.RawMessage `json:"pbs"`
+ PVE []json.RawMessage `json:"pve"`
+ PBSServers []struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Datastores []struct {
+ Name string `json:"name"`
+ UsagePercent float64 `json:"usage_percent"`
+ } `json:"datastores"`
+ } `json:"pbs_servers"`
+ }
+ if err := json.Unmarshal([]byte(resultText), &resp); err != nil {
+ return nil
+ }
+
+ totalBackups := len(resp.PBS) + len(resp.PVE)
+ markerFact := FactEntry{
+ Category: FactCategoryStorage,
+ Key: "backups:queried",
+ Value: fmt.Sprintf("%d PBS + %d PVE backups, %d PBS servers", len(resp.PBS), len(resp.PVE), len(resp.PBSServers)),
+ }
+
+ facts := []FactEntry{markerFact}
+
+ for _, srv := range resp.PBSServers {
+ if srv.Name == "" {
+ continue
+ }
+ var parts []string
+ parts = append(parts, srv.Status)
+ for _, ds := range srv.Datastores {
+ parts = append(parts, fmt.Sprintf("%s: %.1f%% used", ds.Name, ds.UsagePercent))
+ }
+ facts = append(facts, FactEntry{
+ Category: FactCategoryStorage,
+ Key: fmt.Sprintf("backups:server:%s", srv.Name),
+ Value: truncateValue(strings.Join(parts, ", ")),
+ })
+ }
+
+ if totalBackups > 0 {
+ facts = append(facts, FactEntry{
+ Category: FactCategoryStorage,
+ Key: "backups:summary",
+ Value: fmt.Sprintf("%d PBS backups, %d PVE backups", len(resp.PBS), len(resp.PVE)),
+ })
+ }
+
+ return facts
+}
+
+// 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:",
+}
+
// --- helpers ---
func strFromMap(m map[string]interface{}, key string) string {
diff --git a/internal/ai/chat/knowledge_extractor_test.go b/internal/ai/chat/knowledge_extractor_test.go
index ff24619704..bf849ad0b1 100644
--- a/internal/ai/chat/knowledge_extractor_test.go
+++ b/internal/ai/chat/knowledge_extractor_test.go
@@ -1,6 +1,8 @@
package chat
import (
+ "encoding/json"
+ "fmt"
"testing"
"github.com/stretchr/testify/assert"
@@ -36,6 +38,18 @@ func TestExtractFacts_QueryGet(t *testing.T) {
}
func TestExtractFacts_QueryGet_NotFound(t *testing.T) {
+ input := map[string]interface{}{"action": "get", "resource_type": "vm", "resource_id": "999"}
+ result := `{"error":"not_found","resource_id":"999","type":"vm"}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+ assert.Equal(t, "query:get:999:error", facts[0].Key)
+ assert.Equal(t, "not found: not_found", facts[0].Value)
+ assert.Equal(t, FactCategoryResource, facts[0].Category)
+}
+
+func TestExtractFacts_QueryGet_NotFound_NoResourceID(t *testing.T) {
+ // Without resource_id in input, negative fact should not be created
input := map[string]interface{}{"action": "get", "resource_type": "vm"}
result := `{"error":"not_found","resource_id":"999","type":"vm"}`
@@ -43,6 +57,24 @@ func TestExtractFacts_QueryGet_NotFound(t *testing.T) {
assert.Empty(t, facts)
}
+func TestNegativeFactCaching_PreventsRetry(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ // Simulate extracting a negative fact from a not-found response
+ input := map[string]interface{}{"action": "get", "resource_id": "999"}
+ result := `{"error":"not_found","resource_id":"999","type":"vm"}`
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+
+ // Store the negative fact
+ ka.AddFact(facts[0].Category, facts[0].Key, facts[0].Value)
+
+ // Verify the negative fact is stored and can be looked up
+ val, found := ka.Lookup("query:get:999:error")
+ assert.True(t, found)
+ assert.Contains(t, val, "not found")
+}
+
func TestExtractFacts_QueryGet_NoCPU(t *testing.T) {
// Some resources may not have CPU data populated
input := map[string]interface{}{"action": "get", "resource_type": "container"}
@@ -83,9 +115,13 @@ func TestExtractFacts_StoragePools(t *testing.T) {
result := `{"pools":[{"name":"pbs-minipc","node":"","nodes":["delly","minipc"],"type":"PBS","status":"available","active":true,"usage_percent":42.7,"total_gb":1000,"used_gb":427}]}`
facts := ExtractFacts("pulse_storage", input, result)
- require.Len(t, facts, 1)
+ require.Len(t, facts, 2) // marker + 1 pool
- f := facts[0]
+ // First fact is the marker
+ assert.Equal(t, "storage:pools:queried", facts[0].Key)
+ assert.Equal(t, "1 pools extracted", facts[0].Value)
+
+ f := facts[1]
assert.Equal(t, FactCategoryStorage, f.Category)
assert.Contains(t, f.Key, "storage:")
assert.Contains(t, f.Key, "pbs-minipc")
@@ -236,9 +272,9 @@ func TestPredictFactKeys_Metrics(t *testing.T) {
}
func TestPredictFactKeys_UnpredictableTools(t *testing.T) {
- // pulse_query and pulse_storage keys depend on result data
+ // pulse_query get/search keys depend on result data
assert.Nil(t, PredictFactKeys("pulse_query", map[string]interface{}{"action": "get"}))
- assert.Nil(t, PredictFactKeys("pulse_storage", map[string]interface{}{"action": "pools"}))
+ assert.Nil(t, PredictFactKeys("pulse_query", map[string]interface{}{"action": "search"}))
assert.Nil(t, PredictFactKeys("unknown_tool", nil))
}
@@ -268,6 +304,454 @@ func TestPredictFactKeys_FileReadDistinctPaths(t *testing.T) {
assert.Contains(t, keys2[0], "tasks/some-task-log")
}
+func TestExtractFacts_Exec_LogsDistinctKeys(t *testing.T) {
+ // Two different log queries on the same host should produce different keys
+ input1 := map[string]interface{}{
+ "action": "logs",
+ "target_host": "delly",
+ "since": "1h",
+ "grep": "error",
+ }
+ input2 := map[string]interface{}{
+ "action": "logs",
+ "target_host": "delly",
+ "since": "24h",
+ "unit": "nginx",
+ }
+ result := `{"success":true,"exit_code":0,"output":"some log lines here"}`
+
+ facts1 := ExtractFacts("pulse_read", input1, result)
+ facts2 := ExtractFacts("pulse_read", input2, result)
+
+ require.Len(t, facts1, 1)
+ require.Len(t, facts2, 1)
+ assert.NotEqual(t, facts1[0].Key, facts2[0].Key, "different log queries must produce different keys")
+ assert.Contains(t, facts1[0].Key, "logs")
+ assert.Contains(t, facts1[0].Key, "since=1h")
+ assert.Contains(t, facts1[0].Key, "grep=error")
+ assert.Contains(t, facts2[0].Key, "since=24h")
+ assert.Contains(t, facts2[0].Key, "unit=nginx")
+}
+
+func TestPredictFactKeys_LogsDistinct(t *testing.T) {
+ keys1 := PredictFactKeys("pulse_read", map[string]interface{}{
+ "target_host": "delly",
+ "action": "logs",
+ "since": "1h",
+ "grep": "error",
+ })
+ keys2 := PredictFactKeys("pulse_read", map[string]interface{}{
+ "target_host": "delly",
+ "action": "logs",
+ "since": "24h",
+ "unit": "nginx",
+ })
+
+ require.Len(t, keys1, 1)
+ require.Len(t, keys2, 1)
+ assert.NotEqual(t, keys1[0], keys2[0], "different log queries must produce different predicted keys")
+}
+
+// --- Topology ---
+
+func TestExtractFacts_QueryTopology(t *testing.T) {
+ input := map[string]interface{}{"action": "topology"}
+ result := `{"summary":{"total_nodes":3,"total_vms":3,"running_vms":1,"total_lxc_containers":22,"running_lxc":22,"total_docker_hosts":1},"proxmox":{"nodes":[{"name":"delly","status":"online"},{"name":"minipc","status":"online"},{"name":"pi","status":"online"}]}}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+
+ f := facts[0]
+ assert.Equal(t, FactCategoryResource, f.Category)
+ assert.Equal(t, "topology:summary", f.Key)
+ assert.Contains(t, f.Value, "3 nodes")
+ assert.Contains(t, f.Value, "delly=online")
+ assert.Contains(t, f.Value, "minipc=online")
+ assert.Contains(t, f.Value, "pi=online")
+ assert.Contains(t, f.Value, "3 VMs (1 running)")
+ assert.Contains(t, f.Value, "22 LXC (22 running)")
+ assert.Contains(t, f.Value, "1 docker host")
+}
+
+// --- Health ---
+
+func TestExtractFacts_QueryHealth(t *testing.T) {
+ input := map[string]interface{}{"action": "health"}
+ result := `{"connections":[{"instance_id":"delly","connected":true},{"instance_id":"minipc","connected":true},{"instance_id":"pi","connected":true}]}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+
+ f := facts[0]
+ assert.Equal(t, FactCategoryResource, f.Category)
+ assert.Equal(t, "health:connections", f.Key)
+ assert.Equal(t, "3/3 connected", f.Value)
+}
+
+func TestExtractFacts_QueryHealth_Disconnected(t *testing.T) {
+ input := map[string]interface{}{"action": "health"}
+ result := `{"connections":[{"instance_id":"delly","connected":true},{"instance_id":"minipc","connected":false},{"instance_id":"pi","connected":true}]}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+
+ f := facts[0]
+ assert.Contains(t, f.Value, "2/3 connected")
+ assert.Contains(t, f.Value, "disconnected: minipc")
+}
+
+// --- Alerts: Findings ---
+
+func TestExtractFacts_AlertsFindings(t *testing.T) {
+ input := map[string]interface{}{"action": "findings"}
+ result := `{"findings":[{"key":"high-cpu-vm101","severity":"warning","title":"High CPU on vm101","status":"active","resource_id":"vm101"},{"key":"disk-full-ct200","severity":"critical","title":"Disk full on ct200","status":"active","resource_id":"ct200"},{"key":"old-issue","severity":"info","title":"Old issue","status":"dismissed","resource_id":"ct300"}]}`
+
+ facts := ExtractFacts("pulse_alerts", input, result)
+ require.GreaterOrEqual(t, len(facts), 2) // overview + per-finding
+
+ // First fact should be overview
+ assert.Equal(t, "findings:overview", facts[0].Key)
+ assert.Equal(t, FactCategoryFinding, facts[0].Category)
+ assert.Contains(t, facts[0].Value, "2 active")
+ assert.Contains(t, facts[0].Value, "1 dismissed")
+
+ // Per-finding facts
+ var findingKeys []string
+ for _, f := range facts[1:] {
+ findingKeys = append(findingKeys, f.Key)
+ }
+ assert.Contains(t, findingKeys, "finding:high-cpu-vm101")
+ assert.Contains(t, findingKeys, "finding:disk-full-ct200")
+}
+
+// --- Alerts: List ---
+
+func TestExtractFacts_AlertsList(t *testing.T) {
+ input := map[string]interface{}{"action": "list"}
+ result := `{"alerts":[{"resource_name":"vm101","type":"cpu","severity":"critical","value":95.2,"threshold":80,"status":"active"},{"resource_name":"ct200","type":"memory","severity":"warning","value":82.0,"threshold":90,"status":"active"}]}`
+
+ facts := ExtractFacts("pulse_alerts", input, result)
+ require.GreaterOrEqual(t, len(facts), 2)
+
+ assert.Equal(t, "alerts:overview", facts[0].Key)
+ assert.Equal(t, FactCategoryAlert, facts[0].Category)
+ assert.Contains(t, facts[0].Value, "2 active alerts")
+
+ // Per-alert facts
+ var alertKeys []string
+ for _, f := range facts[1:] {
+ alertKeys = append(alertKeys, f.Key)
+ assert.Equal(t, FactCategoryAlert, f.Category)
+ }
+ assert.Contains(t, alertKeys, "alert:vm101:cpu")
+ assert.Contains(t, alertKeys, "alert:ct200:memory")
+}
+
+// --- Metrics: Baselines ---
+
+func TestExtractFacts_MetricsBaselines(t *testing.T) {
+ input := map[string]interface{}{"action": "baselines"}
+ // Real format: baselines.{nodeName}.{resourceKey:metricType} with mean/std_dev/min/max
+ result := `{"baselines":{"delly":{"delly:101:cpu":{"mean":12.3,"std_dev":5.0,"min":0.1,"max":78.5},"delly:101:memory":{"mean":65.0,"std_dev":10.0,"min":20.0,"max":89.0}},"minipc":{"minipc:200:cpu":{"mean":5.0,"std_dev":2.0,"min":0.5,"max":20.0},"minipc:200:memory":{"mean":40.0,"std_dev":8.0,"min":10.0,"max":55.0}}}}`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ require.Len(t, facts, 3) // marker + 2 nodes
+
+ // First fact is the marker
+ assert.Equal(t, "baselines:queried", facts[0].Key)
+ assert.Equal(t, "2 nodes extracted", facts[0].Value)
+
+ // Find delly fact
+ var dellyFact *FactEntry
+ for i := range facts[1:] {
+ idx := i + 1
+ if facts[idx].Key == "baseline:delly" {
+ dellyFact = &facts[idx]
+ break
+ }
+ }
+ require.NotNil(t, dellyFact)
+ assert.Equal(t, FactCategoryMetrics, dellyFact.Category)
+ assert.Contains(t, dellyFact.Value, "cpu: avg=12.3% max=78.5%")
+ assert.Contains(t, dellyFact.Value, "memory: avg=65.0% max=89.0%")
+}
+
+func TestExtractFacts_MetricsBaselines_Cap(t *testing.T) {
+ // Build a response with 15 nodes — should cap at 10
+ baselines := make(map[string]interface{})
+ for i := 0; i < 15; i++ {
+ nodeName := fmt.Sprintf("node%d", i)
+ baselines[nodeName] = map[string]interface{}{
+ nodeName + ":100:cpu": map[string]interface{}{"mean": 10.0, "std_dev": 2.0, "min": 1.0, "max": 50.0},
+ nodeName + ":100:memory": map[string]interface{}{"mean": 30.0, "std_dev": 5.0, "min": 5.0, "max": 60.0},
+ }
+ }
+ resultBytes, _ := json.Marshal(map[string]interface{}{"baselines": baselines})
+
+ input := map[string]interface{}{"action": "baselines"}
+ facts := ExtractFacts("pulse_metrics", input, string(resultBytes))
+ assert.LessOrEqual(t, len(facts), 11, "should cap at 10 resources + 1 marker")
+ assert.GreaterOrEqual(t, len(facts), 2, "should produce marker + at least some facts")
+ assert.Equal(t, "baselines:queried", facts[0].Key)
+}
+
+// --- Storage: Disk Health ---
+
+func TestExtractFacts_StorageDiskHealth(t *testing.T) {
+ input := map[string]interface{}{"action": "disk_health"}
+ result := `{"hosts":[{"hostname":"delly","smart":[{"device":"/dev/sda","model":"WD Blue","health":"PASSED"},{"device":"/dev/sdb","model":"Samsung","health":"FAILED"}]},{"hostname":"minipc","smart":[{"device":"/dev/sda","model":"Crucial","health":"PASSED"}]}]}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 3) // marker + 2 hosts
+
+ // First fact is the marker
+ assert.Equal(t, "disk_health:queried", facts[0].Key)
+ assert.Equal(t, "2 hosts extracted", facts[0].Value)
+
+ // Find delly fact
+ var dellyFact *FactEntry
+ var minipcFact *FactEntry
+ for i := range facts[1:] {
+ idx := i + 1
+ switch facts[idx].Key {
+ case "disk_health:delly":
+ dellyFact = &facts[idx]
+ case "disk_health:minipc":
+ minipcFact = &facts[idx]
+ }
+ }
+
+ require.NotNil(t, dellyFact)
+ assert.Equal(t, FactCategoryStorage, dellyFact.Category)
+ assert.Contains(t, dellyFact.Value, "1 PASSED")
+ assert.Contains(t, dellyFact.Value, "1 FAILED")
+ assert.Contains(t, dellyFact.Value, "/dev/sdb")
+
+ require.NotNil(t, minipcFact)
+ assert.Contains(t, minipcFact.Value, "1 disks all PASSED")
+}
+
+// --- Metrics: Physical Disks ---
+
+func TestExtractFacts_MetricsDisks(t *testing.T) {
+ input := map[string]interface{}{"action": "disks"}
+ result := `{"disks":[{"host":"Tower","device":"/dev/sda","model":"WD Blue","health":"PASSED"},{"host":"Tower","device":"/dev/sdb","model":"Samsung","health":"PASSED"},{"host":"Mini","device":"/dev/sda","model":"Crucial","health":"FAILED"}]}`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ require.Len(t, facts, 2) // marker + summary
+
+ // First fact is the marker
+ assert.Equal(t, "physical_disks:queried", facts[0].Key)
+ assert.Equal(t, "summary extracted", facts[0].Value)
+
+ f := facts[1]
+ assert.Equal(t, FactCategoryStorage, f.Category)
+ assert.Equal(t, "physical_disks:summary", f.Key)
+ assert.Contains(t, f.Value, "3 disks")
+ assert.Contains(t, f.Value, "1 FAILED")
+ assert.Contains(t, f.Value, "Mini /dev/sda Crucial")
+}
+
+func TestExtractFacts_MetricsDisks_AllPassed(t *testing.T) {
+ input := map[string]interface{}{"action": "disks"}
+ result := `{"disks":[{"host":"Tower","device":"/dev/sda","health":"PASSED"},{"host":"Tower","device":"/dev/sdb","health":"PASSED"}]}`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ require.Len(t, facts, 2) // marker + summary
+ assert.Equal(t, "physical_disks:queried", facts[0].Key)
+ assert.Contains(t, facts[1].Value, "2 disks total, all PASSED")
+}
+
+// --- PredictFactKeys: New entries ---
+
+func TestPredictFactKeys_QueryTopology(t *testing.T) {
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{"action": "topology"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "topology:summary", keys[0])
+}
+
+func TestPredictFactKeys_QueryHealth(t *testing.T) {
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{"action": "health"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "health:connections", keys[0])
+}
+
+func TestPredictFactKeys_AlertsFindings(t *testing.T) {
+ keys := PredictFactKeys("pulse_alerts", map[string]interface{}{"action": "findings"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "findings:overview", keys[0])
+}
+
+func TestPredictFactKeys_AlertsList(t *testing.T) {
+ keys := PredictFactKeys("pulse_alerts", map[string]interface{}{"action": "list"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "alerts:overview", keys[0])
+}
+
+func TestPredictFactKeys_MetricsBaselines(t *testing.T) {
+ keys := PredictFactKeys("pulse_metrics", map[string]interface{}{"action": "baselines", "resource_id": "vm101"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "baseline:vm101", keys[0])
+}
+
+func TestPredictFactKeys_MetricsBaselinesGlobal(t *testing.T) {
+ keys := PredictFactKeys("pulse_metrics", map[string]interface{}{"action": "baselines"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "baselines:queried", keys[0])
+}
+
+func TestPredictFactKeys_StoragePools(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "pools"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "storage:pools:queried", keys[0])
+}
+
+func TestPredictFactKeys_StorageDiskHealth(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "disk_health"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "disk_health:queried", keys[0])
+}
+
+func TestPredictFactKeys_MetricsDisks(t *testing.T) {
+ keys := PredictFactKeys("pulse_metrics", map[string]interface{}{"action": "disks"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "physical_disks:queried", keys[0])
+}
+
+// --- Metrics: Temperatures ---
+
+func TestExtractFacts_MetricsTemperatures(t *testing.T) {
+ input := map[string]interface{}{"action": "temperatures"}
+ result := `[{"hostname":"delly","cpu_temps":{"core0":52,"core1":55},"disk_temps":{"sda":38,"sdb":42}},{"hostname":"minipc","cpu_temps":{"core0":45},"disk_temps":{}}]`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ require.Len(t, facts, 3) // marker + 2 hosts
+
+ assert.Equal(t, "temperatures:queried", facts[0].Key)
+ assert.Equal(t, "2 hosts", facts[0].Value)
+
+ var dellyFact, minipcFact *FactEntry
+ for i := range facts[1:] {
+ idx := i + 1
+ switch facts[idx].Key {
+ case "temperatures:delly":
+ dellyFact = &facts[idx]
+ case "temperatures:minipc":
+ minipcFact = &facts[idx]
+ }
+ }
+
+ require.NotNil(t, dellyFact)
+ assert.Equal(t, FactCategoryMetrics, dellyFact.Category)
+ assert.Contains(t, dellyFact.Value, "cpu_max=55°C")
+ assert.Contains(t, dellyFact.Value, "disk_max=42°C")
+
+ require.NotNil(t, minipcFact)
+ assert.Contains(t, minipcFact.Value, "cpu_max=45°C")
+ assert.NotContains(t, minipcFact.Value, "disk_max")
+}
+
+func TestExtractFacts_MetricsTemperatures_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "temperatures"}
+ result := `[]`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "temperatures:queried", facts[0].Key)
+ assert.Equal(t, "0 hosts", facts[0].Value)
+}
+
+// --- Storage: RAID ---
+
+func TestExtractFacts_StorageRAID(t *testing.T) {
+ input := map[string]interface{}{"action": "raid"}
+ result := `{"hosts":[{"hostname":"delly","arrays":[{"device":"/dev/md0","level":"raid1","state":"clean","failed_devices":0,"total_devices":2},{"device":"/dev/md1","level":"raid5","state":"degraded","failed_devices":1,"total_devices":4}]}]}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2) // marker + 1 host
+
+ assert.Equal(t, "raid:queried", facts[0].Key)
+ assert.Equal(t, "1 hosts", facts[0].Value)
+
+ assert.Equal(t, "raid:delly", facts[1].Key)
+ assert.Equal(t, FactCategoryStorage, facts[1].Category)
+ assert.Contains(t, facts[1].Value, "2 arrays")
+ assert.Contains(t, facts[1].Value, "1 degraded/failed")
+}
+
+func TestExtractFacts_StorageRAID_AllClean(t *testing.T) {
+ input := map[string]interface{}{"action": "raid"}
+ result := `{"hosts":[{"hostname":"minipc","arrays":[{"device":"/dev/md0","level":"raid1","state":"clean","failed_devices":0,"total_devices":2}]}]}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 2)
+ assert.Contains(t, facts[1].Value, "all clean")
+}
+
+// --- Storage: Backups ---
+
+func TestExtractFacts_StorageBackups(t *testing.T) {
+ input := map[string]interface{}{"action": "backups"}
+ result := `{"pbs":[{},{}],"pve":[{}],"pbs_servers":[{"name":"pbs-minipc","status":"connected","datastores":[{"name":"datastore1","usage_percent":42.5}]}]}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.GreaterOrEqual(t, len(facts), 3) // marker + server + summary
+
+ assert.Equal(t, "backups:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "2 PBS")
+ assert.Contains(t, facts[0].Value, "1 PVE")
+ assert.Contains(t, facts[0].Value, "1 PBS servers")
+
+ var serverFact, summaryFact *FactEntry
+ for i := range facts[1:] {
+ idx := i + 1
+ switch facts[idx].Key {
+ case "backups:server:pbs-minipc":
+ serverFact = &facts[idx]
+ case "backups:summary":
+ summaryFact = &facts[idx]
+ }
+ }
+
+ require.NotNil(t, serverFact)
+ assert.Contains(t, serverFact.Value, "connected")
+ assert.Contains(t, serverFact.Value, "datastore1: 42.5% used")
+
+ require.NotNil(t, summaryFact)
+ assert.Contains(t, summaryFact.Value, "2 PBS backups")
+ assert.Contains(t, summaryFact.Value, "1 PVE backups")
+}
+
+func TestExtractFacts_StorageBackups_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "backups"}
+ result := `{"pbs":[],"pve":[],"pbs_servers":[]}`
+
+ facts := ExtractFacts("pulse_storage", input, result)
+ require.Len(t, facts, 1) // marker only
+ assert.Equal(t, "backups:queried", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "0 PBS")
+}
+
+// --- PredictFactKeys: New extractors ---
+
+func TestPredictFactKeys_StorageRAID(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "raid"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "raid:queried", keys[0])
+}
+
+func TestPredictFactKeys_StorageBackups(t *testing.T) {
+ keys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "backups"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "backups:queried", keys[0])
+}
+
+func TestPredictFactKeys_MetricsTemperatures(t *testing.T) {
+ keys := PredictFactKeys("pulse_metrics", map[string]interface{}{"action": "temperatures"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "temperatures:queried", keys[0])
+}
+
func TestExtractFacts_ValueTruncation(t *testing.T) {
input := map[string]interface{}{"command": "long-output-cmd", "target_host": "host1"}
// Create a result with very long output
@@ -277,3 +761,267 @@ func TestExtractFacts_ValueTruncation(t *testing.T) {
require.Len(t, facts, 1)
assert.LessOrEqual(t, len(facts[0].Value), maxValueLen)
}
+
+// --- Change 2: Query List Extractor ---
+
+func TestExtractFacts_QueryList(t *testing.T) {
+ input := map[string]interface{}{"action": "list"}
+ result := `{"nodes":[{"name":"delly","status":"online"},{"name":"minipc","status":"online"}],"vms":[{"name":"win10","status":"running"},{"name":"ubuntu","status":"stopped"}],"containers":[{"name":"postfix","status":"running"},{"name":"nginx","status":"running"},{"name":"test","status":"stopped"}],"docker_hosts":[{"hostname":"delly","display_name":"Delly Docker","container_count":5}],"total":{"nodes":2,"vms":2,"containers":3,"docker_hosts":1}}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+
+ f := facts[0]
+ assert.Equal(t, FactCategoryResource, f.Category)
+ assert.Equal(t, "inventory:summary", f.Key)
+ assert.Contains(t, f.Value, "2 nodes")
+ assert.Contains(t, f.Value, "2 VMs (1 running)")
+ assert.Contains(t, f.Value, "3 LXC (2 running)")
+ assert.Contains(t, f.Value, "1 docker hosts (5 containers)")
+}
+
+func TestExtractFacts_QueryList_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "list"}
+ result := `{"nodes":[],"vms":[],"containers":[],"docker_hosts":[],"total":{"nodes":0,"vms":0,"containers":0,"docker_hosts":0}}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ assert.Empty(t, facts)
+}
+
+func TestExtractFacts_QueryList_TypeFiltered(t *testing.T) {
+ // Real-world: model calls pulse_query with action=list AND type=vms
+ // The response only has the vms array, but total has all counts
+ input := map[string]interface{}{"action": "list", "type": "vms"}
+ result := `{"vms":[{"vmid":100,"name":"docker","status":"running","node":"minipc","cpu_percent":0.71,"memory_percent":4593.75},{"vmid":160,"name":"windows-runner","status":"stopped","node":"delly"},{"vmid":250,"name":"tails-anon","status":"stopped","node":"delly"}],"total":{"nodes":3,"vms":3,"containers":22,"docker_hosts":1}}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1, "type-filtered list should still extract inventory:summary")
+ assert.Equal(t, "inventory:summary", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "3 VMs")
+
+ // Also verify PredictFactKeys works with type param
+ keys := PredictFactKeys("pulse_query", input)
+ require.Len(t, keys, 1)
+ assert.Equal(t, "inventory:summary", keys[0])
+
+ // End-to-end: store fact in KA, verify gate would fire
+ ka := NewKnowledgeAccumulator()
+ for _, f := range facts {
+ ka.AddFact(f.Category, f.Key, f.Value)
+ }
+ val, found := ka.Lookup("inventory:summary")
+ assert.True(t, found, "inventory:summary should be in KA after extraction")
+ assert.Contains(t, val, "3 VMs")
+}
+
+func TestPredictFactKeys_QueryList(t *testing.T) {
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{"action": "list"})
+ require.Len(t, keys, 1)
+ assert.Equal(t, "inventory:summary", keys[0])
+}
+
+// --- Change 3: Query Config Extractor ---
+
+func TestExtractFacts_QueryConfig_LXC(t *testing.T) {
+ input := map[string]interface{}{"action": "config", "resource_id": "106", "node": "delly"}
+ result := `{"guest_type":"lxc","vmid":106,"name":"postfix-server","node":"delly","hostname":"postfix","os_type":"ubuntu","onboot":true,"mounts":[{"key":"mp0","mountpoint":"/data"},{"key":"mp1","mountpoint":"/logs"}],"disks":[{"key":"rootfs"}]}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+
+ f := facts[0]
+ assert.Equal(t, FactCategoryResource, f.Category)
+ assert.Equal(t, "config:delly:106", f.Key)
+ assert.Contains(t, f.Value, "lxc")
+ assert.Contains(t, f.Value, "hostname=postfix")
+ assert.Contains(t, f.Value, "os=ubuntu")
+ assert.Contains(t, f.Value, "onboot=yes")
+ assert.Contains(t, f.Value, "2 mounts")
+ assert.Contains(t, f.Value, "1 disks")
+}
+
+func TestExtractFacts_QueryConfig_VM(t *testing.T) {
+ input := map[string]interface{}{"action": "config", "resource_id": "200"}
+ onbootFalse := false
+ _ = onbootFalse
+ result := `{"guest_type":"qemu","vmid":200,"name":"win10","node":"minipc","os_type":"win10","onboot":false,"disks":[{"key":"scsi0"},{"key":"scsi1"}]}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ require.Len(t, facts, 1)
+
+ f := facts[0]
+ assert.Equal(t, "config:minipc:200", f.Key)
+ assert.Contains(t, f.Value, "qemu")
+ assert.Contains(t, f.Value, "onboot=no")
+ assert.Contains(t, f.Value, "2 disks")
+}
+
+func TestExtractFacts_QueryConfig_Empty(t *testing.T) {
+ input := map[string]interface{}{"action": "config", "resource_id": "999"}
+ result := `{}`
+
+ facts := ExtractFacts("pulse_query", input, result)
+ assert.Empty(t, facts)
+}
+
+func TestPredictFactKeys_QueryConfig(t *testing.T) {
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{
+ "action": "config",
+ "resource_id": "106",
+ "node": "delly",
+ })
+ require.Len(t, keys, 1)
+ assert.Equal(t, "config:delly:106", keys[0])
+}
+
+func TestPredictFactKeys_QueryConfig_NoNode(t *testing.T) {
+ // Without node, can't predict exact key
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{
+ "action": "config",
+ "resource_id": "106",
+ })
+ assert.Nil(t, keys)
+}
+
+// --- Change 4: PredictFactKeys for query:get ---
+
+func TestPredictFactKeys_QueryGet_ReturnsNil(t *testing.T) {
+ // get success key depends on response data (type:node:id:status), can't predict
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{
+ "action": "get",
+ "resource_id": "106",
+ })
+ assert.Nil(t, keys)
+}
+
+// --- Change 5: PredictFactKeys for search ---
+
+func TestPredictFactKeys_QuerySearch(t *testing.T) {
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{
+ "action": "search",
+ "query": "postfix",
+ })
+ require.Len(t, keys, 1)
+ assert.Equal(t, "search:postfix:summary", keys[0])
+}
+
+func TestPredictFactKeys_QuerySearch_NoQuery(t *testing.T) {
+ keys := PredictFactKeys("pulse_query", map[string]interface{}{
+ "action": "search",
+ })
+ assert.Nil(t, keys)
+}
+
+// --- Change 1: Negative Marker Tests ---
+
+func TestNegativeMarker_TextResponse(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ // Simulate: tool returns plain text that doesn't parse as JSON
+ // The extractor returns nil, but PredictFactKeys returns a key
+ toolName := "pulse_storage"
+ toolInput := map[string]interface{}{"action": "raid"}
+ resultText := "No RAID arrays found across any hosts"
+
+ // ExtractFacts should return nil for plain text
+ facts := ExtractFacts(toolName, toolInput, resultText)
+ assert.Empty(t, facts)
+
+ // PredictFactKeys should return the raid marker key
+ predictedKeys := PredictFactKeys(toolName, toolInput)
+ require.Len(t, predictedKeys, 1)
+ assert.Equal(t, "raid:queried", predictedKeys[0])
+
+ // Simulate what agentic.go does: store negative marker
+ for _, key := range predictedKeys {
+ if _, found := ka.Lookup(key); !found {
+ cat := categoryForPredictedKey(key)
+ summary := resultText
+ if len(summary) > 120 {
+ summary = summary[:120]
+ }
+ ka.AddFact(cat, key, fmt.Sprintf("checked: %s", summary))
+ }
+ }
+
+ // Verify negative marker is stored
+ val, found := ka.Lookup("raid:queried")
+ assert.True(t, found)
+ assert.Contains(t, val, "checked:")
+ assert.Contains(t, val, "No RAID arrays found")
+}
+
+func TestNegativeMarker_NotStoredOnSuccess(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ // Simulate: tool returns valid JSON that ExtractFacts can parse
+ toolName := "pulse_storage"
+ toolInput := map[string]interface{}{"action": "raid"}
+ resultText := `{"hosts":[{"hostname":"delly","arrays":[{"device":"/dev/md0","level":"raid1","state":"clean","failed_devices":0,"total_devices":2}]}]}`
+
+ facts := ExtractFacts(toolName, toolInput, resultText)
+ require.NotEmpty(t, facts)
+
+ // Store the real facts
+ for _, f := range facts {
+ ka.AddFact(f.Category, f.Key, f.Value)
+ }
+
+ // The negative marker logic only triggers when len(facts) == 0
+ // So "raid:queried" should be stored by the extractor itself (as a marker fact), not as a negative marker
+ val, found := ka.Lookup("raid:queried")
+ assert.True(t, found)
+ assert.NotContains(t, val, "checked:") // Real fact, not a negative marker
+}
+
+func TestNegativeMarker_GatePreventsRetry(t *testing.T) {
+ ka := NewKnowledgeAccumulator()
+
+ // Store a negative marker (as would happen after a text response)
+ ka.AddFact(FactCategoryStorage, "raid:queried", "checked: No RAID arrays found across any hosts")
+
+ // Now simulate the gate check: PredictFactKeys returns the key, Lookup finds it
+ predictedKeys := PredictFactKeys("pulse_storage", map[string]interface{}{"action": "raid"})
+ require.Len(t, predictedKeys, 1)
+
+ val, found := ka.Lookup(predictedKeys[0])
+ assert.True(t, found, "gate should find the negative marker")
+ assert.Contains(t, val, "checked:")
+}
+
+// --- categoryForPredictedKey ---
+
+func TestCategoryForPredictedKey(t *testing.T) {
+ tests := []struct {
+ key string
+ expected FactCategory
+ }{
+ {"storage:pools:queried", FactCategoryStorage},
+ {"disk_health:queried", FactCategoryStorage},
+ {"raid:queried", FactCategoryStorage},
+ {"backups:queried", FactCategoryStorage},
+ {"physical_disks:queried", FactCategoryStorage},
+ {"metrics:vm101", FactCategoryMetrics},
+ {"baseline:delly", FactCategoryMetrics},
+ {"baselines:queried", FactCategoryMetrics},
+ {"temperatures:queried", FactCategoryMetrics},
+ {"exec:delly:some-cmd", FactCategoryExec},
+ {"discovery:delly:106", FactCategoryDiscovery},
+ {"topology:summary", FactCategoryResource},
+ {"health:connections", FactCategoryResource},
+ {"search:postfix:summary", FactCategoryResource},
+ {"inventory:summary", FactCategoryResource},
+ {"config:delly:106", FactCategoryResource},
+ {"finding:high-cpu", FactCategoryFinding},
+ {"findings:overview", FactCategoryFinding},
+ {"alert:vm101:cpu", FactCategoryAlert},
+ {"alerts:overview", FactCategoryAlert},
+ {"unknown:key", FactCategoryResource}, // default
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.key, func(t *testing.T) {
+ assert.Equal(t, tt.expected, categoryForPredictedKey(tt.key))
+ })
+ }
+}