Skip to content

Commit a9769e3

Browse files
committed
fix(agents): preserve find result paths
1 parent 715760d commit a9769e3

3 files changed

Lines changed: 125 additions & 31 deletions

File tree

‎src/agents/sessions/tools/find.fd.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,43 @@ it("rejects partial fd output when fd exits with an error", async () => {
6565
await expect(result).rejects.toThrow("fd failed while reading subtree");
6666
});
6767

68+
it.each([false, true])("preserves fd paths with trailing search separator=%s", async (trailing) => {
69+
const searchRoot = path.resolve(path.sep, "find-fixture");
70+
const paths = [
71+
path.join(searchRoot, "alpha.txt"),
72+
path.join(searchRoot, "report.txt "),
73+
path.join(searchRoot, "🦞.txt"),
74+
`${path.join(searchRoot, "folder space ")}${path.sep}`,
75+
path.join(searchRoot, "literal\\"),
76+
];
77+
const child = createChild();
78+
vi.mocked(spawnCommand).mockReturnValue(child as never);
79+
vi.mocked(ensureTool).mockResolvedValue("fd");
80+
const tool = createFindToolDefinition(searchRoot);
81+
const pending = tool.execute(
82+
"paths",
83+
{ pattern: "*", path: trailing ? `${searchRoot}${path.sep}` : searchRoot },
84+
undefined,
85+
undefined,
86+
{} as never,
87+
);
88+
await vi.waitFor(() => expect(spawnCommand).toHaveBeenCalledOnce());
89+
child.stdout.end(`${paths.join("\n")}\n`);
90+
child.stderr.end();
91+
child.emit("close", 0, null);
92+
const result = await pending;
93+
expect(textContent(result)).toBe(
94+
[
95+
"alpha.txt",
96+
"report.txt ",
97+
"🦞.txt",
98+
"folder space /",
99+
process.platform === "win32" ? "literal/" : "literal\\",
100+
].join("\n"),
101+
);
102+
expect(result.details).toBeUndefined();
103+
});
104+
68105
it("keeps multibyte stderr intact when pipe chunks split a character", async () => {
69106
const child = createChild();
70107
vi.mocked(spawnCommand).mockReturnValue(child as never);

‎src/agents/sessions/tools/find.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// find tool tests cover custom search operation wiring and result-limit
22
// normalization for session file discovery.
3+
import path from "node:path";
34
import { Value } from "typebox/value";
45
import { describe, expect, it, vi } from "vitest";
56
import { createFindToolDefinition, type FindOperations } from "./find.js";
@@ -23,6 +24,72 @@ function execute(tool: ReturnType<typeof createFindToolDefinition>, limit: numbe
2324
}
2425

2526
describe("find tool", () => {
27+
const workspace = path.resolve(path.sep, "find-fixture");
28+
it.each([
29+
{
30+
name: "absolute result",
31+
search: workspace,
32+
found: path.join(workspace, "alpha.txt"),
33+
expected: "alpha.txt",
34+
},
35+
{
36+
name: "trailing search separator",
37+
search: `${workspace}${path.sep}`,
38+
found: path.join(workspace, "alpha.txt"),
39+
expected: "alpha.txt",
40+
},
41+
{
42+
name: "root search",
43+
search: path.parse(workspace).root,
44+
found: path.join(path.parse(workspace).root, "alpha.txt"),
45+
expected: "alpha.txt",
46+
},
47+
{ name: "relative result", search: workspace, found: "alpha.txt", expected: "alpha.txt" },
48+
{ name: "self-directory absolute", search: workspace, found: workspace, expected: "." },
49+
{
50+
name: "self-directory with separator",
51+
search: workspace,
52+
found: `${workspace}${path.sep}`,
53+
expected: "./",
54+
},
55+
{ name: "self-directory relative", search: workspace, found: ".", expected: "." },
56+
{
57+
name: "prefix sibling",
58+
search: workspace,
59+
found: path.join(`${workspace}-other`, "alpha.txt"),
60+
expected: "../find-fixture-other/alpha.txt",
61+
},
62+
{
63+
name: "filename whitespace",
64+
search: workspace,
65+
found: path.join(workspace, "report.txt "),
66+
expected: "report.txt ",
67+
},
68+
{
69+
name: "absolute directory marker",
70+
search: `${workspace}${path.sep}`,
71+
found: `${path.join(workspace, "folder")}${path.sep}`,
72+
expected: "folder/",
73+
},
74+
{
75+
name: "relative directory marker",
76+
search: workspace,
77+
found: `folder${path.sep}`,
78+
expected: "folder/",
79+
},
80+
])("preserves $name from custom operations", async ({ search, found, expected }) => {
81+
const tool = createFindToolDefinition(workspace, { operations: operations([found]) });
82+
const result = await tool.execute(
83+
"paths",
84+
{ pattern: "*", path: search },
85+
undefined,
86+
undefined,
87+
{} as never,
88+
);
89+
expect(textContent(result)).toBe(expected);
90+
expect(result.details).toBeUndefined();
91+
});
92+
2693
it("rejects fractional limits", async () => {
2794
const tool = createFindToolDefinition("/workspace", { operations: operations([]) });
2895

‎src/agents/sessions/tools/find.ts‎

Lines changed: 21 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,29 @@ function formatFindResult(
116116
}
117117

118118
function buildFindResult(params: {
119-
relativized: string[];
119+
paths: string[];
120+
searchPath: string;
120121
effectiveLimit: number;
121122
limitNotice: string;
122123
}): {
123124
content: Array<{ type: "text"; text: string }>;
124125
details: FindToolDetails | undefined;
125126
} {
126-
const resultLimitReached = params.relativized.length > params.effectiveLimit;
127-
const rawOutput = params.relativized.slice(0, params.effectiveLimit).join("\n");
127+
const resultLimitReached = params.paths.length > params.effectiveLimit;
128+
const rawOutput = params.paths
129+
.slice(0, params.effectiveLimit)
130+
.map((foundPath) => {
131+
// Backends may return search-relative paths; only absolute paths need relativizing.
132+
// Preserve directory markers and filename whitespace when formatting either backend.
133+
const normalized = normalizeNativePathSeparators(foundPath);
134+
const relativePath = path.isAbsolute(foundPath)
135+
? normalizeNativePathSeparators(path.relative(params.searchPath, foundPath) || ".")
136+
: normalized;
137+
return normalized.endsWith("/") && !relativePath.endsWith("/")
138+
? `${relativePath}/`
139+
: relativePath;
140+
})
141+
.join("\n");
128142
const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });
129143
let resultOutput = truncation.content;
130144
const details: FindToolDetails = {};
@@ -230,17 +244,11 @@ export function createFindToolDefinition(
230244
return;
231245
}
232246

233-
// Relativize paths against the search root for stable output.
234-
const relativized = results.slice(0, observationLimit).map((p) => {
235-
if (p.startsWith(searchPath)) {
236-
return normalizeNativePathSeparators(p.slice(searchPath.length + 1));
237-
}
238-
return normalizeNativePathSeparators(path.relative(searchPath, p));
239-
});
240247
settle(() =>
241248
resolve(
242249
buildFindResult({
243-
relativized,
250+
paths: results,
251+
searchPath,
244252
effectiveLimit,
245253
limitNotice: `${effectiveLimit} results limit reached`,
246254
}),
@@ -351,29 +359,11 @@ export function createFindToolDefinition(
351359
return;
352360
}
353361

354-
const relativized: string[] = [];
355-
for (const rawLine of lines) {
356-
const line = rawLine.replace(/\r$/, "").trim();
357-
if (!line) {
358-
continue;
359-
}
360-
const hadTrailingSlash = line.endsWith("/") || line.endsWith("\\");
361-
let relativePath;
362-
if (line.startsWith(searchPath)) {
363-
relativePath = line.slice(searchPath.length + 1);
364-
} else {
365-
relativePath = path.relative(searchPath, line);
366-
}
367-
if (hadTrailingSlash && !relativePath.endsWith("/")) {
368-
relativePath += "/";
369-
}
370-
relativized.push(normalizeNativePathSeparators(relativePath));
371-
}
372-
373362
settle(() =>
374363
resolve(
375364
buildFindResult({
376-
relativized,
365+
paths: lines,
366+
searchPath,
377367
effectiveLimit,
378368
limitNotice: `${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
379369
}),

0 commit comments

Comments
 (0)