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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(eval): add patrol-specific eval scenarios and assertions
rcourtmanc409e7a05eda
diff --git a/cmd/eval/main.go b/cmd/eval/main.goindex 3bf8f345a5..b65ab7fd8d 100644--- a/cmd/eval/main.go+++ b/cmd/eval/main.go@@ -26,7 +26,7 @@ import ()func main() {- scenario := flag.String("scenario", "smoke", "Scenario to run: smoke, readonly, enforce, routing, routing-recovery, logs, readonly-recovery, search-id, disambiguate, context-target, discovery, writeverify, strict, strict-recovery, readonly-guardrails, noninteractive, approval, approval-deny, all")+ scenario := flag.String("scenario", "smoke", "Scenario to run: smoke, readonly, enforce, routing, routing-recovery, logs, readonly-recovery, search-id, disambiguate, context-target, discovery, writeverify, strict, strict-recovery, readonly-guardrails, noninteractive, approval, approval-deny, patrol, patrol-basic, patrol-investigation, patrol-finding-quality, all")url := flag.String("url", "http://127.0.0.1:7655", "Pulse API base URL")user := flag.String("user", "admin", "Username for auth")pass := flag.String("pass", "admin", "Password for auth")@@ -49,6 +49,33 @@ func main() {runner := eval.NewRunner(config)+ // Check for patrol scenarios first+ patrolScenarios := getPatrolScenarios(*scenario)+ if len(patrolScenarios) > 0 {+ allPassed := true+ for _, ps := range patrolScenarios {+ fmt.Printf("\n>>> Running patrol scenario: %s\n", ps.Name)+ fmt.Printf(">>> %s\n", ps.Description)++ result := runner.RunPatrolScenario(ps)+ runner.PrintPatrolSummary(result)++ if !result.Success {+ allPassed = false+ }+ }++ if allPassed {+ fmt.Printf("\n>>> ALL PATROL SCENARIOS PASSED\n")+ os.Exit(0)+ } else {+ fmt.Printf("\n>>> SOME PATROL SCENARIOS FAILED\n")+ os.Exit(1)+ }+ return+ }++ // Standard chat scenariosscenarios := getScenarios(*scenario)if len(scenarios) == 0 {fmt.Fprintf(os.Stderr, "Unknown scenario: %s\n", *scenario)@@ -110,6 +137,12 @@ func listScenarios() {fmt.Println(" approval - Approval flow (1 step, opt-in)")fmt.Println(" approval-deny - Approval deny flow (1 step, opt-in)")fmt.Println()+ fmt.Println(" Patrol:")+ fmt.Println(" patrol - Run all patrol scenarios")+ fmt.Println(" patrol-basic - Basic patrol run (completion, tools, findings)")+ fmt.Println(" patrol-investigation - Investigation quality (investigate before report)")+ fmt.Println(" patrol-finding-quality - Finding validation (well-formed findings)")+ fmt.Println()fmt.Println(" Collections:")fmt.Println(" all - Run all basic scenarios")fmt.Println(" advanced - Run all advanced scenarios")@@ -117,6 +150,22 @@ func listScenarios() {fmt.Println()fmt.Println("Example:")fmt.Println(" go run ./cmd/eval -scenario troubleshoot")+ fmt.Println(" go run ./cmd/eval -scenario patrol-basic")+}++func getPatrolScenarios(name string) []eval.PatrolScenario {+ switch name {+ case "patrol":+ return eval.AllPatrolScenarios()+ case "patrol-basic":+ return []eval.PatrolScenario{eval.PatrolBasicScenario()}+ case "patrol-investigation":+ return []eval.PatrolScenario{eval.PatrolInvestigationScenario()}+ case "patrol-finding-quality":+ return []eval.PatrolScenario{eval.PatrolFindingQualityScenario()}+ default:+ return nil+ }}func getScenarios(name string) []eval.Scenario {diff --git a/internal/ai/eval/eval_test.go b/internal/ai/eval/eval_test.goindex fc35cdeae0..e12239f803 100644--- a/internal/ai/eval/eval_test.go+++ b/internal/ai/eval/eval_test.go@@ -137,3 +137,78 @@ func TestAllScenarios(t *testing.T) {t.Fatal("One or more scenarios failed")}}++// TestPatrolBasic runs the basic patrol eval scenario+// Run with: go test -v ./internal/ai/eval -run TestPatrolBasic -live+func TestPatrolBasic(t *testing.T) {+ if !*runLiveEval {+ t.Skip("Skipping live eval test. Use -live flag to run against live Pulse API")+ }++ runner := NewRunner(DefaultConfig())+ result := runner.RunPatrolScenario(PatrolBasicScenario())+ runner.PrintPatrolSummary(result)++ if !result.Success {+ t.Fatalf("Patrol scenario '%s' failed", "Patrol Basic Run")+ }+}++// TestPatrolInvestigation runs the patrol investigation quality scenario+// Run with: go test -v ./internal/ai/eval -run TestPatrolInvestigation -live+func TestPatrolInvestigation(t *testing.T) {+ if !*runLiveEval {+ t.Skip("Skipping live eval test. Use -live flag to run against live Pulse API")+ }++ runner := NewRunner(DefaultConfig())+ result := runner.RunPatrolScenario(PatrolInvestigationScenario())+ runner.PrintPatrolSummary(result)++ if !result.Success {+ t.Fatalf("Patrol scenario '%s' failed", "Patrol Investigation Quality")+ }+}++// TestPatrolFindingQuality runs the patrol finding quality scenario+// Run with: go test -v ./internal/ai/eval -run TestPatrolFindingQuality -live+func TestPatrolFindingQuality(t *testing.T) {+ if !*runLiveEval {+ t.Skip("Skipping live eval test. Use -live flag to run against live Pulse API")+ }++ runner := NewRunner(DefaultConfig())+ result := runner.RunPatrolScenario(PatrolFindingQualityScenario())+ runner.PrintPatrolSummary(result)++ if !result.Success {+ t.Fatalf("Patrol scenario '%s' failed", "Patrol Finding Quality")+ }+}++// TestAllPatrolScenarios runs all patrol eval scenarios+// Run with: go test -v ./internal/ai/eval -run TestAllPatrolScenarios -live+func TestAllPatrolScenarios(t *testing.T) {+ if !*runLiveEval {+ t.Skip("Skipping live eval test. Use -live flag to run against live Pulse API")+ }++ runner := NewRunner(DefaultConfig())++ allPassed := true+ for _, scenario := range AllPatrolScenarios() {+ t.Run(scenario.Name, func(t *testing.T) {+ result := runner.RunPatrolScenario(scenario)+ runner.PrintPatrolSummary(result)++ if !result.Success {+ allPassed = false+ t.Errorf("Patrol scenario '%s' failed", scenario.Name)+ }+ })+ }++ if !allPassed {+ t.Fatal("One or more patrol scenarios failed")+ }+}diff --git a/internal/ai/eval/patrol.go b/internal/ai/eval/patrol.gonew file mode 100644index 0000000000..9604baa67c--- /dev/null+++ b/internal/ai/eval/patrol.go@@ -0,0 +1,455 @@+package eval++import (+ "bufio"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"+)++// PatrolScenario defines a patrol eval scenario.+type PatrolScenario struct {+ Name string+ Description string+ Setup func(r *Runner) error // optional pre-run setup+ Teardown func(r *Runner) error // optional post-run cleanup+ Assertions []PatrolAssertion+ Deep bool // trigger deep patrol+ Timeout time.Duration // default 5m+}++// PatrolRunResult captures complete patrol execution trace.+type PatrolRunResult struct {+ ScenarioName string+ Success bool+ Error error+ Duration time.Duration+ ToolCalls []ToolCallEvent+ Findings []PatrolFinding+ Content string+ RawEvents []PatrolSSEEvent+ Assertions []AssertionResult+}++// PatrolFinding mirrors the Finding JSON from the API.+type PatrolFinding struct {+ ID string `json:"id"`+ 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"`+ Evidence string `json:"evidence"`+}++// PatrolAssertion checks a PatrolRunResult.+type PatrolAssertion func(result *PatrolRunResult) AssertionResult++// PatrolSSEEvent represents a raw SSE event from the patrol stream.+type PatrolSSEEvent struct {+ Type string `json:"type"`+ Content string `json:"content,omitempty"`+ Phase string `json:"phase,omitempty"`+ Tokens int `json:"tokens,omitempty"`+ ToolID string `json:"tool_id,omitempty"`+ ToolName string `json:"tool_name,omitempty"`+ ToolInput string `json:"tool_input,omitempty"`+ ToolOutput string `json:"tool_output,omitempty"`+ ToolSuccess *bool `json:"tool_success,omitempty"`+}++// RunPatrolScenario executes a patrol scenario and returns the results.+func (r *Runner) RunPatrolScenario(scenario PatrolScenario) PatrolRunResult {+ startTime := time.Now()+ result := PatrolRunResult{+ ScenarioName: scenario.Name,+ Success: true,+ }++ timeout := scenario.Timeout+ if timeout == 0 {+ timeout = 5 * time.Minute+ }+ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()++ // Run optional setup+ if scenario.Setup != nil {+ if err := scenario.Setup(r); err != nil {+ result.Error = fmt.Errorf("setup failed: %w", err)+ result.Success = false+ result.Duration = time.Since(startTime)+ return result+ }+ }++ // Run optional teardown on exit+ if scenario.Teardown != nil {+ defer func() {+ if err := scenario.Teardown(r); err != nil {+ fmt.Printf(" [WARN] Teardown error: %v\n", err)+ }+ }()+ }++ // Wait for patrol to be idle before starting+ if err := r.waitForPatrolIdle(ctx); err != nil {+ result.Error = fmt.Errorf("waiting for patrol idle: %w", err)+ result.Success = false+ result.Duration = time.Since(startTime)+ return result+ }++ // Connect to SSE stream before triggering (to catch "start" event)+ streamBody, err := r.connectPatrolStream(ctx)+ if err != nil {+ result.Error = fmt.Errorf("connecting to patrol stream: %w", err)+ result.Success = false+ result.Duration = time.Since(startTime)+ return result+ }+ defer streamBody.Close()++ // Trigger patrol run+ if err := r.triggerPatrolRun(scenario.Deep); err != nil {+ result.Error = fmt.Errorf("triggering patrol run: %w", err)+ result.Success = false+ result.Duration = time.Since(startTime)+ return result+ }++ if r.config.Verbose {+ fmt.Printf(" Patrol triggered (deep=%v), reading SSE stream...\n", scenario.Deep)+ }++ // Parse SSE stream until complete/error/timeout+ rawEvents, toolCalls, content, streamErr := r.parsePatrolSSEStream(ctx, streamBody)+ result.RawEvents = rawEvents+ result.ToolCalls = toolCalls+ result.Content = content+ if streamErr != nil {+ result.Error = streamErr+ result.Success = false+ }++ // Fetch findings from REST API+ findings, findErr := r.fetchPatrolFindings()+ if findErr != nil {+ if result.Error == nil {+ result.Error = fmt.Errorf("fetching findings: %w", findErr)+ }+ }+ result.Findings = findings++ // Run assertions+ for _, assertion := range scenario.Assertions {+ assertResult := assertion(&result)+ result.Assertions = append(result.Assertions, assertResult)+ if !assertResult.Passed {+ result.Success = false+ }+ }++ result.Duration = time.Since(startTime)+ return result+}++// waitForPatrolIdle polls GET /api/ai/patrol/status until Running=false.+func (r *Runner) waitForPatrolIdle(ctx context.Context) error {+ for {+ select {+ case <-ctx.Done():+ return fmt.Errorf("timeout waiting for patrol idle")+ default:+ }++ req, err := http.NewRequestWithContext(ctx, "GET", r.config.BaseURL+"/api/ai/patrol/status", nil)+ if err != nil {+ return err+ }+ req.SetBasicAuth(r.config.Username, r.config.Password)++ resp, err := r.client.Do(req)+ if err != nil {+ return err+ }++ var status struct {+ Running bool `json:"running"`+ }+ json.NewDecoder(resp.Body).Decode(&status)+ resp.Body.Close()++ if !status.Running {+ return nil+ }++ if r.config.Verbose {+ fmt.Printf(" Patrol is running, waiting...\n")+ }++ select {+ case <-ctx.Done():+ return fmt.Errorf("timeout waiting for patrol idle")+ case <-time.After(3 * time.Second):+ }+ }+}++// triggerPatrolRun triggers POST /api/ai/patrol/run.+func (r *Runner) triggerPatrolRun(deep bool) error {+ url := r.config.BaseURL + "/api/ai/patrol/run"+ if deep {+ url += "?deep=true"+ }++ req, err := http.NewRequest("POST", url, nil)+ if err != nil {+ return err+ }+ req.SetBasicAuth(r.config.Username, r.config.Password)++ resp, err := r.client.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("patrol run returned status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ }+ return nil+}++// fetchPatrolFindings fetches GET /api/ai/patrol/findings.+func (r *Runner) fetchPatrolFindings() ([]PatrolFinding, error) {+ req, err := http.NewRequest("GET", r.config.BaseURL+"/api/ai/patrol/findings", nil)+ if err != nil {+ return nil, err+ }+ req.SetBasicAuth(r.config.Username, r.config.Password)++ resp, err := r.client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(resp.Body)+ return nil, fmt.Errorf("findings returned status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ }++ var findings []PatrolFinding+ if err := json.NewDecoder(resp.Body).Decode(&findings); err != nil {+ return nil, fmt.Errorf("decoding findings: %w", err)+ }+ return findings, nil+}++// connectPatrolStream opens GET /api/ai/patrol/stream SSE connection.+func (r *Runner) connectPatrolStream(ctx context.Context) (io.ReadCloser, error) {+ req, err := http.NewRequestWithContext(ctx, "GET", r.config.BaseURL+"/api/ai/patrol/stream", nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Accept", "text/event-stream")+ req.SetBasicAuth(r.config.Username, r.config.Password)++ // Use a client without the default timeout for streaming+ streamClient := &http.Client{}+ resp, err := streamClient.Do(req)+ if err != nil {+ return nil, err+ }++ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(resp.Body)+ resp.Body.Close()+ return nil, fmt.Errorf("stream returned status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ }++ return resp.Body, nil+}++// parsePatrolSSEStream reads patrol SSE events and extracts tool calls + content.+// Patrol SSE events are flat JSON objects (not nested like chat SSE).+func (r *Runner) parsePatrolSSEStream(ctx context.Context, body io.Reader) ([]PatrolSSEEvent, []ToolCallEvent, string, error) {+ var events []PatrolSSEEvent+ var toolCalls []ToolCallEvent+ var contentBuilder strings.Builder++ // Track tool calls in progress (by ID)+ toolCallsInProgress := make(map[string]*ToolCallEvent)++ scanner := bufio.NewScanner(body)+ const maxSSEEventSize = 8 * 1024 * 1024+ scanner.Buffer(make([]byte, 0, 64*1024), maxSSEEventSize)++ done := make(chan struct{})+ var scanErr error++ go func() {+ defer close(done)+ for scanner.Scan() {+ line := scanner.Text()++ if !strings.HasPrefix(line, "data: ") {+ continue+ }++ data := strings.TrimPrefix(line, "data: ")+ if data == "" {+ continue+ }++ var event PatrolSSEEvent+ if err := json.Unmarshal([]byte(data), &event); err != nil {+ continue+ }++ events = append(events, event)++ if r.config.Verbose {+ switch event.Type {+ case "start":+ fmt.Printf(" [SSE] Patrol started\n")+ case "phase":+ fmt.Printf(" [SSE] Phase: %s\n", event.Phase)+ case "tool_start":+ fmt.Printf(" [SSE] Tool start: %s\n", event.ToolName)+ case "tool_end":+ status := "OK"+ if event.ToolSuccess != nil && !*event.ToolSuccess {+ status = "FAILED"+ }+ fmt.Printf(" [SSE] Tool end: %s [%s]\n", event.ToolName, status)+ case "complete":+ fmt.Printf(" [SSE] Patrol complete\n")+ case "error":+ fmt.Printf(" [SSE] Error: %s\n", event.Content)+ }+ }++ switch event.Type {+ case "content":+ contentBuilder.WriteString(event.Content)++ case "tool_start":+ toolCallsInProgress[event.ToolID] = &ToolCallEvent{+ ID: event.ToolID,+ Name: event.ToolName,+ Input: event.ToolInput,+ }++ case "tool_end":+ success := event.ToolSuccess != nil && *event.ToolSuccess+ if tc, ok := toolCallsInProgress[event.ToolID]; ok {+ tc.Output = event.ToolOutput+ tc.Success = success+ toolCalls = append(toolCalls, *tc)+ delete(toolCallsInProgress, event.ToolID)+ } else {+ // tool_end without matching tool_start+ toolCalls = append(toolCalls, ToolCallEvent{+ ID: event.ToolID,+ Name: event.ToolName,+ Input: event.ToolInput,+ Output: event.ToolOutput,+ Success: success,+ })+ }++ case "complete":+ return++ case "error":+ scanErr = fmt.Errorf("patrol error: %s", event.Content)+ return+ }+ }+ if err := scanner.Err(); err != nil {+ scanErr = err+ }+ }()++ select {+ case <-ctx.Done():+ return events, toolCalls, contentBuilder.String(), fmt.Errorf("timeout reading patrol stream")+ case <-done:+ return events, toolCalls, contentBuilder.String(), scanErr+ }+}++// PrintPatrolSummary prints a summary of the patrol run result.+func (r *Runner) PrintPatrolSummary(result PatrolRunResult) {+ fmt.Printf("\n")+ fmt.Printf("========================================\n")+ fmt.Printf("PATROL SCENARIO: %s\n", result.ScenarioName)+ fmt.Printf("========================================\n")+ fmt.Printf("Duration: %v\n", result.Duration)++ if result.Error != nil {+ fmt.Printf("ERROR: %v\n", result.Error)+ }++ if len(result.ToolCalls) > 0 {+ fmt.Printf("\nTool Calls (%d):\n", len(result.ToolCalls))+ for _, tc := range result.ToolCalls {+ status := "OK"+ if !tc.Success {+ status = "FAILED"+ }+ fmt.Printf(" - %s [%s]: %s\n", tc.Name, status, truncate(tc.Input, 80))+ if !tc.Success || r.config.Verbose {+ fmt.Printf(" Output: %s\n", truncate(tc.Output, 200))+ }+ }+ }++ if len(result.Findings) > 0 {+ fmt.Printf("\nFindings (%d):\n", len(result.Findings))+ for _, f := range result.Findings {+ fmt.Printf(" - [%s] %s: %s\n", f.Severity, f.Key, f.Title)+ }+ }++ if result.Content != "" && r.config.Verbose {+ fmt.Printf("\nContent:\n%s\n", truncate(result.Content, 500))+ }++ if len(result.Assertions) > 0 {+ fmt.Printf("\nAssertions:\n")+ for _, a := range result.Assertions {+ status := "PASS"+ if !a.Passed {+ status = "FAIL"+ }+ fmt.Printf(" [%s] %s: %s\n", status, a.Name, a.Message)+ }+ }++ if result.Success {+ fmt.Printf("\nResult: PASSED\n")+ } else {+ fmt.Printf("\nResult: FAILED\n")+ if len(result.Assertions) > 0 {+ fmt.Printf("\nFailures:\n")+ for _, a := range result.Assertions {+ if !a.Passed {+ fmt.Printf(" Assertion '%s': %s\n", a.Name, a.Message)+ }+ }+ }+ }+ fmt.Printf("========================================\n")+}diff --git a/internal/ai/eval/patrol_assertions.go b/internal/ai/eval/patrol_assertions.gonew file mode 100644index 0000000000..e26ec63a6a--- /dev/null+++ b/internal/ai/eval/patrol_assertions.go@@ -0,0 +1,470 @@+package eval++import (+ "encoding/json"+ "fmt"+ "strings"+ "time"+)++// === Execution Assertions ===++// PatrolAssertNoError checks that no execution/network error occurred.+func PatrolAssertNoError() PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ if result.Error == nil {+ return AssertionResult{+ Name: "no_error",+ Passed: true,+ Message: "No execution error",+ }+ }+ return AssertionResult{+ Name: "no_error",+ Passed: false,+ Message: fmt.Sprintf("Execution error: %v", result.Error),+ }+ }+}++// PatrolAssertCompleted checks that the patrol SSE stream included a "complete" event.+func PatrolAssertCompleted() PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ for _, e := range result.RawEvents {+ if e.Type == "complete" {+ return AssertionResult{+ Name: "completed",+ Passed: true,+ Message: "Patrol completed successfully",+ }+ }+ }+ return AssertionResult{+ Name: "completed",+ Passed: false,+ Message: "Patrol did not emit a 'complete' event",+ }+ }+}++// PatrolAssertDurationUnder checks that the total run time is under the given max.+func PatrolAssertDurationUnder(max time.Duration) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ if result.Duration <= max {+ return AssertionResult{+ Name: fmt.Sprintf("duration_under:%v", max),+ Passed: true,+ Message: fmt.Sprintf("Completed in %v (max: %v)", result.Duration.Round(time.Second), max),+ }+ }+ return AssertionResult{+ Name: fmt.Sprintf("duration_under:%v", max),+ Passed: false,+ Message: fmt.Sprintf("Took %v which exceeds max of %v", result.Duration.Round(time.Second), max),+ }+ }+}++// === Tool Usage Assertions ===++// PatrolAssertToolUsed checks that a tool was called at least once.+func PatrolAssertToolUsed(toolName string) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ for _, tc := range result.ToolCalls {+ if tc.Name == toolName {+ return AssertionResult{+ Name: fmt.Sprintf("tool_used:%s", toolName),+ Passed: true,+ Message: fmt.Sprintf("Tool '%s' was called", toolName),+ }+ }+ }+ return AssertionResult{+ Name: fmt.Sprintf("tool_used:%s", toolName),+ Passed: false,+ Message: fmt.Sprintf("Tool '%s' was NOT called. Tools used: %v", toolName, patrolGetToolNames(result.ToolCalls)),+ }+ }+}++// PatrolAssertToolUsedAny checks that at least one of the given tools was called.+func PatrolAssertToolUsedAny(toolNames ...string) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ for _, tc := range result.ToolCalls {+ for _, name := range toolNames {+ if tc.Name == name {+ return AssertionResult{+ Name: "tool_used_any",+ Passed: true,+ Message: fmt.Sprintf("Tool '%s' was called", name),+ }+ }+ }+ }+ return AssertionResult{+ Name: "tool_used_any",+ Passed: false,+ Message: fmt.Sprintf("None of %v were called. Tools used: %v", toolNames, patrolGetToolNames(result.ToolCalls)),+ }+ }+}++// PatrolAssertMinToolCalls checks that the total tool call count is at least min.+func PatrolAssertMinToolCalls(min int) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ if len(result.ToolCalls) >= min {+ return AssertionResult{+ Name: fmt.Sprintf("min_tool_calls:%d", min),+ Passed: true,+ Message: fmt.Sprintf("%d tool calls made (min: %d)", len(result.ToolCalls), min),+ }+ }+ return AssertionResult{+ Name: fmt.Sprintf("min_tool_calls:%d", min),+ Passed: false,+ Message: fmt.Sprintf("Only %d tool calls made (expected at least %d)", len(result.ToolCalls), min),+ }+ }+}++// PatrolAssertNoToolErrors checks that all tool calls succeeded.+func PatrolAssertNoToolErrors() PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ var failures []string+ for _, tc := range result.ToolCalls {+ if !tc.Success {+ failures = append(failures, fmt.Sprintf("%s: %s", tc.Name, truncate(tc.Output, 100)))+ }+ }+ if len(failures) == 0 {+ return AssertionResult{+ Name: "no_tool_errors",+ Passed: true,+ Message: "All tool calls succeeded",+ }+ }+ return AssertionResult{+ Name: "no_tool_errors",+ Passed: false,+ Message: fmt.Sprintf("Tool failures: %v", failures),+ }+ }+}++// PatrolAssertToolSequence checks that tools were called in the given order (non-contiguous).+func PatrolAssertToolSequence(sequence []string) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ if len(sequence) == 0 {+ return AssertionResult{+ Name: "tool_sequence",+ Passed: true,+ Message: "No sequence required",+ }+ }++ seqIdx := 0+ for _, tc := range result.ToolCalls {+ if tc.Name == sequence[seqIdx] {+ seqIdx+++ if seqIdx == len(sequence) {+ return AssertionResult{+ Name: "tool_sequence",+ Passed: true,+ Message: fmt.Sprintf("Tool sequence matched: %v", sequence),+ }+ }+ }+ }++ return AssertionResult{+ Name: "tool_sequence",+ Passed: false,+ Message: fmt.Sprintf("Tool sequence not found. Expected: %v, got: %v", sequence, patrolGetToolNames(result.ToolCalls)),+ }+ }+}++// PatrolAssertToolInputContains checks that a tool's input contains a substring.+func PatrolAssertToolInputContains(toolName, substring string) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ for _, tc := range result.ToolCalls {+ if tc.Name != toolName {+ continue+ }+ if strings.Contains(strings.ToLower(tc.Input), strings.ToLower(substring)) {+ return AssertionResult{+ Name: fmt.Sprintf("tool_input:%s_contains:%s", toolName, truncate(substring, 20)),+ Passed: true,+ Message: fmt.Sprintf("Tool '%s' input contains '%s'", toolName, substring),+ }+ }+ }+ return AssertionResult{+ Name: fmt.Sprintf("tool_input:%s_contains:%s", toolName, truncate(substring, 20)),+ Passed: false,+ Message: fmt.Sprintf("No '%s' call input contains '%s'", toolName, substring),+ }+ }+}++// === Finding Assertions (from REST API results) ===++// PatrolAssertHasFindings checks that at least one finding exists.+func PatrolAssertHasFindings() PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ if len(result.Findings) > 0 {+ return AssertionResult{+ Name: "has_findings",+ Passed: true,+ Message: fmt.Sprintf("%d finding(s) present", len(result.Findings)),+ }+ }+ return AssertionResult{+ Name: "has_findings",+ Passed: false,+ Message: "No findings were produced",+ }+ }+}++// PatrolAssertFindingCount checks that the finding count is within [min, max].+func PatrolAssertFindingCount(minCount, maxCount int) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ count := len(result.Findings)+ if count >= minCount && count <= maxCount {+ return AssertionResult{+ Name: fmt.Sprintf("finding_count:%d-%d", minCount, maxCount),+ Passed: true,+ Message: fmt.Sprintf("%d findings (range: %d-%d)", count, minCount, maxCount),+ }+ }+ return AssertionResult{+ Name: fmt.Sprintf("finding_count:%d-%d", minCount, maxCount),+ Passed: false,+ Message: fmt.Sprintf("%d findings outside range %d-%d", count, minCount, maxCount),+ }+ }+}++// PatrolAssertAllFindingsValid checks that every finding has non-empty required fields.+func PatrolAssertAllFindingsValid() PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ if len(result.Findings) == 0 {+ return AssertionResult{+ Name: "all_findings_valid",+ Passed: true,+ Message: "No findings to validate",+ }+ }++ var issues []string+ for i, f := range result.Findings {+ if f.Key == "" {+ issues = append(issues, fmt.Sprintf("finding[%d]: missing key", i))+ }+ if f.Severity == "" {+ issues = append(issues, fmt.Sprintf("finding[%d]: missing severity", i))+ }+ if f.Title == "" {+ issues = append(issues, fmt.Sprintf("finding[%d]: missing title", i))+ }+ if f.Description == "" {+ issues = append(issues, fmt.Sprintf("finding[%d]: missing description", i))+ }+ if f.ResourceType == "" {+ issues = append(issues, fmt.Sprintf("finding[%d]: missing resource_type", i))+ }+ }++ if len(issues) == 0 {+ return AssertionResult{+ Name: "all_findings_valid",+ Passed: true,+ Message: fmt.Sprintf("All %d findings have required fields", len(result.Findings)),+ }+ }+ return AssertionResult{+ Name: "all_findings_valid",+ Passed: false,+ Message: fmt.Sprintf("Invalid findings: %s", strings.Join(issues, "; ")),+ }+ }+}++// PatrolAssertFindingSeveritiesValid checks that all findings use valid severity values.+func PatrolAssertFindingSeveritiesValid() PatrolAssertion {+ validSeverities := map[string]bool{+ "critical": true,+ "high": true,+ "medium": true,+ "low": true,+ "info": true,+ }+ return func(result *PatrolRunResult) AssertionResult {+ var invalid []string+ for _, f := range result.Findings {+ if !validSeverities[strings.ToLower(f.Severity)] {+ invalid = append(invalid, fmt.Sprintf("%s (severity=%q)", f.Key, f.Severity))+ }+ }+ if len(invalid) == 0 {+ return AssertionResult{+ Name: "finding_severities_valid",+ Passed: true,+ Message: "All finding severities are valid",+ }+ }+ return AssertionResult{+ Name: "finding_severities_valid",+ Passed: false,+ Message: fmt.Sprintf("Invalid severities: %v", invalid),+ }+ }+}++// PatrolAssertFindingCategoriesValid checks that all findings use valid category values.+func PatrolAssertFindingCategoriesValid() PatrolAssertion {+ validCategories := map[string]bool{+ "performance": true,+ "security": true,+ "availability": true,+ "configuration": true,+ "resource_usage": true,+ "best_practice": true,+ "health": true,+ "storage": true,+ "network": true,+ "update": true,+ }+ return func(result *PatrolRunResult) AssertionResult {+ var invalid []string+ for _, f := range result.Findings {+ if f.Category != "" && !validCategories[strings.ToLower(f.Category)] {+ invalid = append(invalid, fmt.Sprintf("%s (category=%q)", f.Key, f.Category))+ }+ }+ if len(invalid) == 0 {+ return AssertionResult{+ Name: "finding_categories_valid",+ Passed: true,+ Message: "All finding categories are valid",+ }+ }+ return AssertionResult{+ Name: "finding_categories_valid",+ Passed: false,+ Message: fmt.Sprintf("Invalid categories: %v", invalid),+ }+ }+}++// PatrolAssertFindingWithKey checks that a finding with the given key exists.+func PatrolAssertFindingWithKey(key string) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ for _, f := range result.Findings {+ if strings.EqualFold(f.Key, key) {+ return AssertionResult{+ Name: fmt.Sprintf("finding_with_key:%s", key),+ Passed: true,+ Message: fmt.Sprintf("Finding with key '%s' exists", key),+ }+ }+ }+ return AssertionResult{+ Name: fmt.Sprintf("finding_with_key:%s", key),+ Passed: false,+ Message: fmt.Sprintf("No finding with key '%s'", key),+ }+ }+}++// PatrolAssertNoFindingWithKey checks that no finding with the given key exists.+func PatrolAssertNoFindingWithKey(key string) PatrolAssertion {+ return func(result *PatrolRunResult) AssertionResult {+ for _, f := range result.Findings {+ if strings.EqualFold(f.Key, key) {+ return AssertionResult{+ Name: fmt.Sprintf("no_finding_with_key:%s", key),+ Passed: false,+ Message: fmt.Sprintf("Finding with key '%s' exists but should not", key),+ }+ }+ }+ return AssertionResult{+ Name: fmt.Sprintf("no_finding_with_key:%s", key),+ Passed: true,+ Message: fmt.Sprintf("No finding with key '%s' (as expected)", key),+ }+ }+}++// === Finding Tool Call Assertions ===++// PatrolAssertReportFindingFieldsPresent checks that every patrol_report_finding+// tool call includes all required fields in input.+func PatrolAssertReportFindingFieldsPresent() PatrolAssertion {+ requiredFields := []string{"key", "severity", "title", "description", "resource_type"}+ return func(result *PatrolRunResult) AssertionResult {+ reportCalls := 0+ var issues []string++ for _, tc := range result.ToolCalls {+ if tc.Name != "patrol_report_finding" {+ continue+ }+ reportCalls++++ // Try to parse input as JSON to check fields+ var inputMap map[string]interface{}+ if err := json.Unmarshal([]byte(tc.Input), &inputMap); err != nil {+ // Fall back to substring check+ for _, field := range requiredFields {+ if !strings.Contains(tc.Input, field) {+ issues = append(issues, fmt.Sprintf("call %d missing '%s'", reportCalls, field))+ }+ }+ continue+ }++ for _, field := range requiredFields {+ val, ok := inputMap[field]+ if !ok {+ issues = append(issues, fmt.Sprintf("call %d missing '%s'", reportCalls, field))+ } else if str, isStr := val.(string); isStr && str == "" {+ issues = append(issues, fmt.Sprintf("call %d has empty '%s'", reportCalls, field))+ }+ }+ }++ if reportCalls == 0 {+ return AssertionResult{+ Name: "report_finding_fields_present",+ Passed: true,+ Message: "No patrol_report_finding calls to validate",+ }+ }++ if len(issues) == 0 {+ return AssertionResult{+ Name: "report_finding_fields_present",+ Passed: true,+ Message: fmt.Sprintf("All %d patrol_report_finding calls have required fields", reportCalls),+ }+ }+ return AssertionResult{+ Name: "report_finding_fields_present",+ Passed: false,+ Message: fmt.Sprintf("Missing fields: %s", strings.Join(issues, "; ")),+ }+ }+}++// === Helpers ===++func patrolGetToolNames(toolCalls []ToolCallEvent) []string {+ names := make([]string, len(toolCalls))+ for i, tc := range toolCalls {+ names[i] = tc.Name+ }+ return names+}diff --git a/internal/ai/eval/patrol_scenarios.go b/internal/ai/eval/patrol_scenarios.gonew file mode 100644index 0000000000..6103104000--- /dev/null+++ b/internal/ai/eval/patrol_scenarios.go@@ -0,0 +1,60 @@+package eval++import "time"++// PatrolBasicScenario tests basic patrol run: completion, tool usage, and findings interaction.+func PatrolBasicScenario() PatrolScenario {+ return PatrolScenario{+ Name: "Patrol Basic Run",+ Description: "Does patrol run to completion, use tools, and interact with the findings system?",+ Assertions: []PatrolAssertion{+ PatrolAssertNoError(),+ PatrolAssertCompleted(),+ PatrolAssertMinToolCalls(3),+ PatrolAssertToolUsed("pulse_query"),+ PatrolAssertToolUsedAny("patrol_report_finding", "patrol_get_findings"),+ PatrolAssertDurationUnder(4 * time.Minute),+ },+ }+}++// PatrolInvestigationScenario tests investigation quality:+// does patrol investigate before reporting and check existing findings?+func PatrolInvestigationScenario() PatrolScenario {+ return PatrolScenario{+ Name: "Patrol Investigation Quality",+ Description: "Does patrol investigate before reporting, and check existing findings?",+ Assertions: []PatrolAssertion{+ PatrolAssertNoError(),+ PatrolAssertCompleted(),+ PatrolAssertToolUsedAny("pulse_query", "pulse_metrics", "pulse_storage"),+ PatrolAssertToolUsed("patrol_get_findings"),+ PatrolAssertNoToolErrors(),+ },+ }+}++// PatrolFindingQualityScenario tests that reported findings are well-formed.+func PatrolFindingQualityScenario() PatrolScenario {+ return PatrolScenario{+ Name: "Patrol Finding Quality",+ Description: "Are reported findings well-formed with valid fields?",+ Assertions: []PatrolAssertion{+ PatrolAssertNoError(),+ PatrolAssertCompleted(),+ PatrolAssertAllFindingsValid(),+ PatrolAssertFindingSeveritiesValid(),+ PatrolAssertFindingCategoriesValid(),+ PatrolAssertReportFindingFieldsPresent(),+ },+ }+}++// AllPatrolScenarios returns all patrol scenarios.+func AllPatrolScenarios() []PatrolScenario {+ return []PatrolScenario{+ PatrolBasicScenario(),+ PatrolInvestigationScenario(),+ PatrolFindingQualityScenario(),+ }+}