File size: 28,563 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { GrepTool, type GrepToolParams } from './grep.js';
import type { ToolResult, GrepResult, ExecuteOptions } from './tools.js';
import path from 'node:path';
import { isSubpath, resolveToRealPath } from '../utils/paths.js';
import fs from 'node:fs/promises';
import os from 'node:os';
import type { Config } from '../config/config.js';
import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
import { ToolErrorType } from './tool-error.js';
import * as glob from 'glob';
import { createMockMessageBus } from '../test-utils/mock-message-bus.js';
import { execStreaming } from '../utils/shell-utils.js';

vi.mock('glob', { spy: true });
vi.mock('../utils/shell-utils.js', () => ({
  execStreaming: vi.fn(),
}));

// Mock the child_process module to control grep/git grep behavior
vi.mock('child_process', () => ({
  spawn: vi.fn(() => ({
    on: (event: string, cb: (...args: unknown[]) => void) => {
      if (event === 'error' || event === 'close') {
        // Simulate command not found or error for git grep and system grep
        // to force it to fall back to JS implementation.
        setTimeout(() => cb(1), 0); // cb(1) for error/close
      }
    },
    stdout: { on: vi.fn() },
    stderr: { on: vi.fn() },
  })),
}));

describe('GrepTool', () => {
  let tempRootDir: string;
  let grepTool: GrepTool;
  const abortSignal = new AbortController().signal;
  let mockConfig: Config;

  beforeEach(async () => {
    tempRootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'grep-tool-root-'));

    mockConfig = {
      getTargetDir: () => tempRootDir,
      getWorkspaceContext: () => createMockWorkspaceContext(tempRootDir),
      getFileExclusions: () => ({
        getGlobExcludes: () => [],
      }),
      getFileFilteringOptions: () => ({
        respectGitIgnore: true,
        respectGeminiIgnore: true,
        maxFileCount: 1000,
        searchTimeout: 30000,
        customIgnoreFilePaths: [],
      }),
      storage: {
        getProjectTempDir: vi.fn().mockReturnValue('/tmp/project'),
      },
      isPathAllowed(this: Config, absolutePath: string): boolean {
        const workspaceContext = this.getWorkspaceContext();
        if (workspaceContext.isPathWithinWorkspace(absolutePath)) {
          return true;
        }

        const projectTempDir = this.storage.getProjectTempDir();
        return isSubpath(path.resolve(projectTempDir), absolutePath);
      },
      validatePathAccess(this: Config, absolutePath: string): string | null {
        if (this.isPathAllowed(absolutePath)) {
          return null;
        }

        const workspaceDirs = this.getWorkspaceContext().getDirectories();
        const projectTempDir = this.storage.getProjectTempDir();
        return `Path not in workspace: Attempted path "${absolutePath}" resolves outside the allowed workspace directories: ${workspaceDirs.join(', ')} or the project temp directory: ${projectTempDir}`;
      },
    } as unknown as Config;

    grepTool = new GrepTool(mockConfig, createMockMessageBus());

    // Create some test files and directories
    await fs.writeFile(
      path.join(tempRootDir, 'fileA.txt'),
      'hello world\nsecond line with world',
    );
    await fs.writeFile(
      path.join(tempRootDir, 'fileB.js'),
      'const foo = "bar";\nfunction baz() { return "hello"; }',
    );
    await fs.mkdir(path.join(tempRootDir, 'sub'));
    await fs.writeFile(
      path.join(tempRootDir, 'sub', 'fileC.txt'),
      'another world in sub dir',
    );
    await fs.writeFile(
      path.join(tempRootDir, 'sub', 'fileD.md'),
      '# Markdown file\nThis is a test.',
    );
  });

  afterEach(async () => {
    await fs.rm(tempRootDir, { recursive: true, force: true });
  });

  describe('validateToolParams', () => {
    it('should return null for valid params (pattern only)', () => {
      const params: GrepToolParams = { pattern: 'hello' };
      expect(grepTool.validateToolParams(params)).toBeNull();
    });

    it('should return null for valid params (pattern and path)', () => {
      const params: GrepToolParams = { pattern: 'hello', dir_path: '.' };
      expect(grepTool.validateToolParams(params)).toBeNull();
    });

    it('should return null for valid params (pattern, path, and include)', () => {
      const params: GrepToolParams = {
        pattern: 'hello',
        dir_path: '.',
        include_pattern: '*.txt',
      };
      expect(grepTool.validateToolParams(params)).toBeNull();
    });

    it('should return error if pattern is missing', () => {
      const params = { dir_path: '.' } as unknown as GrepToolParams;
      expect(grepTool.validateToolParams(params)).toBe(
        `params must have required property 'pattern'`,
      );
    });

    it('should return error for invalid regex pattern', () => {
      const params: GrepToolParams = { pattern: '[[' };
      expect(grepTool.validateToolParams(params)).toContain(
        'Invalid regular expression pattern',
      );
    });

    it('should return error if path does not exist', () => {
      const params: GrepToolParams = {
        pattern: 'hello',
        dir_path: 'nonexistent',
      };
      // Check for the core error message, as the full path might vary
      expect(grepTool.validateToolParams(params)).toContain(
        'Path does not exist',
      );
      expect(grepTool.validateToolParams(params)).toContain('nonexistent');
    });

    it('should return error if path is a file, not a directory', async () => {
      const filePath = resolveToRealPath(path.join(tempRootDir, 'fileA.txt'));
      const params: GrepToolParams = { pattern: 'hello', dir_path: filePath };
      expect(grepTool.validateToolParams(params)).toContain(
        `Path is not a directory: ${filePath}`,
      );
    });
  });

  function createLineGenerator(lines: string[]): AsyncGenerator<string> {
    return (async function* () {
      for (const line of lines) {
        yield line;
      }
    })();
  }

  describe('execute', () => {
    it('should find matches for a simple pattern in all files', async () => {
      const params: GrepToolParams = { pattern: 'world' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain(
        'Found 3 matches for pattern "world" in the workspace directory',
      );
      expect(result.llmContent).toContain('File: fileA.txt');
      expect(result.llmContent).toContain('L1: hello world');
      expect(result.llmContent).toContain('L2: second line with world');
      expect(result.llmContent).toContain(
        `File: ${path.join('sub', 'fileC.txt')}`,
      );
      expect(result.llmContent).toContain('L1: another world in sub dir');
      expect((result.returnDisplay as GrepResult)?.summary).toBe(
        'Found 3 matches',
      );
    }, 30000);

    it('should include files that start with ".." in JS fallback', async () => {
      await fs.writeFile(path.join(tempRootDir, '..env'), 'world in ..env');
      const params: GrepToolParams = { pattern: 'world' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain('File: ..env');
      expect(result.llmContent).toContain('L1: world in ..env');
    });

    it('should ignore system grep output that escapes base path', async () => {
      vi.mocked(execStreaming).mockImplementationOnce(() =>
        createLineGenerator(['..env:1:hello', '../secret.txt:2:leak']),
      );

      const params: GrepToolParams = { pattern: 'hello' };
      const invocation = grepTool.build(params) as unknown as {
        isCommandAvailable: (command: string) => Promise<boolean>;
        execute: (options: ExecuteOptions) => Promise<ToolResult>;
      };
      invocation.isCommandAvailable = vi.fn(
        async (command: string) => command === 'grep',
      );

      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain('File: ..env');
      expect(result.llmContent).toContain('L1: hello');
      expect(result.llmContent).not.toContain('secret.txt');
    });

    it('should find matches in a specific path', async () => {
      const params: GrepToolParams = { pattern: 'world', dir_path: 'sub' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain(
        'Found 1 match for pattern "world" in path "sub"',
      );
      expect(result.llmContent).toContain('File: fileC.txt'); // Path relative to 'sub'
      expect(result.llmContent).toContain('L1: another world in sub dir');
      expect((result.returnDisplay as GrepResult)?.summary).toBe(
        'Found 1 match',
      );
    }, 30000);

    it('should find matches with an include glob', async () => {
      const params: GrepToolParams = {
        pattern: 'hello',
        include_pattern: '*.js',
      };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain(
        'Found 1 match for pattern "hello" in the workspace directory (filter: "*.js"):',
      );
      expect(result.llmContent).toContain('File: fileB.js');
      expect(result.llmContent).toContain(
        'L2: function baz() { return "hello"; }',
      );
      expect((result.returnDisplay as GrepResult)?.summary).toBe(
        'Found 1 match',
      );
    }, 30000);

    it('should find matches with an include glob and path', async () => {
      await fs.writeFile(
        path.join(tempRootDir, 'sub', 'another.js'),
        'const greeting = "hello";',
      );
      const params: GrepToolParams = {
        pattern: 'hello',
        dir_path: 'sub',
        include_pattern: '*.js',
      };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain(
        'Found 1 match for pattern "hello" in path "sub" (filter: "*.js")',
      );
      expect(result.llmContent).toContain('File: another.js');
      expect(result.llmContent).toContain('L1: const greeting = "hello";');
      expect((result.returnDisplay as GrepResult)?.summary).toBe(
        'Found 1 match',
      );
    }, 30000);

    it('should return "No matches found" when pattern does not exist', async () => {
      const params: GrepToolParams = { pattern: 'nonexistentpattern' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain(
        'No matches found for pattern "nonexistentpattern" in the workspace directory.',
      );
      expect((result.returnDisplay as GrepResult)?.summary).toBe(
        'No matches found',
      );
    }, 30000);

    it('should handle regex special characters correctly', async () => {
      const params: GrepToolParams = { pattern: 'foo.*bar' }; // Matches 'const foo = "bar";'
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain(
        'Found 1 match for pattern "foo.*bar" in the workspace directory:',
      );
      expect(result.llmContent).toContain('File: fileB.js');
      expect(result.llmContent).toContain('L1: const foo = "bar";');
    }, 30000);

    it('should be case-insensitive by default (JS fallback)', async () => {
      const params: GrepToolParams = { pattern: 'HELLO' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.llmContent).toContain(
        'Found 2 matches for pattern "HELLO" in the workspace directory:',
      );
      expect(result.llmContent).toContain('File: fileA.txt');
      expect(result.llmContent).toContain('L1: hello world');
      expect(result.llmContent).toContain('File: fileB.js');
      expect(result.llmContent).toContain(
        'L2: function baz() { return "hello"; }',
      );
    }, 30000);

    it('should pass -i flag to system grep for case-insensitivity', async () => {
      vi.mocked(execStreaming).mockImplementationOnce(() =>
        createLineGenerator(['fileA.txt:1:hello world']),
      );

      const params: GrepToolParams = { pattern: 'HELLO' };
      const invocation = grepTool.build(params) as unknown as {
        isCommandAvailable: (command: string) => Promise<boolean>;
        execute: (options: ExecuteOptions) => Promise<ToolResult>;
      };
      // Force system grep strategy by mocking isCommandAvailable and ensuring git grep is not used
      invocation.isCommandAvailable = vi.fn(async (command: string) => {
        if (command === 'git') return false;
        if (command === 'grep') return true;
        return false;
      });

      await invocation.execute({ abortSignal });

      expect(execStreaming).toHaveBeenCalledWith(
        'grep',
        expect.arrayContaining(['-i']),
        expect.objectContaining({
          cwd: expect.any(String),
        }),
      );
    });

    it('should throw an error if params are invalid', async () => {
      const params = { dir_path: '.' } as unknown as GrepToolParams; // Invalid: pattern missing
      expect(() => grepTool.build(params)).toThrow(
        /params must have required property 'pattern'/,
      );
    }, 30000);

    it('should return a GREP_EXECUTION_ERROR on failure', async () => {
      vi.mocked(glob.globStream).mockRejectedValue(new Error('Glob failed'));
      const params: GrepToolParams = { pattern: 'hello' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });
      expect(result.error?.type).toBe(ToolErrorType.GREP_EXECUTION_ERROR);
      vi.mocked(glob.globStream).mockReset();
    }, 30000);
  });

  describe('multi-directory workspace', () => {
    it('should search across all workspace directories when no path is specified', async () => {
      // Create additional directory with test files
      const secondDir = await fs.mkdtemp(
        path.join(os.tmpdir(), 'grep-tool-second-'),
      );
      await fs.writeFile(
        path.join(secondDir, 'other.txt'),
        'hello from second directory\nworld in second',
      );
      await fs.writeFile(
        path.join(secondDir, 'another.js'),
        'function world() { return "test"; }',
      );

      // Create a mock config with multiple directories
      const multiDirConfig = {
        getTargetDir: () => tempRootDir,
        getWorkspaceContext: () =>
          createMockWorkspaceContext(tempRootDir, [secondDir]),
        getFileExclusions: () => ({
          getGlobExcludes: () => [],
        }),
        getFileFilteringOptions: () => ({
          respectGitIgnore: true,
          respectGeminiIgnore: true,
          maxFileCount: 1000,
          searchTimeout: 30000,
          customIgnoreFilePaths: [],
        }),
        storage: {
          getProjectTempDir: vi.fn().mockReturnValue('/tmp/project'),
        },
        isPathAllowed(this: Config, absolutePath: string): boolean {
          const workspaceContext = this.getWorkspaceContext();
          if (workspaceContext.isPathWithinWorkspace(absolutePath)) {
            return true;
          }

          const projectTempDir = this.storage.getProjectTempDir();
          return isSubpath(path.resolve(projectTempDir), absolutePath);
        },
        validatePathAccess(this: Config, absolutePath: string): string | null {
          if (this.isPathAllowed(absolutePath)) {
            return null;
          }

          const workspaceDirs = this.getWorkspaceContext().getDirectories();
          const projectTempDir = this.storage.getProjectTempDir();
          return `Path not in workspace: Attempted path "${absolutePath}" resolves outside the allowed workspace directories: ${workspaceDirs.join(', ')} or the project temp directory: ${projectTempDir}`;
        },
      } as unknown as Config;

      const multiDirGrepTool = new GrepTool(
        multiDirConfig,
        createMockMessageBus(),
      );
      const params: GrepToolParams = { pattern: 'world' };
      const invocation = multiDirGrepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      // Should find matches in both directories
      expect(result.llmContent).toContain(
        'Found 5 matches for pattern "world"',
      );

      // Matches from first directory
      expect(result.llmContent).toContain('fileA.txt');
      expect(result.llmContent).toContain('L1: hello world');
      expect(result.llmContent).toContain('L2: second line with world');
      expect(result.llmContent).toContain('fileC.txt');
      expect(result.llmContent).toContain('L1: another world in sub dir');

      // Matches from second directory (with directory name prefix)
      const secondDirName = path.basename(secondDir);
      expect(result.llmContent).toContain(
        `File: ${path.join(secondDirName, 'other.txt')}`,
      );
      expect(result.llmContent).toContain('L2: world in second');
      expect(result.llmContent).toContain(
        `File: ${path.join(secondDirName, 'another.js')}`,
      );
      expect(result.llmContent).toContain('L1: function world()');

      // Clean up
      await fs.rm(secondDir, { recursive: true, force: true });
    });

    it('should search only specified path within workspace directories', async () => {
      // Create additional directory
      const secondDir = await fs.mkdtemp(
        path.join(os.tmpdir(), 'grep-tool-second-'),
      );
      await fs.mkdir(path.join(secondDir, 'sub'));
      await fs.writeFile(
        path.join(secondDir, 'sub', 'test.txt'),
        'hello from second sub directory',
      );

      // Create a mock config with multiple directories
      const multiDirConfig = {
        getTargetDir: () => tempRootDir,
        getWorkspaceContext: () =>
          createMockWorkspaceContext(tempRootDir, [secondDir]),
        getFileExclusions: () => ({
          getGlobExcludes: () => [],
        }),
        getFileFilteringOptions: () => ({
          respectGitIgnore: true,
          respectGeminiIgnore: true,
          maxFileCount: 1000,
          searchTimeout: 30000,
          customIgnoreFilePaths: [],
        }),
        storage: {
          getProjectTempDir: vi.fn().mockReturnValue('/tmp/project'),
        },
        isPathAllowed(this: Config, absolutePath: string): boolean {
          const workspaceContext = this.getWorkspaceContext();
          if (workspaceContext.isPathWithinWorkspace(absolutePath)) {
            return true;
          }

          const projectTempDir = this.storage.getProjectTempDir();
          return isSubpath(path.resolve(projectTempDir), absolutePath);
        },
        validatePathAccess(this: Config, absolutePath: string): string | null {
          if (this.isPathAllowed(absolutePath)) {
            return null;
          }

          const workspaceDirs = this.getWorkspaceContext().getDirectories();
          const projectTempDir = this.storage.getProjectTempDir();
          return `Path not in workspace: Attempted path "${absolutePath}" resolves outside the allowed workspace directories: ${workspaceDirs.join(', ')} or the project temp directory: ${projectTempDir}`;
        },
      } as unknown as Config;

      const multiDirGrepTool = new GrepTool(
        multiDirConfig,
        createMockMessageBus(),
      );

      // Search only in the 'sub' directory of the first workspace
      const params: GrepToolParams = { pattern: 'world', dir_path: 'sub' };
      const invocation = multiDirGrepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      // Should only find matches in the specified sub directory
      expect(result.llmContent).toContain(
        'Found 1 match for pattern "world" in path "sub"',
      );
      expect(result.llmContent).toContain('File: fileC.txt');
      expect(result.llmContent).toContain('L1: another world in sub dir');

      // Should not contain matches from second directory
      expect(result.llmContent).not.toContain('test.txt');

      // Clean up
      await fs.rm(secondDir, { recursive: true, force: true });
    });

    it('should respect total_max_matches and truncate results', async () => {
      // Use 'world' pattern which has 3 matches across fileA.txt and sub/fileC.txt
      const params: GrepToolParams = {
        pattern: 'world',
        total_max_matches: 2,
      };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      expect(result.llmContent).toContain('Found 2 matches');
      expect(result.llmContent).toContain(
        'results limited to 2 matches for performance',
      );
      // It should find matches in fileA.txt first (2 matches)
      expect(result.llmContent).toContain('File: fileA.txt');
      expect(result.llmContent).toContain('L1: hello world');
      expect(result.llmContent).toContain('L2: second line with world');
      // And sub/fileC.txt should be excluded because limit reached
      expect(result.llmContent).not.toContain('File: sub/fileC.txt');
      expect((result.returnDisplay as GrepResult)?.summary).toBe(
        'Found 2 matches (limited)',
      );
    });

    it('should respect max_matches_per_file in JS fallback', async () => {
      const params: GrepToolParams = {
        pattern: 'world',
        max_matches_per_file: 1,
      };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      // fileA.txt has 2 worlds, but should only return 1.
      // sub/fileC.txt has 1 world, so total matches = 2.
      expect(result.llmContent).toContain('Found 2 matches');
      expect(result.llmContent).toContain('File: fileA.txt');
      // Should be a match
      expect(result.llmContent).toContain('L1: hello world');
      // Should NOT be a match (but might be in context as L2-)
      expect(result.llmContent).not.toContain('L2: second line with world');
      expect(result.llmContent).toContain(
        `File: ${path.join('sub', 'fileC.txt')}`,
      );
      expect(result.llmContent).toContain('L1: another world in sub dir');
    });

    it('should return only file paths when names_only is true', async () => {
      const params: GrepToolParams = {
        pattern: 'world',
        names_only: true,
      };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      expect(result.llmContent).toContain('Found 2 files with matches');
      expect(result.llmContent).toContain('fileA.txt');
      expect(result.llmContent).toContain(path.join('sub', 'fileC.txt'));
      expect(result.llmContent).not.toContain('L1:');
      expect(result.llmContent).not.toContain('hello world');
    });

    it('should filter out matches based on exclude_pattern', async () => {
      await fs.writeFile(
        path.join(tempRootDir, 'copyright.txt'),
        'Copyright 2025 Google LLC\nCopyright 2026 Google LLC',
      );

      const params: GrepToolParams = {
        pattern: 'Copyright .* Google LLC',
        exclude_pattern: '2026',
        dir_path: '.',
      };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      expect(result.llmContent).toContain('Found 1 match');
      expect(result.llmContent).toContain('copyright.txt');
      // Should be a match
      expect(result.llmContent).toContain('L1: Copyright 2025 Google LLC');
      // Should NOT be a match (but might be in context as L2-)
      expect(result.llmContent).not.toContain('L2: Copyright 2026 Google LLC');
    });

    it('should include context when matches are <= 3', async () => {
      const lines = Array.from({ length: 100 }, (_, i) => `Line ${i + 1}`);
      lines[50] = 'Target match';
      await fs.writeFile(
        path.join(tempRootDir, 'context.txt'),
        lines.join('\n'),
      );

      const params: GrepToolParams = { pattern: 'Target match' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      expect(result.llmContent).toContain(
        'Found 1 match for pattern "Target match"',
      );
      // Verify context before
      expect(result.llmContent).toContain('L40- Line 40');
      // Verify match line
      expect(result.llmContent).toContain('L51: Target match');
      // Verify context after
      expect(result.llmContent).toContain('L60- Line 60');
    });

    it('should truncate excessively long lines', async () => {
      const longString = 'a'.repeat(3000);
      await fs.writeFile(
        path.join(tempRootDir, 'longline.txt'),
        `Target match ${longString}`,
      );

      const params: GrepToolParams = { pattern: 'Target match' };
      const invocation = grepTool.build(params);
      const result = await invocation.execute({ abortSignal });

      // MAX_LINE_LENGTH_TEXT_FILE is 2000. It should be truncated.
      expect(result.llmContent).toContain('... [truncated]');
      expect(result.llmContent).not.toContain(longString);
    });
  });

  describe('getDescription', () => {
    it('should generate correct description with pattern only', () => {
      const params: GrepToolParams = { pattern: 'testPattern' };
      const invocation = grepTool.build(params);
      expect(invocation.getDescription()).toBe("'testPattern'");
    });

    it('should generate correct description with pattern and include', () => {
      const params: GrepToolParams = {
        pattern: 'testPattern',
        include_pattern: '*.ts',
      };
      const invocation = grepTool.build(params);
      expect(invocation.getDescription()).toBe("'testPattern' in *.ts");
    });

    it('should generate correct description with pattern and path', async () => {
      const dirPath = path.join(tempRootDir, 'src', 'app');
      await fs.mkdir(dirPath, { recursive: true });
      const params: GrepToolParams = {
        pattern: 'testPattern',
        dir_path: path.join('src', 'app'),
      };
      const invocation = grepTool.build(params);
      // The path will be relative to the tempRootDir, so we check for containment.
      expect(invocation.getDescription()).toContain("'testPattern' within");
      expect(invocation.getDescription()).toContain(path.join('src', 'app'));
    });

    it('should indicate searching across all workspace directories when no path specified', () => {
      // Create a mock config with multiple directories
      const multiDirConfig = {
        getTargetDir: () => tempRootDir,
        getWorkspaceContext: () =>
          createMockWorkspaceContext(tempRootDir, ['/another/dir']),
        getFileExclusions: () => ({
          getGlobExcludes: () => [],
        }),
        getFileFilteringOptions: () => ({
          respectGitIgnore: true,
          respectGeminiIgnore: true,
          maxFileCount: 1000,
          searchTimeout: 30000,
          customIgnoreFilePaths: [],
        }),
      } as unknown as Config;

      const multiDirGrepTool = new GrepTool(
        multiDirConfig,
        createMockMessageBus(),
      );
      const params: GrepToolParams = { pattern: 'testPattern' };
      const invocation = multiDirGrepTool.build(params);
      expect(invocation.getDescription()).toBe(
        "'testPattern' across all workspace directories",
      );
    });

    it('should generate correct description with pattern, include, and path', async () => {
      const dirPath = path.join(tempRootDir, 'src', 'app');
      await fs.mkdir(dirPath, { recursive: true });
      const params: GrepToolParams = {
        pattern: 'testPattern',
        include_pattern: '*.ts',
        dir_path: path.join('src', 'app'),
      };
      const invocation = grepTool.build(params);
      expect(invocation.getDescription()).toContain(
        "'testPattern' in *.ts within",
      );
      expect(invocation.getDescription()).toContain(path.join('src', 'app'));
    });

    it('should use ./ for root path in description', () => {
      const params: GrepToolParams = { pattern: 'testPattern', dir_path: '.' };
      const invocation = grepTool.build(params);
      expect(invocation.getDescription()).toBe("'testPattern' within ./");
    });
  });
});