kaish-kernel 0.7.0

Core kernel for kaish: lexer, parser, interpreter, and runtime
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! In-memory filesystem implementation.
//!
//! Used for `/v` and testing. All data is ephemeral.

use super::traits::{DirEntry, DirEntryKind, Filesystem};
use async_trait::async_trait;
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use tokio::sync::RwLock;

/// Entry in the memory filesystem.
#[derive(Debug, Clone)]
enum Entry {
    File { data: Vec<u8>, modified: SystemTime },
    Directory { modified: SystemTime },
    Symlink { target: PathBuf, modified: SystemTime },
}

/// In-memory filesystem.
///
/// Thread-safe via internal `RwLock`. All data is lost when dropped.
#[derive(Debug)]
pub struct MemoryFs {
    entries: RwLock<HashMap<PathBuf, Entry>>,
}

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

impl MemoryFs {
    /// Create a new empty in-memory filesystem.
    pub fn new() -> Self {
        let mut entries = HashMap::new();
        // Root directory always exists
        entries.insert(
            PathBuf::from(""),
            Entry::Directory {
                modified: SystemTime::now(),
            },
        );
        Self {
            entries: RwLock::new(entries),
        }
    }

    /// Normalize a path: remove leading `/`, resolve `.` and `..`.
    fn normalize(path: &Path) -> PathBuf {
        let mut result = PathBuf::new();
        for component in path.components() {
            match component {
                std::path::Component::RootDir => {}
                std::path::Component::CurDir => {}
                std::path::Component::ParentDir => {
                    result.pop();
                }
                std::path::Component::Normal(s) => {
                    result.push(s);
                }
                std::path::Component::Prefix(_) => {}
            }
        }
        result
    }

    /// Maximum symlink follow depth (matches Linux ELOOP limit).
    const MAX_SYMLINK_DEPTH: usize = 40;

    /// Read a file, following symlinks with depth limit.
    fn read_inner(&self, path: &Path, depth: usize) -> std::pin::Pin<Box<dyn std::future::Future<Output = io::Result<Vec<u8>>> + Send + '_>> {
        let path = path.to_path_buf();
        Box::pin(async move {
            if depth > Self::MAX_SYMLINK_DEPTH {
                return Err(io::Error::other(
                    "too many levels of symbolic links",
                ));
            }
            let normalized = Self::normalize(&path);
            let entries = self.entries.read().await;

            match entries.get(&normalized) {
                Some(Entry::File { data, .. }) => Ok(data.clone()),
                Some(Entry::Directory { .. }) => Err(io::Error::new(
                    io::ErrorKind::IsADirectory,
                    format!("is a directory: {}", path.display()),
                )),
                Some(Entry::Symlink { target, .. }) => {
                    let target = target.clone();
                    drop(entries);
                    self.read_inner(&target, depth + 1).await
                }
                None => Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("not found: {}", path.display()),
                )),
            }
        })
    }

    /// Stat a file, following symlinks with depth limit.
    /// Returns a DirEntry with a placeholder name (caller should override).
    fn stat_inner(&self, path: &Path, depth: usize) -> std::pin::Pin<Box<dyn std::future::Future<Output = io::Result<DirEntry>> + Send + '_>> {
        let path = path.to_path_buf();
        Box::pin(async move {
            if depth > Self::MAX_SYMLINK_DEPTH {
                return Err(io::Error::other(
                    "too many levels of symbolic links",
                ));
            }
            let normalized = Self::normalize(&path);

            if normalized.as_os_str().is_empty() {
                return Ok(DirEntry {
                    name: String::new(),
                    kind: DirEntryKind::Directory,
                    size: 0,
                    modified: Some(SystemTime::now()),
                    permissions: None,
                    symlink_target: None,
                });
            }

            let entry_info: Option<(DirEntry, Option<PathBuf>)> = {
                let entries = self.entries.read().await;
                match entries.get(&normalized) {
                    Some(Entry::File { data, modified }) => Some((
                        DirEntry {
                            name: String::new(),
                            kind: DirEntryKind::File,
                            size: data.len() as u64,
                            modified: Some(*modified),
                            permissions: None,
                            symlink_target: None,
                        },
                        None,
                    )),
                    Some(Entry::Directory { modified }) => Some((
                        DirEntry {
                            name: String::new(),
                            kind: DirEntryKind::Directory,
                            size: 0,
                            modified: Some(*modified),
                            permissions: None,
                            symlink_target: None,
                        },
                        None,
                    )),
                    Some(Entry::Symlink { target, .. }) => Some((
                        DirEntry {
                            name: String::new(),
                            kind: DirEntryKind::File, // placeholder, will be overridden
                            size: 0,
                            modified: None,
                            permissions: None,
                            symlink_target: None,
                        },
                        Some(target.clone()),
                    )),
                    None => None,
                }
            };

            match entry_info {
                Some((entry, None)) => Ok(entry),
                Some((_, Some(target))) => self.stat_inner(&target, depth + 1).await,
                None => Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("not found: {}", path.display()),
                )),
            }
        })
    }

    /// Ensure all parent directories exist.
    async fn ensure_parents(&self, path: &Path) -> io::Result<()> {
        let mut entries = self.entries.write().await;

        let mut current = PathBuf::new();
        for component in path.parent().into_iter().flat_map(|p| p.components()) {
            if let std::path::Component::Normal(s) = component {
                current.push(s);
                match entries.entry(current.clone()) {
                    std::collections::hash_map::Entry::Occupied(e) => {
                        if matches!(e.get(), Entry::File { .. }) {
                            return Err(io::Error::new(
                                io::ErrorKind::NotADirectory,
                                format!("not a directory: {}", current.display()),
                            ));
                        }
                    }
                    std::collections::hash_map::Entry::Vacant(e) => {
                        e.insert(Entry::Directory {
                            modified: SystemTime::now(),
                        });
                    }
                }
            }
        }
        Ok(())
    }
}

#[async_trait]
impl Filesystem for MemoryFs {
    async fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
        self.read_inner(path, 0).await
    }

    async fn write(&self, path: &Path, data: &[u8]) -> io::Result<()> {
        let normalized = Self::normalize(path);

        // Ensure parent directories exist
        self.ensure_parents(&normalized).await?;

        let mut entries = self.entries.write().await;

        // Check we're not overwriting a directory
        if let Some(Entry::Directory { .. }) = entries.get(&normalized) {
            return Err(io::Error::new(
                io::ErrorKind::IsADirectory,
                format!("is a directory: {}", path.display()),
            ));
        }

        entries.insert(
            normalized,
            Entry::File {
                data: data.to_vec(),
                modified: SystemTime::now(),
            },
        );
        Ok(())
    }

    async fn list(&self, path: &Path) -> io::Result<Vec<DirEntry>> {
        let normalized = Self::normalize(path);
        let entries = self.entries.read().await;

        // Verify the path is a directory
        match entries.get(&normalized) {
            Some(Entry::Directory { .. }) => {}
            Some(Entry::File { .. }) => {
                return Err(io::Error::new(
                    io::ErrorKind::NotADirectory,
                    format!("not a directory: {}", path.display()),
                ))
            }
            Some(Entry::Symlink { .. }) => {
                return Err(io::Error::new(
                    io::ErrorKind::NotADirectory,
                    format!("not a directory: {}", path.display()),
                ))
            }
            None if normalized.as_os_str().is_empty() => {
                // Root directory
            }
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("not found: {}", path.display()),
                ))
            }
        }

        // Find all direct children
        let prefix = if normalized.as_os_str().is_empty() {
            PathBuf::new()
        } else {
            normalized.clone()
        };

        let mut result = Vec::new();
        for (entry_path, entry) in entries.iter() {
            if let Some(parent) = entry_path.parent()
                && parent == prefix && entry_path != &normalized
                    && let Some(name) = entry_path.file_name() {
                        let (kind, size, modified, symlink_target) = match entry {
                            Entry::File { data, modified } => (DirEntryKind::File, data.len() as u64, Some(*modified), None),
                            Entry::Directory { modified } => (DirEntryKind::Directory, 0, Some(*modified), None),
                            Entry::Symlink { target, modified } => (DirEntryKind::Symlink, 0, Some(*modified), Some(target.clone())),
                        };
                        result.push(DirEntry {
                            name: name.to_string_lossy().into_owned(),
                            kind,
                            size,
                            modified,
                            permissions: None,
                            symlink_target,
                        });
                    }
        }

        // Sort for consistent ordering
        result.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(result)
    }

    async fn stat(&self, path: &Path) -> io::Result<DirEntry> {
        let mut entry = self.stat_inner(path, 0).await?;
        // Set name from the requested path
        let normalized = Self::normalize(path);
        entry.name = normalized
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "/".to_string());
        Ok(entry)
    }

    async fn lstat(&self, path: &Path) -> io::Result<DirEntry> {
        let normalized = Self::normalize(path);

        let name = normalized
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "/".to_string());

        let entries = self.entries.read().await;

        // Handle root directory
        if normalized.as_os_str().is_empty() {
            return Ok(DirEntry {
                name,
                kind: DirEntryKind::Directory,
                size: 0,
                modified: Some(SystemTime::now()),
                permissions: None,
                symlink_target: None,
            });
        }

        match entries.get(&normalized) {
            Some(Entry::File { data, modified }) => Ok(DirEntry {
                name,
                kind: DirEntryKind::File,
                size: data.len() as u64,
                modified: Some(*modified),
                permissions: None,
                symlink_target: None,
            }),
            Some(Entry::Directory { modified }) => Ok(DirEntry {
                name,
                kind: DirEntryKind::Directory,
                size: 0,
                modified: Some(*modified),
                permissions: None,
                symlink_target: None,
            }),
            Some(Entry::Symlink { target, modified }) => Ok(DirEntry {
                name,
                kind: DirEntryKind::Symlink,
                size: 0,
                modified: Some(*modified),
                permissions: None,
                symlink_target: Some(target.clone()),
            }),
            None => Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("not found: {}", path.display()),
            )),
        }
    }

    async fn read_link(&self, path: &Path) -> io::Result<PathBuf> {
        let normalized = Self::normalize(path);
        let entries = self.entries.read().await;

        match entries.get(&normalized) {
            Some(Entry::Symlink { target, .. }) => Ok(target.clone()),
            Some(_) => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("not a symbolic link: {}", path.display()),
            )),
            None => Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("not found: {}", path.display()),
            )),
        }
    }

    async fn symlink(&self, target: &Path, link: &Path) -> io::Result<()> {
        let normalized = Self::normalize(link);

        // Ensure parent directories exist
        self.ensure_parents(&normalized).await?;

        let mut entries = self.entries.write().await;

        // Check if something already exists at this path
        if entries.contains_key(&normalized) {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                format!("file exists: {}", link.display()),
            ));
        }

        entries.insert(
            normalized,
            Entry::Symlink {
                target: target.to_path_buf(),
                modified: SystemTime::now(),
            },
        );
        Ok(())
    }

    async fn mkdir(&self, path: &Path) -> io::Result<()> {
        let normalized = Self::normalize(path);

        // Ensure parent directories exist
        self.ensure_parents(&normalized).await?;

        let mut entries = self.entries.write().await;

        // Check if something already exists
        if let Some(existing) = entries.get(&normalized) {
            return match existing {
                Entry::Directory { .. } => Ok(()), // Already exists, fine
                Entry::File { .. } | Entry::Symlink { .. } => Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    format!("file exists: {}", path.display()),
                )),
            };
        }

        entries.insert(
            normalized,
            Entry::Directory {
                modified: SystemTime::now(),
            },
        );
        Ok(())
    }

    async fn remove(&self, path: &Path) -> io::Result<()> {
        let normalized = Self::normalize(path);

        if normalized.as_os_str().is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "cannot remove root directory",
            ));
        }

        let mut entries = self.entries.write().await;

        // Check if it's a non-empty directory
        if let Some(Entry::Directory { .. }) = entries.get(&normalized) {
            // Check for children
            let has_children = entries.keys().any(|k| {
                k.parent() == Some(&normalized) && k != &normalized
            });
            if has_children {
                return Err(io::Error::new(
                    io::ErrorKind::DirectoryNotEmpty,
                    format!("directory not empty: {}", path.display()),
                ));
            }
        }

        entries.remove(&normalized).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!("not found: {}", path.display()),
            )
        })?;
        Ok(())
    }

    async fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
        let from_normalized = Self::normalize(from);
        let to_normalized = Self::normalize(to);

        if from_normalized.as_os_str().is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "cannot rename root directory",
            ));
        }

        // Identity rename is a no-op
        if from_normalized == to_normalized {
            return Ok(());
        }

        // Cannot move a directory into itself
        if to_normalized.starts_with(&from_normalized) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("cannot move '{}' into itself", from.display()),
            ));
        }

        // Ensure parent directories exist for destination
        drop(self.ensure_parents(&to_normalized).await);

        let mut entries = self.entries.write().await;

        // Get the source entry
        let entry = entries.remove(&from_normalized).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!("not found: {}", from.display()),
            )
        })?;

        // Check we're not overwriting a directory with a file or vice versa
        if let Some(existing) = entries.get(&to_normalized) {
            match (&entry, existing) {
                (Entry::File { .. }, Entry::Directory { .. }) => {
                    // Put the source back and error
                    entries.insert(from_normalized, entry);
                    return Err(io::Error::new(
                        io::ErrorKind::IsADirectory,
                        format!("destination is a directory: {}", to.display()),
                    ));
                }
                (Entry::Directory { .. }, Entry::File { .. }) => {
                    entries.insert(from_normalized, entry);
                    return Err(io::Error::new(
                        io::ErrorKind::NotADirectory,
                        format!("destination is not a directory: {}", to.display()),
                    ));
                }
                _ => {}
            }
        }

        // For directories, we need to rename all children too
        if matches!(entry, Entry::Directory { .. }) {
            // Collect paths to rename (can't modify while iterating)
            let children_to_rename: Vec<(PathBuf, Entry)> = entries
                .iter()
                .filter(|(k, _)| k.starts_with(&from_normalized) && *k != &from_normalized)
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();

            // Remove old children and insert with new paths
            for (old_path, child_entry) in children_to_rename {
                entries.remove(&old_path);
                let Ok(relative) = old_path.strip_prefix(&from_normalized) else {
                    continue;
                };
                let new_path = to_normalized.join(relative);
                entries.insert(new_path, child_entry);
            }
        }

        // Insert at new location
        entries.insert(to_normalized, entry);
        Ok(())
    }

    fn read_only(&self) -> bool {
        false
    }
}

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

    #[tokio::test]
    async fn test_write_and_read() {
        let fs = MemoryFs::new();
        fs.write(Path::new("test.txt"), b"hello world").await.unwrap();
        let data = fs.read(Path::new("test.txt")).await.unwrap();
        assert_eq!(data, b"hello world");
    }

    #[tokio::test]
    async fn test_read_not_found() {
        let fs = MemoryFs::new();
        let result = fs.read(Path::new("nonexistent.txt")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);
    }

    #[tokio::test]
    async fn test_nested_directories() {
        let fs = MemoryFs::new();
        fs.write(Path::new("a/b/c/file.txt"), b"nested").await.unwrap();

        // Should have created parent directories
        let entry = fs.stat(Path::new("a")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Directory);

        let entry = fs.stat(Path::new("a/b")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Directory);

        let entry = fs.stat(Path::new("a/b/c")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Directory);

        let data = fs.read(Path::new("a/b/c/file.txt")).await.unwrap();
        assert_eq!(data, b"nested");
    }

    #[tokio::test]
    async fn test_list_directory() {
        let fs = MemoryFs::new();
        fs.write(Path::new("a.txt"), b"a").await.unwrap();
        fs.write(Path::new("b.txt"), b"b").await.unwrap();
        fs.mkdir(Path::new("subdir")).await.unwrap();

        let entries = fs.list(Path::new("")).await.unwrap();
        assert_eq!(entries.len(), 3);

        let names: Vec<_> = entries.iter().map(|e| &e.name).collect();
        assert!(names.contains(&&"a.txt".to_string()));
        assert!(names.contains(&&"b.txt".to_string()));
        assert!(names.contains(&&"subdir".to_string()));
    }

    #[tokio::test]
    async fn test_mkdir_and_stat() {
        let fs = MemoryFs::new();
        fs.mkdir(Path::new("mydir")).await.unwrap();

        let entry = fs.stat(Path::new("mydir")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Directory);
    }

    #[tokio::test]
    async fn test_remove_file() {
        let fs = MemoryFs::new();
        fs.write(Path::new("file.txt"), b"data").await.unwrap();

        fs.remove(Path::new("file.txt")).await.unwrap();

        let result = fs.stat(Path::new("file.txt")).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_remove_empty_directory() {
        let fs = MemoryFs::new();
        fs.mkdir(Path::new("emptydir")).await.unwrap();

        fs.remove(Path::new("emptydir")).await.unwrap();

        let result = fs.stat(Path::new("emptydir")).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_remove_non_empty_directory_fails() {
        let fs = MemoryFs::new();
        fs.write(Path::new("dir/file.txt"), b"data").await.unwrap();

        let result = fs.remove(Path::new("dir")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::DirectoryNotEmpty);
    }

    #[tokio::test]
    async fn test_path_normalization() {
        let fs = MemoryFs::new();
        fs.write(Path::new("/a/b/c.txt"), b"data").await.unwrap();

        // Various path forms should all work
        let data1 = fs.read(Path::new("a/b/c.txt")).await.unwrap();
        let data2 = fs.read(Path::new("/a/b/c.txt")).await.unwrap();
        let data3 = fs.read(Path::new("a/./b/c.txt")).await.unwrap();
        let data4 = fs.read(Path::new("a/b/../b/c.txt")).await.unwrap();

        assert_eq!(data1, data2);
        assert_eq!(data2, data3);
        assert_eq!(data3, data4);
    }

    #[tokio::test]
    async fn test_overwrite_file() {
        let fs = MemoryFs::new();
        fs.write(Path::new("file.txt"), b"first").await.unwrap();
        fs.write(Path::new("file.txt"), b"second").await.unwrap();

        let data = fs.read(Path::new("file.txt")).await.unwrap();
        assert_eq!(data, b"second");
    }

    #[tokio::test]
    async fn test_exists() {
        let fs = MemoryFs::new();
        assert!(!fs.exists(Path::new("nope.txt")).await);

        fs.write(Path::new("yes.txt"), b"here").await.unwrap();
        assert!(fs.exists(Path::new("yes.txt")).await);
    }

    #[tokio::test]
    async fn test_rename_file() {
        let fs = MemoryFs::new();
        fs.write(Path::new("old.txt"), b"content").await.unwrap();

        fs.rename(Path::new("old.txt"), Path::new("new.txt")).await.unwrap();

        // New path exists with same content
        let data = fs.read(Path::new("new.txt")).await.unwrap();
        assert_eq!(data, b"content");

        // Old path no longer exists
        assert!(!fs.exists(Path::new("old.txt")).await);
    }

    #[tokio::test]
    async fn test_rename_directory() {
        let fs = MemoryFs::new();
        fs.write(Path::new("dir/a.txt"), b"a").await.unwrap();
        fs.write(Path::new("dir/b.txt"), b"b").await.unwrap();
        fs.write(Path::new("dir/sub/c.txt"), b"c").await.unwrap();

        fs.rename(Path::new("dir"), Path::new("renamed")).await.unwrap();

        // New paths exist
        assert!(fs.exists(Path::new("renamed")).await);
        assert!(fs.exists(Path::new("renamed/a.txt")).await);
        assert!(fs.exists(Path::new("renamed/b.txt")).await);
        assert!(fs.exists(Path::new("renamed/sub/c.txt")).await);

        // Old paths don't exist
        assert!(!fs.exists(Path::new("dir")).await);
        assert!(!fs.exists(Path::new("dir/a.txt")).await);

        // Content preserved
        let data = fs.read(Path::new("renamed/a.txt")).await.unwrap();
        assert_eq!(data, b"a");
    }

    #[tokio::test]
    async fn test_rename_not_found() {
        let fs = MemoryFs::new();
        let result = fs.rename(Path::new("nonexistent"), Path::new("dest")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);
    }

    // --- Symlink tests ---

    #[tokio::test]
    async fn test_symlink_create_and_read_link() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"content").await.unwrap();
        fs.symlink(Path::new("target.txt"), Path::new("link.txt")).await.unwrap();

        // read_link returns the raw target
        let target = fs.read_link(Path::new("link.txt")).await.unwrap();
        assert_eq!(target, Path::new("target.txt"));
    }

    #[tokio::test]
    async fn test_symlink_read_follows_link() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"hello from target").await.unwrap();
        fs.symlink(Path::new("target.txt"), Path::new("link.txt")).await.unwrap();

        // Reading through symlink should return target's content
        let data = fs.read(Path::new("link.txt")).await.unwrap();
        assert_eq!(data, b"hello from target");
    }

    #[tokio::test]
    async fn test_symlink_stat_follows_link() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"12345").await.unwrap();
        fs.symlink(Path::new("target.txt"), Path::new("link.txt")).await.unwrap();

        // stat follows symlinks - should report file metadata
        let entry = fs.stat(Path::new("link.txt")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::File);
        assert_eq!(entry.size, 5);
    }

    #[tokio::test]
    async fn test_symlink_lstat_returns_symlink_info() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"content").await.unwrap();
        fs.symlink(Path::new("target.txt"), Path::new("link.txt")).await.unwrap();

        // lstat does not follow symlinks
        let entry = fs.lstat(Path::new("link.txt")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Symlink);
    }

    #[tokio::test]
    async fn test_symlink_in_list() {
        let fs = MemoryFs::new();
        fs.write(Path::new("file.txt"), b"content").await.unwrap();
        fs.symlink(Path::new("file.txt"), Path::new("link.txt")).await.unwrap();
        fs.mkdir(Path::new("dir")).await.unwrap();

        let entries = fs.list(Path::new("")).await.unwrap();
        assert_eq!(entries.len(), 3);

        // Find the symlink entry
        let link_entry = entries.iter().find(|e| e.name == "link.txt").unwrap();
        assert_eq!(link_entry.kind, DirEntryKind::Symlink);
        assert_eq!(link_entry.symlink_target, Some(PathBuf::from("file.txt")));
    }

    #[tokio::test]
    async fn test_symlink_broken_link() {
        let fs = MemoryFs::new();
        // Create symlink to non-existent target
        fs.symlink(Path::new("nonexistent.txt"), Path::new("broken.txt")).await.unwrap();

        // read_link still works
        let target = fs.read_link(Path::new("broken.txt")).await.unwrap();
        assert_eq!(target, Path::new("nonexistent.txt"));

        // lstat works (the symlink exists)
        let entry = fs.lstat(Path::new("broken.txt")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Symlink);

        // stat fails (target doesn't exist)
        let result = fs.stat(Path::new("broken.txt")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);

        // read fails (target doesn't exist)
        let result = fs.read(Path::new("broken.txt")).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_symlink_read_link_on_non_symlink_fails() {
        let fs = MemoryFs::new();
        fs.write(Path::new("file.txt"), b"content").await.unwrap();

        let result = fs.read_link(Path::new("file.txt")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidInput);
    }

    #[tokio::test]
    async fn test_symlink_already_exists() {
        let fs = MemoryFs::new();
        fs.write(Path::new("existing.txt"), b"content").await.unwrap();

        // Can't create symlink over existing file
        let result = fs.symlink(Path::new("target"), Path::new("existing.txt")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists);
    }

    // --- Edge case tests ---

    #[tokio::test]
    async fn test_symlink_chain() {
        // a -> b -> c -> file.txt
        let fs = MemoryFs::new();
        fs.write(Path::new("file.txt"), b"end of chain").await.unwrap();
        fs.symlink(Path::new("file.txt"), Path::new("c")).await.unwrap();
        fs.symlink(Path::new("c"), Path::new("b")).await.unwrap();
        fs.symlink(Path::new("b"), Path::new("a")).await.unwrap();

        // Reading through chain should work
        let data = fs.read(Path::new("a")).await.unwrap();
        assert_eq!(data, b"end of chain");

        // stat through chain should report file
        let entry = fs.stat(Path::new("a")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::File);
    }

    #[tokio::test]
    async fn test_symlink_to_directory() {
        let fs = MemoryFs::new();
        fs.mkdir(Path::new("realdir")).await.unwrap();
        fs.write(Path::new("realdir/file.txt"), b"inside dir").await.unwrap();
        fs.symlink(Path::new("realdir"), Path::new("linkdir")).await.unwrap();

        // stat follows symlink - should see directory
        let entry = fs.stat(Path::new("linkdir")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Directory);

        // Note: listing through symlink requires following in list(),
        // which we don't currently support (symlink to dir returns NotADirectory)
    }

    #[tokio::test]
    async fn test_symlink_relative_path_stored_as_is() {
        let fs = MemoryFs::new();
        fs.mkdir(Path::new("subdir")).await.unwrap();
        fs.write(Path::new("subdir/target.txt"), b"content").await.unwrap();

        // Store a relative path in the symlink
        fs.symlink(Path::new("../subdir/target.txt"), Path::new("subdir/link.txt")).await.unwrap();

        // read_link returns the path as stored
        let target = fs.read_link(Path::new("subdir/link.txt")).await.unwrap();
        assert_eq!(target.to_string_lossy(), "../subdir/target.txt");
    }

    #[tokio::test]
    async fn test_symlink_absolute_path() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"content").await.unwrap();

        // Store absolute path
        fs.symlink(Path::new("/target.txt"), Path::new("link.txt")).await.unwrap();

        let target = fs.read_link(Path::new("link.txt")).await.unwrap();
        assert_eq!(target.to_string_lossy(), "/target.txt");

        // Following should work (normalize strips leading /)
        let data = fs.read(Path::new("link.txt")).await.unwrap();
        assert_eq!(data, b"content");
    }

    #[tokio::test]
    async fn test_symlink_remove() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"content").await.unwrap();
        fs.symlink(Path::new("target.txt"), Path::new("link.txt")).await.unwrap();

        // Remove symlink (not the target)
        fs.remove(Path::new("link.txt")).await.unwrap();

        // Symlink gone
        assert!(!fs.exists(Path::new("link.txt")).await);

        // Target still exists
        assert!(fs.exists(Path::new("target.txt")).await);
    }

    #[tokio::test]
    async fn test_symlink_overwrite_target_content() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"original").await.unwrap();
        fs.symlink(Path::new("target.txt"), Path::new("link.txt")).await.unwrap();

        // Modify target
        fs.write(Path::new("target.txt"), b"modified").await.unwrap();

        // Reading through link shows new content
        let data = fs.read(Path::new("link.txt")).await.unwrap();
        assert_eq!(data, b"modified");
    }

    #[tokio::test]
    async fn test_symlink_empty_name() {
        let fs = MemoryFs::new();
        fs.write(Path::new("target.txt"), b"content").await.unwrap();

        // Symlink with empty path components in target
        fs.symlink(Path::new("./target.txt"), Path::new("link.txt")).await.unwrap();

        let target = fs.read_link(Path::new("link.txt")).await.unwrap();
        assert_eq!(target.to_string_lossy(), "./target.txt");
    }

    #[tokio::test]
    async fn test_symlink_nested_creation() {
        let fs = MemoryFs::new();
        // Symlink in non-existent directory should create parents
        fs.symlink(Path::new("target"), Path::new("a/b/c/link")).await.unwrap();

        // Parents created
        let entry = fs.stat(Path::new("a/b")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Directory);

        // Symlink exists (lstat)
        let entry = fs.lstat(Path::new("a/b/c/link")).await.unwrap();
        assert_eq!(entry.kind, DirEntryKind::Symlink);
    }

    #[tokio::test]
    async fn test_symlink_read_link_not_found() {
        let fs = MemoryFs::new();

        let result = fs.read_link(Path::new("nonexistent")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);
    }

    #[tokio::test]
    async fn test_symlink_read_link_on_directory() {
        let fs = MemoryFs::new();
        fs.mkdir(Path::new("dir")).await.unwrap();

        let result = fs.read_link(Path::new("dir")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidInput);
    }

    #[tokio::test]
    async fn test_symlink_circular_read_returns_error() {
        // Bug F: circular symlinks should return error, not stack overflow
        let fs = MemoryFs::new();
        fs.symlink(Path::new("b"), Path::new("a")).await.unwrap();
        fs.symlink(Path::new("a"), Path::new("b")).await.unwrap();

        let result = fs.read(Path::new("a")).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("symbolic links"),
            "expected symlink loop error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_symlink_circular_stat_returns_error() {
        let fs = MemoryFs::new();
        fs.symlink(Path::new("b"), Path::new("a")).await.unwrap();
        fs.symlink(Path::new("a"), Path::new("b")).await.unwrap();

        let result = fs.stat(Path::new("a")).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("symbolic links"),
            "expected symlink loop error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_rename_into_self_errors() {
        let fs = MemoryFs::new();
        fs.mkdir(Path::new("a")).await.unwrap();

        let result = fs.rename(Path::new("a"), Path::new("a/b")).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidInput);
    }

    #[tokio::test]
    async fn test_rename_identity_noop() {
        let fs = MemoryFs::new();
        fs.write(Path::new("a"), b"data").await.unwrap();

        // Renaming to self should succeed as a no-op
        fs.rename(Path::new("a"), Path::new("a")).await.unwrap();

        // Data should still be there
        let data = fs.read(Path::new("a")).await.unwrap();
        assert_eq!(data, b"data");
    }

    #[tokio::test]
    async fn test_ensure_parents_rejects_file_as_dir() {
        let fs = MemoryFs::new();
        // Create a file at "a"
        fs.write(Path::new("a"), b"I am a file").await.unwrap();

        // Now try to write "a/b" — "a" is a file, not a directory
        let result = fs.write(Path::new("a/b"), b"child").await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotADirectory);
    }
}