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 branch-coverage tests for AI tools command classifiers
rcourtman7da4890ce919
diff --git a/internal/ai/tools/tools_query_curlwget_branchcov_test.go b/internal/ai/tools/tools_query_curlwget_branchcov_test.gonew file mode 100644index 0000000000..1334433cd6--- /dev/null+++ b/internal/ai/tools/tools_query_curlwget_branchcov_test.go@@ -0,0 +1,340 @@+package tools++import "testing"++// This file raises branch coverage for the curl/wget read-only classifier+// helpers in tools_query.go:+// - isHTTPMutationMethod+// - shortCurlOptionCluster+// - curlHasHTTPURL+// - isWgetWriteOrMutationOption+// - isCurlMutationOrFileOutput+//+// Each function is exercised through table-driven cases that target the+// uncovered switch arms, guard clauses, and early/return-false paths.++// TestIsHTTPMutationMethod_BranchCov covers every case arm of+// isHTTPMutationMethod including the trimming, lowercasing and the default+// (non-mutation) arm.+func TestIsHTTPMutationMethod_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ method string+ want bool+ }{+ {name: "post_lower", method: "post", want: true},+ {name: "put_lower", method: "put", want: true},+ {name: "patch_lower", method: "patch", want: true},+ {name: "delete_lower", method: "delete", want: true},+ {name: "post_upper", method: "POST", want: true},+ {name: "post_mixed_case", method: "PoSt", want: true},+ {name: "delete_upper", method: "DELETE", want: true},+ {name: "post_padded", method: " POST ", want: true},+ {name: "patch_tab", method: "\tpatch\n", want: true},+ {name: "get_is_not_mutation", method: "GET", want: false},+ {name: "get_lower", method: "get", want: false},+ {name: "head", method: "HEAD", want: false},+ {name: "options", method: "OPTIONS", want: false},+ {name: "connect", method: "CONNECT", want: false},+ {name: "trace", method: "TRACE", want: false},+ {name: "empty", method: "", want: false},+ {name: "unknown", method: "BOGUS", want: false},+ {name: "connect_lower_padded", method: " connect ", want: false},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := isHTTPMutationMethod(tc.method)+ if got != tc.want {+ t.Fatalf("isHTTPMutationMethod(%q) = %v, want %v", tc.method, got, tc.want)+ }+ })+ }+}++// TestShortCurlOptionCluster_BranchCov covers every return path of+// shortCurlOptionCluster: non-option tokens, long options, too-short tokens,+// the -X/-d exclusions and the normal short-option cluster return.+func TestShortCurlOptionCluster_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ token string+ want string+ }{+ {name: "no_dash_prefix", token: "output", want: ""},+ {name: "bare_word", token: "http://x", want: ""},+ {name: "empty", token: "", want: ""},+ {name: "single_dash", token: "-", want: ""},+ {name: "short_o_len2", token: "-o", want: ""},+ {name: "short_L_len2", token: "-L", want: ""},+ {name: "short_K_len2", token: "-K", want: ""},+ {name: "short_F_len2", token: "-F", want: ""},+ {name: "long_output", token: "--output", want: ""},+ {name: "long_request_equals", token: "--request=POST", want: ""},+ {name: "long_data_raw", token: "--data-raw", want: ""},+ {name: "X_attached_excluded", token: "-XPOST", want: ""},+ {name: "X_attached_lower", token: "-xpost", want: "xpost"},+ {name: "d_attached_excluded", token: "-ddata", want: ""},+ {name: "cluster_vL", token: "-vL", want: "vL"},+ {name: "cluster_sO", token: "-sO", want: "sO"},+ {name: "cluster_sK", token: "-sK", want: "sK"},+ {name: "cluster_sF", token: "-sF", want: "sF"},+ {name: "cluster_sc", token: "-sc", want: "sc"},+ {name: "cluster_silent", token: "-s", want: ""}, // len 2 < 3+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := shortCurlOptionCluster(tc.token)+ if got != tc.want {+ t.Fatalf("shortCurlOptionCluster(%q) = %q, want %q", tc.token, got, tc.want)+ }+ })+ }+}++// TestCurlHasHTTPURL_BranchCov covers every arm of curlHasHTTPURL: direct+// http(s):// prefixes, the --url space-separated form (matching and+// non-matching next token), the --url= attached form, the --url-at-end guard,+// quoted URLs and the no-match default.+func TestCurlHasHTTPURL_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ fields []string+ want bool+ }{+ {name: "empty", fields: []string{}, want: false},+ {name: "http_direct", fields: []string{"http://example.com"}, want: true},+ {name: "https_direct", fields: []string{"https://example.com"}, want: true},+ {name: "http_uppercase", fields: []string{"HTTP://EXAMPLE.COM"}, want: true},+ {name: "https_mixed_case", fields: []string{"HtTpS://example.com"}, want: true},+ {name: "http_quoted", fields: []string{`"http://example.com"`}, want: true},+ {name: "http_single_quoted", fields: []string{"'https://example.com'"}, want: true},+ {name: "ftp_not_http", fields: []string{"ftp://example.com"}, want: false},+ {name: "ws_not_http", fields: []string{"ws://example.com"}, want: false},+ {name: "bare_host", fields: []string{"example.com"}, want: false},+ {name: "http_after_option", fields: []string{"-s", "http://example.com"}, want: true},+ {name: "url_space_http", fields: []string{"--url", "http://example.com"}, want: true},+ {name: "url_space_https", fields: []string{"--url", "https://example.com"}, want: true},+ {name: "url_space_https_upper", fields: []string{"--url", "HTTPS://example.com"}, want: true},+ {name: "url_space_https_quoted", fields: []string{"--url", `"https://example.com"`}, want: true},+ {name: "url_space_ftp", fields: []string{"--url", "ftp://example.com"}, want: false},+ {name: "url_space_bare", fields: []string{"--url", "example.com"}, want: false},+ {name: "url_at_end_no_next", fields: []string{"--url"}, want: false},+ {name: "url_equals_http", fields: []string{"--url=http://example.com"}, want: true},+ {name: "url_equals_https", fields: []string{"--url=https://example.com"}, want: true},+ {name: "url_equals_https_upper", fields: []string{"--url=HTTPS://EXAMPLE.COM"}, want: true},+ {name: "url_equals_ftp", fields: []string{"--url=ftp://example.com"}, want: false},+ {name: "url_equals_bare", fields: []string{"--url=example.com"}, want: false},+ {name: "options_only_no_url", fields: []string{"-s", "-L", "-o", "out"}, want: false},+ {name: "url_space_http_after_opts", fields: []string{"-s", "--url", "http://x"}, want: true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := curlHasHTTPURL(tc.fields)+ if got != tc.want {+ t.Fatalf("curlHasHTTPURL(%v) = %v, want %v", tc.fields, got, tc.want)+ }+ })+ }+}++// TestIsWgetWriteOrMutationOption_BranchCov covers every switch arm of+// isWgetWriteOrMutationOption. The test reproduces the real caller's contract+// by passing tokenLower = strings.ToLower(token).+func TestIsWgetWriteOrMutationOption_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ token string+ want bool+ }{+ // Case 1: -O / --output-document+ {name: "O_exact", token: "-O", want: true},+ {name: "O_attached", token: "-Ofile", want: true},+ {name: "output_document_long", token: "--output-document", want: true},+ {name: "output_document_equals", token: "--output-document=-", want: true},++ // Case 2: -o / -a / --output-file / --append-output+ {name: "o_exact", token: "-o", want: true},+ {name: "o_attached", token: "-olog", want: true},+ {name: "a_exact", token: "-a", want: true},+ {name: "a_attached", token: "-alog", want: true},+ {name: "output_file_long", token: "--output-file", want: true},+ {name: "output_file_equals", token: "--output-file=err.log", want: true},+ {name: "append_output_long", token: "--append-output", want: true},+ {name: "append_output_equals", token: "--append-output=x.log", want: true},++ // Case 3: -P / --directory-prefix+ {name: "P_exact", token: "-P", want: true},+ {name: "P_attached", token: "-Pdir", want: true},+ {name: "directory_prefix_long", token: "--directory-prefix", want: true},+ {name: "directory_prefix_equals", token: "--directory-prefix=/tmp", want: true},++ // Case 4: --post-data / --post-file / --body-data / --body-file+ {name: "post_data_long", token: "--post-data", want: true},+ {name: "post_data_equals", token: "--post-data=a=1", want: true},+ {name: "post_file_long", token: "--post-file", want: true},+ {name: "post_file_equals", token: "--post-file=/tmp/body", want: true},+ {name: "body_data_long", token: "--body-data", want: true},+ {name: "body_data_equals", token: "--body-data=payload", want: true},+ {name: "body_file_long", token: "--body-file", want: true},+ {name: "body_file_equals", token: "--body-file=/tmp/body", want: true},++ // Case 5: --method+ {name: "method_long", token: "--method", want: true},+ {name: "method_equals", token: "--method=PUT", want: true},++ // Case 6: --warc-file+ {name: "warc_file_long", token: "--warc-file", want: true},+ {name: "warc_file_equals", token: "--warc-file=dump.warc", want: true},++ // Default arm (not a write/mutation option).+ {name: "spider_is_not", token: "--spider", want: false},+ {name: "quiet_is_not", token: "-q", want: false},+ {name: "verbose_is_not", token: "-v", want: false},+ {name: "url_is_not", token: "http://example.com", want: false},+ {name: "empty_is_not", token: "", want: false},+ {name: "random_long_is_not", token: "--no-check-certificate", want: false},+ {name: "random_long_proxy_is_not", token: "--proxy", want: false},+ {name: "uppercase_O_only_matches_O", token: "-OFILE", want: true}, // HasPrefix -O capital+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ tokenLower := toLowerLocal(tc.token)+ got := isWgetWriteOrMutationOption(tc.token, tokenLower)+ if got != tc.want {+ t.Fatalf("isWgetWriteOrMutationOption(%q, %q) = %v, want %v",+ tc.token, tokenLower, got, tc.want)+ }+ })+ }+}++// toLowerLocal mirrors strings.ToLower without adding an extra import, keeping+// the test file's import list to just "testing" as is conventional for the+// pure helpers. It is used solely to reproduce the caller contract for+// isWgetWriteOrMutationOption.+func toLowerLocal(s string) string {+ b := make([]byte, len(s))+ for i := 0; i < len(s); i++ {+ c := s[i]+ if c >= 'A' && c <= 'Z' {+ c += 'a' - 'A'+ }+ b[i] = c+ }+ return string(b)+}++// TestIsCurlMutationOrFileOutput_BranchCov covers the guard clause and every+// switch arm of isCurlMutationOrFileOutput, including the -X non-mutation+// fall-through paths that continue scanning the remaining tokens.+func TestIsCurlMutationOrFileOutput_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ command string+ want bool+ }{+ // Guard: no curl token present.+ {name: "guard_no_curl", command: "echo hello", want: false},+ {name: "guard_other_cmd", command: "wget http://x", want: false},+ {name: "guard_substring_not_token", command: "notcurl http://x", want: false},+ {name: "guard_empty", command: "", want: false},++ // No mutation / file-output option: read-only HTTP request.+ {name: "plain_http_no_opts", command: "curl http://example.com", want: false},+ {name: "silent_location_no_mutation", command: "curl -s -L http://example.com", want: false},+ {name: "only_headers_no_mutation", command: "curl -I http://example.com", want: false},++ // -X / --request separated forms.+ {name: "X_post_separated", command: "curl -X POST http://x", want: true},+ {name: "X_put_separated", command: "curl -X PUT http://x", want: true},+ {name: "X_patch_separated", command: "curl -X PATCH http://x", want: true},+ {name: "X_delete_separated", command: "curl -X DELETE http://x", want: true},+ {name: "X_get_nonmutation_falls_through", command: "curl -X GET http://x", want: false},+ {name: "X_get_then_data_continues", command: "curl -X GET -d a=1 http://x", want: true},+ {name: "X_at_end_no_next", command: "curl -X", want: false},+ {name: "request_long_post_separated", command: "curl --request POST http://x", want: true},+ {name: "request_long_get_nonmutation", command: "curl --request GET http://x", want: false},++ // -X / --request attached (= / glued) forms.+ {name: "X_post_attached", command: "curl -XPOST http://x", want: true},+ {name: "X_get_attached_nonmutation", command: "curl -XGET http://x", want: false},+ {name: "request_equals_post", command: "curl --request=POST http://x", want: true},+ {name: "request_equals_get_nonmutation", command: "curl --request=GET http://x", want: false},++ // -d / --data* / --json (space-separated) forms.+ {name: "d_separated", command: "curl -d a=1 http://x", want: true},+ {name: "d_attached", command: "curl -da=1 http://x", want: true},+ {name: "data_long", command: "curl --data a=1 http://x", want: true},+ {name: "data_raw_long", command: "curl --data-raw a=1 http://x", want: true},+ {name: "data_binary_long", command: "curl --data-binary @file http://x", want: true},+ {name: "data_urlencode_long", command: "curl --data-urlencode a=1 http://x", want: true},+ {name: "json_long", command: "curl --json {..} http://x", want: true},++ // -F / --form forms.+ {name: "F_separated", command: "curl -F field=val http://x", want: true},+ {name: "F_attached", command: "curl -Ffield=val http://x", want: true},+ {name: "form_long", command: "curl --form field=val http://x", want: true},+ {name: "form_string_long", command: "curl --form-string field=val http://x", want: true},++ // -T / --upload forms.+ {name: "T_separated", command: "curl -T file http://x", want: true},+ {name: "T_attached", command: "curl -Tfile http://x", want: true},+ {name: "upload_file_long", command: "curl --upload-file file http://x", want: true},++ // -o / -O / --output* / --remote-name / cluster with o|O.+ {name: "o_separated", command: "curl -o out http://x", want: true},+ {name: "o_attached", command: "curl -oout http://x", want: true},+ {name: "O_capital", command: "curl -O http://x", want: true},+ {name: "cluster_with_O", command: "curl -sO http://x", want: true},+ {name: "cluster_with_o", command: "curl -vo http://x", want: true},+ {name: "output_long", command: "curl --output out http://x", want: true},+ {name: "output_equals", command: "curl --output=out http://x", want: true},+ {name: "output_dir_long", command: "curl --output-dir d http://x", want: true},+ {name: "output_dir_equals", command: "curl --output-dir=d http://x", want: true},+ {name: "remote_name_long", command: "curl --remote-name http://x", want: true},+ {name: "remote_header_name_long", command: "curl --remote-header-name http://x", want: true},++ // -c / --cookie-jar forms.+ {name: "c_separated", command: "curl -c jar http://x", want: true},+ {name: "c_attached", command: "curl -cjar http://x", want: true},+ {name: "cookie_jar_long", command: "curl --cookie-jar jar http://x", want: true},+ {name: "cookie_jar_equals", command: "curl --cookie-jar=jar http://x", want: true},++ // -K / --dump-header / --config / cluster with K.+ {name: "K_separated", command: "curl -K cfg http://x", want: true},+ {name: "cluster_with_K", command: "curl -sK http://x", want: true},+ {name: "dump_header_long", command: "curl --dump-header h http://x", want: true},+ {name: "dump_header_equals", command: "curl --dump-header=h http://x", want: true},+ {name: "config_long", command: "curl --config cfg http://x", want: true},+ {name: "config_equals", command: "curl --config=cfg http://x", want: true},++ // Cluster with F | T | c (last switch arm).+ {name: "cluster_with_F", command: "curl -sF http://x", want: true},+ {name: "cluster_with_T", command: "curl -sT http://x", want: true},+ {name: "cluster_with_c", command: "curl -sc http://x", want: true},++ // Quoted tokens are trimmed before matching.+ {name: "quoted_o_separated", command: `curl -o "out" http://x`, want: true},+ {name: "quoted_X_post", command: `curl -X "POST" http://x`, want: true},++ // curl reachable via a filesystem path (commandTokenBase strips path).+ {name: "curl_path_X_post", command: "/usr/bin/curl -X POST http://x", want: true},+ {name: "curl_path_no_mutation", command: "/usr/local/bin/curl http://x", want: false},++ // Quoted curl binary still recognised after quote trimming.+ {name: "quoted_curl_binary_X_put", command: `"curl" -X PUT http://x`, want: true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := isCurlMutationOrFileOutput(tc.command)+ if got != tc.want {+ t.Fatalf("isCurlMutationOrFileOutput(%q) = %v, want %v", tc.command, got, tc.want)+ }+ })+ }+}diff --git a/internal/ai/tools/tools_query_env_branchcov_test.go b/internal/ai/tools/tools_query_env_branchcov_test.gonew file mode 100644index 0000000000..b53ea2b462--- /dev/null+++ b/internal/ai/tools/tools_query_env_branchcov_test.go@@ -0,0 +1,220 @@+package tools++import "testing"++// This file provides white-box table tests that raise branch coverage for the+// pure env-classification helpers in tools_query.go:+// - classifyEnvCommand (top-level routing: not-env / write / read-only)+// - envCommandHasUtility (per-token switch: -- terminator, continue flags,+// -u/--chdir value skips, --split-string, VAR=value,+// wrapped-command default)+//+// Both helpers are pure (no I/O, no executor/provider state) and return exact+// values, so every sub-case asserts the concrete return values rather than+// "no panic".++func TestClassifyEnvCommand_BranchCoverage(t *testing.T) {+ tests := []struct {+ name string+ command string+ wantOK bool+ wantIntent ExecutionIntent // asserted only when wantOK is true+ wantReason string // asserted only when wantOK is true; when !wantOK the reason must be empty+ }{+ // --- not-handled guard: empty command (no tokens). ---+ {+ name: "empty command is not classified",+ command: "",+ wantOK: false,+ },+ // --- not-handled guard: leading token is not "env". ---+ {+ name: "non-env leading token is not classified",+ command: "ls -la",+ wantOK: false,+ },+ // --- not-handled guard: token that merely starts with env-ish text. ---+ {+ name: "environment assignment token is not the env command",+ command: "ENVIRONMENT=1",+ wantOK: false,+ },++ // --- handled + read-only: bare env (no utility tokens). ---+ {+ name: "bare env prints environment and is read-only certain",+ command: "env",+ wantOK: true,+ wantIntent: IntentReadOnlyCertain,+ wantReason: "bare env command prints environment only",+ },+ // classifyEnvCommand lowercases the whole command first.+ {+ name: "uppercase ENV is treated as bare env via lowercasing",+ command: "ENV",+ wantOK: true,+ wantIntent: IntentReadOnlyCertain,+ wantReason: "bare env command prints environment only",+ },+ // Continue-only flags (--null/-i/etc.) leave no utility, still read-only.+ {+ name: "env with only continue flags stays read-only",+ command: "env -i --null --help",+ wantOK: true,+ wantIntent: IntentReadOnlyCertain,+ wantReason: "bare env command prints environment only",+ },+ // VAR=value assignments without a trailing command stay read-only.+ {+ name: "env with only VAR=value assignment is read-only",+ command: "env FOO=bar",+ wantOK: true,+ wantIntent: IntentReadOnlyCertain,+ wantReason: "bare env command prints environment only",+ },+ // "--" terminator with nothing after it is read-only.+ {+ name: "env terminator alone is read-only",+ command: "env --",+ wantOK: true,+ wantIntent: IntentReadOnlyCertain,+ wantReason: "bare env command prints environment only",+ },+ // -u with a value but no trailing command is read-only.+ {+ name: "env unset with value and no wrapped command is read-only",+ command: "env -u FOO",+ wantOK: true,+ wantIntent: IntentReadOnlyCertain,+ wantReason: "bare env command prints environment only",+ },++ // --- handled + write: utility detected via wrapped command / flags. ---+ {+ name: "env terminator followed by wrapped command is write",+ command: "env -- ls",+ wantOK: true,+ wantIntent: IntentWriteOrUnknown,+ wantReason: "env can execute wrapped commands and is not read-only by construction",+ },+ {+ name: "env split-string flag is write-capable",+ command: "env -s",+ wantOK: true,+ wantIntent: IntentWriteOrUnknown,+ wantReason: "env can execute wrapped commands and is not read-only by construction",+ },+ {+ name: "env VAR=value then wrapped command is write",+ command: "env FOO=bar ls",+ wantOK: true,+ wantIntent: IntentWriteOrUnknown,+ wantReason: "env can execute wrapped commands and is not read-only by construction",+ },+ {+ name: "env unset with value then wrapped command is write",+ command: "env -u FOO ls",+ wantOK: true,+ wantIntent: IntentWriteOrUnknown,+ wantReason: "env can execute wrapped commands and is not read-only by construction",+ },+ {+ name: "env chdir=value then wrapped command is write",+ command: "env --chdir=/tmp ls",+ wantOK: true,+ wantIntent: IntentWriteOrUnknown,+ wantReason: "env can execute wrapped commands and is not read-only by construction",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got, ok := classifyEnvCommand(tc.command)+ if ok != tc.wantOK {+ t.Fatalf("classifyEnvCommand(%q) handled = %v, want %v", tc.command, ok, tc.wantOK)+ }+ if !tc.wantOK {+ if got.Reason != "" {+ t.Fatalf("classifyEnvCommand(%q) not-handled Reason = %q, want empty", tc.command, got.Reason)+ }+ return+ }+ if got.Intent != tc.wantIntent {+ t.Fatalf("classifyEnvCommand(%q) Intent = %v, want %v", tc.command, got.Intent, tc.wantIntent)+ }+ if got.Reason != tc.wantReason {+ t.Fatalf("classifyEnvCommand(%q) Reason = %q, want %q", tc.command, got.Reason, tc.wantReason)+ }+ })+ }+}++func TestEnvCommandHasUtility_BranchCoverage(t *testing.T) {+ tests := []struct {+ name string+ fields []string+ want bool+ }{+ // Loop never executes: only the leading token present.+ {name: "single token never enters loop", fields: []string{"env"}, want: false},++ // "--" terminator arm.+ {name: "terminator with wrapped command after", fields: []string{"env", "--", "ls"}, want: true},+ {name: "terminator as the final token", fields: []string{"env", "--"}, want: false},+ {name: "terminator after a continue flag is still last", fields: []string{"env", "-i", "--"}, want: false},++ // Continue-only flags (arm 2), each exercised in isolation -> loop exits -> false.+ {name: "continue flag -0", fields: []string{"env", "-0"}, want: false},+ {name: "continue flag -i", fields: []string{"env", "-i"}, want: false},+ {name: "continue flag -", fields: []string{"env", "-"}, want: false},+ {name: "continue flag --ignore-environment", fields: []string{"env", "--ignore-environment"}, want: false},+ {name: "continue flag --null", fields: []string{"env", "--null"}, want: false},+ {name: "continue flag --help", fields: []string{"env", "--help"}, want: false},+ {name: "continue flag --version", fields: []string{"env", "--version"}, want: false},+ // Continue flag followed by a bare token: the bare token hits default -> true.+ {name: "continue flag then wrapped command", fields: []string{"env", "-0", "ls"}, want: true},++ // Value-skipping flags (arm 3): -u / --unset / --chdir each consume the next arg.+ {name: "unset -u skips value then nothing follows", fields: []string{"env", "-u", "FOO"}, want: false},+ {name: "unset --unset skips value then nothing follows", fields: []string{"env", "--unset", "FOO"}, want: false},+ {name: "--chdir skips value then nothing follows", fields: []string{"env", "--chdir", "/tmp"}, want: false},+ {name: "-u skips value then wrapped command follows", fields: []string{"env", "-u", "FOO", "ls"}, want: true},+ {name: "trailing -u with no value", fields: []string{"env", "-u"}, want: false},+ {name: "chdir then unset then wrapped command", fields: []string{"env", "--unset", "FOO", "--chdir", "/tmp", "ls"}, want: true},++ // =-form prefixes (arm 4): --unset= / --chdir=.+ {name: "--unset= prefix form", fields: []string{"env", "--unset=FOO"}, want: false},+ {name: "--chdir= prefix form", fields: []string{"env", "--chdir=/tmp"}, want: false},+ {name: "--chdir= prefix then wrapped command", fields: []string{"env", "--chdir=/tmp", "ls"}, want: true},++ // Split-string arm (arm 5) -> immediately true.+ {name: "split-string short -s", fields: []string{"env", "-s"}, want: true},+ {name: "split-string long --split-string", fields: []string{"env", "--split-string"}, want: true},+ {name: "split-string prefix --split-string=", fields: []string{"env", "--split-string=|"}, want: true},++ // VAR=value arm (arm 6): contains '=' and does not start with '='.+ {name: "VAR=value assignment alone", fields: []string{"env", "FOO=bar"}, want: false},+ {name: "VAR=value then wrapped command", fields: []string{"env", "FOO=bar", "ls"}, want: true},+ {name: "empty VAR= assignment alone", fields: []string{"env", "FOO="}, want: false},++ // Default arm (arm 7): bare wrapped command token -> true.+ {name: "bare wrapped command default arm", fields: []string{"env", "ls"}, want: true},+ {name: "unknown token falls to default", fields: []string{"env", "frobnicate"}, want: true},+ // Token starting with '=' is NOT treated as VAR=value; it falls through to default.+ {name: "leading equals token falls to default", fields: []string{"env", "=FOO"}, want: true},++ // Quote-trimming path: surrounding " or ' are stripped before matching.+ {name: "quoted continue flag trims to -i", fields: []string{"env", `"-i"`}, want: false},+ {name: "single-quoted VAR=value trims to assignment", fields: []string{"env", "'FOO=bar'"}, want: false},+ {name: "quoted split-string trims to -s and is write", fields: []string{"env", `'-s'`}, want: true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := envCommandHasUtility(tc.fields)+ if got != tc.want {+ t.Fatalf("envCommandHasUtility(%v) = %v, want %v", tc.fields, got, tc.want)+ }+ })+ }+}diff --git a/internal/ai/tools/tools_query_timeout_branchcov_test.go b/internal/ai/tools/tools_query_timeout_branchcov_test.gonew file mode 100644index 0000000000..e91b3747c4--- /dev/null+++ b/internal/ai/tools/tools_query_timeout_branchcov_test.go@@ -0,0 +1,144 @@+package tools++import (+ "strings"+ "testing"+)++// TestIsTimeoutDurationToken_BranchCoverage exercises every arm of+// isTimeoutDurationToken: the empty-token guard, the digit/first-dot loop+// arms, the suffix-unit check (all four units plus non-matching suffixes and+// the seenDigit=false case), and the loop-completion arm hit by no-unit digit+// and dot-without-unit tokens.+func TestIsTimeoutDurationToken_BranchCoverage(t *testing.T) {+ tests := []struct {+ name string+ token string+ want bool+ }{+ {name: "empty token rejected", token: "", want: false},+ {name: "no-unit digit token accepted", token: "30", want: true},+ {name: "single digit no unit accepted", token: "5", want: true},+ {name: "digit plus s unit", token: "5s", want: true},+ {name: "digit plus m unit", token: "5m", want: true},+ {name: "digit plus h unit", token: "5h", want: true},+ {name: "digit plus d unit", token: "5d", want: true},+ {name: "dot plus unit duration accepted", token: "1.5s", want: true},+ {name: "dot no unit accepted as bare number", token: "1.5", want: true},+ {name: "second dot falls through to suffix mismatch", token: "1.5.5", want: false},+ {name: "bare dot no digit rejected", token: ".", want: false},+ {name: "digit plus non-unit letter rejected", token: "5x", want: false},+ {name: "digit plus multi-char suffix rejected", token: "5ss", want: false},+ {name: "unit suffix without leading digit rejected", token: "s", want: false},+ {name: "non-digit non-unit prefix rejected", token: "abc", want: false},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := isTimeoutDurationToken(tc.token)+ if got != tc.want {+ t.Fatalf("isTimeoutDurationToken(%q) = %v, want %v", tc.token, got, tc.want)+ }+ })+ }+}++// TestTimeoutInnerCommand_BranchCoverage walks every flag-parsing arm of+// timeoutInnerCommand: the too-short guard, the "--" separator, each+// standalone flag (--preserve-status, --foreground, --verbose, -v), the+// value-taking flags -s/--signal/-k/--kill-after, the "=" attached forms, the+// combined short forms (-sX/-kX), the unknown-flag rejection, the missing+// duration arm, the missing command arm, and the success/join arm.+func TestTimeoutInnerCommand_BranchCoverage(t *testing.T) {+ tests := []struct {+ name string+ fields []string+ wantCmd string+ wantOk bool+ }{+ {name: "too short single arg", fields: []string{"timeout"}, wantOk: false},+ {name: "too short two args", fields: []string{"timeout", "5s"}, wantOk: false},+ {name: "bare duration then command", fields: []string{"timeout", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "join multiple args after duration", fields: []string{"timeout", "5s", "ls", "-la"}, wantCmd: "ls -la", wantOk: true},+ {name: "double dash separator", fields: []string{"timeout", "--", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "preserve status flag", fields: []string{"timeout", "--preserve-status", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "foreground flag", fields: []string{"timeout", "--foreground", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "verbose flag", fields: []string{"timeout", "--verbose", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "short verbose flag", fields: []string{"timeout", "-v", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "short signal flag with separate value", fields: []string{"timeout", "-s", "TERM", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "long signal flag with separate value", fields: []string{"timeout", "--signal", "TERM", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "short kill flag with separate value", fields: []string{"timeout", "-k", "2s", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "long kill flag with separate value", fields: []string{"timeout", "--kill-after", "2s", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "attached long signal form", fields: []string{"timeout", "--signal=TERM", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "attached long kill form", fields: []string{"timeout", "--kill-after=2s", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "combined short signal form", fields: []string{"timeout", "-sTERM", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "combined short kill form", fields: []string{"timeout", "-k5s", "5s", "ls"}, wantCmd: "ls", wantOk: true},+ {name: "unknown short flag rejected", fields: []string{"timeout", "-x", "5s"}, wantOk: false},+ {name: "separator then non-duration token", fields: []string{"timeout", "--", "notdur", "ls"}, wantOk: false},+ {name: "bare non-duration token", fields: []string{"timeout", "notdur", "ls"}, wantOk: false},+ {name: "duration present but no command after separator", fields: []string{"timeout", "--", "5s"}, wantOk: false},+ {name: "standalone flags consume everything then no duration", fields: []string{"timeout", "--preserve-status", "--verbose"}, wantOk: false},+ {name: "value flag consumes everything then no duration", fields: []string{"timeout", "-s", "TERM"}, wantOk: false},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ gotCmd, gotOk := timeoutInnerCommand(tc.fields)+ if gotOk != tc.wantOk {+ t.Fatalf("timeoutInnerCommand(%v) ok = %v, want %v", tc.fields, gotOk, tc.wantOk)+ }+ if gotOk && gotCmd != tc.wantCmd {+ t.Fatalf("timeoutInnerCommand(%v) cmd = %q, want %q", tc.fields, gotCmd, tc.wantCmd)+ }+ if !gotOk && gotCmd != "" {+ t.Fatalf("timeoutInnerCommand(%v) returned non-empty cmd %q on failure", tc.fields, gotCmd)+ }+ })+ }+}++// TestClassifyTimeoutWrapper_BranchCoverage drives the four return arms of+// classifyTimeoutWrapper: not-a-timeout (handled=false), malformed timeout+// wrapper, inner read-only-certain, inner read-only-conditional, and inner+// write/unknown.+func TestClassifyTimeoutWrapper_BranchCoverage(t *testing.T) {+ tests := []struct {+ name string+ command string+ wantHandled bool+ wantIntent ExecutionIntent+ reasonContains string+ }{+ {name: "empty command not handled", command: "", wantHandled: false},+ {name: "non-timeout first token not handled", command: "ls -la", wantHandled: false},+ {name: "case-insensitive timeout prefix", command: "TIMEOUT 5s ls", wantHandled: true, wantIntent: IntentReadOnlyCertain, reasonContains: "timeout-bounded"},+ {name: "path-qualified timeout binary", command: "/usr/bin/timeout 5s ls", wantHandled: true, wantIntent: IntentReadOnlyCertain, reasonContains: "timeout-bounded"},+ {name: "quoted timeout token", command: `"timeout" 5s ls`, wantHandled: true, wantIntent: IntentReadOnlyCertain, reasonContains: "timeout-bounded"},+ {name: "bare timeout missing duration and command", command: "timeout", wantHandled: true, wantIntent: IntentWriteOrUnknown, reasonContains: "timeout wrapper must include a duration and command"},+ {name: "timeout duration but no command", command: "timeout 5s", wantHandled: true, wantIntent: IntentWriteOrUnknown, reasonContains: "timeout wrapper must include a duration and command"},+ {name: "timeout wrapping write command stays write", command: "timeout 5s rm -rf /tmp/branch", wantHandled: true, wantIntent: IntentWriteOrUnknown, reasonContains: "timeout-wrapped command not read-only"},+ {name: "timeout wrapping conditional read-only sql", command: `timeout 5s sqlite3 ":memory:" "SELECT 1"`, wantHandled: true, wantIntent: IntentReadOnlyConditional, reasonContains: "timeout-bounded"},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ result, handled := classifyTimeoutWrapper(tc.command)+ if handled != tc.wantHandled {+ t.Fatalf("classifyTimeoutWrapper(%q) handled = %v, want %v", tc.command, handled, tc.wantHandled)+ }+ if !tc.wantHandled {+ // Unhandled invocations return the zero-value IntentResult.+ if result.Intent != 0 || result.Reason != "" || result.NonInteractiveBlock != nil {+ t.Fatalf("classifyTimeoutWrapper(%q) unhandled returned non-zero result %+v", tc.command, result)+ }+ return+ }+ if result.Intent != tc.wantIntent {+ t.Fatalf("classifyTimeoutWrapper(%q) intent = %v, want %v", tc.command, result.Intent, tc.wantIntent)+ }+ if tc.reasonContains != "" && !strings.Contains(result.Reason, tc.reasonContains) {+ t.Fatalf("classifyTimeoutWrapper(%q) reason = %q, want substring %q", tc.command, result.Reason, tc.reasonContains)+ }+ })+ }+}diff --git a/internal/ai/tools/tools_storage_recovery_branchcov_test.go b/internal/ai/tools/tools_storage_recovery_branchcov_test.gonew file mode 100644index 0000000000..abda89e2e2--- /dev/null+++ b/internal/ai/tools/tools_storage_recovery_branchcov_test.go@@ -0,0 +1,358 @@+package tools++import (+ "encoding/json"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/recovery"+)++// These tests raise branch coverage for the small pure helper functions in+// tools_storage.go that canonicalize recovery-point fields. They target the+// previously uncovered branches: nil Details/Display/SubjectRef fallbacks,+// the int/float64/json.Number arms of recoveryPointDetailInt, the Outcome+// switch arms in the status/error mappers, and the SubjectRef.Name/ID parse+// fallbacks in recoveryPointCanonicalVMID.++func TestRecoveryPointDetailString_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ point recovery.RecoveryPoint+ key string+ want string+ }{+ {+ name: "nil_details_returns_empty",+ point: recovery.RecoveryPoint{},+ key: "type",+ want: "",+ },+ {+ name: "missing_key_returns_empty",+ point: recovery.RecoveryPoint{Details: map[string]any{}},+ key: "type",+ want: "",+ },+ {+ name: "nil_value_returns_empty",+ point: recovery.RecoveryPoint{Details: map[string]any{"type": nil}},+ key: "type",+ want: "",+ },+ {+ name: "string_value_is_trimmed",+ point: recovery.RecoveryPoint{Details: map[string]any{"type": " vm "}},+ key: "type",+ want: "vm",+ },+ {+ name: "non_string_value_returns_empty",+ point: recovery.RecoveryPoint{Details: map[string]any{"type": 42}},+ key: "type",+ want: "",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := recoveryPointDetailString(tc.point, tc.key); got != tc.want {+ t.Fatalf("recoveryPointDetailString(%+v, %q) = %q, want %q", tc.point, tc.key, got, tc.want)+ }+ })+ }+}++func TestRecoveryPointDetailInt_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ point recovery.RecoveryPoint+ key string+ want int+ }{+ {+ name: "nil_details_returns_zero",+ point: recovery.RecoveryPoint{},+ key: "vmid",+ want: 0,+ },+ {+ name: "missing_key_returns_zero",+ point: recovery.RecoveryPoint{Details: map[string]any{}},+ key: "vmid",+ want: 0,+ },+ {+ name: "nil_value_returns_zero",+ point: recovery.RecoveryPoint{Details: map[string]any{"vmid": nil}},+ key: "vmid",+ want: 0,+ },+ {+ name: "int_value_returned",+ point: recovery.RecoveryPoint{Details: map[string]any{"vmid": 101}},+ key: "vmid",+ want: 101,+ },+ {+ name: "int64_value_returned",+ point: recovery.RecoveryPoint{Details: map[string]any{"vmid": int64(202)}},+ key: "vmid",+ want: 202,+ },+ {+ name: "float64_value_truncated",+ point: recovery.RecoveryPoint{Details: map[string]any{"vmid": float64(303.99)}},+ key: "vmid",+ want: 303,+ },+ {+ name: "json_number_value_returned",+ point: recovery.RecoveryPoint{Details: map[string]any{"vmid": json.Number("404")}},+ key: "vmid",+ want: 404,+ },+ {+ name: "bool_value_falls_to_default_zero",+ point: recovery.RecoveryPoint{Details: map[string]any{"vmid": true}},+ key: "vmid",+ want: 0,+ },+ {+ name: "string_value_falls_to_default_zero",+ point: recovery.RecoveryPoint{Details: map[string]any{"vmid": "not-a-number"}},+ key: "vmid",+ want: 0,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := recoveryPointDetailInt(tc.point, tc.key); got != tc.want {+ t.Fatalf("recoveryPointDetailInt(%+v, %q) = %d, want %d", tc.point, tc.key, got, tc.want)+ }+ })+ }+}++func TestRecoveryPointCanonicalVMID_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ point recovery.RecoveryPoint+ want int+ }{+ {+ name: "display_entity_id_label_used_when_valid",+ point: recovery.RecoveryPoint{+ Display: &recovery.RecoveryPointDisplay{EntityIDLabel: "100"},+ },+ want: 100,+ },+ {+ // parseRecoveryPointVMID rejects negative numbers, so even with a+ // non-empty EntityIDLabel we must fall through to SubjectRef.Name.+ name: "display_entity_id_label_negative_skips_to_subject_ref_name",+ point: recovery.RecoveryPoint{+ Display: &recovery.RecoveryPointDisplay{EntityIDLabel: "-1"},+ SubjectRef: &recovery.ExternalRef{Name: "200"},+ },+ want: 200,+ },+ {+ // EntityIDLabel unparseable AND SubjectRef.Name parses: Name wins.+ name: "display_unparseable_falls_to_subject_ref_name",+ point: recovery.RecoveryPoint{+ Display: &recovery.RecoveryPointDisplay{EntityIDLabel: "abc"},+ SubjectRef: &recovery.ExternalRef{Name: "300"},+ },+ want: 300,+ },+ {+ // SubjectRef.Name zero is rejected; SubjectRef.ID is the fallback.+ name: "subject_ref_name_zero_falls_to_subject_ref_id",+ point: recovery.RecoveryPoint{+ SubjectRef: &recovery.ExternalRef{Name: "0", ID: "400"},+ },+ want: 400,+ },+ {+ name: "subject_ref_name_unparseable_falls_to_subject_ref_id",+ point: recovery.RecoveryPoint{+ SubjectRef: &recovery.ExternalRef{Name: "node-1", ID: "500"},+ },+ want: 500,+ },+ {+ // No Display, no SubjectRef -> details["vmid"] terminal fallback.+ name: "no_display_no_subject_ref_falls_to_details",+ point: recovery.RecoveryPoint{+ Details: map[string]any{"vmid": 600},+ },+ want: 600,+ },+ {+ // SubjectRef present but neither Name nor ID parses; details wins.+ name: "subject_ref_unparseable_falls_to_details",+ point: recovery.RecoveryPoint{+ SubjectRef: &recovery.ExternalRef{Name: "abc", ID: "xyz"},+ Details: map[string]any{"vmid": 700},+ },+ want: 700,+ },+ {+ name: "all_sources_empty_returns_zero",+ point: recovery.RecoveryPoint{+ Display: &recovery.RecoveryPointDisplay{},+ SubjectRef: &recovery.ExternalRef{},+ },+ want: 0,+ },+ {+ name: "no_sources_at_all_returns_zero",+ point: recovery.RecoveryPoint{},+ want: 0,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := recoveryPointCanonicalVMID(tc.point); got != tc.want {+ t.Fatalf("recoveryPointCanonicalVMID(%+v) = %d, want %d", tc.point, got, tc.want)+ }+ })+ }+}++func TestRecoveryPointCanonicalTaskStatus_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ point recovery.RecoveryPoint+ want string+ }{+ {+ // details["status"] short-circuits the Outcome switch entirely.+ name: "details_status_present_overrides_outcome",+ point: recovery.RecoveryPoint{+ Details: map[string]any{"status": "PAUSED"},+ Outcome: recovery.OutcomeFailed,+ },+ want: "PAUSED",+ },+ {+ // A whitespace-only status trims to empty, so we hit the switch.+ name: "details_status_whitespace_falls_to_outcome_switch",+ point: recovery.RecoveryPoint{+ Details: map[string]any{"status": " "},+ Outcome: recovery.OutcomeRunning,+ },+ want: "RUNNING",+ },+ {+ name: "outcome_success_maps_to_OK",+ point: recovery.RecoveryPoint{Outcome: recovery.OutcomeSuccess},+ want: "OK",+ },+ {+ name: "outcome_failed_maps_to_ERROR",+ point: recovery.RecoveryPoint{Outcome: recovery.OutcomeFailed},+ want: "ERROR",+ },+ {+ name: "outcome_warning_maps_to_WARNING",+ point: recovery.RecoveryPoint{Outcome: recovery.OutcomeWarning},+ want: "WARNING",+ },+ {+ name: "outcome_running_maps_to_RUNNING",+ point: recovery.RecoveryPoint{Outcome: recovery.OutcomeRunning},+ want: "RUNNING",+ },+ {+ name: "unknown_outcome_value_maps_to_UNKNOWN",+ point: recovery.RecoveryPoint{Outcome: recovery.Outcome("bogus")},+ want: "UNKNOWN",+ },+ {+ name: "empty_outcome_maps_to_UNKNOWN",+ point: recovery.RecoveryPoint{},+ want: "UNKNOWN",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := recoveryPointCanonicalTaskStatus(tc.point); got != tc.want {+ t.Fatalf("recoveryPointCanonicalTaskStatus(%+v) = %q, want %q", tc.point, got, tc.want)+ }+ })+ }+}++func TestRecoveryPointCanonicalTaskError_BranchCov(t *testing.T) {+ tests := []struct {+ name string+ point recovery.RecoveryPoint+ want string+ }{+ {+ // details["error"] short-circuits regardless of Outcome.+ name: "details_error_present_overrides_outcome",+ point: recovery.RecoveryPoint{+ Details: map[string]any{"error": " boom "},+ Outcome: recovery.OutcomeSuccess,+ },+ want: "boom",+ },+ {+ name: "outcome_failed_uses_display_details_summary",+ point: recovery.RecoveryPoint{+ Outcome: recovery.OutcomeFailed,+ Display: &recovery.RecoveryPointDisplay{DetailsSummary: " snapshot failed "},+ },+ want: "snapshot failed",+ },+ {+ name: "outcome_warning_uses_display_details_summary",+ point: recovery.RecoveryPoint{+ Outcome: recovery.OutcomeWarning,+ Display: &recovery.RecoveryPointDisplay{DetailsSummary: " partial "},+ },+ want: "partial",+ },+ {+ // Success/Running outcomes ignore the summary entirely.+ name: "outcome_success_returns_empty_even_with_summary",+ point: recovery.RecoveryPoint{+ Outcome: recovery.OutcomeSuccess,+ Display: &recovery.RecoveryPointDisplay{DetailsSummary: "should-not-appear"},+ },+ want: "",+ },+ {+ name: "outcome_running_returns_empty_even_with_summary",+ point: recovery.RecoveryPoint{+ Outcome: recovery.OutcomeRunning,+ Display: &recovery.RecoveryPointDisplay{DetailsSummary: "should-not-appear"},+ },+ want: "",+ },+ {+ // nil Display hits the recoveryPointDisplayString guard.+ name: "outcome_failed_with_nil_display_returns_empty",+ point: recovery.RecoveryPoint{Outcome: recovery.OutcomeFailed},+ want: "",+ },+ {+ name: "empty_outcome_returns_empty",+ point: recovery.RecoveryPoint{},+ want: "",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := recoveryPointCanonicalTaskError(tc.point); got != tc.want {+ t.Fatalf("recoveryPointCanonicalTaskError(%+v) = %q, want %q", tc.point, got, tc.want)+ }+ })+ }+}