stakpak-shared 0.3.87

Stakpak: Your DevOps AI Agent. Generate infrastructure code, debug Kubernetes, configure CI/CD, automate deployments, without giving an LLM the keys to production.
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
use crate::local_store::LocalStore;
use async_trait::async_trait;
use rand::Rng;
use std::fs;
use std::path::{Path, PathBuf};
use uuid::Uuid;
use walkdir::DirEntry;

/// Read .gitignore patterns from the specified base directory
pub fn read_gitignore_patterns(base_dir: &str) -> Vec<String> {
    let mut patterns = vec![".git".to_string()]; // Always ignore .git directory

    let gitignore_path = PathBuf::from(base_dir).join(".gitignore");
    if let Ok(content) = std::fs::read_to_string(&gitignore_path) {
        for line in content.lines() {
            let line = line.trim();
            // Skip empty lines and comments
            if !line.is_empty() && !line.starts_with('#') {
                patterns.push(line.to_string());
            }
        }
    }

    patterns
}

/// Check if a directory entry should be included based on gitignore patterns and file type support
pub fn should_include_entry(entry: &DirEntry, base_dir: &str, ignore_patterns: &[String]) -> bool {
    let path = entry.path();
    let is_file = entry.file_type().is_file();

    // Get relative path from base directory
    let base_path = PathBuf::from(base_dir);
    let relative_path = match path.strip_prefix(&base_path) {
        Ok(rel_path) => rel_path,
        Err(_) => path,
    };

    let path_str = relative_path.to_string_lossy();

    // Check if path matches any ignore pattern
    for pattern in ignore_patterns {
        if matches_gitignore_pattern(pattern, &path_str) {
            return false;
        }
    }

    // For files, also check if they are supported file types
    if is_file {
        is_supported_file(entry.path())
    } else {
        true // Allow directories to be traversed
    }
}

/// Check if a path matches a gitignore pattern
#[allow(clippy::string_slice)] // pattern[1..len-1] guarded by starts_with('*')/ends_with('*'), '*' is ASCII
pub fn matches_gitignore_pattern(pattern: &str, path: &str) -> bool {
    // Basic gitignore pattern matching
    let pattern = pattern.trim_end_matches('/'); // Remove trailing slash

    if pattern.contains('*') {
        if pattern == "*" {
            true
        } else if pattern.starts_with('*') && pattern.ends_with('*') {
            let middle = &pattern[1..pattern.len() - 1];
            path.contains(middle)
        } else if let Some(suffix) = pattern.strip_prefix('*') {
            path.ends_with(suffix)
        } else if let Some(prefix) = pattern.strip_suffix('*') {
            path.starts_with(prefix)
        } else {
            // Pattern contains * but not at start/end, do basic glob matching
            pattern_matches_glob(pattern, path)
        }
    } else {
        // Exact match or directory match
        path == pattern || path.starts_with(&format!("{}/", pattern))
    }
}

/// Simple glob pattern matching for basic cases
#[allow(clippy::string_slice)] // text_pos accumulated from starts_with/find on same string, always valid boundaries
pub fn pattern_matches_glob(pattern: &str, text: &str) -> bool {
    let parts: Vec<&str> = pattern.split('*').collect();
    if parts.len() == 1 {
        return text == pattern;
    }

    let mut text_pos = 0;
    for (i, part) in parts.iter().enumerate() {
        if i == 0 {
            // First part must match at the beginning
            if !text[text_pos..].starts_with(part) {
                return false;
            }
            text_pos += part.len();
        } else if i == parts.len() - 1 {
            // Last part must match at the end
            return text[text_pos..].ends_with(part);
        } else {
            // Middle parts must be found in order
            if let Some(pos) = text[text_pos..].find(part) {
                text_pos += pos + part.len();
            } else {
                return false;
            }
        }
    }
    true
}

/// Check if a directory entry represents a supported file type
pub fn is_supported_file(file_path: &Path) -> bool {
    match file_path.file_name().and_then(|name| name.to_str()) {
        Some(name) => {
            // Only allow supported files
            if file_path.is_file() {
                name.ends_with(".tf")
                    || name.ends_with(".tfvars")
                    || name.ends_with(".yaml")
                    || name.ends_with(".yml")
                    || name.to_lowercase().contains("dockerfile")
            } else {
                true // Allow directories to be traversed
            }
        }
        None => false,
    }
}

/// Generate a secure password with alphanumeric characters and optional symbols
pub fn generate_password(length: usize, no_symbols: bool) -> String {
    let mut rng = rand::rng();

    // Define character sets
    let lowercase = "abcdefghijklmnopqrstuvwxyz";
    let uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let digits = "0123456789";
    let symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";

    // Build the character set based on options
    let mut charset = String::new();
    charset.push_str(lowercase);
    charset.push_str(uppercase);
    charset.push_str(digits);

    if !no_symbols {
        charset.push_str(symbols);
    }

    let charset_chars: Vec<char> = charset.chars().collect();

    // Generate password ensuring at least one character from each required category
    let mut password = String::new();

    // Ensure at least one character from each category
    password.push(
        lowercase
            .chars()
            .nth(rng.random_range(0..lowercase.len()))
            .unwrap(),
    );
    password.push(
        uppercase
            .chars()
            .nth(rng.random_range(0..uppercase.len()))
            .unwrap(),
    );
    password.push(
        digits
            .chars()
            .nth(rng.random_range(0..digits.len()))
            .unwrap(),
    );

    if !no_symbols {
        password.push(
            symbols
                .chars()
                .nth(rng.random_range(0..symbols.len()))
                .unwrap(),
        );
    }

    // Fill the rest with random characters from the full charset
    let remaining_length = if length > password.len() {
        length - password.len()
    } else {
        0
    };

    for _ in 0..remaining_length {
        let random_char = charset_chars[rng.random_range(0..charset_chars.len())];
        password.push(random_char);
    }

    // Shuffle the password to randomize the order
    let mut password_chars: Vec<char> = password.chars().collect();
    for i in 0..password_chars.len() {
        let j = rng.random_range(0..password_chars.len());
        password_chars.swap(i, j);
    }

    // Take only the requested length
    password_chars.into_iter().take(length).collect()
}

/// Normalize an optional string by trimming leading/trailing whitespace.
///
/// Returns `None` when the input is `None` or the trimmed value is empty.
pub fn normalize_optional_string(value: Option<String>) -> Option<String> {
    value.and_then(|value| {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    })
}

/// Sanitize text output by removing control characters while preserving essential whitespace
pub fn sanitize_text_output(text: &str) -> String {
    text.chars()
        .filter(|&c| {
            // Drop replacement char
            if c == '\u{FFFD}' {
                return false;
            }
            // Allow essential whitespace even though they're "control"
            if matches!(c, '\n' | '\t' | '\r' | ' ') {
                return true;
            }
            // Keep everything else that's not a control character
            !c.is_control()
        })
        .collect()
}

/// Truncate a string by character count and append `...` when truncated.
///
/// Uses char iteration (not byte slicing) so it is UTF-8 safe.
pub fn truncate_chars_with_ellipsis(text: &str, max_chars: usize) -> String {
    if text.chars().count() <= max_chars {
        return text.to_string();
    }

    let mut truncated: String = text.chars().take(max_chars).collect();
    truncated.push_str("...");
    truncated
}

pub struct LargeOutputLimits<'a> {
    pub file_prefix: &'a str,
    pub max_lines: usize,
    pub max_bytes: usize,
    pub show_head: bool,
}

fn sanitize_artifact_file_prefix(file_prefix: &str) -> String {
    let sanitized = file_prefix
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
                c
            } else {
                '-'
            }
        })
        .collect::<String>()
        .trim_matches(|c| matches!(c, '-' | '_' | '.'))
        .to_string();

    if sanitized.is_empty() {
        "output".to_string()
    } else {
        sanitized
    }
}

fn write_output_artifact(file_prefix: &str, output: &str) -> Result<String, String> {
    let output_file = format!(
        "{}.{}.txt",
        sanitize_artifact_file_prefix(file_prefix),
        Uuid::new_v4().simple()
    );

    LocalStore::write_session_data(&output_file, output)
        .map_err(|e| format!("Failed to write session data: {}", e))
}

fn line_preview(
    output_lines: &[&str],
    output_file_path: &str,
    max_lines: usize,
    show_head: bool,
) -> String {
    let excerpt = if show_head {
        let head_lines: Vec<&str> = output_lines.iter().take(max_lines).copied().collect();
        head_lines.join("\n")
    } else {
        let mut tail_lines: Vec<&str> =
            output_lines.iter().rev().take(max_lines).copied().collect();
        tail_lines.reverse();
        tail_lines.join("\n")
    };

    let position = if show_head { "first" } else { "last" };
    format!(
        "Showing the {} {} / {} output lines. Full output saved to {}\n{}\n{}",
        position,
        max_lines,
        output_lines.len(),
        output_file_path,
        if show_head { "" } else { "...\n" },
        excerpt
    )
}

// start/end are adjusted to valid UTF-8 character boundaries before slicing.
#[allow(clippy::string_slice)]
fn byte_excerpt(output: &str, max_bytes: usize, show_head: bool) -> (&str, usize) {
    if show_head {
        let mut end = max_bytes.min(output.len());
        while end > 0 && !output.is_char_boundary(end) {
            end -= 1;
        }
        (&output[..end], end)
    } else {
        let mut start = output.len().saturating_sub(max_bytes);
        while start < output.len() && !output.is_char_boundary(start) {
            start += 1;
        }
        (&output[start..], output.len() - start)
    }
}

fn byte_preview(output: &str, output_file_path: &str, max_bytes: usize, show_head: bool) -> String {
    let (excerpt, excerpt_bytes) = byte_excerpt(output, max_bytes, show_head);
    let position = if show_head { "first" } else { "last" };

    format!(
        "Showing the {} {} / {} output bytes. Full output saved to {}\n{}\n{}",
        position,
        excerpt_bytes,
        output.len(),
        output_file_path,
        if show_head { "" } else { "...\n" },
        excerpt
    )
}

pub fn handle_large_output_with_limits(
    output: &str,
    limits: LargeOutputLimits<'_>,
) -> Result<String, String> {
    let output_lines = output.lines().collect::<Vec<_>>();
    if output_lines.len() >= limits.max_lines {
        let output_file_path = write_output_artifact(limits.file_prefix, output)?;
        Ok(line_preview(
            &output_lines,
            &output_file_path,
            limits.max_lines,
            limits.show_head,
        ))
    } else if output.len() > limits.max_bytes {
        let output_file_path = write_output_artifact(limits.file_prefix, output)?;
        Ok(byte_preview(
            output,
            &output_file_path,
            limits.max_bytes,
            limits.show_head,
        ))
    } else {
        Ok(output.to_string())
    }
}

/// Handle large output: if the output has >= `max_lines`, save the full content to session
/// storage and return a string showing only the first or last `max_lines` lines with a pointer
/// to the saved file. Returns `Ok(final_string)` or `Err(error_string)` on failure.
pub fn handle_large_output(
    output: &str,
    file_prefix: &str,
    max_lines: usize,
    show_head: bool,
) -> Result<String, String> {
    handle_large_output_with_limits(
        output,
        LargeOutputLimits {
            file_prefix,
            max_lines,
            max_bytes: usize::MAX,
            show_head,
        },
    )
}

#[cfg(test)]
mod password_tests {
    use super::*;

    #[test]
    fn test_generate_password_length() {
        let password = generate_password(10, false);
        assert_eq!(password.len(), 10);

        let password = generate_password(20, true);
        assert_eq!(password.len(), 20);
    }

    #[test]
    fn test_generate_password_no_symbols() {
        let password = generate_password(50, true);
        let symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";

        for symbol in symbols.chars() {
            assert!(
                !password.contains(symbol),
                "Password should not contain symbol: {}",
                symbol
            );
        }
    }

    #[test]
    fn test_generate_password_with_symbols() {
        let password = generate_password(50, false);
        let symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";

        // At least one symbol should be present (due to our algorithm)
        let has_symbol = password.chars().any(|c| symbols.contains(c));
        assert!(has_symbol, "Password should contain at least one symbol");
    }

    #[test]
    fn test_generate_password_contains_required_chars() {
        let password = generate_password(50, false);

        let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
        let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
        let has_digit = password.chars().any(|c| c.is_ascii_digit());

        assert!(has_lowercase, "Password should contain lowercase letters");
        assert!(has_uppercase, "Password should contain uppercase letters");
        assert!(has_digit, "Password should contain digits");
    }

    #[test]
    fn test_generate_password_uniqueness() {
        let password1 = generate_password(20, false);
        let password2 = generate_password(20, false);

        // Very unlikely to generate the same password twice
        assert_ne!(password1, password2);
    }
}

#[cfg(test)]
mod truncate_tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn normalize_optional_string_trims_and_drops_empty() {
        assert_eq!(
            normalize_optional_string(Some("  hello  ".to_string())),
            Some("hello".to_string())
        );
        assert_eq!(normalize_optional_string(Some("   ".to_string())), None);
        assert_eq!(normalize_optional_string(None), None);
    }

    #[test]
    fn truncate_chars_with_ellipsis_exact_boundary_keeps_value() {
        let value = "a".repeat(20);
        let truncated = truncate_chars_with_ellipsis(&value, 20);
        assert_eq!(truncated, value);
    }

    #[test]
    fn truncate_chars_with_ellipsis_appends_suffix_when_truncated() {
        let value = "é".repeat(10);
        let truncated = truncate_chars_with_ellipsis(&value, 5);
        assert_eq!(truncated, "ééééé...");
    }

    fn artifact_path_from_preview(preview: &str) -> &str {
        preview
            .lines()
            .next()
            .and_then(|line| line.split_once("Full output saved to "))
            .map(|(_, path)| path)
            .expect("preview should contain saved artifact path")
    }

    #[test]
    fn handle_large_output_line_trigger_artifacts_full_output() {
        let output = (1..=4)
            .map(|line| format!("line {line}"))
            .collect::<Vec<_>>()
            .join("\n");

        let preview = handle_large_output(&output, "line-test", 3, true)
            .expect("large output should be handled");

        assert!(preview.starts_with("Showing the first 3 / 4 output lines."));
        assert!(preview.contains("\n\nline 1\nline 2\nline 3"));
        assert!(!preview.contains("line 4"));

        let artifact_path = artifact_path_from_preview(&preview);
        let artifact = std::fs::read_to_string(artifact_path).expect("artifact should be readable");
        assert_eq!(artifact, output);
        std::fs::remove_file(artifact_path).expect("artifact should be removable");
    }

    #[test]
    fn handle_large_output_with_limits_byte_trigger_artifacts_full_output() {
        let output = "a".repeat(64);

        let preview = handle_large_output_with_limits(
            &output,
            LargeOutputLimits {
                file_prefix: "mcp tool/output",
                max_lines: 300,
                max_bytes: 32,
                show_head: true,
            },
        )
        .expect("large output should be handled");

        assert!(preview.starts_with("Showing the first 32 / 64 output bytes."));
        assert!(preview.contains("Full output saved to "));
        assert!(preview.contains(&"a".repeat(32)));
        assert!(!preview.contains(&"a".repeat(64)));

        let artifact_path = artifact_path_from_preview(&preview);
        let artifact = std::fs::read_to_string(artifact_path).expect("artifact should be readable");
        assert_eq!(artifact, output);

        let file_name = Path::new(artifact_path)
            .file_name()
            .and_then(|name| name.to_str())
            .expect("artifact should have a valid UTF-8 file name");
        assert!(file_name.starts_with("mcp-tool-output."));
        assert!(file_name.ends_with(".txt"));
        assert_eq!(
            file_name.len(),
            "mcp-tool-output.".len() + 32 + ".txt".len()
        );

        std::fs::remove_file(artifact_path).expect("artifact should be removable");
    }

    #[test]
    fn handle_large_output_with_limits_byte_preview_is_utf8_safe() {
        let output = format!("{}end", "é".repeat(20));

        let preview = handle_large_output_with_limits(
            &output,
            LargeOutputLimits {
                file_prefix: "utf8-test",
                max_lines: 300,
                max_bytes: 9,
                show_head: true,
            },
        )
        .expect("large output should be handled");

        assert!(preview.starts_with("Showing the first 8 / 43 output bytes."));
        assert!(preview.contains("\n\néééé"));
        assert!(!preview.contains("end"));

        let artifact_path = artifact_path_from_preview(&preview);
        let artifact = std::fs::read_to_string(artifact_path).expect("artifact should be readable");
        assert_eq!(artifact, output);
        std::fs::remove_file(artifact_path).expect("artifact should be removable");
    }

    #[test]
    fn handle_large_output_with_limits_small_output_passes_through() {
        let output = "small\noutput";

        let preview = handle_large_output_with_limits(
            output,
            LargeOutputLimits {
                file_prefix: "small-test",
                max_lines: 300,
                max_bytes: 1024,
                show_head: true,
            },
        )
        .expect("small output should pass through");

        assert_eq!(preview, output);
    }
}

/// Directory entry information for tree generation
#[derive(Debug, Clone)]
pub struct DirectoryEntry {
    pub name: String,
    pub path: String,
    pub is_directory: bool,
}

/// Trait for abstracting file system operations for tree generation
#[async_trait]
pub trait FileSystemProvider {
    type Error: std::fmt::Display;

    /// List directory contents
    async fn list_directory(&self, path: &str) -> Result<Vec<DirectoryEntry>, Self::Error>;
}

/// Generate a tree view of a directory structure using a generic file system provider
pub async fn generate_directory_tree<P: FileSystemProvider>(
    provider: &P,
    path: &str,
    prefix: &str,
    max_depth: usize,
    current_depth: usize,
) -> Result<String, P::Error> {
    let mut result = String::new();

    if current_depth >= max_depth || current_depth >= 10 {
        return Ok(result);
    }

    let entries = provider.list_directory(path).await?;
    let mut file_entries = Vec::new();
    let mut dir_entries = Vec::new();
    for entry in entries.iter() {
        if entry.is_directory {
            if entry.name == "."
                || entry.name == ".."
                || entry.name == ".git"
                || entry.name == "node_modules"
            {
                continue;
            }
            dir_entries.push(entry.clone());
        } else {
            file_entries.push(entry.clone());
        }
    }

    dir_entries.sort_by(|a, b| a.name.cmp(&b.name));
    file_entries.sort_by(|a, b| a.name.cmp(&b.name));

    const MAX_ITEMS: usize = 5;
    let total_items = dir_entries.len() + file_entries.len();
    let should_limit = current_depth > 0 && total_items > MAX_ITEMS;

    if should_limit {
        if dir_entries.len() > MAX_ITEMS {
            dir_entries.truncate(MAX_ITEMS);
            file_entries.clear();
        } else {
            let remaining_items = MAX_ITEMS - dir_entries.len();
            file_entries.truncate(remaining_items);
        }
    }

    let mut dir_headers = Vec::new();
    let mut dir_futures = Vec::new();
    for (i, entry) in dir_entries.iter().enumerate() {
        let is_last_dir = i == dir_entries.len() - 1;
        let is_last_overall = is_last_dir && file_entries.is_empty() && !should_limit;
        let current_prefix = if is_last_overall {
            "└── "
        } else {
            "├── "
        };
        let next_prefix = format!(
            "{}{}",
            prefix,
            if is_last_overall { "    " } else { "│   " }
        );

        let header = format!("{}{}{}/\n", prefix, current_prefix, entry.name);
        dir_headers.push(header);

        let entry_path = entry.path.clone();
        let next_prefix_clone = next_prefix.clone();
        let future = async move {
            generate_directory_tree(
                provider,
                &entry_path,
                &next_prefix_clone,
                max_depth,
                current_depth + 1,
            )
            .await
        };
        dir_futures.push(future);
    }
    if !dir_futures.is_empty() {
        let subtree_results = futures::future::join_all(dir_futures).await;

        for (i, header) in dir_headers.iter().enumerate() {
            result.push_str(header);
            if let Some(Ok(subtree)) = subtree_results.get(i) {
                result.push_str(subtree);
            }
        }
    }

    for (i, entry) in file_entries.iter().enumerate() {
        let is_last_file = i == file_entries.len() - 1;
        let is_last_overall = is_last_file && !should_limit;
        let current_prefix = if is_last_overall {
            "└── "
        } else {
            "├── "
        };
        result.push_str(&format!("{}{}{}\n", prefix, current_prefix, entry.name));
    }

    if should_limit {
        let remaining_count = total_items - MAX_ITEMS;
        result.push_str(&format!(
            "{}└── ... {} more item{}\n",
            prefix,
            remaining_count,
            if remaining_count == 1 { "" } else { "s" }
        ));
    }

    Ok(result)
}

/// Strip the MCP server prefix and any trailing "()" from a tool name.
/// Example: "stakpak__run_command" -> "run_command"
/// Example: "run_command" -> "run_command"
/// Example: "str_replace()" -> "str_replace"
pub fn strip_tool_name(name: &str) -> &str {
    let mut result = name;

    // Strip the MCP server prefix (e.g., "stakpak__")
    if let Some((_, suffix)) = result.split_once("__") {
        result = suffix;
    }

    // Strip trailing "()" if present
    if let Some(stripped) = result.strip_suffix("()") {
        result = stripped;
    }

    backward_compatibility_mapping(result)
}

/// Map legacy tool names to their current counterparts.
/// Currently handles mapping "read_rulebook" to "load_skill".
pub fn backward_compatibility_mapping(name: &str) -> &str {
    match name {
        "read_rulebook" | "read_rulebooks" => "load_skill",
        _ => name,
    }
}

/// Local file system provider implementation
pub struct LocalFileSystemProvider;

#[async_trait]
impl FileSystemProvider for LocalFileSystemProvider {
    type Error = std::io::Error;

    async fn list_directory(&self, path: &str) -> Result<Vec<DirectoryEntry>, Self::Error> {
        let entries = fs::read_dir(path)?;
        let mut result = Vec::new();

        for entry in entries {
            let entry = entry?;
            let file_name = entry.file_name().to_string_lossy().to_string();
            let file_path = entry.path().to_string_lossy().to_string();
            let is_directory = entry.file_type()?.is_dir();

            result.push(DirectoryEntry {
                name: file_name,
                path: file_path,
                is_directory,
            });
        }

        Ok(result)
    }
}

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

    #[test]
    fn test_matches_gitignore_pattern_exact() {
        assert!(matches_gitignore_pattern("node_modules", "node_modules"));
        assert!(matches_gitignore_pattern(
            "node_modules",
            "node_modules/package.json"
        ));
        assert!(!matches_gitignore_pattern(
            "node_modules",
            "src/node_modules"
        ));
    }

    #[test]
    fn test_matches_gitignore_pattern_wildcard_prefix() {
        assert!(matches_gitignore_pattern("*.log", "debug.log"));
        assert!(matches_gitignore_pattern("*.log", "error.log"));
        assert!(!matches_gitignore_pattern("*.log", "log.txt"));
    }

    #[test]
    fn test_matches_gitignore_pattern_wildcard_suffix() {
        assert!(matches_gitignore_pattern("temp*", "temp"));
        assert!(matches_gitignore_pattern("temp*", "temp.txt"));
        assert!(matches_gitignore_pattern("temp*", "temporary"));
        assert!(!matches_gitignore_pattern("temp*", "mytemp"));
    }

    #[test]
    fn test_matches_gitignore_pattern_wildcard_middle() {
        assert!(matches_gitignore_pattern("*temp*", "temp"));
        assert!(matches_gitignore_pattern("*temp*", "mytemp"));
        assert!(matches_gitignore_pattern("*temp*", "temporary"));
        assert!(matches_gitignore_pattern("*temp*", "mytemporary"));
        assert!(!matches_gitignore_pattern("*temp*", "example"));
    }

    #[test]
    fn test_pattern_matches_glob() {
        assert!(pattern_matches_glob("test*.txt", "test.txt"));
        assert!(pattern_matches_glob("test*.txt", "test123.txt"));
        assert!(pattern_matches_glob("*test*.txt", "mytest.txt"));
        assert!(pattern_matches_glob("*test*.txt", "mytestfile.txt"));
        assert!(!pattern_matches_glob("test*.txt", "test.log"));
        assert!(!pattern_matches_glob("*test*.txt", "example.txt"));
    }

    #[test]
    fn test_read_gitignore_patterns() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Create a .gitignore file
        let gitignore_content = r#"
# This is a comment
node_modules
*.log
dist/
.env

# Another comment
temp*
"#;

        let gitignore_path = temp_path.join(".gitignore");
        let mut file = fs::File::create(&gitignore_path)?;
        file.write_all(gitignore_content.as_bytes())?;

        let patterns = read_gitignore_patterns(temp_path.to_str().unwrap());

        // Should include .git by default
        assert!(patterns.contains(&".git".to_string()));
        assert!(patterns.contains(&"node_modules".to_string()));
        assert!(patterns.contains(&"*.log".to_string()));
        assert!(patterns.contains(&"dist/".to_string()));
        assert!(patterns.contains(&".env".to_string()));
        assert!(patterns.contains(&"temp*".to_string()));

        // Should not include comments or empty lines
        assert!(!patterns.iter().any(|p| p.starts_with('#')));
        assert!(!patterns.contains(&"".to_string()));

        Ok(())
    }

    #[test]
    fn test_read_gitignore_patterns_no_file() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        let patterns = read_gitignore_patterns(temp_path.to_str().unwrap());

        // Should only contain .git when no .gitignore exists
        assert_eq!(patterns, vec![".git".to_string()]);
    }

    #[test]
    fn test_strip_tool_name() {
        assert_eq!(strip_tool_name("stakpak__run_command"), "run_command");
        assert_eq!(strip_tool_name("run_command"), "run_command");
        assert_eq!(strip_tool_name("str_replace()"), "str_replace");
        assert_eq!(strip_tool_name("stakpak__read_rulebook"), "load_skill");
        assert_eq!(strip_tool_name("read_rulebook()"), "load_skill");
        assert_eq!(strip_tool_name("read_rulebooks"), "load_skill");
        // Additional edge cases
        assert_eq!(strip_tool_name("just_name"), "just_name");
        assert_eq!(strip_tool_name("prefix__name()"), "name");
        assert_eq!(strip_tool_name("nested__prefix__tool"), "prefix__tool");
        assert_eq!(strip_tool_name("empty_suffix()"), "empty_suffix");
    }

    #[test]
    fn test_backward_compatibility_mapping() {
        assert_eq!(
            backward_compatibility_mapping("read_rulebook"),
            "load_skill"
        );
        assert_eq!(
            backward_compatibility_mapping("read_rulebooks"),
            "load_skill"
        );
        assert_eq!(backward_compatibility_mapping("run_command"), "run_command");
    }

    #[test]
    fn test_gitignore_integration() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = TempDir::new()?;
        let temp_path = temp_dir.path();

        // Create a .gitignore file
        let gitignore_content = "node_modules\n*.log\ndist/\n";
        let gitignore_path = temp_path.join(".gitignore");
        let mut file = fs::File::create(&gitignore_path)?;
        file.write_all(gitignore_content.as_bytes())?;

        let patterns = read_gitignore_patterns(temp_path.to_str().unwrap());

        // Test various paths
        assert!(
            patterns
                .iter()
                .any(|p| matches_gitignore_pattern(p, "node_modules"))
        );
        assert!(
            patterns
                .iter()
                .any(|p| matches_gitignore_pattern(p, "node_modules/package.json"))
        );
        assert!(
            patterns
                .iter()
                .any(|p| matches_gitignore_pattern(p, "debug.log"))
        );
        assert!(
            patterns
                .iter()
                .any(|p| matches_gitignore_pattern(p, "dist/bundle.js"))
        );
        assert!(
            patterns
                .iter()
                .any(|p| matches_gitignore_pattern(p, ".git"))
        );

        // These should not match
        assert!(
            !patterns
                .iter()
                .any(|p| matches_gitignore_pattern(p, "src/main.js"))
        );
        assert!(
            !patterns
                .iter()
                .any(|p| matches_gitignore_pattern(p, "README.md"))
        );

        Ok(())
    }
}