[Bug] adk/filesystem: grep counts context lines as matches in count mode
Describe the bug
The grep tool of the filesystem middleware documents -C, -A and -B as "Requires output_mode: 'content', ignored otherwise" (grepArgs, adk/middlewares/filesystem/filesystem.go:1150-1160). GrepRequest.AfterLines and GrepRequest.BeforeLines say the same: "Only applicable when OutputMode is "content"" (adk/filesystem/backend.go:127-137). newGrepTool still computes the context line counts and passes them to GrepRaw for every output mode:
var beforeLines, afterLines int
if input.Context != nil {
beforeLines = valueOrDefault(input.Context, 0)
afterLines = valueOrDefault(input.Context, 0)
} else {
// Extract context parameters
beforeLines = valueOrDefault(input.BeforeLines, 0)
afterLines = valueOrDefault(input.AfterLines, 0)
}The backend returns context lines as GrepMatch entries, and formatCountMatches counts every entry. In count mode, a model that also sends -C, which is common, gets an inflated number of occurrences. The files_with_matches output is not affected because paths are de-duplicated, but the backend still reads the context lines.
To Reproduce
backend := filesystem.NewInMemoryBackend()
_ = backend.Write(ctx, &filesystem.WriteRequest{FilePath: "/a.txt", Content: "hello world\nfoo bar\nhello again"})
mw, _ := fsmw.New(ctx, &fsmw.MiddlewareConfig{Backend: backend})
_, runCtx, _ := mw.BeforeAgent(ctx, &adk.ChatModelAgentContext{})
for _, t := range runCtx.Tools {
if info, _ := t.Info(ctx); info.Name == "grep" {
out, _ := t.(tool.InvokableTool).InvokableRun(ctx, `{"pattern": "hello", "output_mode": "count", "-C": 1}`)
fmt.Println(out)
}
}On alpha/10 @ 58daeda this prints:
/a.txt:3
Found 3 total occurrences across 1 file.Without -C it prints /a.txt:2 and Found 2 total occurrences across 1 file. The context line foo bar is counted as a match.
Expected behavior
-C, -A and -B are ignored unless output_mode is content, as documented. The example prints Found 2 total occurrences across 1 file.
Version:
alpha/10 @ 58daeda (adk/middlewares/filesystem/filesystem.go:1198-1207). The same code exists on main @ ba04fde (adk/middlewares/filesystem/filesystem.go:961-970).
Source: cloudwego/eino