diff --git a/internal/tools/builtin/grep.go b/internal/tools/builtin/grep.go index 1424eb41a..e1f5d4669 100644 --- a/internal/tools/builtin/grep.go +++ b/internal/tools/builtin/grep.go @@ -212,8 +212,13 @@ func makeGrepExecutor(cwd string, workspaceIndex GrepIndex) Executor { output = stdout.String() } if output == "" && err != nil { - exitErr := &exec.ExitError{} - if errors.As(err, &exitErr) { + // Exit 1 means "no matches"; exit 2 means a real failure (bad + // pattern, unreadable path). Reporting the latter as an empty + // result would have the model state a file contains nothing when + // the search never ran, so the code must be checked, not just the + // error type. + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 { return grepBackendResult(Result{Content: "no matches found"}, searchBackend, clamped), nil } errMsg := stderr.String() diff --git a/internal/tools/builtin/grep_test.go b/internal/tools/builtin/grep_test.go index 7d185a0f3..81335d6e8 100644 --- a/internal/tools/builtin/grep_test.go +++ b/internal/tools/builtin/grep_test.go @@ -32,6 +32,30 @@ func TestGrepUsesIndexCandidatesAsAdvisoryFileSet(t *testing.T) { } } +// TestGrepReportsSearchFailureRatherThanNoMatches guards the distinction +// between ripgrep's exit 1 (no matches) and exit 2 (the search never ran). An +// errorlint autofix once rewrote the check to match any *exec.ExitError and +// dropped the exit code, which reported a failed search as an empty result -- +// the model would then state that a file contains nothing on the strength of a +// search that never happened. An unterminated group is a parse error, so +// ripgrep exits 2 here. +func TestGrepReportsSearchFailureRatherThanNoMatches(t *testing.T) { + tmp := t.TempDir() + createGrepTestFile(t, tmp, "haystack.txt", "needle\n") + tool := NewGrepTool(tmp, nil) + + result, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"(unclosed"}`), nil) + if err != nil { + t.Fatalf("execute: %v", err) + } + if !result.IsError { + t.Fatalf("a failed search must be reported as an error, got %#v", result) + } + if strings.Contains(result.Content, "no matches found") { + t.Fatalf("a failed search was reported as an empty result: %s", result.Content) + } +} + func TestGrepRetriesDirectSearchWhenIndexedCandidatesAreStale(t *testing.T) { tmp := t.TempDir() createGrepTestFile(t, tmp, "live.txt", "needle\n")