Skip to main content

poly_mcp/modules/
filesystem.rs

1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::path::{Path, PathBuf};
4use std::fs;
5use std::collections::HashMap;
6use chrono::Local;
7use notify::{Watcher, RecursiveMode};
8use walkdir::WalkDir;
9use std::sync::{Arc, Mutex};
10use regex::Regex;
11
12pub struct FilesystemModule {
13    snapshots: Arc<Mutex<HashMap<String, Vec<SnapshotInfo>>>>,
14}
15
16#[derive(Clone)]
17struct SnapshotInfo {
18    #[allow(dead_code)]
19    timestamp: String,
20    path: PathBuf,
21    compressed: bool,
22}
23
24impl Default for FilesystemModule {
25    fn default() -> Self {
26        Self::new()
27    }
28}
29
30impl FilesystemModule {
31    pub fn new() -> Self {
32        Self {
33            snapshots: Arc::new(Mutex::new(HashMap::new())),
34        }
35    }
36
37    pub fn get_tools(&self) -> Vec<Value> {
38        vec![
39            json!({
40                "name": "fs_read",
41                "description": "Read file contents, optionally reading specific line ranges",
42                "inputSchema": {
43                    "type": "object",
44                    "properties": {
45                        "path": {
46                            "type": "string",
47                            "description": "Path to the file to read"
48                        },
49                        "lines": {
50                            "type": "array",
51                            "description": "Optional array of line ranges to read, e.g. [[1,10], [15,20]] reads lines 1-10 and 15-20",
52                            "items": {
53                                "type": "array",
54                                "minItems": 2,
55                                "maxItems": 2,
56                                "items": {
57                                    "type": "integer"
58                                }
59                            }
60                        }
61                    },
62                    "required": ["path"]
63                }
64            }),
65            json!({
66                "name": "fs_write",
67                "description": "Write content to a file, optionally writing to specific line ranges",
68                "inputSchema": {
69                    "type": "object",
70                    "properties": {
71                        "path": {
72                            "type": "string",
73                            "description": "Path to the file to write"
74                        },
75                        "content": {
76                            "type": "string",
77                            "description": "Content to write to the file"
78                        },
79                        "lines": {
80                            "type": "array",
81                            "description": "Optional array of line ranges to replace, e.g. [[1,10], [15,20]]. Content will be split and replace specified ranges.",
82                            "items": {
83                                "type": "array",
84                                "minItems": 2,
85                                "maxItems": 2,
86                                "items": {
87                                    "type": "integer"
88                                }
89                            }
90                        }
91                    },
92                    "required": ["path", "content"]
93                }
94            }),
95            json!({
96                "name": "fs_move",
97                "description": "Move files or directories",
98                "inputSchema": {
99                    "type": "object",
100                    "properties": {
101                        "source": {
102                            "type": "string",
103                            "description": "Source path"
104                        },
105                        "destination": {
106                            "type": "string",
107                            "description": "Destination path"
108                        }
109                    },
110                    "required": ["source", "destination"]
111                }
112            }),
113            json!({
114                "name": "fs_copy",
115                "description": "Copy files or directories",
116                "inputSchema": {
117                    "type": "object",
118                    "properties": {
119                        "source": {
120                            "type": "string",
121                            "description": "Source path"
122                        },
123                        "destination": {
124                            "type": "string",
125                            "description": "Destination path"
126                        }
127                    },
128                    "required": ["source", "destination"]
129                }
130            }),
131            json!({
132                "name": "fs_create",
133                "description": "Create files or directories",
134                "inputSchema": {
135                    "type": "object",
136                    "properties": {
137                        "path": {
138                            "type": "string",
139                            "description": "Path to create"
140                        },
141                        "type": {
142                            "type": "string",
143                            "enum": ["file", "dir"],
144                            "description": "Type to create (file or dir)"
145                        }
146                    },
147                    "required": ["path", "type"]
148                }
149            }),
150            json!({
151                "name": "fs_delete",
152                "description": "Delete files or directories",
153                "inputSchema": {
154                    "type": "object",
155                    "properties": {
156                        "path": {
157                            "type": "string",
158                            "description": "Path to delete"
159                        }
160                    },
161                    "required": ["path"]
162                }
163            }),
164            json!({
165                "name": "fs_move_desktop",
166                "description": "Move and organize items within the Desktop directory",
167                "inputSchema": {
168                    "type": "object",
169                    "properties": {
170                        "item": {
171                            "type": "string",
172                            "description": "Item name or path within Desktop"
173                        },
174                        "destination": {
175                            "type": "string",
176                            "description": "Destination subfolder within Desktop"
177                        }
178                    },
179                    "required": ["item", "destination"]
180                }
181            }),
182            json!({
183                "name": "fs_find",
184                "description": "Search for files and directories by name pattern",
185                "inputSchema": {
186                    "type": "object",
187                    "properties": {
188                        "path": {
189                            "type": "string",
190                            "description": "Root path to search from"
191                        },
192                        "pattern": {
193                            "type": "string",
194                            "description": "Search pattern (substring match, or glob with wildcards like *.rs)"
195                        },
196                        "type": {
197                            "type": "string",
198                            "enum": ["file", "dir", "all"],
199                            "description": "Type to search for (default: all)"
200                        },
201                        "max_depth": {
202                            "type": "number",
203                            "description": "Maximum directory depth to search (default: unlimited)"
204                        },
205                        "max_results": {
206                            "type": "number",
207                            "description": "Maximum number of results to return (default: 1000)"
208                        }
209                    },
210                    "required": ["path", "pattern"]
211                }
212            }),
213            json!({
214                "name": "fs_ld",
215                "description": "List directory contents with details (like ls -la)",
216                "inputSchema": {
217                    "type": "object",
218                    "properties": {
219                        "path": {
220                            "type": "string",
221                            "description": "Path to list"
222                        }
223                    },
224                    "required": ["path"]
225                }
226            }),
227            json!({
228                "name": "fs_stat",
229                "description": "Get file/directory metadata and statistics",
230                "inputSchema": {
231                    "type": "object",
232                    "properties": {
233                        "path": {
234                            "type": "string",
235                            "description": "Path to get stats for"
236                        }
237                    },
238                    "required": ["path"]
239                }
240            }),
241            json!({
242                "name": "fs_permissions",
243                "description": "Get or set file permissions",
244                "inputSchema": {
245                    "type": "object",
246                    "properties": {
247                        "path": {
248                            "type": "string",
249                            "description": "Path to file/directory"
250                        },
251                        "mode": {
252                            "type": "string",
253                            "description": "Permission mode (e.g., '755', '644') - omit to get current permissions"
254                        }
255                    },
256                    "required": ["path"]
257                }
258            }),
259            json!({
260                "name": "fs_watch",
261                "description": "Watch a file or directory for changes",
262                "inputSchema": {
263                    "type": "object",
264                    "properties": {
265                        "path": {
266                            "type": "string",
267                            "description": "Path to watch"
268                        },
269                        "duration": {
270                            "type": "number",
271                            "description": "Duration to watch in seconds (default: 60)"
272                        }
273                    },
274                    "required": ["path"]
275                }
276            }),
277            json!({
278                "name": "fs_snapshot",
279                "description": "Create lightweight timestamped backups with automatic management",
280                "inputSchema": {
281                    "type": "object",
282                    "properties": {
283                        "path": {
284                            "type": "string",
285                            "description": "Path to snapshot"
286                        },
287                        "max_snapshots": {
288                            "type": "number",
289                            "description": "Maximum number of snapshots to keep (default: 10)"
290                        }
291                    },
292                    "required": ["path"]
293                }
294            }),
295            json!({
296                "name": "fs_tree",
297                "description": "Display a visual directory tree structure. Much faster than recursive fs_find + fs_ld for understanding project layout.",
298                "inputSchema": {
299                    "type": "object",
300                    "properties": {
301                        "path": {
302                            "type": "string",
303                            "description": "Root directory path"
304                        },
305                        "max_depth": {
306                            "type": "number",
307                            "description": "Maximum depth to display (default: 4)"
308                        },
309                        "show_hidden": {
310                            "type": "boolean",
311                            "description": "Show hidden files/directories (default: false)"
312                        },
313                        "show_size": {
314                            "type": "boolean",
315                            "description": "Show file sizes (default: false)"
316                        },
317                        "dirs_only": {
318                            "type": "boolean",
319                            "description": "Only show directories (default: false)"
320                        },
321                        "pattern": {
322                            "type": "string",
323                            "description": "Only show entries matching this pattern (substring match)"
324                        }
325                    },
326                    "required": ["path"]
327                }
328            }),
329            json!({
330                "name": "fs_grep",
331                "description": "Search file contents by pattern across a directory. Returns matching lines with file paths and line numbers.",
332                "inputSchema": {
333                    "type": "object",
334                    "properties": {
335                        "path": {
336                            "type": "string",
337                            "description": "File or directory to search in"
338                        },
339                        "pattern": {
340                            "type": "string",
341                            "description": "Search pattern (regex supported)"
342                        },
343                        "case_insensitive": {
344                            "type": "boolean",
345                            "description": "Case-insensitive search (default: false)"
346                        },
347                        "max_results": {
348                            "type": "number",
349                            "description": "Maximum number of matches to return (default: 200)"
350                        },
351                        "context_lines": {
352                            "type": "number",
353                            "description": "Number of context lines before/after each match (default: 0)"
354                        },
355                        "file_pattern": {
356                            "type": "string",
357                            "description": "Only search files matching this pattern (e.g. '*.rs', '*.py')"
358                        }
359                    },
360                    "required": ["path", "pattern"]
361                }
362            }),
363            json!({
364                "name": "fs_tail",
365                "description": "Read the last N lines of a file. Essential for reading log files and build output.",
366                "inputSchema": {
367                    "type": "object",
368                    "properties": {
369                        "path": {
370                            "type": "string",
371                            "description": "Path to the file"
372                        },
373                        "lines": {
374                            "type": "number",
375                            "description": "Number of lines from the end (default: 20)"
376                        }
377                    },
378                    "required": ["path"]
379                }
380            }),
381            json!({
382                "name": "fs_replace",
383                "description": "Find and replace text across one or multiple files. Supports regex patterns and directory-wide bulk replacement.",
384                "inputSchema": {
385                    "type": "object",
386                    "properties": {
387                        "path": {
388                            "type": "string",
389                            "description": "File or directory to perform replacements in"
390                        },
391                        "find": {
392                            "type": "string",
393                            "description": "Text or regex pattern to find"
394                        },
395                        "replace": {
396                            "type": "string",
397                            "description": "Replacement text (supports $1 capture groups with regex)"
398                        },
399                        "regex": {
400                            "type": "boolean",
401                            "description": "Treat find as regex pattern (default: false)"
402                        },
403                        "file_pattern": {
404                            "type": "string",
405                            "description": "Only process files matching this pattern (e.g. '*.rs') — required for directories"
406                        },
407                        "dry_run": {
408                            "type": "boolean",
409                            "description": "Preview changes without writing (default: false)"
410                        }
411                    },
412                    "required": ["path", "find", "replace"]
413                }
414            }),
415        ]
416    }
417
418    pub async fn read(&self, args: Value) -> Result<Value> {
419        let path = args["path"].as_str().context("Missing 'path' parameter")?;
420        let full_content = fs::read_to_string(path)
421            .with_context(|| format!("Failed to read file: {}", path))?;
422
423        if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
424            let all_lines: Vec<&str> = full_content.lines().collect();
425            let total_lines = all_lines.len();
426            let mut selected_lines = Vec::new();
427
428            for range in lines_array {
429                if let Some(range_arr) = range.as_array() {
430                    if range_arr.len() == 2 {
431                        let from = range_arr[0].as_i64().unwrap_or(1) as usize;
432                        let to = range_arr[1].as_i64().unwrap_or(all_lines.len() as i64) as usize;
433                        let from_idx = from.saturating_sub(1);
434                        let to_idx = to.min(all_lines.len());
435                        if from_idx < all_lines.len() && from_idx < to_idx {
436                            selected_lines.extend_from_slice(&all_lines[from_idx..to_idx]);
437                        }
438                    }
439                }
440            }
441
442            let content = selected_lines.join("\n");
443            Ok(json!({
444                "path": path,
445                "content": content,
446                "size": content.len(),
447                "total_lines": total_lines
448            }))
449        } else {
450            let total_lines = bytecount_lines(&full_content);
451            let size = full_content.len();
452            Ok(json!({
453                "path": path,
454                "content": full_content,
455                "size": size,
456                "total_lines": total_lines
457            }))
458        }
459    }
460
461    pub async fn write(&self, args: Value) -> Result<Value> {
462        let path = args["path"].as_str().context("Missing 'path' parameter")?;
463        let content = args["content"].as_str().context("Missing 'content' parameter")?;
464
465        // Check if lines parameter is provided
466        let final_content = if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
467            // Read existing file or create empty if not exists
468            let existing_content = fs::read_to_string(path).unwrap_or_default();
469            let mut all_lines: Vec<String> = existing_content.lines().map(|s| s.to_string()).collect();
470            let new_lines: Vec<&str> = content.lines().collect();
471            let mut new_line_idx = 0;
472
473            for range in lines_array {
474                if let Some(range_arr) = range.as_array() {
475                    if range_arr.len() == 2 {
476                        let from = range_arr[0].as_i64().unwrap_or(1) as usize;
477                        let to = range_arr[1].as_i64().unwrap_or(all_lines.len() as i64) as usize;
478
479                        // Convert from 1-indexed to 0-indexed
480                        let from_idx = from.saturating_sub(1);
481                        let to_idx = to.min(all_lines.len());
482
483                        // Calculate how many lines to replace
484                        let range_size = to_idx.saturating_sub(from_idx);
485
486                        // Extend file if needed
487                        while all_lines.len() < to_idx {
488                            all_lines.push(String::new());
489                        }
490
491                        // Replace lines in this range with corresponding new lines
492                        for i in 0..range_size {
493                            if new_line_idx < new_lines.len() {
494                                all_lines[from_idx + i] = new_lines[new_line_idx].to_string();
495                                new_line_idx += 1;
496                            }
497                        }
498                    }
499                }
500            }
501
502            all_lines.join("\n") + "\n"
503        } else {
504            content.to_string()
505        };
506
507        fs::write(path, &final_content)
508            .with_context(|| format!("Failed to write file: {}", path))?;
509
510        Ok(json!({
511            "success": true,
512            "path": path,
513            "bytes_written": final_content.len()
514        }))
515    }
516
517    pub async fn move_file(&self, args: Value) -> Result<Value> {
518        let source = args["source"].as_str().context("Missing 'source' parameter")?;
519        let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;
520
521        fs::rename(source, destination)
522            .with_context(|| format!("Failed to move from {} to {}", source, destination))?;
523
524        Ok(json!({
525            "success": true,
526            "source": source,
527            "destination": destination
528        }))
529    }
530
531    pub async fn copy(&self, args: Value) -> Result<Value> {
532        let source = args["source"].as_str().context("Missing 'source' parameter")?;
533        let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;
534
535        let source_path = Path::new(source);
536
537        if source_path.is_file() {
538            fs::copy(source, destination)
539                .with_context(|| format!("Failed to copy file from {} to {}", source, destination))?;
540        } else if source_path.is_dir() {
541            copy_dir_all(source, destination)
542                .with_context(|| format!("Failed to copy directory from {} to {}", source, destination))?;
543        } else {
544            anyhow::bail!("Source path does not exist: {}", source);
545        }
546
547        Ok(json!({
548            "success": true,
549            "source": source,
550            "destination": destination
551        }))
552    }
553
554    pub async fn create(&self, args: Value) -> Result<Value> {
555        let path = args["path"].as_str().context("Missing 'path' parameter")?;
556        let type_str = args["type"].as_str().context("Missing 'type' parameter")?;
557
558        match type_str {
559            "file" => {
560                fs::File::create(path)
561                    .with_context(|| format!("Failed to create file: {}", path))?;
562            }
563            "dir" => {
564                fs::create_dir_all(path)
565                    .with_context(|| format!("Failed to create directory: {}", path))?;
566            }
567            _ => anyhow::bail!("Invalid type: {}. Must be 'file' or 'dir'", type_str),
568        }
569
570        Ok(json!({
571            "success": true,
572            "path": path,
573            "type": type_str
574        }))
575    }
576
577    pub async fn delete(&self, args: Value) -> Result<Value> {
578        let path = args["path"].as_str().context("Missing 'path' parameter")?;
579        let path_obj = Path::new(path);
580
581        if path_obj.is_file() {
582            fs::remove_file(path)
583                .with_context(|| format!("Failed to delete file: {}", path))?;
584        } else if path_obj.is_dir() {
585            fs::remove_dir_all(path)
586                .with_context(|| format!("Failed to delete directory: {}", path))?;
587        } else {
588            anyhow::bail!("Path does not exist: {}", path);
589        }
590
591        Ok(json!({
592            "success": true,
593            "path": path
594        }))
595    }
596
597    pub async fn move_desktop(&self, args: Value) -> Result<Value> {
598        let item = args["item"].as_str().context("Missing 'item' parameter")?;
599        let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;
600
601        // Get Desktop path
602        let desktop = dirs::desktop_dir()
603            .context("Could not find Desktop directory")?;
604
605        let source_path = desktop.join(item);
606        let dest_path = desktop.join(destination).join(item);
607
608        // Create destination directory if it doesn't exist
609        if let Some(parent) = dest_path.parent() {
610            fs::create_dir_all(parent)?;
611        }
612
613        fs::rename(&source_path, &dest_path)
614            .with_context(|| format!("Failed to move {} to {}", source_path.display(), dest_path.display()))?;
615
616        Ok(json!({
617            "success": true,
618            "item": item,
619            "from": source_path,
620            "to": dest_path
621        }))
622    }
623
624    pub async fn find(&self, args: Value) -> Result<Value> {
625        let root_path = args["path"].as_str().context("Missing 'path' parameter")?;
626        let pattern = args["pattern"].as_str().context("Missing 'pattern' parameter")?;
627        let search_type = args["type"].as_str().unwrap_or("all");
628        let max_results = args["max_results"].as_u64().unwrap_or(1000) as usize;
629
630        let mut walker = WalkDir::new(root_path);
631        if let Some(depth) = args["max_depth"].as_u64() {
632            walker = walker.max_depth(depth as usize);
633        }
634
635        // Determine if pattern is a glob (contains * or ?)
636        let is_glob = pattern.contains('*') || pattern.contains('?');
637
638        let mut results = Vec::new();
639
640        for entry in walker.into_iter().filter_map(|e| e.ok()) {
641            if results.len() >= max_results {
642                break;
643            }
644
645            let path = entry.path();
646            let file_name = entry.file_name().to_string_lossy();
647
648            let matches = if is_glob {
649                glob_match(pattern, &file_name)
650            } else {
651                file_name.contains(pattern) || path.to_string_lossy().contains(pattern)
652            };
653
654            if !matches {
655                continue;
656            }
657
658            // Type filtering
659            match search_type {
660                "file" if !path.is_file() => continue,
661                "dir" if !path.is_dir() => continue,
662                _ => {}
663            }
664
665            let size = path.metadata().map(|m| m.len()).unwrap_or(0);
666
667            results.push(json!({
668                "path": path.to_string_lossy(),
669                "name": file_name,
670                "type": if path.is_file() { "file" } else { "dir" },
671                "size": size
672            }));
673        }
674
675        let truncated = results.len() >= max_results;
676
677        Ok(json!({
678            "results": results,
679            "count": results.len(),
680            "truncated": truncated
681        }))
682    }
683
684    pub async fn ld(&self, args: Value) -> Result<Value> {
685        let path = args["path"].as_str().context("Missing 'path' parameter")?;
686        let path_obj = Path::new(path);
687
688        if !path_obj.exists() {
689            anyhow::bail!("Path does not exist: {}", path);
690        }
691
692        let mut entries = Vec::new();
693
694        for entry in fs::read_dir(path)? {
695            let entry = entry?;
696            let metadata = entry.metadata()?;
697            let file_name = entry.file_name().to_string_lossy().to_string();
698
699            #[cfg(unix)]
700            use std::os::unix::fs::PermissionsExt;
701
702            #[cfg(unix)]
703            let permissions = format!("{:o}", metadata.permissions().mode() & 0o777);
704
705            #[cfg(not(unix))]
706            let permissions = if metadata.permissions().readonly() {
707                "r--".to_string()
708            } else {
709                "rw-".to_string()
710            };
711
712            entries.push(json!({
713                "name": file_name,
714                "type": if metadata.is_file() { "file" } else if metadata.is_dir() { "dir" } else { "other" },
715                "size": metadata.len(),
716                "permissions": permissions,
717                "modified": metadata.modified().ok().and_then(|t| {
718                    t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
719                })
720            }));
721        }
722
723        Ok(json!({
724            "path": path,
725            "entries": entries,
726            "count": entries.len()
727        }))
728    }
729
730    pub async fn stat(&self, args: Value) -> Result<Value> {
731        let path = args["path"].as_str().context("Missing 'path' parameter")?;
732        let metadata = fs::metadata(path)
733            .with_context(|| format!("Failed to get metadata for: {}", path))?;
734
735        #[cfg(unix)]
736        use std::os::unix::fs::PermissionsExt;
737
738        #[cfg(unix)]
739        let permissions = format!("{:o}", metadata.permissions().mode() & 0o777);
740
741        #[cfg(not(unix))]
742        let permissions = if metadata.permissions().readonly() {
743            "readonly".to_string()
744        } else {
745            "read-write".to_string()
746        };
747
748        Ok(json!({
749            "path": path,
750            "type": if metadata.is_file() { "file" } else if metadata.is_dir() { "dir" } else { "other" },
751            "size": metadata.len(),
752            "permissions": permissions,
753            "readonly": metadata.permissions().readonly(),
754            "created": metadata.created().ok().and_then(|t| {
755                t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
756            }),
757            "modified": metadata.modified().ok().and_then(|t| {
758                t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
759            }),
760            "accessed": metadata.accessed().ok().and_then(|t| {
761                t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
762            })
763        }))
764    }
765
766    pub async fn permissions(&self, args: Value) -> Result<Value> {
767        let path = args["path"].as_str().context("Missing 'path' parameter")?;
768
769        if let Some(mode_str) = args["mode"].as_str() {
770            // Set permissions
771            #[cfg(unix)]
772            {
773                use std::os::unix::fs::PermissionsExt;
774                let mode = u32::from_str_radix(mode_str, 8)
775                    .with_context(|| format!("Invalid permission mode: {}", mode_str))?;
776                let permissions = std::fs::Permissions::from_mode(mode);
777                fs::set_permissions(path, permissions)
778                    .with_context(|| format!("Failed to set permissions for: {}", path))?;
779
780                Ok(json!({
781                    "success": true,
782                    "path": path,
783                    "mode": mode_str
784                }))
785            }
786
787            #[cfg(not(unix))]
788            {
789                anyhow::bail!("Setting permissions is only supported on Unix systems");
790            }
791        } else {
792            // Get permissions
793            let metadata = fs::metadata(path)?;
794
795            #[cfg(unix)]
796            use std::os::unix::fs::PermissionsExt;
797
798            #[cfg(unix)]
799            let mode = format!("{:o}", metadata.permissions().mode() & 0o777);
800
801            #[cfg(not(unix))]
802            let mode = if metadata.permissions().readonly() {
803                "readonly"
804            } else {
805                "read-write"
806            };
807
808            Ok(json!({
809                "path": path,
810                "mode": mode,
811                "readonly": metadata.permissions().readonly()
812            }))
813        }
814    }
815
816    pub async fn watch(&self, args: Value) -> Result<Value> {
817        let path = args["path"].as_str().context("Missing 'path' parameter")?;
818        let duration = args["duration"].as_u64().unwrap_or(60);
819        let path_owned = path.to_string();
820
821        let events = tokio::task::spawn_blocking(move || -> Result<Vec<Value>> {
822            let (tx, rx) = std::sync::mpsc::channel();
823            let mut watcher = notify::recommended_watcher(tx)?;
824            watcher.watch(Path::new(&path_owned), RecursiveMode::Recursive)?;
825
826            let mut events = Vec::new();
827            let start = std::time::Instant::now();
828
829            while start.elapsed().as_secs() < duration {
830                if let Ok(Ok(event)) = rx.recv_timeout(std::time::Duration::from_secs(1)) {
831                    events.push(json!({
832                        "kind": format!("{:?}", event.kind),
833                        "paths": event.paths.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>()
834                    }));
835                }
836            }
837            Ok(events)
838        }).await??;
839
840        Ok(json!({
841            "path": path,
842            "duration": duration,
843            "events": events,
844            "event_count": events.len()
845        }))
846    }
847
848    pub async fn snapshot(&self, args: Value) -> Result<Value> {
849        let path = args["path"].as_str().context("Missing 'path' parameter")?;
850        let max_snapshots = args["max_snapshots"].as_u64().unwrap_or(10) as usize;
851
852        let path_obj = Path::new(path);
853        if !path_obj.exists() {
854            anyhow::bail!("Path does not exist: {}", path);
855        }
856
857        // Create snapshot directory
858        let snapshot_dir = path_obj.parent()
859            .unwrap_or_else(|| Path::new("."))
860            .join(".snapshots")
861            .join(path_obj.file_name().unwrap_or(path_obj.as_os_str()));
862
863        fs::create_dir_all(&snapshot_dir)?;
864
865        // Create timestamp
866        let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string();
867        let snapshot_name = format!("snapshot_{}", timestamp);
868        let snapshot_path = snapshot_dir.join(&snapshot_name);
869
870        // Copy the file/directory
871        if path_obj.is_file() {
872            fs::copy(path, &snapshot_path)?;
873        } else {
874            copy_dir_all(path, &snapshot_path)?;
875        }
876
877        // Store snapshot info
878        let mut snapshots = self.snapshots.lock().unwrap();
879        let key = path.to_string();
880        let snapshot_list = snapshots.entry(key.clone()).or_default();
881
882        snapshot_list.push(SnapshotInfo {
883            timestamp: timestamp.clone(),
884            path: snapshot_path.clone(),
885            compressed: false,
886        });
887
888        // Manage snapshots (compress old ones, delete oldest)
889        if snapshot_list.len() > max_snapshots {
890            // Compress older snapshots
891            for snapshot in snapshot_list.iter_mut().rev().skip(3) {
892                if !snapshot.compressed {
893                    // TODO: Implement compression
894                    snapshot.compressed = true;
895                }
896            }
897
898            // Remove oldest snapshots
899            while snapshot_list.len() > max_snapshots {
900                if let Some(oldest) = snapshot_list.first() {
901                    if oldest.path.exists() {
902                        if oldest.path.is_file() {
903                            fs::remove_file(&oldest.path)?;
904                        } else {
905                            fs::remove_dir_all(&oldest.path)?;
906                        }
907                    }
908                }
909                snapshot_list.remove(0);
910            }
911        }
912
913        Ok(json!({
914            "success": true,
915            "path": path,
916            "snapshot": snapshot_path,
917            "timestamp": timestamp,
918            "total_snapshots": snapshot_list.len(),
919            "max_snapshots": max_snapshots
920        }))
921    }
922
923    pub async fn tree(&self, args: Value) -> Result<Value> {
924        let path = args["path"].as_str().context("Missing 'path' parameter")?;
925        let max_depth = args["max_depth"].as_u64().unwrap_or(4) as usize;
926        let show_hidden = args["show_hidden"].as_bool().unwrap_or(false);
927        let show_size = args["show_size"].as_bool().unwrap_or(false);
928        let dirs_only = args["dirs_only"].as_bool().unwrap_or(false);
929        let pattern = args["pattern"].as_str();
930
931        let root = Path::new(path);
932        if !root.exists() {
933            anyhow::bail!("Path does not exist: {}", path);
934        }
935
936        let mut output = String::new();
937        let mut file_count = 0usize;
938        let mut dir_count = 0usize;
939
940        output.push_str(&format!("{}\n", root.display()));
941        build_tree(root, "", max_depth, 0, show_hidden, show_size, dirs_only, pattern, &mut output, &mut file_count, &mut dir_count)?;
942
943        Ok(json!({
944            "tree": output,
945            "path": path,
946            "directories": dir_count,
947            "files": file_count,
948            "max_depth": max_depth
949        }))
950    }
951
952    pub async fn grep(&self, args: Value) -> Result<Value> {
953        let path = args["path"].as_str().context("Missing 'path' parameter")?;
954        let pattern = args["pattern"].as_str().context("Missing 'pattern' parameter")?;
955        let case_insensitive = args["case_insensitive"].as_bool().unwrap_or(false);
956        let max_results = args["max_results"].as_u64().unwrap_or(200) as usize;
957        let context_lines = args["context_lines"].as_u64().unwrap_or(0) as usize;
958        let file_pattern = args["file_pattern"].as_str();
959
960        let mut regex_pattern = String::new();
961        if case_insensitive {
962            regex_pattern.push_str("(?i)");
963        }
964        regex_pattern.push_str(pattern);
965
966        let re = Regex::new(&regex_pattern)
967            .with_context(|| format!("Invalid regex pattern: {}", pattern))?;
968
969        let root = Path::new(path);
970        let mut matches = Vec::new();
971        let mut files_searched = 0usize;
972
973        if root.is_file() {
974            files_searched = 1;
975            search_file(root, &re, max_results, context_lines, &mut matches);
976        } else {
977            for entry in WalkDir::new(root).into_iter().filter_map(|e| e.ok()) {
978                if matches.len() >= max_results {
979                    break;
980                }
981                if !entry.path().is_file() {
982                    continue;
983                }
984                if let Some(fp) = file_pattern {
985                    let name = entry.file_name().to_string_lossy();
986                    if !glob_match(fp, &name) {
987                        continue;
988                    }
989                }
990                files_searched += 1;
991                search_file(entry.path(), &re, max_results, context_lines, &mut matches);
992            }
993        }
994
995        let truncated = matches.len() >= max_results;
996
997        Ok(json!({
998            "matches": matches,
999            "count": matches.len(),
1000            "files_searched": files_searched,
1001            "pattern": pattern,
1002            "truncated": truncated
1003        }))
1004    }
1005
1006    pub async fn tail(&self, args: Value) -> Result<Value> {
1007        let path = args["path"].as_str().context("Missing 'path' parameter")?;
1008        let n = args["lines"].as_u64().unwrap_or(20) as usize;
1009
1010        let content = fs::read_to_string(path)
1011            .with_context(|| format!("Failed to read file: {}", path))?;
1012
1013        // Count total and find the start of the last N lines in a single pass
1014        let mut total = 0usize;
1015        let mut newline_positions = Vec::new(); // store byte offsets of newlines
1016        for (i, b) in content.as_bytes().iter().enumerate() {
1017            if *b == b'\n' {
1018                newline_positions.push(i);
1019                total += 1;
1020            }
1021        }
1022        // Account for last line without trailing newline
1023        if !content.is_empty() && !content.ends_with('\n') {
1024            total += 1;
1025        }
1026
1027        let start_line = total.saturating_sub(n);
1028        let byte_start = if start_line == 0 {
1029            0
1030        } else if start_line <= newline_positions.len() {
1031            newline_positions[start_line - 1] + 1
1032        } else {
1033            content.len()
1034        };
1035
1036        let tail_content = &content[byte_start..];
1037        let lines_returned = total - start_line;
1038
1039        Ok(json!({
1040            "path": path,
1041            "content": tail_content.trim_end_matches('\n'),
1042            "lines_returned": lines_returned,
1043            "total_lines": total,
1044            "from_line": start_line + 1
1045        }))
1046    }
1047
1048    pub async fn replace(&self, args: Value) -> Result<Value> {
1049        let path = args["path"].as_str().context("Missing 'path' parameter")?;
1050        let find = args["find"].as_str().context("Missing 'find' parameter")?;
1051        let replace_with = args["replace"].as_str().context("Missing 'replace' parameter")?;
1052        let use_regex = args["regex"].as_bool().unwrap_or(false);
1053        let dry_run = args["dry_run"].as_bool().unwrap_or(false);
1054        let file_pattern = args["file_pattern"].as_str();
1055
1056        let root = Path::new(path);
1057
1058        let files: Vec<PathBuf> = if root.is_file() {
1059            vec![root.to_path_buf()]
1060        } else if root.is_dir() {
1061            let fp = file_pattern.context("'file_pattern' is required when path is a directory")?;
1062            WalkDir::new(root)
1063                .into_iter()
1064                .filter_map(|e| e.ok())
1065                .filter(|e| e.path().is_file())
1066                .filter(|e| glob_match(fp, &e.file_name().to_string_lossy()))
1067                .map(|e| e.path().to_path_buf())
1068                .collect()
1069        } else {
1070            anyhow::bail!("Path does not exist: {}", path);
1071        };
1072
1073        let re = if use_regex {
1074            Some(Regex::new(find).with_context(|| format!("Invalid regex: {}", find))?)
1075        } else {
1076            None
1077        };
1078
1079        let mut results = Vec::new();
1080        let mut total_replacements = 0usize;
1081
1082        for file_path in &files {
1083            let content = match fs::read_to_string(file_path) {
1084                Ok(c) => c,
1085                Err(_) => continue,
1086            };
1087
1088            let (new_content, count) = if let Some(ref re) = re {
1089                let count = re.find_iter(&content).count();
1090                if count == 0 {
1091                    (content, 0)
1092                } else {
1093                    let replaced = re.replace_all(&content, replace_with).to_string();
1094                    (replaced, count)
1095                }
1096            } else {
1097                let count = content.matches(find).count();
1098                let replaced = content.replace(find, replace_with);
1099                (replaced, count)
1100            };
1101
1102            if count > 0 {
1103                if !dry_run {
1104                    fs::write(file_path, &new_content)
1105                        .with_context(|| format!("Failed to write: {}", file_path.display()))?;
1106                }
1107                total_replacements += count;
1108                results.push(json!({
1109                    "file": file_path.to_string_lossy(),
1110                    "replacements": count
1111                }));
1112            }
1113        }
1114
1115        Ok(json!({
1116            "success": true,
1117            "dry_run": dry_run,
1118            "files_modified": results.len(),
1119            "total_replacements": total_replacements,
1120            "files_searched": files.len(),
1121            "details": results
1122        }))
1123    }
1124}
1125
1126/// Fast line counting using memchr for newline bytes
1127fn bytecount_lines(s: &str) -> usize {
1128    if s.is_empty() { return 0; }
1129    let count = s.as_bytes().iter().filter(|&&b| b == b'\n').count();
1130    // If the string doesn't end with newline, add 1 for the last line
1131    if s.ends_with('\n') { count } else { count + 1 }
1132}
1133
1134fn search_file(file_path: &Path, re: &Regex, max_results: usize, context_lines: usize, matches: &mut Vec<Value>) {
1135    let content = match fs::read_to_string(file_path) {
1136        Ok(c) => c,
1137        Err(_) => return,
1138    };
1139
1140    let lines: Vec<&str> = content.lines().collect();
1141
1142    for (line_num, line) in lines.iter().enumerate() {
1143        if matches.len() >= max_results {
1144            return;
1145        }
1146        if !re.is_match(line) {
1147            continue;
1148        }
1149
1150        let mut entry = json!({
1151            "file": file_path.to_string_lossy(),
1152            "line": line_num + 1,
1153            "content": line
1154        });
1155
1156        if context_lines > 0 {
1157            let start = line_num.saturating_sub(context_lines);
1158            let end = (line_num + 1 + context_lines).min(lines.len());
1159            entry["context_before"] = json!(&lines[start..line_num]);
1160            entry["context_after"] = json!(&lines[line_num + 1..end]);
1161        }
1162
1163        matches.push(entry);
1164    }
1165}
1166
1167
1168fn build_tree(
1169    dir: &Path,
1170    prefix: &str,
1171    max_depth: usize,
1172    current_depth: usize,
1173    show_hidden: bool,
1174    show_size: bool,
1175    dirs_only: bool,
1176    pattern: Option<&str>,
1177    output: &mut String,
1178    file_count: &mut usize,
1179    dir_count: &mut usize,
1180) -> Result<()> {
1181    if current_depth >= max_depth {
1182        return Ok(());
1183    }
1184
1185    let mut entries: Vec<_> = fs::read_dir(dir)?
1186        .filter_map(|e| e.ok())
1187        .collect();
1188
1189    entries.sort_by_key(|a| a.file_name());
1190
1191    // Filter hidden files
1192    if !show_hidden {
1193        entries.retain(|e| {
1194            !e.file_name().to_string_lossy().starts_with('.')
1195        });
1196    }
1197
1198    // Filter by pattern
1199    if let Some(pat) = pattern {
1200        entries.retain(|e| {
1201            let name = e.file_name().to_string_lossy().to_string();
1202            let is_dir = e.path().is_dir();
1203            is_dir || name.contains(pat) || glob_match(pat, &name)
1204        });
1205    }
1206
1207    // Filter dirs_only
1208    if dirs_only {
1209        entries.retain(|e| e.path().is_dir());
1210    }
1211
1212    let count = entries.len();
1213
1214    for (i, entry) in entries.iter().enumerate() {
1215        let is_last = i == count - 1;
1216        let connector = if is_last { "└── " } else { "├── " };
1217        let name = entry.file_name().to_string_lossy().to_string();
1218        let path = entry.path();
1219        let is_dir = path.is_dir();
1220
1221        let size_str = if show_size && !is_dir {
1222            let size = path.metadata().map(|m| m.len()).unwrap_or(0);
1223            format!(" ({})", format_size(size))
1224        } else {
1225            String::new()
1226        };
1227
1228        let dir_marker = if is_dir { "/" } else { "" };
1229
1230        output.push_str(&format!("{}{}{}{}{}\n", prefix, connector, name, dir_marker, size_str));
1231
1232        if is_dir {
1233            *dir_count += 1;
1234            let new_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });
1235            build_tree(&path, &new_prefix, max_depth, current_depth + 1, show_hidden, show_size, dirs_only, pattern, output, file_count, dir_count)?;
1236        } else {
1237            *file_count += 1;
1238        }
1239    }
1240
1241    Ok(())
1242}
1243
1244fn format_size(bytes: u64) -> String {
1245    if bytes >= 1_073_741_824 {
1246        format!("{:.1}G", bytes as f64 / 1_073_741_824.0)
1247    } else if bytes >= 1_048_576 {
1248        format!("{:.1}M", bytes as f64 / 1_048_576.0)
1249    } else if bytes >= 1024 {
1250        format!("{:.1}K", bytes as f64 / 1024.0)
1251    } else {
1252        format!("{}B", bytes)
1253    }
1254}
1255
1256/// Iterative glob matching using dynamic programming — O(n*m) worst-case
1257fn glob_match(pattern: &str, text: &str) -> bool {
1258    let pat: Vec<char> = pattern.chars().collect();
1259    let txt: Vec<char> = text.chars().collect();
1260    let (plen, tlen) = (pat.len(), txt.len());
1261
1262    let mut pi = 0usize;
1263    let mut ti = 0usize;
1264    let mut star_pi = usize::MAX;
1265    let mut star_ti = 0usize;
1266
1267    while ti < tlen {
1268        if pi < plen && (pat[pi] == '?' || pat[pi].to_lowercase().eq(txt[ti].to_lowercase())) {
1269            pi += 1;
1270            ti += 1;
1271        } else if pi < plen && pat[pi] == '*' {
1272            star_pi = pi;
1273            star_ti = ti;
1274            pi += 1;
1275        } else if star_pi != usize::MAX {
1276            pi = star_pi + 1;
1277            star_ti += 1;
1278            ti = star_ti;
1279        } else {
1280            return false;
1281        }
1282    }
1283
1284    while pi < plen && pat[pi] == '*' {
1285        pi += 1;
1286    }
1287
1288    pi == plen
1289}
1290
1291// Helper function to copy directories recursively
1292fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
1293    fs::create_dir_all(&dst)?;
1294
1295    for entry in fs::read_dir(src)? {
1296        let entry = entry?;
1297        let ty = entry.file_type()?;
1298
1299        if ty.is_dir() {
1300            copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?;
1301        } else {
1302            fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?;
1303        }
1304    }
1305
1306    Ok(())
1307}