summaryrefslogtreecommitdiff
path: root/packages/core/src/tools/code_parser.test.ts
blob: 358edc7dd7ba56326a34a7eedbe274165622da6f (plain)
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import {
  vi,
  describe,
  it,
  expect,
  beforeEach,
  afterEach,
  Mocked,
} from 'vitest';
import { CodeParserTool, CodeParserToolParams } from './code_parser.js';
import { Config } from '../config/config.js';
import fs from 'fs/promises';
import { Stats, PathLike } from 'fs'; // Added Stats import
import path from 'path';
import os from 'os';
import actualFs from 'fs'; // For actual fs operations in setup

// Mock fs/promises
vi.mock('fs/promises');

// Mock tree-sitter and its language grammars
const mockTreeSitterParse = vi.fn();
const mockSetLanguage = vi.fn();

vi.mock('tree-sitter', () => ({
  default: vi.fn().mockImplementation(() => ({
    setLanguage: mockSetLanguage,
    parse: mockTreeSitterParse,
  })),
}));

const mockPythonGrammar = vi.hoisted(() => ({ name: 'python' }));
const mockJavaGrammar = vi.hoisted(() => ({ name: 'java' }));
const mockGoGrammar = vi.hoisted(() => ({ name: 'go' }));
const mockCSharpGrammar = vi.hoisted(() => ({ name: 'csharp' }));
const mockTypeScriptGrammar = vi.hoisted(() => ({ name: 'typescript' }));
const mockTSXGrammar = vi.hoisted(() => ({ name: 'tsx' }));
const mockRustGrammar = vi.hoisted(() => ({ name: 'rust' })); // Added for Rust

vi.mock('tree-sitter-python', () => ({ default: mockPythonGrammar }));
vi.mock('tree-sitter-java', () => ({ default: mockJavaGrammar }));
vi.mock('tree-sitter-go', () => ({ default: mockGoGrammar }));
vi.mock('tree-sitter-c-sharp', () => ({ default: mockCSharpGrammar }));
vi.mock('tree-sitter-typescript', () => ({
  default: {
    typescript: mockTypeScriptGrammar,
    tsx: mockTSXGrammar,
  },
}));
vi.mock('tree-sitter-rust', () => ({ default: mockRustGrammar })); // Added for Rust

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

  // Use Mocked type for fs/promises
  let mockFs: Mocked<typeof fs>;

  beforeEach(() => {
    const tempDirPrefix = path.join(os.tmpdir(), 'code-parser-tool-root-');
    tempRootDir = actualFs.mkdtempSync(tempDirPrefix);
    tempRootDir = path.resolve(tempRootDir);

    mockConfig = { get: vi.fn() } as unknown as Config;
    tool = new CodeParserTool(tempRootDir, mockConfig);
    mockFs = fs as Mocked<typeof fs>;

    mockTreeSitterParse.mockReset();
    mockSetLanguage.mockReset();
    mockFs.stat.mockReset();
    mockFs.readFile.mockReset();
    mockFs.readdir.mockReset();

    mockTreeSitterParse.mockReturnValue({
      rootNode: { toString: () => '(mock_ast)' },
    });
  });

  afterEach(() => {
    if (actualFs.existsSync(tempRootDir)) {
      actualFs.rmSync(tempRootDir, { recursive: true, force: true });
    }
    vi.clearAllMocks();
  });

  describe('constructor and schema', () => {
    it('should have correct name', () => {
      expect(tool.name).toBe('code_parser');
    });

    it('should have correct schema definition', () => {
      const schema = tool.schema.parameters!;
      expect(schema.type).toBe('object');
      expect(schema.properties).toHaveProperty('path');
      expect(schema.properties!.path.type).toBe('string');
      expect(schema.properties!.path.description).toContain('absolute path');
      expect(schema.properties).toHaveProperty('languages');
      expect(schema.properties!.languages.type).toBe('array');
      expect(schema.properties!.languages.description).toContain('go');
      expect(schema.properties!.languages.description).toContain('csharp');
      expect(schema.properties!.languages.description).toContain('typescript');
      expect(schema.properties!.languages.description).toContain('tsx');
      expect(schema.properties!.languages.description).toContain('javascript');
      expect(schema.properties!.languages.description).toContain('rust'); // Added for Rust
      expect(schema.required).toEqual(['path']);
    });
  });

  describe('validateToolParams', () => {
    it('should return null for valid path with languages', () => {
      const params: CodeParserToolParams = {
        path: path.join(tempRootDir, 'dir'),
        languages: [
          'python',
          'go',
          'csharp',
          'typescript',
          'tsx',
          'javascript',
        ],
      };
      expect(tool.validateToolParams(params)).toBeNull();
    });

    it('should return error for relative path', () => {
      const params: CodeParserToolParams = { path: 'file.py' };
      expect(tool.validateToolParams(params)).toMatch(/Path must be absolute/);
    });

    it('should return error for path outside root directory', () => {
      const outsidePath = path.resolve(
        os.tmpdir(),
        'some-other-dir',
        'file.py',
      );
      if (outsidePath.startsWith(tempRootDir)) {
        console.warn(
          'Skipping outside root test due to overlapping temp/outside paths',
        );
        return;
      }
      const params: CodeParserToolParams = { path: outsidePath };
      expect(tool.validateToolParams(params)).toMatch(
        /Path must be within the root directory/,
      );
    });

    it('should return error if languages is not an array of strings', () => {
      const params = {
        path: path.join(tempRootDir, 'file.py'),
        languages: [123],
      } as unknown as CodeParserToolParams;
      expect(tool.validateToolParams(params)).toBe(
        'Languages parameter must be an array of strings.',
      );
    });
  });

  describe('getDescription', () => {
    it('should return "Parse <shortened_relative_path>"', () => {
      const filePath = path.join(tempRootDir, 'src', 'app', 'main.py');
      const params: CodeParserToolParams = { path: filePath };
      expect(tool.getDescription(params)).toBe('Parse src/app/main.py');
    });
  });

  describe('execute', () => {
    // --- Error Handling Tests ---
    it('should return validation error if params are invalid', async () => {
      const params: CodeParserToolParams = { path: 'relative/path.txt' };
      const result = await tool.execute(params, abortSignal);
      expect(result.llmContent).toMatch(
        /Error: Invalid parameters provided. Reason: Path must be absolute/,
      );
      expect(result.returnDisplay).toBe('Error: Failed to execute tool.');
    });

    it('should return error if target path does not exist', async () => {
      const targetPath = path.join(tempRootDir, 'nonexistent.py');
      mockFs.stat.mockRejectedValue({
        code: 'ENOENT',
      } as NodeJS.ErrnoException);
      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);
      expect(result.llmContent).toMatch(
        /Error: Path not found or inaccessible/,
      );
      expect(result.returnDisplay).toMatch(
        /Error: Path not found or inaccessible/,
      );
    });

    it('should return error if target path is not a file or directory', async () => {
      const targetPath = path.join(tempRootDir, 'neither_file_nor_dir');
      mockFs.stat.mockResolvedValue({
        isFile: () => false,
        isDirectory: () => false,
        size: 0,
      } as Stats);
      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);
      expect(result.llmContent).toMatch(
        /Error: Path is not a file or directory/,
      );
      expect(result.returnDisplay).toMatch(
        /Error: Path is not a file or directory/,
      );
    });

    it('should return error if no supported languages are specified or available', async () => {
      const targetPath = path.join(tempRootDir, 'file.py');
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: 100,
      } as Stats);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const originalGetLanguageParser = (tool as any).getLanguageParser;
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (tool as any).getLanguageParser = vi.fn().mockReturnValue(undefined);

      const params: CodeParserToolParams = {
        path: targetPath,
        languages: ['fantasy-lang'],
      };
      const result = await tool.execute(params, abortSignal);
      expect(result.llmContent).toMatch(
        /Error: No supported languages specified for parsing/,
      );
      expect(result.returnDisplay).toMatch(
        /Error: No supported languages to parse/,
      );
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (tool as any).getLanguageParser = originalGetLanguageParser; // Restore
    });

    // --- Single File Parsing Tests ---
    it('should parse a single Python file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'test.py');
      const fileContent = 'print("hello")';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(python_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockPythonGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(python_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a single Java file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'Test.java');
      const fileContent = 'class Test {}';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(java_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockJavaGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(java_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a single Go file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'main.go');
      const fileContent = 'package main\nfunc main(){}';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(go_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockGoGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(go_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a single C# file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'Program.cs');
      const fileContent =
        'namespace HelloWorld { class Program { static void Main(string[] args) { System.Console.WriteLine("Hello World!"); } } }';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(csharp_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockCSharpGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(csharp_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a single TypeScript (.ts) file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'app.ts');
      const fileContent = 'const x: number = 10;';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(ts_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockTypeScriptGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(ts_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a single TSX (.tsx) file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'component.tsx');
      const fileContent = 'const Comp = () => <div />;';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(tsx_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockTSXGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(tsx_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a single JavaScript (.js) file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'script.js');
      const fileContent = 'console.log("hello");';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(js_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockTypeScriptGrammar); // Uses TypeScript grammar for JS
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(js_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a single Rust (.rs) file successfully', async () => {
      const targetPath = path.join(tempRootDir, 'main.rs');
      const fileContent = 'fn main() { println!("Hello, Rust!"); }';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(rust_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockRustGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(rust_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should parse a JavaScript JSX (.jsx) file successfully (using tsx parser)', async () => {
      const targetPath = path.join(tempRootDir, 'component.jsx');
      const fileContent = 'const Comp = () => <div />;';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockReturnValue({
        rootNode: { toString: () => '(jsx_ast)' },
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockSetLanguage).toHaveBeenCalledWith(mockTSXGrammar);
      expect(mockTreeSitterParse).toHaveBeenCalledWith(fileContent);
      expect(result.llmContent).toBe(
        `Parsed code from ${targetPath}:\n-------------${targetPath}-------------\n(jsx_ast)\n\n`,
      );
      expect(result.returnDisplay).toBe('Parsed 1 file(s).');
    });

    it('should return error for unsupported file type if specified directly', async () => {
      const targetPath = path.join(tempRootDir, 'notes.txt');
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: 10,
      } as Stats);

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(result.llmContent).toMatch(
        /Error: File .* is not of a supported language type/,
      );
      expect(result.returnDisplay).toMatch(
        /Error: Unsupported file type or language/,
      );
    });

    it('should skip file if it exceeds maxFileSize', async () => {
      const targetPath = path.join(tempRootDir, 'large.py');
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: 1024 * 1024 + 1,
      } as Stats); // 1MB + 1 byte

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(mockFs.readFile).not.toHaveBeenCalled();
      expect(result.llmContent).toMatch(
        /Error: Could not parse file .*large.py/,
      );
      expect(result.returnDisplay).toBe('Error: Failed to parse file.');
    });

    it('should return error if parsing a supported file fails internally', async () => {
      const targetPath = path.join(tempRootDir, 'broken.py');
      const fileContent = 'print("hello")';
      mockFs.stat.mockResolvedValue({
        isFile: () => true,
        isDirectory: () => false,
        size: fileContent.length,
      } as Stats);
      mockFs.readFile.mockResolvedValue(fileContent);
      mockTreeSitterParse.mockImplementation(() => {
        throw new Error('TreeSitterCrashed');
      });

      const params: CodeParserToolParams = { path: targetPath };
      const result = await tool.execute(params, abortSignal);

      expect(result.llmContent).toMatch(
        /Error: Could not parse file .*broken.py/,
      );
      expect(result.returnDisplay).toMatch(/Error: Failed to parse file./);
    });

    // --- Directory Parsing Tests ---
    it('should parse supported files in a directory (including Go, C#, TS, JS, TSX)', async () => {
      const dirPath = path.join(tempRootDir, 'src');
      const files = [
        'main.py',
        'helper.java',
        'service.go',
        'App.cs',
        'logic.ts',
        'ui.tsx',
        'utils.js',
        'main.rs', // Added Rust file
        'config.txt',
      ];
      const pythonContent = 'import os';
      const javaContent = 'public class Helper {}';
      const goContent = 'package main';
      const csharpContent = 'public class App {}';
      const tsContent = 'let val: number = 1;';
      const tsxContent = 'const MyComp = () => <p />;';
      const jsContent = 'function hello() {}';
      const rustContent = 'fn start() {}'; // Added Rust content

      mockFs.stat.mockImplementation(async (p) => {
        if (p === dirPath)
          return { isFile: () => false, isDirectory: () => true } as Stats;
        if (p === path.join(dirPath, 'main.py'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: pythonContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'helper.java'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: javaContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'service.go'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: goContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'App.cs'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: csharpContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'logic.ts'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: tsContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'ui.tsx'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: tsxContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'utils.js'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: jsContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'main.rs'))
          // Added for Rust
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: rustContent.length,
          } as Stats;
        if (p === path.join(dirPath, 'config.txt'))
          return {
            isFile: () => true,
            isDirectory: () => false,
            size: 10,
          } as Stats;
        throw { code: 'ENOENT' };
      });
      mockFs.readdir.mockImplementation(
        vi.fn(async (p: PathLike): Promise<string[]> => {
          const dirPath = path.join(tempRootDir, 'src'); // Path for this specific test
          if (p === dirPath) {
            return files; // files is in scope for this test
          }
          throw new Error(
            `fs.readdir mock: Unhandled path ${p} in test 'should parse supported files in a directory'`,
          );
        }) as unknown as typeof fs.readdir,
      );
      mockFs.readFile.mockImplementation(async (p) => {
        if (p === path.join(dirPath, 'main.py')) return pythonContent;
        if (p === path.join(dirPath, 'helper.java')) return javaContent;
        if (p === path.join(dirPath, 'service.go')) return goContent;
        if (p === path.join(dirPath, 'App.cs')) return csharpContent;
        if (p === path.join(dirPath, 'logic.ts')) return tsContent;
        if (p === path.join(dirPath, 'ui.tsx')) return tsxContent;
        if (p === path.join(dirPath, 'utils.js')) return jsContent;
        if (p === path.join(dirPath, 'main.rs')) return rustContent; // Added for Rust
        return '';
      });
      mockTreeSitterParse.mockImplementation((content) => {
        if (content === pythonContent)
          return { rootNode: { toString: () => '(py_ast_dir)' } };
        if (content === javaContent)
          return { rootNode: { toString: () => '(java_ast_dir)' } };
        if (content === goContent)
          return { rootNode: { toString: () => '(go_ast_dir)' } };
        if (content === csharpContent)
          return { rootNode: { toString: () => '(csharp_ast_dir)' } };
        if (content === tsContent)
          return { rootNode: { toString: () => '(ts_ast_dir)' } };
        if (content === tsxContent)
          return { rootNode: { toString: () => '(tsx_ast_dir)' } };
        if (content === jsContent)
          return { rootNode: { toString: () => '(js_ast_dir)' } };
        if (content === rustContent)
          // Added for Rust
          return { rootNode: { toString: () => '(rust_ast_dir)' } };
        return { rootNode: { toString: () => '(other_ast)' } };
      });

      const params: CodeParserToolParams = { path: dirPath };
      const result = await tool.execute(params, abortSignal);

      expect(result.llmContent).toContain(
        `-------------${path.join(dirPath, 'main.py')}-------------\n(py_ast_dir)\n`,
      );
      expect(result.llmContent).toContain(
        `-------------${path.join(dirPath, 'helper.java')}-------------\n(java_ast_dir)\n`,
      );
      expect(result.llmContent).toContain(
        `-------------${path.join(dirPath, 'service.go')}-------------\n(go_ast_dir)\n`,
      );
      expect(result.llmContent).toContain(
        `-------------${path.join(dirPath, 'App.cs')}-------------\n(csharp_ast_dir)\n`,
      );
      expect(result.llmContent).toContain(
        `-------------${path.join(dirPath, 'logic.ts')}-------------\n(ts_ast_dir)\n`,
      );
      expect(result.llmContent).toContain(
        `-------------${path.join(dirPath, 'ui.tsx')}-------------\n(tsx_ast_dir)\n`,
      );
      expect(result.llmContent).toContain(
        `-------------${path.join(dirPath, 'utils.js')}-------------\n(js_ast_dir)\n`,
      );
      expect(result.llmContent).toContain(
        // Added for Rust
        `-------------${path.join(dirPath, 'main.rs')}-------------\n(rust_ast_dir)\n`,
      );
      expect(result.llmContent).not.toContain('config.txt');
      expect(result.returnDisplay).toBe('Parsed 8 file(s).'); // Updated count
    });

    it('should only parse languages specified in the languages parameter for directory', async () => {
      const dirPath = path.join(tempRootDir, 'mixed_lang_project');
      const files = [
        'script.py',
        'Main.java',
        'another.py',
        'app.go',
        'Logic.cs',
        'index.ts',
        'view.tsx',
        'helper.js',
        'main.rs', // Added Rust file
      ];
      mockFs.stat.mockImplementation(async (p) => {
        if (p === dirPath)
          return { isFile: () => false, isDirectory: () => true } as Stats;
        return {
          isFile: () => true,
          isDirectory: () => false,
          size: 10,
        } as Stats;
      });
      mockFs.readdir.mockImplementation(
        vi.fn(async (p: PathLike): Promise<string[]> => {
          // dirPath and files are in scope for this specific test
          if (p === dirPath) {
            return files;
          }
          throw new Error(
            `fs.readdir mock: Unhandled path ${p} in test 'should only parse languages specified'`,
          );
        }) as unknown as typeof fs.readdir,
      );
      mockFs.readFile.mockResolvedValue('content');

      const params: CodeParserToolParams = {
        path: dirPath,
        languages: [
          'java',
          'go',
          'csharp',
          'typescript',
          'tsx',
          'javascript',
          'rust',
        ], // Added rust
      };
      const result = await tool.execute(params, abortSignal);

      expect(result.llmContent).toContain(path.join(dirPath, 'Main.java'));
      expect(result.llmContent).toContain(path.join(dirPath, 'app.go'));
      expect(result.llmContent).toContain(path.join(dirPath, 'Logic.cs'));
      expect(result.llmContent).toContain(path.join(dirPath, 'index.ts'));
      expect(result.llmContent).toContain(path.join(dirPath, 'view.tsx'));
      expect(result.llmContent).toContain(path.join(dirPath, 'helper.js'));
      expect(result.llmContent).toContain(path.join(dirPath, 'main.rs')); // Added for Rust
      expect(result.llmContent).not.toContain('script.py');
      expect(result.llmContent).not.toContain('another.py');
      expect(result.returnDisplay).toBe('Parsed 7 file(s).'); // Updated count
    });

    it('should return "Directory is empty" for an empty directory', async () => {
      const dirPath = path.join(tempRootDir, 'empty_dir');
      mockFs.stat.mockResolvedValue({
        isFile: () => false,
        isDirectory: () => true,
      } as Stats);
      mockFs.readdir.mockResolvedValue([]);

      const params: CodeParserToolParams = { path: dirPath };
      const result = await tool.execute(params, abortSignal);

      expect(result.llmContent).toBe(`Directory ${dirPath} is empty.`);
      expect(result.returnDisplay).toBe('Directory is empty.');
    });

    it('should handle error if fs.readdir fails', async () => {
      const dirPath = path.join(tempRootDir, 'unreadable_dir');
      mockFs.stat.mockResolvedValue({
        isFile: () => false,
        isDirectory: () => true,
      } as Stats);
      mockFs.readdir.mockRejectedValue(new Error('Permission denied'));

      const params: CodeParserToolParams = { path: dirPath };
      const result = await tool.execute(params, abortSignal);

      expect(result.llmContent).toMatch(
        /Error listing or processing directory/,
      );
      expect(result.returnDisplay).toMatch(
        /Error: Failed to process directory./,
      );
    });
  });

  describe('requiresConfirmation', () => {
    it('should return null', async () => {
      const params: CodeParserToolParams = { path: 'anypath' };
      expect(await tool.requiresConfirmation(params)).toBeNull();
    });
  });
});