Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

feat(ai): add patrol-specific tools for agentic finding creation

rcourtmanf83356b43029
diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.go
index 54a96d4670..905b63c45b 100644
--- a/internal/ai/tools/executor.go
+++ b/internal/ai/tools/executor.go
@@ -68,6 +68,46 @@ type FindingsProvider interface {
GetDismissedFindings() []Finding
}
+// PatrolFindingCreator is set on the executor during a patrol run to allow
+// patrol-specific tools (patrol_report_finding, patrol_resolve_finding,
+// patrol_get_findings) to create, resolve, and query findings.
+// Outside of a patrol run this is nil, and the tools return a clear error.
+type PatrolFindingCreator interface {
+ CreateFinding(input PatrolFindingInput) (findingID string, isNew bool, err error)
+ ResolveFinding(findingID, reason string) error
+ GetActiveFindings(resourceID, minSeverity string) []PatrolFindingInfo
+}
+
+// PatrolFindingInput contains the structured parameters the LLM passes
+// to the patrol_report_finding tool.
+type PatrolFindingInput struct {
+ Key string `json:"key"`
+ Severity string `json:"severity"`
+ Category string `json:"category"`
+ ResourceID string `json:"resource_id"`
+ ResourceName string `json:"resource_name"`
+ ResourceType string `json:"resource_type"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Recommendation string `json:"recommendation,omitempty"`
+ Evidence string `json:"evidence,omitempty"`
+}
+
+// PatrolFindingInfo is a lightweight view of a finding returned by
+// PatrolFindingCreator.GetActiveFindings.
+type PatrolFindingInfo struct {
+ ID string `json:"id"`
+ Key string `json:"key,omitempty"`
+ Severity string `json:"severity"`
+ Category string `json:"category"`
+ ResourceID string `json:"resource_id"`
+ ResourceName string `json:"resource_name"`
+ ResourceType string `json:"resource_type"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ DetectedAt string `json:"detected_at"`
+}
+
// BackupProvider provides backup information
type BackupProvider interface {
GetBackups() models.Backups
@@ -361,6 +401,10 @@ type PulseToolExecutor struct {
// This is optional - if nil, no telemetry is recorded
telemetryCallback TelemetryCallback
+ // Patrol finding creator — set only during a patrol run, nil otherwise.
+ // Enables patrol_report_finding, patrol_resolve_finding, patrol_get_findings tools.
+ patrolFindingCreator PatrolFindingCreator
+
// Tool registry
registry *ToolRegistry
}
@@ -542,6 +586,17 @@ func (e *PulseToolExecutor) SetTelemetryCallback(cb TelemetryCallback) {
e.telemetryCallback = cb
}
+// SetPatrolFindingCreator sets (or clears) the patrol finding creator.
+// This must be set before a patrol run and cleared after.
+func (e *PulseToolExecutor) SetPatrolFindingCreator(creator PatrolFindingCreator) {
+ e.patrolFindingCreator = creator
+}
+
+// GetPatrolFindingCreator returns the current patrol finding creator (may be nil).
+func (e *PulseToolExecutor) GetPatrolFindingCreator() PatrolFindingCreator {
+ return e.patrolFindingCreator
+}
+
// GetResolvedContext returns the current resolved context (may be nil)
func (e *PulseToolExecutor) GetResolvedContext() ResolvedContextProvider {
return e.resolvedContext
@@ -590,6 +645,9 @@ func (e *PulseToolExecutor) isToolAvailable(name string) bool {
return e.knowledgeStoreProvider != nil || e.incidentRecorderProvider != nil || e.eventCorrelatorProvider != nil || e.topologyProvider != nil
case "pulse_pmg":
return e.stateProvider != nil
+ case "patrol_report_finding", "patrol_resolve_finding", "patrol_get_findings":
+ // Always available when registered; handler checks patrolFindingCreator at runtime
+ return e.patrolFindingCreator != nil
default:
return e.stateProvider != nil
}
@@ -646,4 +704,8 @@ func (e *PulseToolExecutor) registerTools() {
// pulse_pmg - status, mail_stats, queues, spam
e.registerPMGTools()
+
+ // patrol_report_finding, patrol_resolve_finding, patrol_get_findings
+ // These are always registered but only functional when patrolFindingCreator is set.
+ e.registerPatrolTools()
}
diff --git a/internal/ai/tools/tools_patrol.go b/internal/ai/tools/tools_patrol.go
new file mode 100644
index 0000000000..8a5767b4be
--- /dev/null
+++ b/internal/ai/tools/tools_patrol.go
@@ -0,0 +1,261 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+// registerPatrolTools registers the three patrol-specific tools.
+// These tools are only functional during a patrol run when patrolFindingCreator is set.
+func (e *PulseToolExecutor) registerPatrolTools() {
+ // patrol_report_finding — LLM calls this to create a finding
+ e.registry.Register(RegisteredTool{
+ Definition: Tool{
+ Name: "patrol_report_finding",
+ Description: `Report an infrastructure finding discovered during patrol investigation.
+
+Call this tool to create a structured finding after you have gathered sufficient evidence via investigation tools.
+The finding will be validated against current metrics and deduplicated automatically.
+
+Returns: {"ok": true, "finding_id": "...", "is_new": true/false} on success.`,
+ InputSchema: InputSchema{
+ Type: "object",
+ Properties: map[string]PropertySchema{
+ "key": {
+ Type: "string",
+ Description: "Stable issue key for deduplication (e.g. high-cpu, high-memory, high-disk, backup-stale, backup-never, storage-high-usage, node-offline, restart-loop, pbs-job-failed)",
+ },
+ "severity": {
+ Type: "string",
+ Description: "Finding severity level",
+ Enum: []string{"critical", "warning", "watch", "info"},
+ },
+ "category": {
+ Type: "string",
+ Description: "Finding category",
+ Enum: []string{"performance", "capacity", "reliability", "backup", "security", "general"},
+ },
+ "resource_id": {
+ Type: "string",
+ Description: "Resource ID (e.g. node/pve1, qemu/100, lxc/101)",
+ },
+ "resource_name": {
+ Type: "string",
+ Description: "Human-readable resource name",
+ },
+ "resource_type": {
+ Type: "string",
+ Description: "Resource type",
+ Enum: []string{"node", "vm", "container", "docker_container", "storage", "host", "kubernetes_cluster", "pbs"},
+ },
+ "title": {
+ Type: "string",
+ Description: "Brief finding title (1 sentence)",
+ },
+ "description": {
+ Type: "string",
+ Description: "Detailed description of the issue found",
+ },
+ "recommendation": {
+ Type: "string",
+ Description: "Specific actionable recommendation for the operator",
+ },
+ "evidence": {
+ Type: "string",
+ Description: "Specific data/metrics/commands that support this finding",
+ },
+ },
+ Required: []string{"key", "severity", "category", "resource_id", "resource_name", "resource_type", "title", "description"},
+ },
+ },
+ Handler: handlePatrolReportFinding,
+ })
+
+ // patrol_resolve_finding — LLM calls this to resolve an active finding
+ e.registry.Register(RegisteredTool{
+ Definition: Tool{
+ Name: "patrol_resolve_finding",
+ Description: `Resolve an active patrol finding after verifying the issue is no longer present.
+
+Call this after investigating an existing finding and confirming the issue has been resolved.
+Returns: {"ok": true, "resolved": true} on success.`,
+ InputSchema: InputSchema{
+ Type: "object",
+ Properties: map[string]PropertySchema{
+ "finding_id": {
+ Type: "string",
+ Description: "The ID of the finding to resolve",
+ },
+ "reason": {
+ Type: "string",
+ Description: "Brief explanation of why this finding is being resolved (e.g. 'CPU has returned to 35%, well below threshold')",
+ },
+ },
+ Required: []string{"finding_id", "reason"},
+ },
+ },
+ Handler: handlePatrolResolveFinding,
+ })
+
+ // patrol_get_findings — LLM calls this to check existing active findings
+ e.registry.Register(RegisteredTool{
+ Definition: Tool{
+ Name: "patrol_get_findings",
+ Description: `Get currently active patrol findings. Use this to check what findings already exist before reporting new ones (avoids duplicates) and to identify findings that may need resolution.
+
+Returns a list of active findings with their IDs, severity, resource, and title.`,
+ InputSchema: InputSchema{
+ Type: "object",
+ Properties: map[string]PropertySchema{
+ "resource_id": {
+ Type: "string",
+ Description: "Filter by resource ID (optional)",
+ },
+ "severity": {
+ Type: "string",
+ Description: "Minimum severity to include (optional, default: info)",
+ Enum: []string{"info", "watch", "warning", "critical"},
+ },
+ },
+ },
+ },
+ Handler: handlePatrolGetFindings,
+ })
+}
+
+func handlePatrolReportFinding(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
+ creator := e.patrolFindingCreator
+ if creator == nil {
+ return NewTextResult("patrol_report_finding is only available during a patrol run."), nil
+ }
+
+ // Extract required fields
+ key, _ := args["key"].(string)
+ severity, _ := args["severity"].(string)
+ category, _ := args["category"].(string)
+ resourceID, _ := args["resource_id"].(string)
+ resourceName, _ := args["resource_name"].(string)
+ resourceType, _ := args["resource_type"].(string)
+ title, _ := args["title"].(string)
+ description, _ := args["description"].(string)
+
+ // Validate required fields
+ var missing []string
+ if key == "" {
+ missing = append(missing, "key")
+ }
+ if severity == "" {
+ missing = append(missing, "severity")
+ }
+ if category == "" {
+ missing = append(missing, "category")
+ }
+ if resourceID == "" {
+ missing = append(missing, "resource_id")
+ }
+ if resourceName == "" {
+ missing = append(missing, "resource_name")
+ }
+ if resourceType == "" {
+ missing = append(missing, "resource_type")
+ }
+ if title == "" {
+ missing = append(missing, "title")
+ }
+ if description == "" {
+ missing = append(missing, "description")
+ }
+ if len(missing) > 0 {
+ return NewErrorResult(fmt.Errorf("missing required fields: %s", strings.Join(missing, ", "))), nil
+ }
+
+ // Validate enums
+ validSeverities := map[string]bool{"critical": true, "warning": true, "watch": true, "info": true}
+ if !validSeverities[severity] {
+ return NewErrorResult(fmt.Errorf("invalid severity %q: must be critical, warning, watch, or info", severity)), nil
+ }
+ validCategories := map[string]bool{"performance": true, "capacity": true, "reliability": true, "backup": true, "security": true, "general": true}
+ if !validCategories[category] {
+ return NewErrorResult(fmt.Errorf("invalid category %q: must be performance, capacity, reliability, backup, security, or general", category)), nil
+ }
+
+ // Extract optional fields
+ recommendation, _ := args["recommendation"].(string)
+ evidence, _ := args["evidence"].(string)
+
+ input := PatrolFindingInput{
+ Key: key,
+ Severity: severity,
+ Category: category,
+ ResourceID: resourceID,
+ ResourceName: resourceName,
+ ResourceType: resourceType,
+ Title: title,
+ Description: description,
+ Recommendation: recommendation,
+ Evidence: evidence,
+ }
+
+ findingID, isNew, err := creator.CreateFinding(input)
+ if err != nil {
+ return NewErrorResult(fmt.Errorf("failed to create finding: %w", err)), nil
+ }
+
+ result := map[string]interface{}{
+ "ok": true,
+ "finding_id": findingID,
+ "is_new": isNew,
+ }
+ b, _ := json.Marshal(result)
+ return NewTextResult(string(b)), nil
+}
+
+func handlePatrolResolveFinding(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
+ creator := e.patrolFindingCreator
+ if creator == nil {
+ return NewTextResult("patrol_resolve_finding is only available during a patrol run."), nil
+ }
+
+ findingID, _ := args["finding_id"].(string)
+ reason, _ := args["reason"].(string)
+
+ if findingID == "" {
+ return NewErrorResult(fmt.Errorf("missing required field: finding_id")), nil
+ }
+ if reason == "" {
+ return NewErrorResult(fmt.Errorf("missing required field: reason")), nil
+ }
+
+ if err := creator.ResolveFinding(findingID, reason); err != nil {
+ return NewErrorResult(fmt.Errorf("failed to resolve finding: %w", err)), nil
+ }
+
+ result := map[string]interface{}{
+ "ok": true,
+ "resolved": true,
+ }
+ b, _ := json.Marshal(result)
+ return NewTextResult(string(b)), nil
+}
+
+func handlePatrolGetFindings(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
+ creator := e.patrolFindingCreator
+ if creator == nil {
+ return NewTextResult("patrol_get_findings is only available during a patrol run."), nil
+ }
+
+ resourceID, _ := args["resource_id"].(string)
+ minSeverity, _ := args["severity"].(string)
+
+ findings := creator.GetActiveFindings(resourceID, minSeverity)
+
+ result := map[string]interface{}{
+ "ok": true,
+ "count": len(findings),
+ "findings": findings,
+ }
+ b, _ := json.Marshal(result)
+ return NewTextResult(string(b)), nil
+}
diff --git a/internal/ai/tools/tools_patrol_test.go b/internal/ai/tools/tools_patrol_test.go
new file mode 100644
index 0000000000..95558db29b
--- /dev/null
+++ b/internal/ai/tools/tools_patrol_test.go
@@ -0,0 +1,564 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- Mock PatrolFindingCreator ---
+
+type mockPatrolFindingCreator struct {
+ createFindingFunc func(input PatrolFindingInput) (string, bool, error)
+ resolveFindingFunc func(findingID, reason string) error
+ getActiveFn func(resourceID, minSeverity string) []PatrolFindingInfo
+
+ // Track calls for assertions
+ createCalls []PatrolFindingInput
+ resolveCalls []struct {
+ FindingID string
+ Reason string
+ }
+ getCalls []struct {
+ ResourceID string
+ MinSeverity string
+ }
+}
+
+func (m *mockPatrolFindingCreator) CreateFinding(input PatrolFindingInput) (string, bool, error) {
+ m.createCalls = append(m.createCalls, input)
+ if m.createFindingFunc != nil {
+ return m.createFindingFunc(input)
+ }
+ return "finding-123", true, nil
+}
+
+func (m *mockPatrolFindingCreator) ResolveFinding(findingID, reason string) error {
+ m.resolveCalls = append(m.resolveCalls, struct {
+ FindingID string
+ Reason string
+ }{findingID, reason})
+ if m.resolveFindingFunc != nil {
+ return m.resolveFindingFunc(findingID, reason)
+ }
+ return nil
+}
+
+func (m *mockPatrolFindingCreator) GetActiveFindings(resourceID, minSeverity string) []PatrolFindingInfo {
+ m.getCalls = append(m.getCalls, struct {
+ ResourceID string
+ MinSeverity string
+ }{resourceID, minSeverity})
+ if m.getActiveFn != nil {
+ return m.getActiveFn(resourceID, minSeverity)
+ }
+ return nil
+}
+
+// --- Helper to create executor with patrol creator ---
+
+func newPatrolTestExecutor(creator PatrolFindingCreator) *PulseToolExecutor {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+ exec.SetPatrolFindingCreator(creator)
+ return exec
+}
+
+func validReportArgs() map[string]interface{} {
+ return map[string]interface{}{
+ "key": "high-cpu",
+ "severity": "warning",
+ "category": "performance",
+ "resource_id": "node/pve1",
+ "resource_name": "pve1",
+ "resource_type": "node",
+ "title": "High CPU usage on pve1",
+ "description": "CPU usage is at 92% for the last 15 minutes",
+ }
+}
+
+// --- patrol_report_finding tests ---
+
+func TestHandlePatrolReportFinding_NilCreator(t *testing.T) {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+ // Creator is nil (not in a patrol run)
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, validReportArgs())
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "only available during a patrol run")
+}
+
+func TestHandlePatrolReportFinding_ValidInput(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ args := validReportArgs()
+ args["recommendation"] = "Consider migrating VMs to reduce load"
+ args["evidence"] = "CPU at 92% over 15 minutes"
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, args)
+ require.NoError(t, err)
+
+ var parsed map[string]interface{}
+ text := extractText(result)
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+
+ assert.Equal(t, true, parsed["ok"])
+ assert.Equal(t, "finding-123", parsed["finding_id"])
+ assert.Equal(t, true, parsed["is_new"])
+
+ // Verify the creator was called with correct input
+ require.Len(t, creator.createCalls, 1)
+ input := creator.createCalls[0]
+ assert.Equal(t, "high-cpu", input.Key)
+ assert.Equal(t, "warning", input.Severity)
+ assert.Equal(t, "performance", input.Category)
+ assert.Equal(t, "node/pve1", input.ResourceID)
+ assert.Equal(t, "pve1", input.ResourceName)
+ assert.Equal(t, "node", input.ResourceType)
+ assert.Equal(t, "High CPU usage on pve1", input.Title)
+ assert.Equal(t, "CPU usage is at 92% for the last 15 minutes", input.Description)
+ assert.Equal(t, "Consider migrating VMs to reduce load", input.Recommendation)
+ assert.Equal(t, "CPU at 92% over 15 minutes", input.Evidence)
+}
+
+func TestHandlePatrolReportFinding_MissingRequiredFields(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ tests := []struct {
+ name string
+ remove string
+ missing string
+ }{
+ {"missing key", "key", "key"},
+ {"missing severity", "severity", "severity"},
+ {"missing category", "category", "category"},
+ {"missing resource_id", "resource_id", "resource_id"},
+ {"missing resource_name", "resource_name", "resource_name"},
+ {"missing resource_type", "resource_type", "resource_type"},
+ {"missing title", "title", "title"},
+ {"missing description", "description", "description"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ args := validReportArgs()
+ delete(args, tt.remove)
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, args)
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "missing required fields")
+ assert.Contains(t, text, tt.missing)
+ })
+ }
+}
+
+func TestHandlePatrolReportFinding_AllRequiredFieldsMissing(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, map[string]interface{}{})
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "missing required fields")
+ // Should mention all 8 required fields
+ for _, field := range []string{"key", "severity", "category", "resource_id", "resource_name", "resource_type", "title", "description"} {
+ assert.Contains(t, text, field)
+ }
+}
+
+func TestHandlePatrolReportFinding_InvalidSeverity(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ args := validReportArgs()
+ args["severity"] = "extreme"
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, args)
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "invalid severity")
+ assert.Contains(t, text, "extreme")
+}
+
+func TestHandlePatrolReportFinding_InvalidCategory(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ args := validReportArgs()
+ args["category"] = "networking"
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, args)
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "invalid category")
+ assert.Contains(t, text, "networking")
+}
+
+func TestHandlePatrolReportFinding_ValidSeverities(t *testing.T) {
+ for _, sev := range []string{"critical", "warning", "watch", "info"} {
+ t.Run(sev, func(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ args := validReportArgs()
+ args["severity"] = sev
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, args)
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.NotContains(t, text, "invalid severity")
+
+ var parsed map[string]interface{}
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+ assert.Equal(t, true, parsed["ok"])
+ })
+ }
+}
+
+func TestHandlePatrolReportFinding_ValidCategories(t *testing.T) {
+ for _, cat := range []string{"performance", "capacity", "reliability", "backup", "security", "general"} {
+ t.Run(cat, func(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ args := validReportArgs()
+ args["category"] = cat
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, args)
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.NotContains(t, text, "invalid category")
+
+ var parsed map[string]interface{}
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+ assert.Equal(t, true, parsed["ok"])
+ })
+ }
+}
+
+func TestHandlePatrolReportFinding_DuplicateFinding(t *testing.T) {
+ creator := &mockPatrolFindingCreator{
+ createFindingFunc: func(input PatrolFindingInput) (string, bool, error) {
+ return "finding-existing", false, nil // isNew = false
+ },
+ }
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, validReportArgs())
+ require.NoError(t, err)
+
+ var parsed map[string]interface{}
+ text := extractText(result)
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+
+ assert.Equal(t, true, parsed["ok"])
+ assert.Equal(t, "finding-existing", parsed["finding_id"])
+ assert.Equal(t, false, parsed["is_new"])
+}
+
+func TestHandlePatrolReportFinding_CreatorError(t *testing.T) {
+ creator := &mockPatrolFindingCreator{
+ createFindingFunc: func(input PatrolFindingInput) (string, bool, error) {
+ return "", false, fmt.Errorf("validation failed: CPU is below threshold")
+ },
+ }
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolReportFinding(context.Background(), exec, validReportArgs())
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "failed to create finding")
+ assert.Contains(t, text, "validation failed")
+}
+
+func TestHandlePatrolReportFinding_OptionalFieldsOmitted(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ // Only required fields, no recommendation or evidence
+ result, err := handlePatrolReportFinding(context.Background(), exec, validReportArgs())
+ require.NoError(t, err)
+
+ var parsed map[string]interface{}
+ text := extractText(result)
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+ assert.Equal(t, true, parsed["ok"])
+
+ // Verify optional fields are empty strings
+ require.Len(t, creator.createCalls, 1)
+ assert.Equal(t, "", creator.createCalls[0].Recommendation)
+ assert.Equal(t, "", creator.createCalls[0].Evidence)
+}
+
+// --- patrol_resolve_finding tests ---
+
+func TestHandlePatrolResolveFinding_NilCreator(t *testing.T) {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+
+ result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{
+ "finding_id": "f-123",
+ "reason": "CPU recovered",
+ })
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "only available during a patrol run")
+}
+
+func TestHandlePatrolResolveFinding_ValidInput(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{
+ "finding_id": "f-123",
+ "reason": "CPU has returned to 35%",
+ })
+ require.NoError(t, err)
+
+ var parsed map[string]interface{}
+ text := extractText(result)
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+
+ assert.Equal(t, true, parsed["ok"])
+ assert.Equal(t, true, parsed["resolved"])
+
+ require.Len(t, creator.resolveCalls, 1)
+ assert.Equal(t, "f-123", creator.resolveCalls[0].FindingID)
+ assert.Equal(t, "CPU has returned to 35%", creator.resolveCalls[0].Reason)
+}
+
+func TestHandlePatrolResolveFinding_MissingFindingID(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{
+ "reason": "CPU recovered",
+ })
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "missing required field: finding_id")
+}
+
+func TestHandlePatrolResolveFinding_MissingReason(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{
+ "finding_id": "f-123",
+ })
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "missing required field: reason")
+}
+
+func TestHandlePatrolResolveFinding_ResolveError(t *testing.T) {
+ creator := &mockPatrolFindingCreator{
+ resolveFindingFunc: func(findingID, reason string) error {
+ return fmt.Errorf("finding not found: %s", findingID)
+ },
+ }
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{
+ "finding_id": "f-nonexistent",
+ "reason": "CPU recovered",
+ })
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "failed to resolve finding")
+ assert.Contains(t, text, "finding not found")
+}
+
+// --- patrol_get_findings tests ---
+
+func TestHandlePatrolGetFindings_NilCreator(t *testing.T) {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+
+ result, err := handlePatrolGetFindings(context.Background(), exec, map[string]interface{}{})
+ require.NoError(t, err)
+
+ text := extractText(result)
+ assert.Contains(t, text, "only available during a patrol run")
+}
+
+func TestHandlePatrolGetFindings_EmptyResult(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolGetFindings(context.Background(), exec, map[string]interface{}{})
+ require.NoError(t, err)
+
+ var parsed map[string]interface{}
+ text := extractText(result)
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+
+ assert.Equal(t, true, parsed["ok"])
+ assert.Equal(t, float64(0), parsed["count"])
+}
+
+func TestHandlePatrolGetFindings_WithFindings(t *testing.T) {
+ creator := &mockPatrolFindingCreator{
+ getActiveFn: func(resourceID, minSeverity string) []PatrolFindingInfo {
+ return []PatrolFindingInfo{
+ {
+ ID: "f-1",
+ Key: "high-cpu",
+ Severity: "warning",
+ Category: "performance",
+ ResourceID: "node/pve1",
+ ResourceName: "pve1",
+ ResourceType: "node",
+ Title: "High CPU on pve1",
+ DetectedAt: "2024-01-15T10:00:00Z",
+ },
+ {
+ ID: "f-2",
+ Key: "high-disk",
+ Severity: "critical",
+ Category: "capacity",
+ ResourceID: "node/pve2",
+ ResourceName: "pve2",
+ ResourceType: "node",
+ Title: "Disk almost full on pve2",
+ DetectedAt: "2024-01-15T09:00:00Z",
+ },
+ }
+ },
+ }
+ exec := newPatrolTestExecutor(creator)
+
+ result, err := handlePatrolGetFindings(context.Background(), exec, map[string]interface{}{})
+ require.NoError(t, err)
+
+ var parsed map[string]interface{}
+ text := extractText(result)
+ require.NoError(t, json.Unmarshal([]byte(text), &parsed))
+
+ assert.Equal(t, true, parsed["ok"])
+ assert.Equal(t, float64(2), parsed["count"])
+
+ findings := parsed["findings"].([]interface{})
+ require.Len(t, findings, 2)
+
+ f1 := findings[0].(map[string]interface{})
+ assert.Equal(t, "f-1", f1["id"])
+ assert.Equal(t, "high-cpu", f1["key"])
+ assert.Equal(t, "warning", f1["severity"])
+
+ f2 := findings[1].(map[string]interface{})
+ assert.Equal(t, "f-2", f2["id"])
+ assert.Equal(t, "critical", f2["severity"])
+}
+
+func TestHandlePatrolGetFindings_WithFilters(t *testing.T) {
+ creator := &mockPatrolFindingCreator{
+ getActiveFn: func(resourceID, minSeverity string) []PatrolFindingInfo {
+ // Verify filters are passed through
+ return nil
+ },
+ }
+ exec := newPatrolTestExecutor(creator)
+
+ _, err := handlePatrolGetFindings(context.Background(), exec, map[string]interface{}{
+ "resource_id": "node/pve1",
+ "severity": "warning",
+ })
+ require.NoError(t, err)
+
+ require.Len(t, creator.getCalls, 1)
+ assert.Equal(t, "node/pve1", creator.getCalls[0].ResourceID)
+ assert.Equal(t, "warning", creator.getCalls[0].MinSeverity)
+}
+
+func TestHandlePatrolGetFindings_NoFilters(t *testing.T) {
+ creator := &mockPatrolFindingCreator{}
+ exec := newPatrolTestExecutor(creator)
+
+ _, err := handlePatrolGetFindings(context.Background(), exec, map[string]interface{}{})
+ require.NoError(t, err)
+
+ require.Len(t, creator.getCalls, 1)
+ assert.Equal(t, "", creator.getCalls[0].ResourceID)
+ assert.Equal(t, "", creator.getCalls[0].MinSeverity)
+}
+
+// --- SetPatrolFindingCreator tests ---
+
+func TestSetPatrolFindingCreator(t *testing.T) {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+
+ // Initially nil
+ assert.Nil(t, exec.GetPatrolFindingCreator())
+
+ // Set a creator
+ creator := &mockPatrolFindingCreator{}
+ exec.SetPatrolFindingCreator(creator)
+ assert.NotNil(t, exec.GetPatrolFindingCreator())
+
+ // Clear it
+ exec.SetPatrolFindingCreator(nil)
+ assert.Nil(t, exec.GetPatrolFindingCreator())
+}
+
+// --- Tool registration tests ---
+
+func TestPatrolToolsRegistered(t *testing.T) {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+
+ // Patrol tools should be registered but availability depends on patrolFindingCreator
+ tools := exec.registry.ListTools(ControlLevelReadOnly)
+ found := map[string]bool{}
+ for _, tool := range tools {
+ if tool.Name == "patrol_report_finding" || tool.Name == "patrol_resolve_finding" || tool.Name == "patrol_get_findings" {
+ found[tool.Name] = true
+ }
+ }
+
+ assert.True(t, found["patrol_report_finding"], "patrol_report_finding should be registered")
+ assert.True(t, found["patrol_resolve_finding"], "patrol_resolve_finding should be registered")
+ assert.True(t, found["patrol_get_findings"], "patrol_get_findings should be registered")
+}
+
+func TestPatrolToolsAvailability(t *testing.T) {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+
+ // Without creator, patrol tools should not be available
+ assert.False(t, exec.isToolAvailable("patrol_report_finding"))
+ assert.False(t, exec.isToolAvailable("patrol_resolve_finding"))
+ assert.False(t, exec.isToolAvailable("patrol_get_findings"))
+
+ // Set creator
+ exec.SetPatrolFindingCreator(&mockPatrolFindingCreator{})
+
+ // Now they should be available
+ assert.True(t, exec.isToolAvailable("patrol_report_finding"))
+ assert.True(t, exec.isToolAvailable("patrol_resolve_finding"))
+ assert.True(t, exec.isToolAvailable("patrol_get_findings"))
+}
+
+// --- Helper ---
+
+func extractText(result CallToolResult) string {
+ if len(result.Content) == 0 {
+ return ""
+ }
+ return result.Content[0].Text
+}