mixtape-tools 0.4.0

Ready-to-use tool implementations for the mixtape agent framework
Documentation
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
use crate::filesystem::validate_path;
use crate::prelude::*;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use tokio::fs;

/// Input for listing directory contents
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListDirectoryInput {
    /// Path to the directory to list (relative to base path)
    pub path: PathBuf,

    /// Maximum recursion depth (default: 2)
    #[serde(default = "default_depth")]
    pub depth: usize,

    /// Maximum lines in output. If omitted, returns all entries (up to internal hard limit).
    /// Use this to control output size for large directories.
    #[serde(default)]
    pub max_lines: Option<usize>,
}

fn default_depth() -> usize {
    2
}

/// Hard limit on output lines to prevent runaway memory usage
const HARD_MAX_LINES: usize = 10_000;

/// Entry info collected during scan
#[derive(Debug)]
struct EntryInfo {
    name: String,
    is_dir: bool,
    size: Option<u64>,
    children: Vec<EntryInfo>,
    child_count: usize, // Total count including nested
}

/// Tool for listing directory contents
pub struct ListDirectoryTool {
    base_path: PathBuf,
}

impl Default for ListDirectoryTool {
    fn default() -> Self {
        Self::new()
    }
}

impl ListDirectoryTool {
    /// Creates a new tool using the current working directory as the base path.
    ///
    /// Equivalent to `Default::default()`.
    ///
    /// # Panics
    ///
    /// Panics if the current working directory cannot be determined.
    /// Use [`try_new`](Self::try_new) or [`with_base_path`](Self::with_base_path) instead.
    pub fn new() -> Self {
        Self {
            base_path: std::env::current_dir().expect("Failed to get current working directory"),
        }
    }

    /// Creates a new tool using the current working directory as the base path.
    ///
    /// Returns an error if the current working directory cannot be determined.
    pub fn try_new() -> std::io::Result<Self> {
        Ok(Self {
            base_path: std::env::current_dir()?,
        })
    }

    /// Creates a tool with a custom base directory.
    ///
    /// All file operations will be constrained to this directory.
    pub fn with_base_path(base_path: PathBuf) -> Self {
        Self { base_path }
    }

    /// Scan directory and collect entry info (phase 1)
    #[allow(clippy::only_used_in_recursion)]
    fn scan_directory<'a>(
        &'a self,
        path: PathBuf,
        current_depth: usize,
        max_depth: usize,
    ) -> Pin<Box<dyn Future<Output = std::result::Result<Vec<EntryInfo>, ToolError>> + Send + 'a>>
    {
        Box::pin(async move {
            let mut read_dir = fs::read_dir(&path)
                .await
                .map_err(|e| ToolError::from(format!("Failed to read directory: {}", e)))?;

            let mut dir_entries = Vec::new();
            while let Some(entry) = read_dir
                .next_entry()
                .await
                .map_err(|e| ToolError::from(format!("Failed to read directory entry: {}", e)))?
            {
                dir_entries.push(entry);
            }

            dir_entries.sort_by_key(|e| e.file_name());

            let mut entries = Vec::new();
            for entry in dir_entries {
                let file_name = entry.file_name();
                let file_name_str = file_name.to_string_lossy().to_string();

                if file_name_str == ".git" {
                    continue;
                }

                let metadata = entry
                    .metadata()
                    .await
                    .map_err(|e| ToolError::from(format!("Failed to read metadata: {}", e)))?;

                if metadata.is_dir() {
                    let (children, child_count) = if current_depth < max_depth {
                        let children = self
                            .scan_directory(entry.path(), current_depth + 1, max_depth)
                            .await?;
                        let count = children.iter().map(|c| 1 + c.child_count).sum();
                        (children, count)
                    } else {
                        // At max depth, count direct children
                        let mut count = 0;
                        if let Ok(mut rd) = fs::read_dir(entry.path()).await {
                            while let Ok(Some(_)) = rd.next_entry().await {
                                count += 1;
                            }
                        }
                        (vec![], count)
                    };

                    entries.push(EntryInfo {
                        name: file_name_str,
                        is_dir: true,
                        size: None,
                        children,
                        child_count,
                    });
                } else {
                    entries.push(EntryInfo {
                        name: file_name_str,
                        is_dir: false,
                        size: Some(metadata.len()),
                        children: vec![],
                        child_count: 0,
                    });
                }
            }

            Ok(entries)
        })
    }

    /// Format entries with fair budget allocation (phase 2)
    fn format_entries(entries: &[EntryInfo], prefix: &str, budget: usize) -> (Vec<String>, usize) {
        if budget == 0 || entries.is_empty() {
            return (vec![], 0);
        }

        let mut output = Vec::new();
        let mut used = 0;
        let remaining_budget = budget;

        // Calculate fair share per entry
        // Each entry needs at least 1 line, dirs with children need 2 (dir + "X more")
        let num_entries = entries.len();
        let budget_per_entry = (remaining_budget / num_entries).max(1);

        for (i, entry) in entries.iter().enumerate() {
            if used >= budget {
                let remaining = entries.len() - i;
                output.push(format!("{}[MORE] ... {} more entries", prefix, remaining));
                used += 1;
                break;
            }

            let entry_budget = if i == entries.len() - 1 {
                // Last entry gets remaining budget
                budget.saturating_sub(used)
            } else {
                budget_per_entry.min(budget.saturating_sub(used))
            };

            if entry.is_dir {
                output.push(format!("{}[DIR]  {}/", prefix, entry.name));
                used += 1;

                if entry_budget > 1 && !entry.children.is_empty() {
                    let child_prefix = format!("{}  ", prefix);
                    let child_budget = entry_budget - 1; // -1 for the dir line itself

                    let (child_output, child_used) =
                        Self::format_entries(&entry.children, &child_prefix, child_budget);
                    output.extend(child_output);
                    used += child_used;
                } else if !entry.children.is_empty() || entry.child_count > 0 {
                    // No budget for children, show count
                    let count = if entry.children.is_empty() {
                        entry.child_count
                    } else {
                        entry.children.len()
                    };
                    if count > 0 && used < budget {
                        output.push(format!("{}  [MORE] ... {} items", prefix, count));
                        used += 1;
                    }
                }
            } else {
                let size = entry.size.unwrap_or(0);
                let size_str = if size < 1024 {
                    format!("{} B", size)
                } else if size < 1024 * 1024 {
                    format!("{:.1} KB", size as f64 / 1024.0)
                } else {
                    format!("{:.1} MB", size as f64 / (1024.0 * 1024.0))
                };
                output.push(format!("{}[FILE] {} ({})", prefix, entry.name, size_str));
                used += 1;
            }
        }

        (output, used)
    }
}

impl Tool for ListDirectoryTool {
    type Input = ListDirectoryInput;

    fn name(&self) -> &str {
        "list_directory"
    }

    fn description(&self) -> &str {
        "List the contents of a directory recursively up to a specified depth. Shows files and subdirectories with sizes."
    }

    async fn execute(&self, input: Self::Input) -> std::result::Result<ToolResult, ToolError> {
        let path = validate_path(&self.base_path, &input.path)
            .map_err(|e| ToolError::from(e.to_string()))?;

        if !path.is_dir() {
            return Err(format!("{} is not a directory", input.path.display()).into());
        }

        // Validate max_lines doesn't exceed hard limit
        if let Some(max) = input.max_lines {
            if max > HARD_MAX_LINES {
                return Err(format!(
                    "max_lines ({}) exceeds maximum allowed value ({})",
                    max, HARD_MAX_LINES
                )
                .into());
            }
        }

        // Phase 1: Scan directory tree
        let entries = self.scan_directory(path, 0, input.depth).await?;

        // Phase 2: Format with fair budget allocation
        let budget = input.max_lines.unwrap_or(HARD_MAX_LINES);
        let (formatted, _used) = Self::format_entries(&entries, "", budget);

        let content = if formatted.is_empty() {
            format!("Directory {} is empty", input.path.display())
        } else {
            format!(
                "Contents of {} (depth={}):\n{}",
                input.path.display(),
                input.depth,
                formatted.join("\n")
            )
        };

        Ok(content.into())
    }

    fn format_output_plain(&self, result: &ToolResult) -> String {
        let output = result.as_text();
        let mut lines: Vec<&str> = output.lines().collect();
        if lines.is_empty() {
            return output.to_string();
        }

        let header = lines.remove(0);
        let mut out = String::new();
        out.push_str(header);
        out.push('\n');

        let entries: Vec<(usize, &str)> = lines
            .iter()
            .map(|line| {
                let depth = line.len() - line.trim_start().len();
                (depth / 2, line.trim())
            })
            .collect();

        for (i, (depth, content)) in entries.iter().enumerate() {
            let is_last_at_depth = entries
                .iter()
                .skip(i + 1)
                .find(|(d, _)| *d <= *depth)
                .map(|(d, _)| *d < *depth)
                .unwrap_or(true);

            let mut prefix = String::new();
            for d in 0..*depth {
                let has_more = entries.iter().skip(i + 1).any(|(dd, _)| *dd == d);
                prefix.push_str(if has_more { "│   " } else { "    " });
            }

            let connector = if is_last_at_depth {
                "└── "
            } else {
                "├── "
            };

            let formatted = if content.starts_with("[DIR]") {
                format!(
                    "{} {}",
                    connector,
                    content.trim_start_matches("[DIR]").trim()
                )
            } else if content.starts_with("[FILE]") {
                let rest = content.trim_start_matches("[FILE]").trim();
                if let Some(paren_idx) = rest.rfind(" (") {
                    format!(
                        "{} {} ({})",
                        connector,
                        &rest[..paren_idx],
                        &rest[paren_idx + 2..rest.len() - 1]
                    )
                } else {
                    format!("{} {}", connector, rest)
                }
            } else {
                format!("{} {}", connector, content)
            };

            out.push_str(&prefix);
            out.push_str(&formatted);
            out.push('\n');
        }
        out
    }

    fn format_output_ansi(&self, result: &ToolResult) -> String {
        let output = result.as_text();
        let mut lines: Vec<&str> = output.lines().collect();
        if lines.is_empty() {
            return output.to_string();
        }

        let header = lines.remove(0);
        let mut out = format!("\x1b[1m{}\x1b[0m\n", header);

        let entries: Vec<(usize, &str)> = lines
            .iter()
            .map(|line| {
                let depth = line.len() - line.trim_start().len();
                (depth / 2, line.trim())
            })
            .collect();

        for (i, (depth, content)) in entries.iter().enumerate() {
            let is_last_at_depth = entries
                .iter()
                .skip(i + 1)
                .find(|(d, _)| *d <= *depth)
                .map(|(d, _)| *d < *depth)
                .unwrap_or(true);

            let mut prefix = String::new();
            for d in 0..*depth {
                let has_more = entries.iter().skip(i + 1).any(|(dd, _)| *dd == d);
                prefix.push_str(if has_more {
                    "\x1b[2m│\x1b[0m   "
                } else {
                    "    "
                });
            }

            let connector = if is_last_at_depth {
                "\x1b[2m└──\x1b[0m "
            } else {
                "\x1b[2m├──\x1b[0m "
            };

            let formatted = if content.starts_with("[DIR]") {
                let name = content.trim_start_matches("[DIR]").trim();
                format!("{}\x1b[1;34m{}\x1b[0m", connector, name)
            } else if content.starts_with("[FILE]") {
                let rest = content.trim_start_matches("[FILE]").trim();
                if let Some(paren_idx) = rest.rfind(" (") {
                    let name = &rest[..paren_idx];
                    let size = &rest[paren_idx + 2..rest.len() - 1];
                    format!(
                        "{}{} \x1b[2m{}\x1b[0m",
                        connector,
                        colorize_filename(name),
                        size
                    )
                } else {
                    format!("{}{}", connector, colorize_filename(rest))
                }
            } else if content.starts_with("...") {
                format!("{}\x1b[2m{}\x1b[0m", connector, content)
            } else {
                format!("{}{}", connector, content)
            };

            out.push_str(&prefix);
            out.push_str(&formatted);
            out.push('\n');
        }
        out
    }

    fn format_output_markdown(&self, result: &ToolResult) -> String {
        format!("```\n{}\n```", self.format_output_plain(result))
    }
}

/// Colorize filename based on extension (eza-inspired)
fn colorize_filename(name: &str) -> String {
    let ext = name.rsplit('.').next().unwrap_or("");
    match ext.to_lowercase().as_str() {
        // Source code - green
        "rs" | "py" | "js" | "ts" | "go" | "c" | "cpp" | "h" | "java" | "rb" | "php" => {
            format!("\x1b[32m{}\x1b[0m", name)
        }
        // Config/data - yellow
        "json" | "yaml" | "yml" | "toml" | "xml" | "ini" | "cfg" | "conf" => {
            format!("\x1b[33m{}\x1b[0m", name)
        }
        // Docs - cyan
        "md" | "txt" | "rst" | "doc" | "pdf" => {
            format!("\x1b[36m{}\x1b[0m", name)
        }
        // Archives - red
        "zip" | "tar" | "gz" | "bz2" | "xz" | "rar" | "7z" => {
            format!("\x1b[31m{}\x1b[0m", name)
        }
        // Images - magenta
        "png" | "jpg" | "jpeg" | "gif" | "svg" | "ico" | "webp" => {
            format!("\x1b[35m{}\x1b[0m", name)
        }
        // Executables - bold green
        "sh" | "bash" | "zsh" | "exe" | "bin" => {
            format!("\x1b[1;32m{}\x1b[0m", name)
        }
        // Lock files - dim
        _ if name.ends_with(".lock") || name.ends_with("-lock.json") => {
            format!("\x1b[2m{}\x1b[0m", name)
        }
        _ => name.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // =========================================================================
    // Smoke test - basic functionality
    // =========================================================================

    #[tokio::test]
    async fn test_list_directory_basic() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("file1.txt"), "content").unwrap();
        fs::write(temp_dir.path().join("file2.txt"), "content").unwrap();
        fs::create_dir(temp_dir.path().join("subdir")).unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: None,
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        assert!(output.contains("file1.txt"));
        assert!(output.contains("file2.txt"));
        assert!(output.contains("subdir"));
    }

    // =========================================================================
    // Constructor and metadata tests
    // =========================================================================

    #[test]
    fn test_tool_metadata() {
        let tool: ListDirectoryTool = Default::default();
        assert_eq!(tool.name(), "list_directory");
        assert!(!tool.description().is_empty());

        let tool2 = ListDirectoryTool::new();
        assert_eq!(tool2.name(), "list_directory");
    }

    #[test]
    fn test_try_new() {
        let tool = ListDirectoryTool::try_new();
        assert!(tool.is_ok());
    }

    // =========================================================================
    // Core functionality tests
    // =========================================================================

    #[tokio::test]
    async fn test_empty_directory() {
        let temp_dir = TempDir::new().unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: None,
        };

        let result = tool.execute(input).await.unwrap();
        assert!(result.as_text().contains("empty"));
    }

    #[tokio::test]
    async fn test_skips_git_directory() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("file.txt"), "content").unwrap();
        fs::create_dir(temp_dir.path().join(".git")).unwrap();
        fs::write(temp_dir.path().join(".git/config"), "git config").unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 2,
            max_lines: None,
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        assert!(output.contains("file.txt"), "Should show regular files");
        assert!(!output.contains(".git"), "Should skip .git directory");
    }

    #[tokio::test]
    async fn test_respects_depth_limit() {
        let temp_dir = TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("a/b/c/d")).unwrap();
        fs::write(temp_dir.path().join("a/b/c/d/deep.txt"), "deep").unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 2,
            max_lines: None,
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        assert!(output.contains("a/"), "Should show first level");
        assert!(output.contains("b/"), "Should show second level");
        assert!(
            !output.contains("deep.txt"),
            "Should not show files beyond depth limit"
        );
    }

    #[tokio::test]
    async fn test_sorts_entries_alphabetically() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("zebra.txt"), "").unwrap();
        fs::write(temp_dir.path().join("alpha.txt"), "").unwrap();
        fs::write(temp_dir.path().join("beta.txt"), "").unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: None,
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        let alpha_pos = output.find("alpha.txt").unwrap();
        let beta_pos = output.find("beta.txt").unwrap();
        let zebra_pos = output.find("zebra.txt").unwrap();

        assert!(
            alpha_pos < beta_pos && beta_pos < zebra_pos,
            "Entries should be sorted alphabetically"
        );
    }

    // =========================================================================
    // Size formatting tests (consolidated)
    // =========================================================================

    #[tokio::test]
    async fn test_size_formatting() {
        let temp_dir = TempDir::new().unwrap();

        // Create files of different sizes
        fs::write(temp_dir.path().join("tiny.txt"), "hi").unwrap(); // 2 bytes
        fs::write(temp_dir.path().join("medium.txt"), "x".repeat(2048)).unwrap(); // 2 KB
        fs::write(
            temp_dir.path().join("large.txt"),
            "x".repeat(1024 * 1024 + 1),
        )
        .unwrap(); // 1+ MB

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: None,
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        assert!(output.contains("2 B"), "Should show bytes for tiny files");
        assert!(output.contains("KB"), "Should show KB for medium files");
        assert!(output.contains("MB"), "Should show MB for large files");
    }

    // =========================================================================
    // max_lines parameter tests
    // =========================================================================

    #[tokio::test]
    async fn test_max_lines_limits_output() {
        let temp_dir = TempDir::new().unwrap();
        for i in 0..50 {
            fs::write(temp_dir.path().join(format!("file{:03}.txt", i)), "x").unwrap();
        }

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: Some(10),
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        let file_count = output.matches("[FILE]").count();
        assert!(file_count <= 10, "Should respect max_lines limit");
        assert!(output.contains("[MORE]"), "Should indicate truncation");
    }

    #[tokio::test]
    async fn test_max_lines_none_returns_all() {
        let temp_dir = TempDir::new().unwrap();
        for i in 0..100 {
            fs::write(temp_dir.path().join(format!("file{:03}.txt", i)), "x").unwrap();
        }

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: None, // No limit
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        let file_count = output.matches("[FILE]").count();
        assert_eq!(
            file_count, 100,
            "Should show all files when max_lines is None"
        );
        assert!(!output.contains("[MORE]"), "Should not truncate");
    }

    #[tokio::test]
    async fn test_max_lines_boundary_cases() {
        let temp_dir = TempDir::new().unwrap();
        for i in 0..20 {
            fs::write(temp_dir.path().join(format!("file{:02}.txt", i)), "x").unwrap();
        }

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());

        // Exactly at limit - no truncation
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: Some(20),
        };
        let result = tool.execute(input).await.unwrap();
        assert!(
            !result.as_text().contains("[MORE]"),
            "Should not truncate at exact boundary"
        );

        // One under limit - truncates
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: Some(19),
        };
        let result = tool.execute(input).await.unwrap();
        assert!(
            result.as_text().contains("[MORE]"),
            "Should truncate when over limit"
        );
    }

    // =========================================================================
    // Fair budget allocation tests
    // =========================================================================

    #[tokio::test]
    async fn test_fair_allocation_across_directories() {
        let temp_dir = TempDir::new().unwrap();

        // Create 5 directories, each with many files
        for d in 0..5 {
            let dir_path = temp_dir.path().join(format!("dir{}", d));
            fs::create_dir(&dir_path).unwrap();
            for f in 0..50 {
                fs::write(dir_path.join(format!("file{:02}.txt", f)), "x").unwrap();
            }
        }

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 2,
            max_lines: Some(30),
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        // All 5 directories should be visible (fair allocation)
        let dir_count = output.matches("[DIR]").count();
        assert_eq!(dir_count, 5, "All directories should be visible");

        // Each directory should show some files (not first-dir-takes-all)
        let file_count = output.matches("[FILE]").count();
        assert!(
            file_count >= 5,
            "Should show files from multiple directories"
        );
    }

    #[tokio::test]
    async fn test_asymmetric_directories() {
        let temp_dir = TempDir::new().unwrap();

        // Big directory with 100 files
        let big = temp_dir.path().join("dir_big");
        fs::create_dir(&big).unwrap();
        for f in 0..100 {
            fs::write(big.join(format!("f{:03}.txt", f)), "x").unwrap();
        }

        // Small directory with 2 files
        let small = temp_dir.path().join("dir_small");
        fs::create_dir(&small).unwrap();
        fs::write(small.join("a.txt"), "x").unwrap();
        fs::write(small.join("b.txt"), "x").unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 2,
            max_lines: Some(20),
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        // Both directories should be visible
        assert!(output.contains("dir_big/"));
        assert!(output.contains("dir_small/"));

        // Small dir should show all its files
        assert!(output.contains("a.txt"));
        assert!(output.contains("b.txt"));
    }

    // =========================================================================
    // Error handling tests
    // =========================================================================

    #[tokio::test]
    async fn test_rejects_path_traversal() {
        let temp_dir = TempDir::new().unwrap();
        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());

        let input = ListDirectoryInput {
            path: PathBuf::from("../../../etc"),
            depth: 1,
            max_lines: None,
        };

        let result = tool.execute(input).await;
        assert!(result.is_err(), "Should reject path traversal");
    }

    #[tokio::test]
    async fn test_rejects_non_directory() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("file.txt"), "content").unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("file.txt"),
            depth: 1,
            max_lines: None,
        };

        let result = tool.execute(input).await;
        assert!(result.is_err(), "Should reject non-directory path");
        assert!(
            result.unwrap_err().to_string().contains("not a directory"),
            "Error should mention 'not a directory'"
        );
    }

    #[tokio::test]
    async fn test_rejects_max_lines_exceeding_hard_limit() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("file.txt"), "x").unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: Some(50_000), // Exceeds HARD_MAX_LINES (10,000)
        };

        let result = tool.execute(input).await;
        assert!(result.is_err(), "Should reject max_lines > HARD_MAX_LINES");

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("50000") && err_msg.contains("10000"),
            "Error should mention both requested and max values: {}",
            err_msg
        );
    }

    #[tokio::test]
    async fn test_zero_max_lines_returns_empty() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("file.txt"), "content").unwrap();

        let tool = ListDirectoryTool::with_base_path(temp_dir.path().to_path_buf());
        let input = ListDirectoryInput {
            path: PathBuf::from("."),
            depth: 1,
            max_lines: Some(0),
        };

        let result = tool.execute(input).await.unwrap();
        let output = result.as_text();

        // With zero budget, format_entries returns empty vec, so we get "empty" message
        assert!(
            output.contains("empty"),
            "Zero max_lines should report directory as empty"
        );
    }
}