diff options
| author | Adam Malczewski <[email protected]> | 2026-06-02 16:48:12 +0900 |
|---|---|---|
| committer | Adam Malczewski <[email protected]> | 2026-06-02 16:48:12 +0900 |
| commit | 644cfb097b845384c4a470a97328922e5d6dd129 (patch) | |
| tree | 75d43b9a272a412c3524ba762f177e2c8a614c21 | |
| parent | 0f99a0c92707b44aef7c627012c4711bad5a8efd (diff) | |
| download | dispatch-644cfb097b845384c4a470a97328922e5d6dd129.tar.gz dispatch-644cfb097b845384c4a470a97328922e5d6dd129.zip | |
fix(search_code): surface cs failures + harden query/path handling
Address findings from an independent code review of the search_code tool:
- Critical: cs failures (non-zero exit, or SIGTERM from the spawn timeout)
were swallowed and reported to the model as 'No matches found', discarding
stderr. Now capture exit code + signal from 'close' and return a real
Error: (timeout message for SIGTERM, exit-code + stderr otherwise). cs
exits 0 on a genuine no-match, so that path still reports correctly.
- High: a query beginning with '-' (e.g. '-foo') was parsed by cs as a
(usually invalid) flag. Insert a '--' separator before the query so it is
always treated as the positional search term.
- Low: relative-path display fallback now matches the workdir only at a path
boundary, so a sibling dir sharing the prefix (e.g. /app vs /app-secrets)
isn't rendered as a '../app-secrets/...' path.
Adds tests for the non-zero-exit (stderr surfaced, not 'No matches') and
dash-leading-query cases. All tests (598), biome, and tsc pass.
| -rw-r--r-- | packages/core/src/tools/search-code.ts | 48 | ||||
| -rw-r--r-- | packages/core/tests/tools/search-code.test.ts | 34 |
2 files changed, 74 insertions, 8 deletions
diff --git a/packages/core/src/tools/search-code.ts b/packages/core/src/tools/search-code.ts index 39cbbdd..c9ad086 100644 --- a/packages/core/src/tools/search-code.ts +++ b/packages/core/src/tools/search-code.ts @@ -1,5 +1,5 @@ import { spawn } from "node:child_process"; -import { relative } from "node:path"; +import { relative, sep } from "node:path"; import { z } from "zod"; import type { ToolDefinition } from "../types/index.js"; import { canonicalize } from "./path-utils.js"; @@ -134,11 +134,19 @@ export function createSearchCodeTool(workingDirectory: string): ToolDefinition { } const flags = buildFlags(args, searchDir); - const spawnArgs = [...flags, query]; + // `--` terminates cs flag parsing so a query that begins with "-" + // (e.g. "-hello" or "--foo") is treated as the positional search term + // rather than parsed as a (possibly invalid) cs flag. + const spawnArgs = [...flags, "--", query]; let stdout = ""; let stderr = ""; - const result = await new Promise<{ error?: string; errorCode?: string }>((resolve) => { + const result = await new Promise<{ + code: number | null; + signal: NodeJS.Signals | null; + error?: string; + errorCode?: string; + }>((resolve) => { const child = spawn(resolveCsBin(), spawnArgs, { cwd: workingDirectory, env: process.env, @@ -151,9 +159,14 @@ export function createSearchCodeTool(workingDirectory: string): ToolDefinition { child.stderr?.on("data", (d: Buffer) => { stderr += d.toString(); }); - child.on("close", () => resolve({})); + child.on("close", (code, signal) => resolve({ code, signal })); child.on("error", (err) => - resolve({ error: err.message, errorCode: (err as NodeJS.ErrnoException).code }), + resolve({ + code: null, + signal: null, + error: err.message, + errorCode: (err as NodeJS.ErrnoException).code, + }), ); }); @@ -165,6 +178,22 @@ export function createSearchCodeTool(workingDirectory: string): ToolDefinition { return `Error: failed to run cs: ${result.error}`; } + // A signal kill (e.g. SIGTERM from the spawn timeout) or a non-zero + // exit means cs failed — surface it (with stderr) instead of silently + // reporting "No matches found". cs exits 0 even when there are no + // matches, so a clean exit always falls through to the parsing below. + if (result.signal) { + const detail = stderr.trim() ? `\n${stderr.trim()}` : ""; + if (result.signal === "SIGTERM") { + return `Error: cs search timed out after ${TIMEOUT_MS / 1000}s. Try a narrower query or a smaller path.${detail}`; + } + return `Error: cs was terminated by signal ${result.signal}.${detail}`; + } + if (result.code !== 0) { + const detail = stderr.trim() ? `\n${stderr.trim()}` : ""; + return `Error: cs exited with code ${result.code}.${detail}`; + } + // cs prints `null` (and exit 0) when there are no matches. const trimmed = stdout.trim(); if (trimmed === "" || trimmed === "null") { @@ -226,11 +255,14 @@ function buildFlags(args: Record<string, unknown>, searchDir: string): string[] /** Render cs JSON results into compact, readable per-file blocks. */ function formatResults(results: CsResult[], absoluteWorkDir: string): string { const blocks: string[] = []; + // Match the workdir only at a path boundary so a sibling dir that merely + // shares the prefix (e.g. workdir "/app" vs "/app-secrets") isn't treated + // as nested and rendered as a "../app-secrets/..." relative path. + const workdirPrefix = absoluteWorkDir.endsWith(sep) ? absoluteWorkDir : absoluteWorkDir + sep; for (const r of results) { // Present paths relative to the workdir so output is portable and compact. - const rel = r.location.startsWith(absoluteWorkDir) - ? relative(absoluteWorkDir, r.location) || r.filename - : r.location; + const insideWorkdir = r.location === absoluteWorkDir || r.location.startsWith(workdirPrefix); + const rel = insideWorkdir ? relative(absoluteWorkDir, r.location) || r.filename : r.location; const lang = r.language ? ` [${r.language}]` : ""; const score = typeof r.score === "number" ? ` (score ${r.score.toFixed(2)})` : ""; const header = `${rel}${lang}${score}`; diff --git a/packages/core/tests/tools/search-code.test.ts b/packages/core/tests/tools/search-code.test.ts index b805d15..1632214 100644 --- a/packages/core/tests/tools/search-code.test.ts +++ b/packages/core/tests/tools/search-code.test.ts @@ -20,6 +20,13 @@ const ECHO_ENV_STUB = `#!/usr/bin/env bash printf '%s' "$CS_STUB_OUTPUT" `; +// A stub that writes to stderr and exits non-zero, impersonating a cs failure +// (bad flag, invalid regex, etc.). +const FAIL_STUB = `#!/usr/bin/env bash +echo "cs: simulated failure on stderr" >&2 +exit 3 +`; + describe("search_code tool", () => { let workDir: string; const savedBin = process.env.DISPATCH_CS_BIN; @@ -147,6 +154,22 @@ describe("search_code tool", () => { } }); + it("reports an error (not 'No matches') when cs exits non-zero", async () => { + const stubDir = await mkdtempP(join(tmpdir(), "dispatch-cs-stub-")); + try { + process.env.DISPATCH_CS_BIN = writeStub(stubDir, FAIL_STUB); + const tool = createSearchCodeTool(workDir); + const out = await tool.execute({ query: "x" }); + expect(out).toMatch(/^Error:/); + expect(out).toContain("exited with code 3"); + // stderr from cs is surfaced to the caller. + expect(out).toContain("simulated failure on stderr"); + expect(out).not.toContain("No matches found"); + } finally { + await rmP(stubDir, { recursive: true, force: true }); + } + }); + // ── Live integration: only runs when a real `cs` binary is available. ── const liveCsBin = findRealCs(); describe.runIf(liveCsBin)("live cs binary", () => { @@ -165,6 +188,17 @@ describe("search_code tool", () => { expect(out).not.toContain("Error:"); }); + it("treats a dash-leading query as a search term, not a cs flag", async () => { + process.env.DISPATCH_CS_BIN = liveCsBin as string; + // A literal token beginning with '-' must not be parsed as a flag. + await writeFileP(join(workDir, "dash.ts"), "const dashToken = 1;\n"); + const tool = createSearchCodeTool(workDir); + const out = await tool.execute({ query: "-dashToken" }); + // Whether or not cs ranks a hit, it must NOT error out on flag parsing. + expect(out).not.toContain("unknown shorthand flag"); + expect(out).not.toMatch(/^Error: cs exited/); + }); + it("returns 'No matches found.' for a query with no hits", async () => { process.env.DISPATCH_CS_BIN = liveCsBin as string; await writeFileP(join(workDir, "alpha.ts"), "export const a = 1;\n"); |
