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
Add pure branch-coverage tests for the fresh Patrol and Docker drop
rcourtmanc2b8d6b9a08d
diff --git a/internal/ai/chat/agentic_investigation_budget_w0716_coverage_test.go b/internal/ai/chat/agentic_investigation_budget_w0716_coverage_test.gonew file mode 100644index 0000000000..151328c4b8--- /dev/null+++ b/internal/ai/chat/agentic_investigation_budget_w0716_coverage_test.go@@ -0,0 +1,279 @@+package chat++import (+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"+)++// msgWithResult builds a providers.Message carrying a non-nil tool result so+// appendInvestigationBudgetMessage has something to mutate.+func msgWithResult(id, content string, isError bool) providers.Message {+ return providers.Message{+ Role: "user",+ ToolResult: &providers.ToolResult{ToolUseID: id, Content: content, IsError: isError},+ }+}++func Test_w0716_budget_IsPatrolInvestigationExecution(t *testing.T) {+ tests := []struct {+ name string+ profile tools.ExecutionProfile+ want bool+ }{+ {name: "investigation profile matches", profile: tools.ProfilePatrolInvestigation, want: true},+ {name: "interactive assistant is not investigation", profile: tools.ProfileInteractiveAssistant, want: false},+ {name: "patrol detection is not investigation", profile: tools.ProfilePatrolDetection, want: false},+ {name: "zero value falls through to interactive", profile: tools.ProfileInteractiveAssistant, want: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := isPatrolInvestigationExecution(tt.profile); got != tt.want {+ t.Fatalf("isPatrolInvestigationExecution(%v) = %v, want %v", tt.profile, got, tt.want)+ }+ })+ }+}++func Test_w0716_budget_IsInvestigationEvidenceTool(t *testing.T) {+ tests := []struct {+ name string+ in string+ want bool+ }{+ {name: "read-only query consumes evidence budget", in: agentcapabilities.PulseQueryToolName, want: true},+ {name: "arbitrary evidence tool consumes budget", in: "pulse_read", want: true},+ {name: "terminal proposal does not consume budget", in: agentcapabilities.PatrolProposeActionToolName, want: false},+ {name: "whitespace-padded proposal still not evidence", in: " " + agentcapabilities.PatrolProposeActionToolName + "\t", want: false},+ {name: "empty name treated as evidence tool", in: "", want: true},+ {name: "only-whitespace name treated as evidence tool", in: " ", want: true},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := isInvestigationEvidenceTool(tt.in); got != tt.want {+ t.Fatalf("isInvestigationEvidenceTool(%q) = %v, want %v", tt.in, got, tt.want)+ }+ })+ }+}++func Test_w0716_budget_InvestigationTerminalTools(t *testing.T) {+ proposal := providers.Tool{Name: agentcapabilities.PatrolProposeActionToolName}+ query := providers.Tool{Name: agentcapabilities.PulseQueryToolName}+ caps := providers.Tool{Name: agentcapabilities.PatrolActionCapabilitiesToolName}++ tests := []struct {+ name string+ available []providers.Tool+ wantFound bool+ wantName string+ }{+ {name: "empty input returns nil", available: nil, wantFound: false},+ {name: "no terminal tool available returns nil", available: []providers.Tool{query, caps}, wantFound: false},+ {name: "terminal tool at index zero", available: []providers.Tool{proposal, query}, wantFound: true, wantName: agentcapabilities.PatrolProposeActionToolName},+ {name: "terminal tool in middle", available: []providers.Tool{query, proposal, caps}, wantFound: true, wantName: agentcapabilities.PatrolProposeActionToolName},+ {name: "terminal tool at end", available: []providers.Tool{query, caps, proposal}, wantFound: true, wantName: agentcapabilities.PatrolProposeActionToolName},+ {name: "duplicate terminal tools returns only the first", available: []providers.Tool{proposal, proposal}, wantFound: true, wantName: agentcapabilities.PatrolProposeActionToolName},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := investigationTerminalTools(tt.available)+ if !tt.wantFound {+ if got != nil {+ t.Fatalf("investigationTerminalTools() = %+v, want nil", got)+ }+ return+ }+ if len(got) != 1 {+ t.Fatalf("investigationTerminalTools() len = %d, want 1 (only patrol_propose_action): %+v", len(got), got)+ }+ if got[0].Name != tt.wantName {+ t.Fatalf("investigationTerminalTools()[0].Name = %q, want %q", got[0].Name, tt.wantName)+ }+ })+ }+}++func Test_w0716_budget_InvestigationEvidenceCheckpoint(t *testing.T) {+ tests := []struct {+ name string+ max int+ want int+ }{+ {name: "zero max clamps to floor", max: 0, want: 3},+ {name: "negative max clamps to floor", max: -5, want: 3},+ {name: "max 1 clamps to floor", max: 1, want: 3},+ {name: "max 4 half-rounded-down still clamps", max: 4, want: 3},+ {name: "max 5 hits floor via normal path", max: 5, want: 3},+ {name: "max 6 still at floor", max: 6, want: 3},+ {name: "max 7 exceeds floor", max: 7, want: 4},+ {name: "max 15 halves up", max: 15, want: 8},+ {name: "large budget halves", max: 100, want: 50},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := investigationEvidenceCheckpoint(tt.max); got != tt.want {+ t.Fatalf("investigationEvidenceCheckpoint(%d) = %d, want %d", tt.max, got, tt.want)+ }+ })+ }+}++func Test_w0716_budget_AppendInvestigationBudgetMessage(t *testing.T) {+ const guidance = "[budget note]"++ t.Run("empty messages returns false and mutates nothing", func(t *testing.T) {+ var msgs []providers.Message+ if appendInvestigationBudgetMessage(msgs, guidance, "phase") {+ t.Fatal("expected false on empty messages")+ }+ })++ t.Run("only nil tool results returns false", func(t *testing.T) {+ msgs := []providers.Message{+ {Role: "user", Content: "plain"},+ {Role: "assistant", Content: "prose"},+ }+ if appendInvestigationBudgetMessage(msgs, guidance, "phase") {+ t.Fatal("expected false when no message carries a tool result")+ }+ if msgs[0].Content != "plain" || msgs[1].Content != "prose" {+ t.Fatalf("non-result content was mutated: %+v", msgs)+ }+ })++ t.Run("only error tool results returns false", func(t *testing.T) {+ msgs := []providers.Message{msgWithResult("err-1", "boom", true)}+ if appendInvestigationBudgetMessage(msgs, guidance, "phase") {+ t.Fatal("expected false when the only result is an error")+ }+ if msgs[0].ToolResult.Content != "boom" {+ t.Fatalf("error result content was mutated: %q", msgs[0].ToolResult.Content)+ }+ })++ t.Run("appends guidance to the most recent non-error result only", func(t *testing.T) {+ msgs := []providers.Message{+ msgWithResult("ok-early", "early-ok", false),+ msgWithResult("err-mid", "mid-err", true),+ msgWithResult("ok-late", "late-ok", false),+ }+ if !appendInvestigationBudgetMessage(msgs, guidance, "phase") {+ t.Fatal("expected true when a non-error result exists")+ }+ wantEarly := "early-ok"+ wantLate := "late-ok" + "\n\n" + guidance+ if msgs[0].ToolResult.Content != wantEarly {+ t.Fatalf("earlier non-error result was mutated: got %q, want %q", msgs[0].ToolResult.Content, wantEarly)+ }+ if msgs[2].ToolResult.Content != wantLate {+ t.Fatalf("latest non-error result = %q, want %q", msgs[2].ToolResult.Content, wantLate)+ }+ if msgs[1].ToolResult.Content != "mid-err" {+ t.Fatalf("error result content was mutated: %q", msgs[1].ToolResult.Content)+ }+ })++ t.Run("skips trailing error to mutate earlier non-error result", func(t *testing.T) {+ msgs := []providers.Message{+ msgWithResult("ok-0", "first-ok", false),+ msgWithResult("err-1", "trailing-err", true),+ }+ if !appendInvestigationBudgetMessage(msgs, guidance, "phase") {+ t.Fatal("expected true when an earlier non-error result exists")+ }+ if want := "first-ok" + "\n\n" + guidance; msgs[0].ToolResult.Content != want {+ t.Fatalf("earlier result = %q, want %q", msgs[0].ToolResult.Content, want)+ }+ if msgs[1].ToolResult.Content != "trailing-err" {+ t.Fatalf("trailing error result was mutated: %q", msgs[1].ToolResult.Content)+ }+ })++ t.Run("mutates exactly one result when several qualify", func(t *testing.T) {+ msgs := []providers.Message{+ msgWithResult("ok-a", "a-ok", false),+ msgWithResult("ok-b", "b-ok", false),+ }+ if !appendInvestigationBudgetMessage(msgs, guidance, "phase") {+ t.Fatal("expected true")+ }+ if msgs[0].ToolResult.Content != "a-ok" {+ t.Fatalf("first qualifying result should be untouched: %q", msgs[0].ToolResult.Content)+ }+ if want := "b-ok" + "\n\n" + guidance; msgs[1].ToolResult.Content != want {+ t.Fatalf("only the last qualifying result should be mutated: got %q, want %q", msgs[1].ToolResult.Content, want)+ }+ })+}++func Test_w0716_budget_MaybeInjectInvestigationEvidenceCheckpoint(t *testing.T) {+ t.Run("injects checkpoint guidance with used and remaining counts", func(t *testing.T) {+ msgs := []providers.Message{msgWithResult("evidence-1", "raw-evidence", false)}+ if !maybeInjectInvestigationEvidenceCheckpoint(msgs, 4, 3) {+ t.Fatal("expected checkpoint injection to return true")+ }+ got := msgs[0].ToolResult.Content+ if !strings.Contains(got, "raw-evidence") {+ t.Fatalf("original content must be preserved, got %q", got)+ }+ for _, want := range []string{"4 evidence calls used", "3 remain", "checkpoint", "completion questions"} {+ if !strings.Contains(got, want) {+ t.Fatalf("checkpoint content missing %q: %q", want, got)+ }+ }+ if !strings.HasPrefix(got, "raw-evidence\n\n") {+ t.Fatalf("guidance must be appended after a blank line, got %q", got)+ }+ })++ t.Run("returns false when no injectable result exists", func(t *testing.T) {+ msgs := []providers.Message{+ {Role: "user", Content: "no result here"},+ msgWithResult("err", "boom", true),+ }+ if maybeInjectInvestigationEvidenceCheckpoint(msgs, 1, 0) {+ t.Fatal("expected false when no non-error tool result is present")+ }+ if msgs[1].ToolResult.Content != "boom" {+ t.Fatalf("error result must not be mutated: %q", msgs[1].ToolResult.Content)+ }+ })+}++func Test_w0716_budget_MaybeInjectInvestigationEvidenceBudgetWarning(t *testing.T) {+ t.Run("injects budget warning with used and remaining counts", func(t *testing.T) {+ msgs := []providers.Message{+ msgWithResult("evidence-early", "first", false),+ msgWithResult("evidence-late", "second", false),+ }+ if !maybeInjectInvestigationEvidenceBudgetWarning(msgs, 9, 1) {+ t.Fatal("expected warning injection to return true")+ }+ if msgs[0].ToolResult.Content != "first" {+ t.Fatalf("earlier result must be untouched, got %q", msgs[0].ToolResult.Content)+ }+ got := msgs[1].ToolResult.Content+ for _, want := range []string{"9 evidence calls used", "1 remain", "budget", "Stop exploratory investigation", "typed proposal"} {+ if !strings.Contains(got, want) {+ t.Fatalf("warning content missing %q: %q", want, got)+ }+ }+ })++ t.Run("returns false on empty messages", func(t *testing.T) {+ if maybeInjectInvestigationEvidenceBudgetWarning(nil, 5, 0) {+ t.Fatal("expected false on empty messages")+ }+ })++ t.Run("returns false when all results are errors", func(t *testing.T) {+ msgs := []providers.Message{msgWithResult("e1", "err1", true), msgWithResult("e2", "err2", true)}+ if maybeInjectInvestigationEvidenceBudgetWarning(msgs, 5, 0) {+ t.Fatal("expected false when every result is an error")+ }+ })+}diff --git a/internal/ai/chat/agentic_pure_helpers_w0716_coverage_test.go b/internal/ai/chat/agentic_pure_helpers_w0716_coverage_test.gonew file mode 100644index 0000000000..bbdb9dfd75--- /dev/null+++ b/internal/ai/chat/agentic_pure_helpers_w0716_coverage_test.go@@ -0,0 +1,517 @@+package chat++import (+ "encoding/json"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"+)++func Test_w0716_agentic_providerRetryStatusMessage(t *testing.T) {+ tests := []struct {+ name string+ err error+ want string+ }{+ {name: "nil error uses generic interrupted message", err: nil, want: "Selected route stream interrupted before any output; retrying."},+ {name: "rate limit", err: strErr("HTTP 429: rate limit exceeded"), want: "Selected route is rate limiting the request; retrying."},+ {name: "too many requests", err: strErr("too many requests"), want: "Selected route is rate limiting the request; retrying."},+ {name: "429 token", err: strErr("429 Quota exceeded"), want: "Selected route is rate limiting the request; retrying."},+ {name: "timeout", err: strErr("context timeout"), want: "Selected route timed out before any output; retrying."},+ {name: "timed out", err: strErr("request timed out"), want: "Selected route timed out before any output; retrying."},+ {name: "deadline", err: strErr("context deadline exceeded"), want: "Selected route timed out before any output; retrying."},+ {name: "connection", err: strErr("connection reset by peer"), want: "Selected route connection failed before any output; retrying."},+ {name: "broken pipe", err: strErr("write: broken pipe"), want: "Selected route connection failed before any output; retrying."},+ {name: "eof", err: strErr("unexpected EOF"), want: "Selected route connection failed before any output; retrying."},+ {name: "default falls back to interrupted", err: strErr("internal server error"), want: "Selected route stream interrupted before any output; retrying."},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := providerRetryStatusMessage(tt.err); got != tt.want {+ t.Fatalf("providerRetryStatusMessage() = %q, want %q", got, tt.want)+ }+ })+ }+}++func Test_w0716_agentic_removeToolCallFromResultMessages(t *testing.T) {+ tr := func(id, content string) *ToolResult { return &ToolResult{ToolUseID: id, Content: content} }++ tests := []struct {+ name string+ messages []Message+ toolUseID string+ wantLen int+ check func(t *testing.T, got []Message)+ }{+ {+ name: "blank id returns messages unchanged",+ messages: []Message{{Role: "assistant", Content: "hi"}},+ toolUseID: " ",+ wantLen: 1,+ },+ {+ name: "no messages carry tool calls",+ messages: []Message{+ {Role: "user", Content: "hello"},+ {Role: "assistant", Content: "hi"},+ },+ toolUseID: "call-1",+ wantLen: 2,+ },+ {+ name: "tool calls present but no id match leaves them",+ messages: []Message{+ {Role: "assistant", Content: "text", ToolCalls: []ToolCall{{ID: "call-1", Name: "t"}}},+ },+ toolUseID: "call-2",+ wantLen: 1,+ check: func(t *testing.T, got []Message) {+ if len(got[0].ToolCalls) != 1 || got[0].ToolCalls[0].ID != "call-1" {+ t.Fatalf("unmatched tool call was removed: %+v", got[0].ToolCalls)+ }+ },+ },+ {+ name: "matching id removed but message keeps remaining content",+ messages: []Message{+ {Role: "assistant", Content: "keep me", ToolCalls: []ToolCall{{ID: "call-1", Name: "t"}, {ID: "call-2", Name: "u"}}},+ },+ toolUseID: "call-1",+ wantLen: 1,+ check: func(t *testing.T, got []Message) {+ if len(got[0].ToolCalls) != 1 || got[0].ToolCalls[0].ID != "call-2" {+ t.Fatalf("remaining tool call not preserved: %+v", got[0].ToolCalls)+ }+ if got[0].Content != "keep me" {+ t.Fatalf("content changed: %q", got[0].Content)+ }+ },+ },+ {+ name: "matching id empties message and removes it",+ messages: []Message{+ {Role: "user", Content: "hello"},+ {Role: "assistant", ToolCalls: []ToolCall{{ID: "call-1", Name: "t"}}},+ {Role: "assistant", Content: "tail"},+ },+ toolUseID: "call-1",+ wantLen: 2,+ check: func(t *testing.T, got []Message) {+ for _, m := range got {+ if len(m.ToolCalls) > 0 {+ t.Fatalf("message with removed tool call was not dropped: %+v", got)+ }+ }+ if got[0].Content != "hello" || got[1].Content != "tail" {+ t.Fatalf("remaining messages reordered: %+v", got)+ }+ },+ },+ {+ name: "matching id leaves message because tool result present",+ messages: []Message{+ {Role: "user", ToolResult: tr("call-1", "ok"), ToolCalls: []ToolCall{{ID: "call-1", Name: "t"}}},+ },+ toolUseID: "call-1",+ wantLen: 1,+ check: func(t *testing.T, got []Message) {+ if len(got[0].ToolCalls) != 0 {+ t.Fatalf("tool call not removed: %+v", got[0].ToolCalls)+ }+ if got[0].ToolResult == nil {+ t.Fatal("tool result should keep message alive")+ }+ },+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := removeToolCallFromResultMessages(tt.messages, tt.toolUseID)+ if len(got) != tt.wantLen {+ t.Fatalf("len = %d, want %d (%+v)", len(got), tt.wantLen, got)+ }+ if tt.check != nil {+ tt.check(t, got)+ }+ })+ }+}++func Test_w0716_agentic_toolStartKey(t *testing.T) {+ tests := []struct {+ name string+ id string+ nameArg string+ want string+ }{+ {name: "non-empty id wins", id: "call-1", nameArg: "pulse_query", want: "call-1"},+ {name: "whitespace id falls back to name", id: " ", nameArg: "pulse_query", want: "pulse_query"},+ {name: "empty id falls back to trimmed name", id: "", nameArg: " pulse_read ", want: "pulse_read"},+ {name: "both empty yields empty", id: "", nameArg: "", want: ""},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := toolStartKey(tt.id, tt.nameArg); got != tt.want {+ t.Fatalf("toolStartKey(%q, %q) = %q, want %q", tt.id, tt.nameArg, got, tt.want)+ }+ })+ }+}++func Test_w0716_agentic_toolExecutionProgressMessage(t *testing.T) {+ tests := []struct {+ name string+ toolName string+ input map[string]interface{}+ toolKind ToolKind+ want string+ }{+ {name: "run command", toolName: agentcapabilities.PulseRunCommandToolName, want: "Running command."},+ {name: "legacy run command", toolName: agentcapabilities.LegacyAssistantRunCommandToolName, want: "Running command."},+ {name: "query reads inventory", toolName: agentcapabilities.PulseQueryToolName, want: "Reading inventory."},+ {name: "read reads target", toolName: agentcapabilities.PulseReadToolName, want: "Reading target."},+ {name: "bare read alias reads target", toolName: "read", want: "Reading target."},+ {name: "governed write control", toolName: agentcapabilities.PulseControlToolName, toolKind: ToolKindWrite, want: "Executing governed action."},+ {name: "patrol report finding lifecycle", toolName: agentcapabilities.PatrolReportFindingToolName, toolKind: ToolKindWrite, want: "Executing governed action."},+ {name: "unknown tool generic running", toolName: "some_other_tool", want: "Running."},+ {name: "unknown write tool not in governed set", toolName: "mystery_writer", toolKind: ToolKindWrite, want: "Running."},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := toolExecutionProgressMessage(tt.toolName, tt.input, tt.toolKind); got != tt.want {+ t.Fatalf("toolExecutionProgressMessage(%q) = %q, want %q", tt.toolName, got, tt.want)+ }+ })+ }+}++func Test_w0716_agentic_isKnownGovernedWriteProgress(t *testing.T) {+ tests := []struct {+ name string+ toolName string+ input map[string]interface{}+ toolKind ToolKind+ want bool+ }{+ {name: "read kind never governed", toolName: agentcapabilities.PulseControlToolName, toolKind: ToolKindRead, want: false},+ {name: "control write", toolName: agentcapabilities.PulseControlToolName, toolKind: ToolKindWrite, want: true},+ {name: "control guest write", toolName: agentcapabilities.PulseControlGuestToolName, toolKind: ToolKindWrite, want: true},+ {name: "control docker write", toolName: agentcapabilities.PulseControlDockerToolName, toolKind: ToolKindWrite, want: true},+ {name: "alerts resolve", toolName: agentcapabilities.PulseAlertsToolName, input: map[string]interface{}{"action": "resolve"}, toolKind: ToolKindWrite, want: true},+ {name: "alerts dismiss", toolName: agentcapabilities.PulseAlertsToolName, input: map[string]interface{}{"action": "dismiss"}, toolKind: ToolKindWrite, want: true},+ {name: "alerts list is read-only", toolName: agentcapabilities.PulseAlertsToolName, input: map[string]interface{}{"action": "list"}, toolKind: ToolKindWrite, want: false},+ {name: "alerts uppercase action matches", toolName: agentcapabilities.PulseAlertsToolName, input: map[string]interface{}{"action": " RESOLVE "}, toolKind: ToolKindWrite, want: true},+ {name: "alerts no action", toolName: agentcapabilities.PulseAlertsToolName, input: nil, toolKind: ToolKindWrite, want: false},+ {name: "docker control", toolName: agentcapabilities.PulseDockerToolName, input: map[string]interface{}{"action": "control"}, toolKind: ToolKindWrite, want: true},+ {name: "docker update", toolName: agentcapabilities.PulseDockerToolName, input: map[string]interface{}{"action": "update"}, toolKind: ToolKindWrite, want: true},+ {name: "docker check_updates", toolName: agentcapabilities.PulseDockerToolName, input: map[string]interface{}{"action": "check_updates"}, toolKind: ToolKindWrite, want: true},+ {name: "docker trigger_update", toolName: agentcapabilities.PulseDockerToolName, input: map[string]interface{}{"action": "trigger_update"}, toolKind: ToolKindWrite, want: true},+ {name: "docker services is read-only", toolName: agentcapabilities.PulseDockerToolName, input: map[string]interface{}{"action": "services"}, toolKind: ToolKindWrite, want: false},+ {name: "kubernetes scale", toolName: agentcapabilities.PulseKubernetesToolName, input: map[string]interface{}{"action": "scale"}, toolKind: ToolKindWrite, want: true},+ {name: "kubernetes restart", toolName: agentcapabilities.PulseKubernetesToolName, input: map[string]interface{}{"action": "restart"}, toolKind: ToolKindWrite, want: true},+ {name: "kubernetes delete_pod", toolName: agentcapabilities.PulseKubernetesToolName, input: map[string]interface{}{"action": "delete_pod"}, toolKind: ToolKindWrite, want: true},+ {name: "kubernetes exec", toolName: agentcapabilities.PulseKubernetesToolName, input: map[string]interface{}{"action": "exec"}, toolKind: ToolKindWrite, want: true},+ {name: "kubernetes pods is read-only", toolName: agentcapabilities.PulseKubernetesToolName, input: map[string]interface{}{"action": "pods"}, toolKind: ToolKindWrite, want: false},+ {name: "file edit write", toolName: agentcapabilities.PulseFileEditToolName, input: map[string]interface{}{"action": "write"}, toolKind: ToolKindWrite, want: true},+ {name: "file edit append", toolName: agentcapabilities.PulseFileEditToolName, input: map[string]interface{}{"action": "append"}, toolKind: ToolKindWrite, want: true},+ {name: "file edit read is not governed", toolName: agentcapabilities.PulseFileEditToolName, input: map[string]interface{}{"action": "read"}, toolKind: ToolKindWrite, want: false},+ {name: "knowledge remember", toolName: agentcapabilities.PulseKnowledgeToolName, input: map[string]interface{}{"action": "remember"}, toolKind: ToolKindWrite, want: true},+ {name: "knowledge note", toolName: agentcapabilities.PulseKnowledgeToolName, input: map[string]interface{}{"action": "note"}, toolKind: ToolKindWrite, want: true},+ {name: "knowledge save", toolName: agentcapabilities.PulseKnowledgeToolName, input: map[string]interface{}{"action": "save"}, toolKind: ToolKindWrite, want: true},+ {name: "knowledge recall is read-only", toolName: agentcapabilities.PulseKnowledgeToolName, input: map[string]interface{}{"action": "recall"}, toolKind: ToolKindWrite, want: false},+ {name: "patrol report finding", toolName: agentcapabilities.PatrolReportFindingToolName, toolKind: ToolKindWrite, want: true},+ {name: "patrol assess finding", toolName: agentcapabilities.PatrolAssessFindingToolName, toolKind: ToolKindWrite, want: true},+ {name: "patrol resolve finding", toolName: agentcapabilities.PatrolResolveFindingToolName, toolKind: ToolKindWrite, want: true},+ {name: "unknown write tool default false", toolName: "mystery_tool", toolKind: ToolKindWrite, want: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := isKnownGovernedWriteProgress(tt.toolName, tt.input, tt.toolKind); got != tt.want {+ t.Fatalf("isKnownGovernedWriteProgress(%q, %+v, %s) = %v, want %v", tt.toolName, tt.input, tt.toolKind, got, tt.want)+ }+ })+ }+}++func Test_w0716_agentic_emitToolStartEvent(t *testing.T) {+ t.Run("nil callback is a no-op", func(t *testing.T) {+ emitToolStartEvent(nil, "id-1", agentcapabilities.PulseQueryToolName, map[string]interface{}{"query": "x"})+ })++ t.Run("emits tool_start with projected input", func(t *testing.T) {+ var got []StreamEvent+ emitToolStartEvent(func(e StreamEvent) { got = append(got, e) }, "id-1", agentcapabilities.PulseControlToolName, map[string]interface{}{"command": "uptime"})+ if len(got) != 1 || got[0].Type != "tool_start" {+ t.Fatalf("expected one tool_start event, got %+v", got)+ }+ var data ToolStartData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.ID != "id-1" || data.Name != agentcapabilities.PulseControlToolName {+ t.Fatalf("unexpected id/name: %+v", data)+ }+ if data.Input != "Running: uptime" {+ t.Fatalf("input not projected through frontend formatter: %q", data.Input)+ }+ if data.Phase != "running" {+ t.Fatalf("phase = %q, want running", data.Phase)+ }+ if !strings.Contains(data.RawInput, "uptime") {+ t.Fatalf("raw input missing command: %q", data.RawInput)+ }+ })++ t.Run("nil input yields empty object input string", func(t *testing.T) {+ var got []StreamEvent+ emitToolStartEvent(func(e StreamEvent) { got = append(got, e) }, "id-2", "custom_tool", nil)+ var data ToolStartData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.Input != "{}" {+ t.Fatalf("nil input should project to {}, got %q", data.Input)+ }+ })+}++func Test_w0716_agentic_emitToolCancelEvent(t *testing.T) {+ t.Run("nil callback is a no-op", func(t *testing.T) {+ emitToolCancelEvent(nil, "id-1", "pulse_query", " blocked ")+ })++ t.Run("emits tool_cancel with trimmed reason", func(t *testing.T) {+ var got []StreamEvent+ emitToolCancelEvent(func(e StreamEvent) { got = append(got, e) }, "id-1", "pulse_query", " current_resource unavailable ")+ if len(got) != 1 || got[0].Type != "tool_cancel" {+ t.Fatalf("expected one tool_cancel event, got %+v", got)+ }+ var data ToolCancelData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.ID != "id-1" || data.Name != "pulse_query" {+ t.Fatalf("unexpected id/name: %+v", data)+ }+ if data.Reason != "current_resource unavailable" {+ t.Fatalf("reason not trimmed: %q", data.Reason)+ }+ })+}++func Test_w0716_agentic_emitToolEndEvent(t *testing.T) {+ t.Run("nil callback is a no-op", func(t *testing.T) {+ emitToolEndEvent(nil, "id-1", "pulse_query", map[string]interface{}{"query": "x"}, "done", true)+ })++ t.Run("emits tool_end with projected input and output", func(t *testing.T) {+ var got []StreamEvent+ emitToolEndEvent(func(e StreamEvent) { got = append(got, e) }, "id-1", agentcapabilities.PulseControlToolName, map[string]interface{}{"command": "uptime"}, "ok output", true)+ if len(got) != 1 || got[0].Type != "tool_end" {+ t.Fatalf("expected one tool_end event, got %+v", got)+ }+ var data ToolEndData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.ID != "id-1" || data.Name != agentcapabilities.PulseControlToolName {+ t.Fatalf("unexpected id/name: %+v", data)+ }+ if data.Input != "Running: uptime" {+ t.Fatalf("input not projected: %q", data.Input)+ }+ if data.Output != "ok output" || !data.Success {+ t.Fatalf("output/success mismatch: %+v", data)+ }+ })++ t.Run("nil input yields empty input string for end event", func(t *testing.T) {+ var got []StreamEvent+ emitToolEndEvent(func(e StreamEvent) { got = append(got, e) }, "id-2", "custom_tool", nil, "out", false)+ var data ToolEndData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.Input != "" {+ t.Fatalf("nil input should project to empty for end event, got %q", data.Input)+ }+ })+}++func Test_w0716_agentic_emitToolProgressEventWithRawInput(t *testing.T) {+ t.Run("nil callback is a no-op", func(t *testing.T) {+ emitToolProgressEventWithRawInput(nil, "id-1", "pulse_query", map[string]interface{}{"query": "x"}, "OVERRIDE", "running", "msg")+ })++ t.Run("no override uses projected raw input", func(t *testing.T) {+ var got []StreamEvent+ emitToolProgressEventWithRawInput(func(e StreamEvent) { got = append(got, e) }, "id-1", "pulse_query", map[string]interface{}{"query": "containers"}, "", "pending", "Reading inventory.")+ if len(got) != 1 || got[0].Type != "tool_progress" {+ t.Fatalf("expected one tool_progress event, got %+v", got)+ }+ var data ToolProgressData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.ID != "id-1" || data.Name != "pulse_query" {+ t.Fatalf("unexpected id/name: %+v", data)+ }+ if data.Phase != "pending" || data.Message != "Reading inventory." {+ t.Fatalf("phase/message mismatch: %+v", data)+ }+ if !strings.Contains(data.RawInput, "containers") {+ t.Fatalf("raw input should carry projected value: %q", data.RawInput)+ }+ })++ t.Run("override applied for non-restricted tool", func(t *testing.T) {+ var got []StreamEvent+ emitToolProgressEventWithRawInput(func(e StreamEvent) { got = append(got, e) }, "id-1", "pulse_query", map[string]interface{}{"query": "x"}, "PROVIDER_RAW_OVERRIDE", "running", "msg")+ var data ToolProgressData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.RawInput != "PROVIDER_RAW_OVERRIDE" {+ t.Fatalf("non-restricted tool should use override, got %q", data.RawInput)+ }+ })++ t.Run("override suppressed for exposure-restricted patrol_propose_action", func(t *testing.T) {+ var got []StreamEvent+ emitToolProgressEventWithRawInput(+ func(e StreamEvent) { got = append(got, e) },+ "id-1",+ agentcapabilities.PatrolProposeActionToolName,+ map[string]interface{}{"params": "secret-value", "finding_id": "f1"},+ "LEAK_ATTEMPT_OVERRIDE",+ "running",+ "msg",+ )+ var data ToolProgressData+ if err := json.Unmarshal(got[0].Data, &data); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if data.RawInput == "LEAK_ATTEMPT_OVERRIDE" {+ t.Fatal("restricted-exposure tool must not surface provider raw override")+ }+ if strings.Contains(data.RawInput, "secret-value") {+ t.Fatalf("restricted params leaked into raw input: %q", data.RawInput)+ }+ if !strings.Contains(data.RawInput, "redacted-proposal-params") {+ t.Fatalf("expected redacted marker in raw input: %q", data.RawInput)+ }+ })+}++func Test_w0716_agentic_normalizeToolUseID(t *testing.T) {+ tests := []struct {+ name string+ toolUseID string+ want string+ }{+ {name: "empty", toolUseID: "", want: ""},+ {name: "whitespace only", toolUseID: " ", want: ""},+ {name: "no underscore returned as-is", toolUseID: "abc", want: "abc"},+ {name: "leading underscore returned as-is", toolUseID: "_abc", want: "_abc"},+ {name: "trailing underscore returned as-is", toolUseID: "abc_", want: "abc_"},+ {name: "numeric suffix stripped", toolUseID: "abc_123", want: "abc"},+ {name: "single digit suffix stripped", toolUseID: "x_0", want: "x"},+ {name: "non-numeric suffix kept", toolUseID: "abc_12a", want: "abc_12a"},+ {name: "multi underscore strips only trailing numeric", toolUseID: "a_b_3", want: "a_b"},+ {name: "real pulse call id stripped", toolUseID: "pulse_query_0", want: "pulse_query"},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := normalizeToolUseID(tt.toolUseID); got != tt.want {+ t.Fatalf("normalizeToolUseID(%q) = %q, want %q", tt.toolUseID, got, tt.want)+ }+ })+ }+}++func Test_w0716_agentic_fallbackToolDisplayName(t *testing.T) {+ tests := []struct {+ name string+ toolUseID string+ idToName map[string]string+ want string+ }{+ {name: "resolved via id map strips pulse prefix", toolUseID: "call_27f0", idToName: map[string]string{"call_27f0": "pulse_query"}, want: "query"},+ {name: "resolved via id map keeps non-pulse name", toolUseID: "x", idToName: map[string]string{"x": "custom_tool"}, want: "custom_tool"},+ {name: "opaque call id suppressed", toolUseID: "call_27f0f389aba4652a1e292dc", idToName: map[string]string{}, want: ""},+ {name: "opaque toolu id suppressed", toolUseID: "toolu_abcDEF123", idToName: map[string]string{}, want: ""},+ {name: "opaque fc id suppressed", toolUseID: "fc_xyz789", idToName: map[string]string{}, want: ""},+ {name: "empty tool use id suppressed", toolUseID: "", idToName: map[string]string{}, want: ""},+ {name: "normalized numeric call id resolves to bare name", toolUseID: "pulse_query_0", idToName: map[string]string{}, want: "query"},+ {name: "whitespace id suppressed", toolUseID: " ", idToName: map[string]string{}, want: ""},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := fallbackToolDisplayName(tt.toolUseID, tt.idToName); got != tt.want {+ t.Fatalf("fallbackToolDisplayName(%q) = %q, want %q", tt.toolUseID, got, tt.want)+ }+ })+ }+}++func Test_w0716_agentic_ResetTokenCounts(t *testing.T) {+ loop := &AgenticLoop{+ totalInputTokens: 1500,+ totalOutputTokens: 900,+ totalToolCalls: 7,+ }+ loop.ResetTokenCounts()+ if loop.totalInputTokens != 0 || loop.totalOutputTokens != 0 || loop.totalToolCalls != 0 {+ t.Fatalf("ResetTokenCounts left non-zero counters: in=%d out=%d calls=%d",+ loop.totalInputTokens, loop.totalOutputTokens, loop.totalToolCalls)+ }+ if loop.GetTotalInputTokens() != 0 || loop.GetTotalOutputTokens() != 0 || loop.GetTotalToolCalls() != 0 {+ t.Fatal("public token getters must report zero after reset")+ }+}++func Test_w0716_agentic_SetExecutionProfile(t *testing.T) {+ t.Run("patrol detection sets stream idle timeout", func(t *testing.T) {+ loop := &AgenticLoop{}+ loop.SetExecutionProfile(tools.ProfilePatrolDetection)+ if loop.streamIdleTimeout != patrolProviderStreamIdleTimeout {+ t.Fatalf("detection stream idle timeout = %s, want %s", loop.streamIdleTimeout, patrolProviderStreamIdleTimeout)+ }+ if loop.executionProfile != tools.ProfilePatrolDetection {+ t.Fatalf("executionProfile = %d, want %d", loop.executionProfile, tools.ProfilePatrolDetection)+ }+ })++ t.Run("patrol investigation sets stream idle timeout", func(t *testing.T) {+ loop := &AgenticLoop{}+ loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)+ if loop.streamIdleTimeout != patrolProviderStreamIdleTimeout {+ t.Fatalf("investigation stream idle timeout = %s, want %s", loop.streamIdleTimeout, patrolProviderStreamIdleTimeout)+ }+ })++ t.Run("interactive assistant clears stream idle timeout", func(t *testing.T) {+ loop := &AgenticLoop{streamIdleTimeout: patrolProviderStreamIdleTimeout}+ loop.SetExecutionProfile(tools.ProfileInteractiveAssistant)+ if loop.streamIdleTimeout != 0 {+ t.Fatalf("interactive stream idle timeout = %s, want 0", loop.streamIdleTimeout)+ }+ })++ t.Run("invalid profile panics", func(t *testing.T) {+ loop := &AgenticLoop{}+ defer func() {+ if r := recover(); r == nil {+ t.Fatal("expected SetExecutionProfile to panic on an invalid profile")+ }+ }()+ loop.SetExecutionProfile(tools.ExecutionProfile(99))+ })+}++type strErr string++func (e strErr) Error() string { return string(e) }diff --git a/internal/ai/qualification/qualification_validate_w0716_coverage_test.go b/internal/ai/qualification/qualification_validate_w0716_coverage_test.gonew file mode 100644index 0000000000..76a756dc68--- /dev/null+++ b/internal/ai/qualification/qualification_validate_w0716_coverage_test.go@@ -0,0 +1,443 @@+package qualification++import (+ "encoding/json"+ "reflect"+ "strings"+ "testing"+)++// This file is a white-box table-test suite targeting currently-undercovered+// branches of:+// - Manifest.Validate (manifest.go)+// - validateExistingFindingPrerequisite (runner.go)+// - validateCollectedDockerPredicate (runner.go)+// - patrolScopeResourceIDs (runner.go)+//+// Every helper and identifier introduced here is prefixed qualw0716 so it+// cannot collide with sibling test files in package qualification.++// qualw0716ValidRemediation returns a manifest that is a fully-valid+// remediation-track scenario. It is the base used by the remediation error-arm+// table; each row mutates a fresh copy.+func qualw0716ValidRemediation() Manifest {+ m := validTestManifest()+ m.Track = TrackRemediation+ m.Patrol.Mode = "approval"+ m.Investigation = &InvestigationSpec{+ MinEvidenceIDs: 1,+ RequiredSummaryTerms: []string{"stopped"},+ RequireCompletedStatus: true,+ }+ m.Remediation = &RemediationSpec{+ ActionTarget: "target",+ ExpectedCapabilities: []string{"restart"},+ Decision: "observe",+ ActionTimeout: "1m",+ }+ return m+}++// qualw0716AssertErrContains fails t when err is nil or lacks substring.+func qualw0716AssertErrContains(t *testing.T, err error, want string) {+ t.Helper()+ if err == nil {+ t.Fatalf("expected error containing %q, got nil", want)+ }+ if !strings.Contains(err.Error(), want) {+ t.Fatalf("error %q does not contain substring %q", err.Error(), want)+ }+}++func Test_w0716_qual_Validate_ErrorArms(t *testing.T) {+ cases := []struct {+ name string+ mutate func(*Manifest)+ wantSub string+ }{+ {"schema version mismatch", func(m *Manifest) { m.SchemaVersion = "wrong" }, "schema_version must be"},+ {"id too short", func(m *Manifest) { m.ID = "x" }, "id must be 3-96"},+ {"version not positive", func(m *Manifest) { m.Version = 0 }, "version must be positive"},+ {"title missing", func(m *Manifest) { m.Title = "" }, "title, description, and owner are required"},+ {"owner missing", func(m *Manifest) { m.Owner = " " }, "title, description, and owner are required"},+ {"unsupported track", func(m *Manifest) { m.Track = "bogus" }, `unsupported track "bogus"`},+ {"unsupported lab driver", func(m *Manifest) { m.Lab.Driver = "vagrant" }, "unsupported lab driver"},+ {"no resources", func(m *Manifest) { m.Resources = nil }, "at least one disposable resource"},+ {"resource alias invalid", func(m *Manifest) { m.Resources[0].Alias = "X" }, "resources[0].alias is invalid"},+ {"duplicate resource alias", func(m *Manifest) {+ m.Resources = append(m.Resources, ResourceSpec{Alias: "target", Kind: "container", Name: "pulse-qual-${run_id}-target-2"})+ }, `duplicate resource alias "target"`},+ {"unsupported resource kind", func(m *Manifest) { m.Resources[0].Kind = "vm" }, `unsupported kind "vm"`},+ {"resource has no image", func(m *Manifest) {+ m.Lab.Image = ""+ m.Resources[0].Image = ""+ }, `resource "target" has no image`},+ {"fault id invalid", func(m *Manifest) { m.Faults[0].ID = "X" }, "faults[0].id is invalid"},+ {"duplicate fault id", func(m *Manifest) {+ m.Faults = append(m.Faults, FaultSpec{+ ID: "fault", CausalGroup: "fault2", Target: "target", Required: true,+ Injector: InjectorSpec{Kind: "stop", Resource: "target"},+ Oracle: []Predicate{{Probe: "docker.running", Target: "target", Operator: "eq", Value: json.RawMessage("false")}},+ Expected: ExpectedFinding{Resource: "target", ResourceTypes: []string{"app"}, Categories: []string{"reliability"}, Severities: []string{"warning"}, MaxPrimaryFindings: 1},+ })+ }, `duplicate fault id "fault"`},+ {"fault target unknown", func(m *Manifest) { m.Faults[0].Target = "ghost" }, "targets unknown resource"},+ {"fault injector resource unknown", func(m *Manifest) { m.Faults[0].Injector.Resource = "ghost" }, "injector targets unknown resource"},+ {"unsupported injector", func(m *Manifest) { m.Faults[0].Injector.Kind = "bomb" }, `unsupported injector "bomb"`},+ {"fault missing causal group", func(m *Manifest) { m.Faults[0].CausalGroup = "" }, "has no causal_group"},+ {"fault related resource unknown", func(m *Manifest) { m.Faults[0].RelatedResources = []string{"ghost"} }, "references unknown related resource"},+ {"fault related duplicates target", func(m *Manifest) { m.Faults[0].RelatedResources = []string{"target"} }, "related resource duplicates its target"},+ {"fault not required", func(m *Manifest) { m.Faults[0].Required = false }, "must be required for qualification"},+ {"fault incomplete expected finding", func(m *Manifest) { m.Faults[0].Expected.Severities = nil }, "incomplete expected finding semantics"},+ {"fault expected finding unknown resource", func(m *Manifest) { m.Faults[0].Expected.Resource = "ghost" }, "expected finding references unknown resource"},+ {"fault expected finding must equal target or related", func(m *Manifest) {+ m.Resources = append(m.Resources, ResourceSpec{Alias: "decoy", Kind: "container", Name: "pulse-qual-${run_id}-decoy"})+ m.Faults[0].Expected.Resource = "decoy"+ }, "must equal target \"target\" or a declared related resource"},+ {"fault detect_within unparseable", func(m *Manifest) { m.Faults[0].DetectWithin = "bad" }, "detect_within:"},+ {"fault max_primary_findings zero", func(m *Manifest) { m.Faults[0].Expected.MaxPrimaryFindings = 0 }, "max_primary_findings must be positive"},+ {"baseline predicates required", func(m *Manifest) { m.Baseline = nil }, "baseline predicates are required"},+ {"negative control unknown resource", func(m *Manifest) {+ m.NegativeControls = []NegativeControl{{Resource: "ghost", Reason: "none"}}+ }, "negative control references unknown resource"},+ {"scope resources requires scoped flag", func(m *Manifest) {+ m.Patrol.ScopeResources = []string{"target"}+ }, "scope_resources requires patrol.scoped=true"},+ {"scope resources duplicates", func(m *Manifest) {+ m.Patrol.Scoped = true+ m.Patrol.ScopeResources = []string{"target", "target"}+ }, "scope_resources duplicates resource"},+ {"durations unparseable", func(m *Manifest) { m.Collection.ConvergenceTimeout = "bad" }, "collection.convergence_timeout:"},+ {"unsupported patrol mode", func(m *Manifest) { m.Patrol.Mode = "bogus" }, `unsupported Patrol mode "bogus"`},+ {"collection sources empty", func(m *Manifest) { m.Collection.Sources = nil }, "collection.sources must not be empty"},+ {"require exact name false", func(m *Manifest) { m.Collection.RequireExactName = false }, "collection.require_exact_name must be true"},+ {"require real model false", func(m *Manifest) { m.Patrol.RequireRealModel = false }, "require_real_model must be true"},+ {"require tool call evidence false", func(m *Manifest) { m.Patrol.RequireToolCallEvidence = false }, "require_tool_call_evidence must be true"},+ {"require no mutation false", func(m *Manifest) { m.Security.RequireNoMutation = false }, "require_no_unexpected_mutation must be true"},+ {"require fault intact false with faults", func(m *Manifest) { m.Security.RequireFaultIntact = false }, "require_fault_intact_after_patrol must be true when faults are declared"},+ {"teardown second noop false", func(m *Manifest) { m.Teardown.RequireSecondNoop = false }, "teardown must require a second cleanup no-op"},+ {"repeat counts not positive", func(m *Manifest) { m.Repeat.Development = 0 }, "repeat counts must all be positive"},+ {"repeat counts out of order", func(m *Manifest) {+ m.Repeat.Development = 5+ m.Repeat.Nightly = 2+ }, "repeat counts must satisfy qualification >= nightly >= development"},+ {"repeat qualification below wilson floor", func(m *Manifest) { m.Repeat.Qualification = 5 }, "cannot satisfy the 0.850 Wilson lower-bound gate"},+ {"replay lab cannot require real model", func(m *Manifest) { m.Lab.Driver = "replay" }, "replay-only lab cannot require a real model"},+ {"watch track must not declare investigation", func(m *Manifest) {+ m.Investigation = &InvestigationSpec{MinEvidenceIDs: 1, RequiredSummaryTerms: []string{"x"}}+ }, "Watch scenarios must not declare investigation"},+ {"only remediation track may declare remediation", func(m *Manifest) {+ m.Remediation = &RemediationSpec{ActionTarget: "target", ExpectedCapabilities: []string{"restart"}, Decision: "observe", ActionTimeout: "1m"}+ }, "only remediation-track scenarios may declare remediation expectations"},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ manifest := validTestManifest()+ tc.mutate(&manifest)+ qualw0716AssertErrContains(t, manifest.Validate(), tc.wantSub)+ })+ }+}++func Test_w0716_qual_Validate_InvestigationArms(t *testing.T) {+ // Base is an investigation-track manifest with a valid Investigation spec.+ base := func() Manifest {+ m := validTestManifest()+ m.Track = TrackInvestigation+ m.Investigation = &InvestigationSpec{+ MinEvidenceIDs: 1,+ RequiredSummaryTerms: []string{"stopped"},+ }+ return m+ }++ cases := []struct {+ name string+ mutate func(*Manifest)+ wantSub string+ }{+ {"investigation required for pro track", func(m *Manifest) { m.Investigation = nil }, "investigation expectations are required for Pro tracks"},+ {"investigation min evidence calls must be positive", func(m *Manifest) {+ m.Investigation.MinEvidenceIDs = 0+ m.Investigation.RequiredSummaryTerms = []string{"x"}+ }, "investigation.min_evidence_calls must be positive"},+ {"investigation summary expectations required", func(m *Manifest) {+ m.Investigation.MinEvidenceIDs = 1+ m.Investigation.RequiredSummaryTerms = nil+ m.Investigation.RequiredSummaryTermGroups = nil+ }, "investigation summary expectations must include"},+ {"investigation term group empty", func(m *Manifest) {+ m.Investigation.RequiredSummaryTermGroups = [][]string{{}}+ }, "required_summary_term_groups[0] must not be empty"},+ {"investigation term group element empty", func(m *Manifest) {+ m.Investigation.RequiredSummaryTermGroups = [][]string{{"ok", " "}}+ }, "required_summary_term_groups[0][1] must not be empty"},+ {"investigation resource expectation unknown", func(m *Manifest) {+ m.Investigation.RootCauseResources = []string{"ghost"}+ }, "investigation resource expectation references unknown resource"},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ manifest := base()+ tc.mutate(&manifest)+ qualw0716AssertErrContains(t, manifest.Validate(), tc.wantSub)+ })+ }+}++func Test_w0716_qual_Validate_RemediationArms(t *testing.T) {+ cases := []struct {+ name string+ mutate func(*Manifest)+ wantSub string+ }{+ {"remediation required for remediation track", func(m *Manifest) { m.Remediation = nil }, "remediation expectations are required for remediation track"},+ {"remediation action target unknown", func(m *Manifest) { m.Remediation.ActionTarget = "ghost" }, "remediation.action_target references unknown resource"},+ {"remediation expected capabilities empty", func(m *Manifest) { m.Remediation.ExpectedCapabilities = nil }, "remediation.expected_capabilities must not be empty"},+ {"remediation decision unsupported", func(m *Manifest) { m.Remediation.Decision = "maybe" }, `unsupported remediation decision "maybe"`},+ {"remediation action timeout invalid", func(m *Manifest) { m.Remediation.ActionTimeout = "bad" }, "remediation.action_timeout:"},+ {"remediation non-observe requires postconditions", func(m *Manifest) {+ m.Remediation.Decision = "reject"+ m.Remediation.DecisionReason = "why"+ }, "remediation decisions require independent postconditions"},+ {"remediation non-observe requires a reason", func(m *Manifest) {+ m.Remediation.Decision = "reject"+ m.Remediation.Postconditions = []Predicate{{Probe: "docker.running", Target: "target", Operator: "eq", Value: json.RawMessage("true")}}+ }, "remediation decisions require a reason"},+ {"remediation lifecycle verification needs statuses", func(m *Manifest) {+ m.Remediation.RequireLifecycleVerification = true+ }, "required lifecycle verification needs allowed statuses"},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ manifest := qualw0716ValidRemediation()+ tc.mutate(&manifest)+ qualw0716AssertErrContains(t, manifest.Validate(), tc.wantSub)+ })+ }+}++func Test_w0716_qual_Validate_ValidManifestsPass(t *testing.T) {+ t.Run("watch base manifest passes", func(t *testing.T) {+ if err := validTestManifest().Validate(); err != nil {+ t.Fatalf("watch base manifest rejected: %v", err)+ }+ })++ t.Run("investigation manifest passes", func(t *testing.T) {+ m := validTestManifest()+ m.Track = TrackInvestigation+ m.Investigation = &InvestigationSpec{MinEvidenceIDs: 2, RequiredSummaryTerms: []string{"stopped"}}+ if err := m.Validate(); err != nil {+ t.Fatalf("investigation manifest rejected: %v", err)+ }+ })++ t.Run("remediation observe manifest passes", func(t *testing.T) {+ if err := qualw0716ValidRemediation().Validate(); err != nil {+ t.Fatalf("remediation manifest rejected: %v", err)+ }+ })++ t.Run("remediation approve_execute with postconditions passes", func(t *testing.T) {+ m := qualw0716ValidRemediation()+ m.Remediation.Decision = "approve_execute"+ m.Remediation.DecisionReason = "restart to recover"+ m.Remediation.Postconditions = []Predicate{{Probe: "docker.running", Target: "target", Operator: "eq", Value: json.RawMessage("true")}}+ if err := m.Validate(); err != nil {+ t.Fatalf("remediation approve_execute manifest rejected: %v", err)+ }+ })+}++func Test_w0716_qual_ValidateExistingFindingPrerequisite(t *testing.T) {+ twoFaults := []FaultSpec{+ {ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}},+ {ID: "f2", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}},+ }++ cases := []struct {+ name string+ faults []FaultSpec+ collected map[string]Resource+ warmup PatrolRun+ findings []Finding+ wantErr string+ }{+ {+ name: "error status fails prerequisite",+ faults: []FaultSpec{{ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}}},+ collected: map[string]Resource{"alpha": {ID: "res-alpha"}},+ warmup: PatrolRun{Status: "error"},+ findings: []Finding{{ResourceID: "res-alpha"}},+ wantErr: "prerequisite Patrol run failed",+ },+ {+ name: "positive error count fails prerequisite even with ok status",+ faults: []FaultSpec{{ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}}},+ collected: map[string]Resource{"alpha": {ID: "res-alpha"}},+ warmup: PatrolRun{Status: "issues_found", ErrorCount: 2},+ findings: []Finding{{ResourceID: "res-alpha"}},+ wantErr: "prerequisite Patrol run failed",+ },+ {+ name: "no run-owned finding created",+ faults: []FaultSpec{{ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}}},+ collected: map[string]Resource{"alpha": {ID: "res-alpha"}},+ warmup: PatrolRun{Status: "issues_found"},+ findings: nil,+ wantErr: "did not create a run-owned finding",+ },+ {+ name: "expected resource not collected",+ faults: []FaultSpec{{ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}}},+ collected: map[string]Resource{},+ warmup: PatrolRun{Status: "issues_found"},+ findings: []Finding{{ResourceID: "other"}},+ wantErr: `expected resource "alpha" was not collected`,+ },+ {+ name: "collected resource has empty id",+ faults: []FaultSpec{{ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}}},+ collected: map[string]Resource{"alpha": {ID: ""}},+ warmup: PatrolRun{Status: "issues_found"},+ findings: []Finding{{ResourceID: "other"}},+ wantErr: `expected resource "alpha" was not collected`,+ },+ {+ name: "no finding for expected resource",+ faults: []FaultSpec{{ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}}},+ collected: map[string]Resource{"alpha": {ID: "res-alpha"}},+ warmup: PatrolRun{Status: "issues_found"},+ findings: []Finding{{ResourceID: "res-beta"}},+ wantErr: "created no finding for expected resource",+ },+ {+ name: "empty expected resource falls back to target and succeeds",+ faults: []FaultSpec{{ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: ""}}},+ collected: map[string]Resource{"alpha": {ID: "res-alpha"}},+ warmup: PatrolRun{Status: "issues_found"},+ findings: []Finding{{ResourceID: "res-alpha"}},+ wantErr: "",+ },+ {+ name: "duplicate alias dedup skips second fault and succeeds",+ faults: twoFaults,+ collected: map[string]Resource{"alpha": {ID: "res-alpha"}},+ warmup: PatrolRun{Status: "issues_found"},+ findings: []Finding{{ResourceID: "res-alpha"}},+ wantErr: "",+ },+ {+ name: "non-required fault is skipped",+ faults: []FaultSpec{+ {ID: "f1", Target: "alpha", Required: true, Expected: ExpectedFinding{Resource: "alpha"}},+ {ID: "f2", Target: "beta", Required: false, Expected: ExpectedFinding{Resource: "beta"}},+ },+ collected: map[string]Resource{"alpha": {ID: "res-alpha"}},+ warmup: PatrolRun{Status: "issues_found"},+ findings: []Finding{{ResourceID: "res-alpha"}},+ wantErr: "",+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ manifest := Manifest{Faults: tc.faults}+ err := validateExistingFindingPrerequisite(manifest, tc.collected, tc.warmup, tc.findings)+ if tc.wantErr == "" {+ if err != nil {+ t.Fatalf("expected nil error, got %v", err)+ }+ return+ }+ qualw0716AssertErrContains(t, err, tc.wantErr)+ })+ }+}++func Test_w0716_qual_ValidateCollectedDockerPredicate(t *testing.T) {+ resources := map[string]Resource{+ "up": {ID: "r-up", Docker: &DockerResource{ContainerState: "running", Health: "healthy", RestartCount: 3}},+ "down": {ID: "r-down", Docker: &DockerResource{ContainerState: "exited", Health: "unhealthy", RestartCount: 0}},+ "bare": {ID: "r-bare"},+ }++ cases := []struct {+ name string+ predicate Predicate+ resources map[string]Resource+ wantErr string+ }{+ {"target absent", Predicate{Probe: "docker.running", Target: "missing", Operator: "eq", Value: json.RawMessage("true")}, resources, "absent from collected resources"},+ {"no docker projection", Predicate{Probe: "docker.running", Target: "bare", Operator: "eq", Value: json.RawMessage("true")}, resources, "has no collected Docker projection"},+ {"health value parse error", Predicate{Probe: "docker.health", Target: "up", Operator: "eq", Value: json.RawMessage("not-a-string")}, resources, "invalid collected health expectation"},+ {"health mismatch", Predicate{Probe: "docker.health", Target: "up", Operator: "eq", Value: json.RawMessage(`"unhealthy"`)}, resources, "collected health="},+ {"health match", Predicate{Probe: "docker.health", Target: "up", Operator: "eq", Value: json.RawMessage(`"healthy"`)}, resources, ""},+ {"health match case insensitive", Predicate{Probe: "docker.health", Target: "up", Operator: "eq", Value: json.RawMessage(`" HEALTHY "`)}, resources, ""},+ {"running value parse error", Predicate{Probe: "docker.running", Target: "up", Operator: "eq", Value: json.RawMessage("not-a-bool")}, resources, "invalid collected running expectation"},+ {"running mismatch", Predicate{Probe: "docker.running", Target: "up", Operator: "eq", Value: json.RawMessage("false")}, resources, "collected running=true"},+ {"running match true", Predicate{Probe: "docker.running", Target: "up", Operator: "eq", Value: json.RawMessage("true")}, resources, ""},+ {"running match false", Predicate{Probe: "docker.running", Target: "down", Operator: "eq", Value: json.RawMessage("false")}, resources, ""},+ {"restart count value parse error", Predicate{Probe: "docker.restart_count", Target: "up", Operator: "eq", Value: json.RawMessage("not-an-int")}, resources, "invalid collected restart-count expectation"},+ {"restart count eq fail", Predicate{Probe: "docker.restart_count", Target: "up", Operator: "eq", Value: json.RawMessage("5")}, resources, "does not satisfy eq 5"},+ {"restart count eq success", Predicate{Probe: "docker.restart_count", Target: "up", Operator: "eq", Value: json.RawMessage("3")}, resources, ""},+ {"restart count gte success", Predicate{Probe: "docker.restart_count", Target: "up", Operator: "gte", Value: json.RawMessage("2")}, resources, ""},+ {"restart count gte fail", Predicate{Probe: "docker.restart_count", Target: "up", Operator: "gte", Value: json.RawMessage("10")}, resources, "does not satisfy gte 10"},+ {"restart count unhandled operator fails", Predicate{Probe: "docker.restart_count", Target: "up", Operator: "gt", Value: json.RawMessage("1")}, resources, "does not satisfy gt 1"},+ {"unhandled probe falls through with nil", Predicate{Probe: "docker.exists", Target: "up", Operator: "eq", Value: json.RawMessage("true")}, resources, ""},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ err := validateCollectedDockerPredicate("subject", tc.predicate, tc.resources)+ if tc.wantErr == "" {+ if err != nil {+ t.Fatalf("expected nil error, got %v", err)+ }+ return+ }+ qualw0716AssertErrContains(t, err, tc.wantErr)+ })+ }+}++func Test_w0716_qual_PatrolScopeResourceIDs(t *testing.T) {+ collected := map[string]Resource{+ "alpha": {ID: "id-alpha"},+ "beta": {ID: "id-beta"},+ "gamma": {ID: "id-gamma"},+ }++ cases := []struct {+ name string+ scoped bool+ scope []string+ want []string+ }{+ {"unscoped returns nil", false, nil, nil},+ {"unscoped ignores scope resources", false, []string{"alpha"}, nil},+ {"scoped with explicit subset sorted", true, []string{"gamma", "alpha"}, []string{"id-alpha", "id-gamma"}},+ {"scoped with empty scope returns all sorted", true, nil, []string{"id-alpha", "id-beta", "id-gamma"}},+ {"scoped all resources sorted", true, []string{"beta", "alpha", "gamma"}, []string{"id-alpha", "id-beta", "id-gamma"}},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ manifest := Manifest{Patrol: PatrolSpec{Scoped: tc.scoped, ScopeResources: tc.scope}}+ got := patrolScopeResourceIDs(manifest, collected)+ if !reflect.DeepEqual(got, tc.want) {+ t.Fatalf("patrolScopeResourceIDs = %v, want %v", got, tc.want)+ }+ })+ }+}diff --git a/internal/config/ai_nil_receiver_w0716_coverage_test.go b/internal/config/ai_nil_receiver_w0716_coverage_test.gonew file mode 100644index 0000000000..d46f25cf59--- /dev/null+++ b/internal/config/ai_nil_receiver_w0716_coverage_test.go@@ -0,0 +1,177 @@+package config++import "testing"++// Test_w0716_cfg_GetOllamaKeepAlive exercises both the nil-receiver+// default-return branch and the field-read branch of GetOllamaKeepAlive.+func Test_w0716_cfg_GetOllamaKeepAlive(t *testing.T) {+ tests := []struct {+ name string+ cfg *AIConfig+ want string+ }{+ {name: "nil receiver returns pulse default", cfg: nil, want: DefaultOllamaKeepAlive},+ {name: "populated returns trimmed value", cfg: &AIConfig{OllamaKeepAlive: " 45m "}, want: "45m"},+ {name: "empty field preserved as empty", cfg: &AIConfig{OllamaKeepAlive: ""}, want: ""},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := tt.cfg.GetOllamaKeepAlive(); got != tt.want {+ t.Fatalf("GetOllamaKeepAlive() = %q, want %q", got, tt.want)+ }+ })+ }+}++// Test_w0716_cfg_GetModel covers the nil-receiver arm of GetModel alongside the+// field-read arm.+func Test_w0716_cfg_GetModel(t *testing.T) {+ tests := []struct {+ name string+ cfg *AIConfig+ want string+ }{+ {name: "nil receiver returns empty", cfg: nil, want: ""},+ {name: "populated returns normalized model", cfg: &AIConfig{Model: "openai:gpt-4o"}, want: "openai:gpt-4o"},+ {name: "retired quickstart normalized away", cfg: &AIConfig{Model: "pulse-hosted"}, want: ""},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := tt.cfg.GetModel(); got != tt.want {+ t.Fatalf("GetModel() = %q, want %q", got, tt.want)+ }+ })+ }+}++// Test_w0716_cfg_NormalizePatrolEventTriggerSettings covers the nil-receiver+// arm and each normalization mutation arm (already-consistent, legacy-aggregate+// backfill, and fully-disabled).+func Test_w0716_cfg_NormalizePatrolEventTriggerSettings(t *testing.T) {+ t.Run("nil receiver returns false", func(t *testing.T) {+ var c *AIConfig+ if c.NormalizePatrolEventTriggerSettings() {+ t.Fatal("nil receiver NormalizePatrolEventTriggerSettings() = true, want false")+ }+ })++ t.Run("already consistent returns false without mutation", func(t *testing.T) {+ cfg := &AIConfig{+ PatrolAlertTriggersEnabled: true,+ PatrolAnomalyTriggersEnabled: true,+ PatrolEventTriggersEnabled: true,+ }+ if cfg.NormalizePatrolEventTriggerSettings() {+ t.Fatal("expected no change for already-consistent config")+ }+ if !cfg.PatrolAlertTriggersEnabled || !cfg.PatrolAnomalyTriggersEnabled || !cfg.PatrolEventTriggersEnabled {+ t.Fatal("consistent config must not be mutated")+ }+ })++ t.Run("legacy aggregate backfills both split flags", func(t *testing.T) {+ cfg := &AIConfig{+ PatrolAlertTriggersEnabled: false,+ PatrolAnomalyTriggersEnabled: false,+ PatrolEventTriggersEnabled: true,+ }+ if !cfg.NormalizePatrolEventTriggerSettings() {+ t.Fatal("expected change when legacy aggregate forces split flags")+ }+ if !cfg.PatrolAlertTriggersEnabled || !cfg.PatrolAnomalyTriggersEnabled {+ t.Fatalf("expected both split flags enabled after normalize, got alert=%v anomaly=%v",+ cfg.PatrolAlertTriggersEnabled, cfg.PatrolAnomalyTriggersEnabled)+ }+ if !cfg.PatrolEventTriggersEnabled {+ t.Fatal("aggregate flag should remain enabled")+ }+ })++ t.Run("fully disabled stays consistent", func(t *testing.T) {+ cfg := &AIConfig{+ PatrolAlertTriggersEnabled: false,+ PatrolAnomalyTriggersEnabled: false,+ PatrolEventTriggersEnabled: false,+ }+ if cfg.NormalizePatrolEventTriggerSettings() {+ t.Fatal("expected no change for fully-disabled consistent config")+ }+ })+}++// Test_w0716_cfg_IsPatrolAlertTriggersEnabled covers the AI-disabled gate arm.+func Test_w0716_cfg_IsPatrolAlertTriggersEnabled(t *testing.T) {+ tests := []struct {+ name string+ cfg *AIConfig+ want bool+ }{+ {name: "disabled when AI master switch off", cfg: &AIConfig{Enabled: false, PatrolAlertTriggersEnabled: true}, want: false},+ {name: "enabled when AI on and alert triggers on", cfg: &AIConfig{Enabled: true, PatrolAlertTriggersEnabled: true}, want: true},+ {name: "false when alert triggers off", cfg: &AIConfig{Enabled: true, PatrolAlertTriggersEnabled: false}, want: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := tt.cfg.IsPatrolAlertTriggersEnabled(); got != tt.want {+ t.Fatalf("IsPatrolAlertTriggersEnabled() = %v, want %v", got, tt.want)+ }+ })+ }+}++// Test_w0716_cfg_IsPatrolAnomalyTriggersEnabled covers the AI-disabled gate arm.+func Test_w0716_cfg_IsPatrolAnomalyTriggersEnabled(t *testing.T) {+ tests := []struct {+ name string+ cfg *AIConfig+ want bool+ }{+ {name: "disabled when AI master switch off", cfg: &AIConfig{Enabled: false, PatrolAnomalyTriggersEnabled: true}, want: false},+ {name: "enabled when AI on and anomaly triggers on", cfg: &AIConfig{Enabled: true, PatrolAnomalyTriggersEnabled: true}, want: true},+ {name: "false when anomaly triggers off", cfg: &AIConfig{Enabled: true, PatrolAnomalyTriggersEnabled: false}, want: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := tt.cfg.IsPatrolAnomalyTriggersEnabled(); got != tt.want {+ t.Fatalf("IsPatrolAnomalyTriggersEnabled() = %v, want %v", got, tt.want)+ }+ })+ }+}++// Test_w0716_cfg_patrolEventTriggerPreferences covers the nil-receiver arm of+// the unexported helper, exercised both directly and via the public accessor,+// plus the legacy-aggregate and split-flag pass-through arms.+func Test_w0716_cfg_patrolEventTriggerPreferences(t *testing.T) {+ t.Run("nil receiver returns false false directly", func(t *testing.T) {+ var c *AIConfig+ alert, anomaly := c.patrolEventTriggerPreferences()+ if alert || anomaly {+ t.Fatalf("nil patrolEventTriggerPreferences() = (%v, %v), want (false, false)", alert, anomaly)+ }+ })++ t.Run("nil receiver via public accessor", func(t *testing.T) {+ var c *AIConfig+ settings := c.GetPatrolEventTriggerSettings()+ if settings.AlertTriggersEnabled || settings.AnomalyTriggersEnabled {+ t.Fatalf("nil GetPatrolEventTriggerSettings() = %+v, want both false", settings)+ }+ })++ t.Run("legacy aggregate enables both", func(t *testing.T) {+ cfg := &AIConfig{PatrolEventTriggersEnabled: true}+ alert, anomaly := cfg.patrolEventTriggerPreferences()+ if !alert || !anomaly {+ t.Fatalf("patrolEventTriggerPreferences() = (%v, %v), want (true, true) via legacy aggregate", alert, anomaly)+ }+ })++ t.Run("split flags pass through unchanged", func(t *testing.T) {+ cfg := &AIConfig{PatrolAlertTriggersEnabled: true, PatrolAnomalyTriggersEnabled: false}+ alert, anomaly := cfg.patrolEventTriggerPreferences()+ if !alert || anomaly {+ t.Fatalf("patrolEventTriggerPreferences() = (%v, %v), want (true, false)", alert, anomaly)+ }+ })+}diff --git a/internal/unifiedresources/adapters_pure_w0716_coverage_test.go b/internal/unifiedresources/adapters_pure_w0716_coverage_test.gonew file mode 100644index 0000000000..8872b29c9c--- /dev/null+++ b/internal/unifiedresources/adapters_pure_w0716_coverage_test.go@@ -0,0 +1,509 @@+package unifiedresources++import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++// ---------------------------------------------------------------------------+// maxNodeTemp — pure transform over *models.Temperature; exercises the nil,+// unavailable, CPUMax, CPUPackage, and Cores-loop branches.+// ---------------------------------------------------------------------------++func Test_w0716_ur_maxNodeTemp(t *testing.T) {+ core42 := 42.0+ core55 := 55.0+ cpuMax := 60.0+ cpuPkg := 58.0++ tests := []struct {+ name string+ in *models.Temperature+ want *float64+ }{+ {name: "nil input returns nil", in: nil, want: nil},+ {name: "available=false returns nil", in: &models.Temperature{Available: false, CPUMax: 90}, want: nil},+ {name: "CPUMax > 0 preferred", in: &models.Temperature{Available: true, CPUMax: cpuMax, CPUPackage: cpuPkg}, want: &cpuMax},+ {name: "CPUPackage used when CPUMax is zero", in: &models.Temperature{Available: true, CPUPackage: cpuPkg}, want: &cpuPkg},+ {name: "CPUPackage ignored when zero, falls to cores", in: &models.Temperature{+ Available: true,+ Cores: []models.CoreTemp{{Core: 0, Temp: core42}, {Core: 1, Temp: core55}},+ }, want: &core55},+ {name: "negative core temps still picked (no filtering)", in: &models.Temperature{+ Available: true,+ Cores: []models.CoreTemp{{Core: 0, Temp: -1}},+ }, want: ptrFloat(-1)},+ {name: "no CPU data at all returns nil", in: &models.Temperature{Available: true}, want: nil},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := maxNodeTemp(tt.in)+ if tt.want == nil {+ if got != nil {+ t.Fatalf("maxNodeTemp() = %v, want nil", *got)+ }+ return+ }+ if got == nil {+ t.Fatalf("maxNodeTemp() = nil, want %v", *tt.want)+ }+ if *got != *tt.want {+ t.Fatalf("maxNodeTemp() = %v, want %v", *got, *tt.want)+ }+ })+ }+}++func ptrFloat(v float64) *float64 { return &v }++// ---------------------------------------------------------------------------+// convertCephServices — pure transform over []models.CephServiceStatus.+// ---------------------------------------------------------------------------++func Test_w0716_ur_convertCephServices(t *testing.T) {+ t.Run("nil slice returns nil", func(t *testing.T) {+ if got := convertCephServices(nil); got != nil {+ t.Fatalf("expected nil, got %v", got)+ }+ })+ t.Run("empty slice returns nil", func(t *testing.T) {+ if got := convertCephServices([]models.CephServiceStatus{}); got != nil {+ t.Fatalf("expected nil, got %v", got)+ }+ })+ t.Run("populated slice copies fields", func(t *testing.T) {+ in := []models.CephServiceStatus{+ {Type: "mon", Running: 3, Total: 3, Message: "ok"},+ {Type: "osd", Running: 5, Total: 6, Message: "1 down"},+ }+ got := convertCephServices(in)+ if len(got) != 2 {+ t.Fatalf("expected 2 entries, got %d", len(got))+ }+ if got[0].Type != "mon" || got[0].Running != 3 || got[0].Total != 3 {+ t.Fatalf("entry 0 mismatch: %+v", got[0])+ }+ if got[1].Type != "osd" || got[1].Running != 5 || got[1].Total != 6 {+ t.Fatalf("entry 1 mismatch: %+v", got[1])+ }+ })+ t.Run("message field is dropped", func(t *testing.T) {+ got := convertCephServices([]models.CephServiceStatus{{Type: "mgr", Running: 1, Total: 1, Message: "dropped"}})+ if len(got) != 1 {+ t.Fatalf("expected 1 entry, got %d", len(got))+ }+ })+}++// ---------------------------------------------------------------------------+// convertGuestInterfaces — pure transform over []models.GuestNetworkInterface.+// ---------------------------------------------------------------------------++func Test_w0716_ur_convertGuestInterfaces(t *testing.T) {+ t.Run("nil returns nil", func(t *testing.T) {+ if got := convertGuestInterfaces(nil); got != nil {+ t.Fatalf("expected nil, got %v", got)+ }+ })+ t.Run("empty returns nil", func(t *testing.T) {+ if got := convertGuestInterfaces([]models.GuestNetworkInterface{}); got != nil {+ t.Fatalf("expected nil, got %v", got)+ }+ })+ t.Run("populated trims fields and deduplicates addresses", func(t *testing.T) {+ in := []models.GuestNetworkInterface{+ {Name: " eth0 ", MAC: " AA:BB:CC:DD:EE:FF ", Addresses: []string{"10.0.0.1", "10.0.0.2", "10.0.0.1"}, RXBytes: 1024, TXBytes: 2048},+ }+ got := convertGuestInterfaces(in)+ if len(got) != 1 {+ t.Fatalf("expected 1, got %d", len(got))+ }+ iface := got[0]+ if iface.Name != "eth0" {+ t.Fatalf("Name = %q", iface.Name)+ }+ if iface.MAC != "AA:BB:CC:DD:EE:FF" {+ t.Fatalf("MAC = %q", iface.MAC)+ }+ if len(iface.Addresses) != 2 || iface.Addresses[0] != "10.0.0.1" || iface.Addresses[1] != "10.0.0.2" {+ t.Fatalf("Addresses = %v", iface.Addresses)+ }+ if iface.RXBytes != 1024 || iface.TXBytes != 2048 {+ t.Fatalf("RX/TX = %d/%d", iface.RXBytes, iface.TXBytes)+ }+ })+ t.Run("negative RX/TX clamped to zero", func(t *testing.T) {+ in := []models.GuestNetworkInterface{+ {Name: "net0", RXBytes: -500, TXBytes: -100},+ }+ got := convertGuestInterfaces(in)+ if got[0].RXBytes != 0 || got[0].TXBytes != 0 {+ t.Fatalf("expected 0/0, got %d/%d", got[0].RXBytes, got[0].TXBytes)+ }+ })+}++// ---------------------------------------------------------------------------+// firstDockerImageReference — pure transform over models.DockerImage.+// ---------------------------------------------------------------------------++func Test_w0716_ur_firstDockerImageReference(t *testing.T) {+ tests := []struct {+ name string+ image models.DockerImage+ want string+ }{+ {name: "empty image returns empty", image: models.DockerImage{}, want: ""},+ {name: "first valid repo tag returned", image: models.DockerImage{+ RepoTags: []string{"nginx:latest", "nginx:1.21"},+ }, want: "nginx:latest"},+ {name: "none tag skipped falls to next tag", image: models.DockerImage{+ RepoTags: []string{"<none>:<none>", "redis:7"},+ }, want: "redis:7"},+ {name: "whitespace-only tag skipped", image: models.DockerImage{+ RepoTags: []string{" ", "alpine:3"},+ }, want: "alpine:3"},+ {name: "all none tags fall to digests", image: models.DockerImage{+ RepoTags: []string{"<none>:<none>"},+ RepoDigests: []string{"nginx@sha256:abc123"},+ }, want: "nginx@sha256:abc123"},+ {name: "no tags no digests returns empty", image: models.DockerImage{+ RepoTags: []string{"<none>:<none>"},+ }, want: ""},+ {name: "leading whitespace in tag is trimmed", image: models.DockerImage{+ RepoTags: []string{" busybox:latest "},+ }, want: "busybox:latest"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := firstDockerImageReference(tt.image)+ if got != tt.want {+ t.Fatalf("firstDockerImageReference() = %q, want %q", got, tt.want)+ }+ })+ }+}++// ---------------------------------------------------------------------------+// hostUnraidCacheStorageIdentity — pure transform over (host, disk).+// ---------------------------------------------------------------------------++func Test_w0716_ur_hostUnraidCacheStorageIdentity(t *testing.T) {+ tests := []struct {+ name string+ host models.Host+ disk models.HostUnraidDisk+ want string+ }{+ {name: "no pool name returns empty", host: models.Host{MachineID: "m1"}, disk: models.HostUnraidDisk{}, want: ""},+ {name: "pool from device when name empty", host: models.Host{MachineID: "m1"}, disk: models.HostUnraidDisk{Device: "/dev/sdb"}, want: "m1/storage/unraid-cache/sdb"},+ {name: "machineID preferred", host: models.Host{MachineID: "mid", Hostname: "tower"}, disk: models.HostUnraidDisk{Name: "cache"}, want: "mid/storage/unraid-cache/cache"},+ {name: "hostname fallback when no machineID", host: models.Host{Hostname: "tower"}, disk: models.HostUnraidDisk{Name: "cache"}, want: "tower/storage/unraid-cache/cache"},+ {name: "whitespace machineID falls to hostname", host: models.Host{MachineID: " ", Hostname: "nas"}, disk: models.HostUnraidDisk{Name: "nvme-cache"}, want: "nas/storage/unraid-cache/nvme-cache"},+ {name: "both empty returns empty", host: models.Host{}, disk: models.HostUnraidDisk{Name: "cache"}, want: ""},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := hostUnraidCacheStorageIdentity(tt.host, tt.disk)+ if got != tt.want {+ t.Fatalf("hostUnraidCacheStorageIdentity() = %q, want %q", got, tt.want)+ }+ })+ }+}++// ---------------------------------------------------------------------------+// unraidStorageCapacity — pure transform over models.Host (requires+// host.Unraid != nil). Exercises the /mnt/user short-circuit, the data-disk+// sum path, the deviceUsage fallback, and the zero-total arm.+// ---------------------------------------------------------------------------++func Test_w0716_ur_unraidStorageCapacity(t *testing.T) {+ t.Run("mnt/user mountpoint short-circuits", func(t *testing.T) {+ host := models.Host{+ Disks: []models.Disk{{Mountpoint: "/mnt/user", Total: 10000, Used: 4000, Free: 6000, Usage: 40.0}},+ Unraid: &models.HostUnraidStorage{},+ }+ total, used, free, pct := unraidStorageCapacity(host)+ if total != 10000 || used != 4000 || free != 6000 || pct != 40.0 {+ t.Fatalf("got (%d,%d,%d,%f), want (10000,4000,6000,40.0)", total, used, free, pct)+ }+ })++ t.Run("mnt/user0 mountpoint short-circuits", func(t *testing.T) {+ host := models.Host{+ Disks: []models.Disk{{Mountpoint: "/mnt/user0", Total: 5000, Used: 2500, Free: 2500, Usage: 50.0}},+ Unraid: &models.HostUnraidStorage{},+ }+ total, used, free, pct := unraidStorageCapacity(host)+ if total != 5000 || used != 2500 || free != 2500 || pct != 50.0 {+ t.Fatalf("got (%d,%d,%d,%f), want (5000,2500,2500,50.0)", total, used, free, pct)+ }+ })++ t.Run("data disk capacity summed from UsedBytes and FreeBytes", func(t *testing.T) {+ host := models.Host{+ Disks: []models.Disk{},+ Unraid: &models.HostUnraidStorage{Disks: []models.HostUnraidDisk{+ {Name: "disk1", Role: "data", UsedBytes: 3000, FreeBytes: 7000},+ {Name: "disk2", Role: "data", UsedBytes: 2000, FreeBytes: 8000},+ }},+ }+ total, used, free, pct := unraidStorageCapacity(host)+ if total != 20000 || used != 5000 || free != 15000 {+ t.Fatalf("got (%d,%d,%d), want (20000,5000,15000)", total, used, free)+ }+ wantPct := float64(5000) / float64(20000) * 100+ if pct != wantPct {+ t.Fatalf("pct = %f, want %f", pct, wantPct)+ }+ })++ t.Run("parity disk excluded from sum", func(t *testing.T) {+ host := models.Host{+ Disks: []models.Disk{},+ Unraid: &models.HostUnraidStorage{Disks: []models.HostUnraidDisk{+ {Name: "disk1", Role: "data", UsedBytes: 1000, FreeBytes: 1000},+ {Name: "parity1", Role: "parity", UsedBytes: 9999, FreeBytes: 9999},+ }},+ }+ total, _, _, _ := unraidStorageCapacity(host)+ if total != 2000 {+ t.Fatalf("total = %d, want 2000 (parity excluded)", total)+ }+ })++ t.Run("deviceUsage fallback when disk has no capacity", func(t *testing.T) {+ host := models.Host{+ Disks: []models.Disk{{Device: "/dev/sda", Total: 5000, Used: 2000, Free: 3000, Mountpoint: ""}},+ Unraid: &models.HostUnraidStorage{Disks: []models.HostUnraidDisk{+ {Name: "disk1", Role: "data", Device: "/dev/sda", SizeBytes: 0, UsedBytes: 0, FreeBytes: 0},+ }},+ }+ total, used, free, pct := unraidStorageCapacity(host)+ if total != 5000 || used != 2000 || free != 3000 {+ t.Fatalf("got (%d,%d,%d), want (5000,2000,3000)", total, used, free)+ }+ if pct != 40.0 {+ t.Fatalf("pct = %f, want 40.0", pct)+ }+ })++ t.Run("no data yields all zeros", func(t *testing.T) {+ host := models.Host{+ Disks: []models.Disk{},+ Unraid: &models.HostUnraidStorage{Disks: []models.HostUnraidDisk{}},+ }+ total, used, free, pct := unraidStorageCapacity(host)+ if total != 0 || used != 0 || free != 0 || pct != 0 {+ t.Fatalf("got (%d,%d,%d,%f), want all zeros", total, used, free, pct)+ }+ })+}++// ---------------------------------------------------------------------------+// shouldScaleLegacyUnraidKiBSize — pure predicate with branches for size+// bounds, direct UsedBytes+FreeBytes match, and per-role array/cache checks.+// ---------------------------------------------------------------------------++func Test_w0716_ur_shouldScaleLegacyUnraidKiBSize(t *testing.T) {+ tests := []struct {+ name string+ host models.Host+ disk models.HostUnraidDisk+ size int64+ want bool+ }{+ {+ name: "size <= 0 returns false",+ host: models.Host{Unraid: &models.HostUnraidStorage{}},+ disk: models.HostUnraidDisk{Role: "data"},+ size: 0, want: false,+ },+ {+ name: "size negative returns false",+ host: models.Host{Unraid: &models.HostUnraidStorage{}},+ disk: models.HostUnraidDisk{Role: "data"},+ size: -1, want: false,+ },+ {+ name: "size >= max plausible returns false",+ host: models.Host{Unraid: &models.HostUnraidStorage{}},+ disk: models.HostUnraidDisk{Role: "data"},+ size: 100_000_000_000, want: false,+ },+ {+ name: "direct UsedBytes+FreeBytes match returns true",+ host: models.Host{Unraid: &models.HostUnraidStorage{}},+ disk: models.HostUnraidDisk{Role: "data", UsedBytes: 500_000, FreeBytes: 524_000},+ size: 1000, want: true,+ },+ {+ name: "data role no array mount returns false",+ host: models.Host{Disks: []models.Disk{}, Unraid: &models.HostUnraidStorage{}},+ disk: models.HostUnraidDisk{Name: "disk1", Role: "data"},+ size: 1000, want: false,+ },+ {+ name: "data role array total matches raw KiB total",+ host: models.Host{+ Disks: []models.Disk{{Mountpoint: "/mnt/user", Total: 1_024_000_000_000}},+ Unraid: &models.HostUnraidStorage{Disks: []models.HostUnraidDisk{{Name: "disk1", Role: "data", SizeBytes: 1_000_000_000}}},+ },+ disk: models.HostUnraidDisk{Name: "disk1", Role: "data"},+ size: 1000, want: true,+ },+ {+ name: "data role array total does not match returns false",+ host: models.Host{+ Disks: []models.Disk{{Mountpoint: "/mnt/user", Total: 999}},+ Unraid: &models.HostUnraidStorage{Disks: []models.HostUnraidDisk{{Name: "disk1", Role: "data", SizeBytes: 1_000_000_000}}},+ },+ disk: models.HostUnraidDisk{Name: "disk1", Role: "data"},+ size: 1000, want: false,+ },+ {+ name: "cache role mount total matches size",+ host: models.Host{+ Disks: []models.Disk{{Mountpoint: "/mnt/cache", Total: 1_024_000}},+ },+ disk: models.HostUnraidDisk{Name: "cache", Role: "cache"},+ size: 1000, want: true,+ },+ {+ name: "cache role mount total does not match returns false",+ host: models.Host{+ Disks: []models.Disk{{Mountpoint: "/mnt/cache", Total: 5}},+ },+ disk: models.HostUnraidDisk{Name: "cache", Role: "cache"},+ size: 1000, want: false,+ },+ {+ name: "unknown role returns false",+ host: models.Host{Unraid: &models.HostUnraidStorage{}},+ disk: models.HostUnraidDisk{Name: "mystery"},+ size: 1000, want: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := shouldScaleLegacyUnraidKiBSize(tt.host, tt.disk, tt.size)+ if got != tt.want {+ t.Fatalf("shouldScaleLegacyUnraidKiBSize() = %v, want %v", got, tt.want)+ }+ })+ }+}++// ---------------------------------------------------------------------------+// normalizeDockerLifecycleRuntime — pure normalizer over runtime + podman flag.+// ---------------------------------------------------------------------------++func Test_w0716_ur_normalizeDockerLifecycleRuntime(t *testing.T) {+ tests := []struct {+ name string+ runtime string+ podman bool+ want string+ }{+ {name: "docker stays docker", runtime: "docker", podman: false, want: "docker"},+ {name: "podman stays podman", runtime: "podman", podman: false, want: "podman"},+ {name: "empty with podman flag yields podman", runtime: "", podman: true, want: "podman"},+ {name: "empty without podman yields docker", runtime: "", podman: false, want: "docker"},+ {name: "unknown runtime yields empty", runtime: "containerd", podman: false, want: ""},+ {name: "whitespace runtime treated as empty", runtime: " ", podman: false, want: "docker"},+ {name: "uppercase docker normalized", runtime: "DOCKER", podman: false, want: "docker"},+ {name: "uppercase podman with whitespace", runtime: " Podman ", podman: true, want: "podman"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := normalizeDockerLifecycleRuntime(tt.runtime, tt.podman)+ if got != tt.want {+ t.Fatalf("normalizeDockerLifecycleRuntime() = %q, want %q", got, tt.want)+ }+ })+ }+}++// ---------------------------------------------------------------------------+// ContractResourceType — switch over ResourceType with per-case arms.+// ---------------------------------------------------------------------------++func Test_w0716_ur_ContractResourceType(t *testing.T) {+ tests := []struct {+ name string+ resource Resource+ want ResourceType+ }{+ {+ name: "agent with proxmox payload",+ resource: Resource{Type: ResourceTypeAgent, Proxmox: &ProxmoxData{}},+ want: ResourceTypeAgent,+ },+ {+ name: "agent with agent payload",+ resource: Resource{Type: ResourceTypeAgent, Agent: &AgentData{}},+ want: ResourceTypeAgent,+ },+ {+ name: "agent with truenas payload",+ resource: Resource{Type: ResourceTypeAgent, TrueNAS: &TrueNASData{}},+ want: ResourceTypeAgent,+ },+ {+ name: "agent with vmware payload",+ resource: Resource{Type: ResourceTypeAgent, VMware: &VMwareData{}},+ want: ResourceTypeAgent,+ },+ {+ name: "agent with docker payload maps to docker-host",+ resource: Resource{Type: ResourceTypeAgent, Docker: &DockerData{}},+ want: ResourceType("docker-host"),+ },+ {+ name: "agent with no payload defaults to agent",+ resource: Resource{Type: ResourceTypeAgent},+ want: ResourceTypeAgent,+ },+ {+ name: "system container",+ resource: Resource{Type: ResourceTypeSystemContainer},+ want: ResourceTypeSystemContainer,+ },+ {+ name: "app container",+ resource: Resource{Type: ResourceTypeAppContainer},+ want: ResourceTypeAppContainer,+ },+ {+ name: "storage falls through default arm",+ resource: Resource{Type: ResourceTypeStorage},+ want: ResourceTypeStorage,+ },+ {+ name: "vm falls through default arm",+ resource: Resource{Type: ResourceTypeVM},+ want: ResourceTypeVM,+ },+ {+ name: "unknown type normalized in default arm",+ resource: Resource{Type: ResourceType(" K8S-CLUSTER ")},+ want: ResourceType("k8s-cluster"),+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := ContractResourceType(tt.resource)+ if got != tt.want {+ t.Fatalf("ContractResourceType() = %q, want %q", got, tt.want)+ }+ })+ }+}diff --git a/pkg/aicontracts/investigation_pure_w0716_coverage_test.go b/pkg/aicontracts/investigation_pure_w0716_coverage_test.gonew file mode 100644index 0000000000..09d53b4fd3--- /dev/null+++ b/pkg/aicontracts/investigation_pure_w0716_coverage_test.go@@ -0,0 +1,167 @@+package aicontracts++import (+ "errors"+ "strings"+ "testing"+ "time"+)++// Test_w0716_contracts_OrchestratorInvestigationError_NilReceiverDefensiveBranches+// exercises the typed-nil-receiver defensive arms of Error/Unwrap/RunFailure/+// ProposalFailure. These methods are deliberately nil-safe so a typed nil+// pointer flowing through an error chain does not panic; the coverage gaps+// were exactly these nil arms.+func Test_w0716_contracts_OrchestratorInvestigationError_NilReceiverDefensiveBranches(t *testing.T) {+ // Typed nil pointer of *OrchestratorInvestigationError.+ var nilTypedErr *OrchestratorInvestigationError = (*OrchestratorInvestigationError)(nil)++ if got := nilTypedErr.Error(); got != "" {+ t.Fatalf("nil receiver Error() = %q, want %q", got, "")+ }+ if got := nilTypedErr.Unwrap(); got != nil {+ t.Fatalf("nil receiver Unwrap() = %v, want nil", got)+ }+ if got := nilTypedErr.RunFailure(); got != nil {+ t.Fatalf("nil receiver RunFailure() = %v, want nil", got)+ }+ if got := nilTypedErr.ProposalFailure(); got != nil {+ t.Fatalf("nil receiver ProposalFailure() = %v, want nil", got)+ }+}++// Test_w0716_contracts_OrchestratorInvestigationError_PopulatedErrorAndUnwrap+// covers the populated arms of Error() (0% covered — never called directly by+// existing tests) and Unwrap() (populated arm), asserting the joined string+// carries both failure channels and Unwrap returns exactly the two errors.+func Test_w0716_contracts_OrchestratorInvestigationError_PopulatedErrorAndUnwrap(t *testing.T) {+ runFailure := errors.New("provider unavailable")+ err := NewOrchestratorInvestigationError(runFailure, ErrInvestigationProposalAmbiguous)+ oie, ok := err.(*OrchestratorInvestigationError)+ if !ok {+ t.Fatalf("expected *OrchestratorInvestigationError, got %T", err)+ }++ msg := oie.Error()+ if !strings.Contains(msg, "provider unavailable") {+ t.Fatalf("Error() missing run failure message: %q", msg)+ }+ if !strings.Contains(msg, ErrInvestigationProposalAmbiguous.Error()) {+ t.Fatalf("Error() missing proposal failure message: %q", msg)+ }++ unwrapped := oie.Unwrap()+ if len(unwrapped) != 2 {+ t.Fatalf("Unwrap() returned %d errors, want 2", len(unwrapped))+ }+ if unwrapped[0] != runFailure {+ t.Fatalf("Unwrap()[0] = %v, want %v", unwrapped[0], runFailure)+ }+ if unwrapped[1] != ErrInvestigationProposalAmbiguous {+ t.Fatalf("Unwrap()[1] = %v, want %v", unwrapped[1], ErrInvestigationProposalAmbiguous)+ }+}++// Test_w0716_contracts_NewOrchestratorInvestigationError_NilArm covers the+// uncovered both-nil arm of NewOrchestratorInvestigationError, which must+// return a literal nil (not a typed nil pointer) so errors.Is/!=nil checks+// behave correctly downstream.+func Test_w0716_contracts_NewOrchestratorInvestigationError_NilArm(t *testing.T) {+ if got := NewOrchestratorInvestigationError(nil, nil); got != nil {+ t.Fatalf("NewOrchestratorInvestigationError(nil, nil) = %#v, want nil", got)+ }+}++// Test_w0716_contracts_NewOrchestratorInvestigationError_PartialFailure+// covers the constructor's populated arm when only one channel is set,+// confirming the other accessor returns nil and the build path works for a+// run-only failure (mirrors a completed-but-proposal-rejected outcome).+func Test_w0716_contracts_NewOrchestratorInvestigationError_PartialFailure(t *testing.T) {+ runFailure := errors.New("provider unavailable")+ err := NewOrchestratorInvestigationError(runFailure, nil)+ if err == nil {+ t.Fatal("expected non-nil error when only runFailure set")+ }+ oie, ok := err.(*OrchestratorInvestigationError)+ if !ok {+ t.Fatalf("expected *OrchestratorInvestigationError, got %T", err)+ }+ if oie.RunFailure() != runFailure {+ t.Fatalf("RunFailure() = %v, want %v", oie.RunFailure(), runFailure)+ }+ if oie.ProposalFailure() != nil {+ t.Fatalf("ProposalFailure() = %v, want nil", oie.ProposalFailure())+ }+}++// Test_w0716_contracts_DefaultInvestigationConfig_FieldDefaults asserts every+// default field value of the returned InvestigationConfig. The function is+// pure and previously had 0% coverage; pinning each field guards the safety+// ceilings and budgets against silent drift.+func Test_w0716_contracts_DefaultInvestigationConfig_FieldDefaults(t *testing.T) {+ cfg := DefaultInvestigationConfig()++ // MaxTurns reserves two responses on top of the default 15-call evidence+ // budget: 15 + 2 = 17.+ if cfg.MaxTurns != 17 {+ t.Fatalf("MaxTurns = %d, want 17", cfg.MaxTurns)+ }+ if cfg.MaxEvidenceCalls != 15 {+ t.Fatalf("MaxEvidenceCalls = %d, want 15", cfg.MaxEvidenceCalls)+ }+ if cfg.Timeout != 10*time.Minute {+ t.Fatalf("Timeout = %v, want 10m", cfg.Timeout)+ }+ if cfg.MaxConcurrent != 3 {+ t.Fatalf("MaxConcurrent = %d, want 3", cfg.MaxConcurrent)+ }+ if cfg.MaxAttemptsPerFinding != 3 {+ t.Fatalf("MaxAttemptsPerFinding = %d, want 3", cfg.MaxAttemptsPerFinding)+ }+ if cfg.CooldownDuration != 1*time.Hour {+ t.Fatalf("CooldownDuration = %v, want 1h", cfg.CooldownDuration)+ }+ if cfg.TimeoutCooldownDuration != 10*time.Minute {+ t.Fatalf("TimeoutCooldownDuration = %v, want 10m", cfg.TimeoutCooldownDuration)+ }+ if cfg.VerificationDelay != 30*time.Second {+ t.Fatalf("VerificationDelay = %v, want 30s", cfg.VerificationDelay)+ }+}++// Test_w0716_contracts_InvestigationModelTurnLimit covers both the positive+// path (budget + 2) and the <=0 clamp branch, which resets the evidence budget+// to its default of 15 before adding the two reserved turns.+func Test_w0716_contracts_InvestigationModelTurnLimit(t *testing.T) {+ tests := []struct {+ name string+ maxEvidenceCalls int+ want int+ }{+ {name: "positive limit adds two reserved turns", maxEvidenceCalls: 15, want: 17},+ {name: "small positive value honored", maxEvidenceCalls: 3, want: 5},+ {name: "zero clamps to default budget then adds two", maxEvidenceCalls: 0, want: 17},+ {name: "negative clamps to default budget then adds two", maxEvidenceCalls: -1, want: 17},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := InvestigationModelTurnLimit(tt.maxEvidenceCalls); got != tt.want {+ t.Fatalf("InvestigationModelTurnLimit(%d) = %d, want %d", tt.maxEvidenceCalls, got, tt.want)+ }+ })+ }+}++// Test_w0716_contracts_InvestigationRecordFix_NormalizeCollections covers the+// zero-value normalization path: a nil Commands slice must become a non-nil+// empty slice so downstream JSON/wire projections emit "commands":[] rather+// than omitting the field.+func Test_w0716_contracts_InvestigationRecordFix_NormalizeCollections(t *testing.T) {+ fix := InvestigationRecordFix{}.NormalizeCollections()+ if fix.Commands == nil {+ t.Fatal("NormalizeCollections must replace nil Commands with a non-nil empty slice")+ }+ if len(fix.Commands) != 0 {+ t.Fatalf("Commands len = %d, want 0", len(fix.Commands))+ }+}