codetree 0.1.2

AI-native version control system for autonomous agents
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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
//! VcsManager — the native VCS manager replacing GitManager.
//!
//! Wraps `Repository` and provides the same API surface that commands.rs
//! and mcp.rs previously consumed from `git::GitManager`.

use crate::error::{Context, Result};
use crate::resolution::ConflictInfo;
use super::objects::{hash_object, Blob, ObjectType, Tree, TreeEntry, Commit};
use super::repo::Repository;
use std::path::{Path, PathBuf};

/// Read the tree entries of a commit.
pub(super) fn commit_tree_entries(repo: &Repository, commit_id: &str) -> Result<Vec<TreeEntry>> {
    let commit = repo.read_commit(&commit_id.to_string())?;
    let tree = repo.read_tree(&commit.tree)?;
    Ok(tree.entries)
}

/// Walk the object store and return all object hashes (full 40-char hex).
fn walk_object_hashes(objects_dir: &Path) -> Result<Vec<String>> {
    let mut hashes = Vec::new();
    if !objects_dir.exists() {
        return Ok(hashes);
    }
    for entry in std::fs::read_dir(objects_dir)? {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let dir_name = entry.file_name().to_string_lossy().to_string();
        if dir_name.len() != 2 {
            continue;
        }
        for file_entry in std::fs::read_dir(entry.path())? {
            let file_entry = file_entry?;
            let file_name = file_entry.file_name().to_string_lossy().to_string();
            let hash = format!("{}{}", dir_name, file_name);
            if hash.len() == 40 {
                hashes.push(hash);
            }
        }
    }
    Ok(hashes)
}

/// Stat fingerprint of a working-tree file: (mtime_secs, mtime_nanos, size, inode).
/// Combined with the index stat cache, an unchanged fingerprint means the file
/// content is unchanged and re-hashing can be skipped (same trade-off as git).
fn stat_fingerprint(meta: &std::fs::Metadata) -> (u64, u32, u64, u64) {
    let (secs, nanos) = meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| (d.as_secs(), d.subsec_nanos()))
        .unwrap_or((0, 0));
    #[cfg(unix)]
    let ino = std::os::unix::fs::MetadataExt::ino(meta);
    #[cfg(not(unix))]
    let ino = 0u64;
    (secs, nanos, meta.len(), ino)
}

/// Status of a file in the working tree.
#[derive(Debug, Clone, serde::Serialize)]
pub struct VcsStatus {
    pub modified: Vec<String>,
    pub untracked: Vec<String>,
    pub staged: Vec<String>,
}

/// Information about a branch.
#[derive(Debug, Clone, serde::Serialize)]
pub struct BranchInfo {
    pub name: String,
    pub is_current: bool,
    pub commit_hash: String,
    pub commit_message: String,
    pub author: String,
    pub timestamp: i64,
}

/// Information about a commit.
#[derive(Debug, Clone)]
pub struct CommitInfo {
    pub hash: String,
    pub message: String,
    pub author: String,
    pub timestamp: i64,
    pub files_changed: Vec<String>,
}

/// Result of a merge attempt with cache support.
#[derive(Debug)]
pub struct MergeResult {
    pub resolved_from_cache: bool,
    pub conflicts: Vec<ConflictInfo>,
    /// Files auto-resolved by a configured merge driver (subset of `conflicts`).
    pub driver_resolved: Vec<String>,
}

/// Result of a working-copy snapshot.
#[derive(Debug)]
pub struct SnapshotResult {
    pub commit_hash: String,
    pub file_count: usize,
    pub branch: String,
    pub timestamp: u64,
}

/// Result of an absorb operation.
#[derive(Debug)]
pub struct AbsorbResult {
    pub new_head: String,
    pub target_commit: String,
    pub absorbed_files: Vec<String>,
    pub was_head: bool,
}

/// Result of a readiness check (read-only merge feasibility).
#[derive(Debug, serde::Serialize)]
pub struct ReadyCheck {
    pub ahead: usize,
    pub behind: usize,
    pub up_to_date: bool,
    pub conflict_count: usize,
    pub auto_resolvable: bool,
    pub conflict_files: Vec<String>,
}

/// The native VCS manager. Replaces GitManager.
#[derive(Clone)]
pub struct VcsManager {
    pub(super) repo_path: PathBuf,
    pub(super) repo: Repository,
    pub(super) max_file_size: u64,
    /// Merge drivers: glob pattern → command template with %base %ours
    /// %theirs %result placeholders (TODO Round 13: pluggable, syntax-aware
    /// merging à la mergiraf). Empty by default — zero-dep line merges.
    pub(super) merge_drivers: std::collections::HashMap<String, String>,
}

impl VcsManager {
    /// Create a new VcsManager, opening or initializing the repository.
    pub fn new(repo_path: PathBuf) -> Result<Self> {
        let codetree_dir = repo_path.join(".codetree");
        if !codetree_dir.exists() {
            bail!("No CodeTree repository found at {}. Run `codetree init` first.", repo_path.display());
        }
        let repo = Repository::open(&repo_path)?;
        Ok(Self { repo_path, repo, max_file_size: 0, merge_drivers: std::collections::HashMap::new() })
    }

    /// Initialize a new native VCS repository at the given path.
    pub fn init_at(path: &Path) -> Result<Self> {
        let repo = Repository::init(path)?;
        Ok(Self {
            repo_path: path.to_path_buf(),
            repo,
            max_file_size: 0,
            merge_drivers: std::collections::HashMap::new(),
        })
    }

    /// Configure merge drivers (glob pattern → command template).
    /// Callers load these from `[merge] drivers` in config.toml.
    pub fn set_merge_drivers(&mut self, drivers: std::collections::HashMap<String, String>) {
        self.merge_drivers = drivers;
    }

    /// Get the repository working directory path.
    pub fn repo_path(&self) -> &Path {
        &self.repo_path
    }

    /// Get the underlying repository.
    pub fn repo(&self) -> &Repository {
        &self.repo
    }

    // ── Branch operations ──────────────────────────────────────────

    /// Get the current branch name from HEAD.
    pub async fn get_current_branch(&self) -> Result<String> {
        self.repo
            .refs()
            .current_branch()?
            .context("HEAD is detached (no current branch)")
    }

    /// Create a new branch pointing at the given base branch's commit (or HEAD if None).
    pub async fn create_branch(&self, branch_name: &str, base_branch: Option<&str>) -> Result<()> {
        let commit_id = if let Some(base) = base_branch {
            self.repo
                .refs()
                .get_branch(base)?
                .with_context(|| format!("Base branch '{}' not found", base))?
        } else {
            self.repo
                .refs()
                .resolve_head()?
                .context("HEAD does not point to a commit")?
        };
        self.repo.refs().set_branch(branch_name, &commit_id)?;
        Ok(())
    }

    /// Checkout a branch: update HEAD and restore working tree.
    pub async fn checkout_branch(&self, branch_name: &str) -> Result<()> {
        let commit_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        // Restore working tree from the branch's commit tree
        self.restore_working_tree(&commit_id)?;

        // Update HEAD
        self.repo.refs().set_head(branch_name)?;

        // Reset index to match the commit
        let tree = self.commit_tree(&commit_id)?;
        let mut index = self.repo.load_index()?;
        index.clear();
        for entry in &tree.entries {
            index.add(&entry.name, &entry.id);
        }
        index.save()?;

        Ok(())
    }

    /// Delete a branch ref.
    pub async fn delete_branch(&self, branch_name: &str, _force: bool) -> Result<()> {
        // Don't allow deleting the current branch
        if let Ok(Some(current)) = self.repo.refs().current_branch()
            && current == branch_name
        {
            bail!("Cannot delete current branch '{}'", branch_name);
        }
        self.repo.refs().delete_branch(branch_name)?;
        Ok(())
    }

    /// Check if a branch exists.
    pub fn branch_exists(&self, branch_name: &str) -> bool {
        self.repo
            .refs()
            .get_branch(branch_name)
            .map(|o| o.is_some())
            .unwrap_or(false)
    }

    /// List all branches with metadata.
    pub fn list_branches(&self) -> Result<Vec<BranchInfo>> {
        let names = self.repo.refs().list_branches()?;
        let current = self
            .repo
            .refs()
            .current_branch()
            .unwrap_or(None)
            .unwrap_or_default();

        let mut branches = Vec::new();
        for name in names {
            let commit_hash = self
                .repo
                .refs()
                .get_branch(&name)?
                .unwrap_or_default();
            let (message, author, timestamp) = self
                .read_commit_meta(&commit_hash)
                .unwrap_or(("".to_string(), "".to_string(), 0));
            branches.push(BranchInfo {
                name: name.clone(),
                is_current: name == current,
                commit_hash,
                commit_message: message,
                author,
                timestamp: timestamp as i64,
            });
        }
        Ok(branches)
    }

    // ── Staging operations ─────────────────────────────────────────

    /// Set the maximum file size for staging. Files larger than this are
    /// skipped during `add_all`/`add_files`. 0 = no limit.
    pub fn set_max_file_size(&mut self, size: u64) {
        self.max_file_size = size;
    }

    /// Stage all files in the working tree (except .codetree/).
    ///
    /// Uses the index stat cache: files whose stat fingerprint is unchanged
    /// since they were last staged are skipped without reading or hashing.
    pub async fn add_all(&self) -> Result<()> {
        let repo_path = self.repo_path.clone();
        let repo = self.repo.clone();
        let max_size = self.max_file_size;
        tokio::task::spawn_blocking(move || -> Result<()> {
            let files = {
                let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };
                mgr.walk_working_tree(&repo_path)?
            };
            let mut index = repo.load_index()?;
            for file in &files {
                let relative = file.strip_prefix(&repo_path).unwrap_or(file);
                let relative_str = relative.to_string_lossy().to_string();
                let meta = std::fs::metadata(file)?;
                let (secs, nanos, size, ino) = stat_fingerprint(&meta);
                if max_size > 0 && size > max_size {
                    eprintln!("[warn] Skipping large file: {} ({} bytes, limit: {})", relative_str, size, max_size);
                    continue;
                }
                if let Some(entry) = index.entry(&relative_str)
                    && entry.matches_stat(secs, nanos, size, ino)
                    && repo.has_object(&entry.blob_id)
                {
                    continue;
                }
                let content = std::fs::read(file)?;
                let blob_id = repo.write_blob(&content)?;
                index.add_staged(&relative_str, &blob_id, secs, nanos, size, ino);
            }
            index.save()?;
            Ok(())
        }).await?
    }

    /// Stage specific files.
    ///
    /// Uses the same index stat cache as [`Self::add_all`].
    pub async fn add_files(&self, files: &[String]) -> Result<()> {
        if files.is_empty() {
            return self.add_all().await;
        }
        let repo_path = self.repo_path.clone();
        let repo = self.repo.clone();
        let files = files.to_vec();
        tokio::task::spawn_blocking(move || -> Result<()> {
            let mut index = repo.load_index()?;
            for file in &files {
                let full_path = repo_path.join(file);
                if !full_path.exists() {
                    index.remove(file);
                    continue;
                }
                let meta = std::fs::metadata(&full_path)?;
                let (secs, nanos, size, ino) = stat_fingerprint(&meta);
                if let Some(entry) = index.entry(file)
                    && entry.matches_stat(secs, nanos, size, ino)
                    && repo.has_object(&entry.blob_id)
                {
                    continue;
                }
                let content = std::fs::read(&full_path)?;
                let blob_id = repo.write_blob(&content)?;
                index.add_staged(file, &blob_id, secs, nanos, size, ino);
            }
            index.save()?;
            Ok(())
        }).await?
    }

    // ── Commit operations ──────────────────────────────────────────

    /// Commit staged changes. Returns the commit hash.
    pub async fn commit(&self, message: &str) -> Result<String> {
        let author = "CodeTree <agent@codetree>";
        let commit_id = self.repo.commit(message, author)?;
        Ok(commit_id)
    }

    /// Commit staged changes with custom author and timestamp (for import).
    pub async fn commit_with_meta(&self, message: &str, author: &str, timestamp: u64) -> Result<String> {
        let commit_id = self.repo.commit_with_meta(message, author, timestamp)?;
        Ok(commit_id)
    }

    /// Create an empty commit (same tree as HEAD) on top of HEAD. Returns the
    /// commit hash. Useful as a clean checkpoint before experimenting — the
    /// agent can `undo` back to it without losing the working tree.
    pub async fn commit_empty(&self, message: &str) -> Result<String> {
        let repo = self.repo.clone();
        let message = message.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let head_id = repo
                .refs()
                .resolve_head()?
                .context("HEAD does not point to a commit")?;
            let head_commit = repo.read_commit(&head_id)?;

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let commit = Commit::new(
                head_commit.tree,
                vec![head_id],
                "CodeTree <agent@codetree>".to_string(),
                message,
                timestamp,
            );
            let commit_id = repo.write_commit(&commit)?;

            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &commit_id)?;
            }

            Ok(commit_id)
        })
        .await?
    }

    /// Public wrapper for resolve_commit.
    pub fn resolve_commit_pub(&self, spec: &str, head_id: &str) -> Result<String> {
        self.resolve_commit(spec, head_id)
    }

    /// Checkout a specific commit (detached HEAD). Useful for inspecting
    /// an arbitrary commit's state without creating a branch.
    pub async fn goto_commit(&self, commit_spec: &str) -> Result<()> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let commit_spec = commit_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<()> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };
            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;

            // Restore working tree from the target commit.
            mgr.restore_working_tree(&target_id)?;

            // Set detached HEAD.
            repo.refs().set_detached_head(&target_id)?;

            // Reset index to match the commit.
            let tree = mgr.commit_tree(&target_id)?;
            let mut index = repo.load_index()?;
            index.clear();
            for entry in &tree.entries {
                index.add(&entry.name, &entry.id);
            }
            index.save()?;

            Ok(())
        })
        .await?
    }

    pub(super) fn resolve_commit(&self, spec: &str, head_id: &str) -> Result<String> {
        if spec == "HEAD" {
            return Ok(head_id.to_string());
        }
        if let Some(rest) = spec.strip_prefix("HEAD~") {
            let n: usize = rest.parse().unwrap_or(0);
            let mut current = head_id.to_string();
            for _ in 0..n {
                let commit = self.repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("HEAD~{} goes beyond the root commit", n);
                }
                current = commit.parents[0].clone();
            }
            return Ok(current);
        }
        // Try as a hash prefix — check all objects.
        let objects_dir = self.repo.root().join("objects");
        for entry in walk_object_hashes(&objects_dir)? {
            if entry.starts_with(spec) {
                return Ok(entry);
            }
        }
        bail!("Commit '{}' not found", spec)
    }

    /// Snapshot the working tree as an anonymous commit (no ref update, no
    /// index mutation). Returns `None` if the working tree matches HEAD (clean).
    pub async fn snapshot_working_tree(&self) -> Result<Option<SnapshotResult>> {
        let repo_path = self.repo_path.clone();
        let repo = self.repo.clone();
        tokio::task::spawn_blocking(move || -> Result<Option<SnapshotResult>> {
            // Check if the working tree differs from HEAD.
            let head_tree = {
                let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };
                mgr.head_tree()?
            };
            let head_map: std::collections::HashMap<String, String> = head_tree
                .entries
                .iter()
                .map(|e| (e.name.clone(), e.id.clone()))
                .collect();

            let files = {
                let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };
                mgr.walk_working_tree(&repo_path)?
            };

            // Build tree entries from the working tree, tracking whether anything
            // differs from HEAD.
            let mut entries = Vec::with_capacity(files.len());
            let mut dirty = false;
            for file in &files {
                let relative = file.strip_prefix(&repo_path).unwrap_or(file);
                let relative_str = relative.to_string_lossy().to_string();
                let content = std::fs::read(file)?;
                let blob_id = repo.write_blob(&content)?;
                match head_map.get(&relative_str) {
                    Some(h) if *h == blob_id => {}
                    _ => dirty = true,
                }
                entries.push(TreeEntry {
                    mode: 0o100644,
                    name: relative_str,
                    id: blob_id,
                });
            }
            // Deleted files (in HEAD but not in working tree) also count as dirty.
            let wt_set: std::collections::HashSet<&str> =
                entries.iter().map(|e| e.name.as_str()).collect();
            for name in head_map.keys() {
                if !wt_set.contains(name.as_str()) {
                    dirty = true;
                    break;
                }
            }

            if !dirty {
                return Ok(None);
            }

            let tree = Tree::new(entries);
            let tree_id = repo.write_tree(&tree)?;

            let parents = repo
                .refs()
                .resolve_head()?
                .map(|h| vec![h])
                .unwrap_or_default();

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let commit = Commit::new(
                tree_id,
                parents,
                "CodeTree <agent@codetree>".to_string(),
                "Working copy snapshot".to_string(),
                timestamp,
            );
            let commit_id = repo.write_commit(&commit)?;

            let branch = repo
                .refs()
                .current_branch()?
                .unwrap_or_default();

            Ok(Some(SnapshotResult {
                commit_hash: commit_id,
                file_count: tree.entries.len(),
                branch,
                timestamp,
            }))
        })
        .await?
    }

    /// Get working tree status.
    pub async fn get_status(&self) -> Result<VcsStatus> {
        let head_tree = self.head_tree()?;
        let index = self.repo.load_index()?;

        // Walk working tree
        let wt_files = self.walk_working_tree(&self.repo_path)?;
        let wt_set: std::collections::HashMap<String, PathBuf> = wt_files
            .iter()
            .map(|p| {
                let rel = p.strip_prefix(&self.repo_path).unwrap_or(p);
                (rel.to_string_lossy().to_string(), p.clone())
            })
            .collect();

        let head_set: std::collections::HashMap<&String, &String> = head_tree
            .entries
            .iter()
            .map(|e| (&e.name, &e.id))
            .collect();

        let index_entries = index.entries_sorted();
        let index_set: std::collections::HashMap<&String, &String> = index_entries
            .iter()
            .map(|(p, h)| (p, h))
            .collect();

        let mut modified = Vec::new();
        let mut untracked = Vec::new();
        let mut staged = Vec::new();

        // Check working tree files against HEAD
        for (rel, full) in &wt_set {
            if let Some(head_blob) = head_set.get(rel) {
                // File exists in HEAD — check if modified.
                // Fast path: the index stat cache proves the file matches its
                // staged content; if that equals HEAD, no read/hash is needed.
                let mut is_modified = true;
                if let Some(entry) = index.entry(rel)
                    && entry.blob_id == **head_blob
                {
                    let meta = std::fs::metadata(full)?;
                    let (secs, nanos, size, ino) = stat_fingerprint(&meta);
                    if entry.matches_stat(secs, nanos, size, ino) {
                        is_modified = false;
                    }
                }
                if is_modified {
                    let content = std::fs::read(full)?;
                    let blob = Blob::new(content);
                    if &blob.id() != *head_blob {
                        modified.push(rel.clone());
                    }
                }
            } else if index_set.contains_key(rel) {
                // File is staged but not in HEAD — check if modified from staged version
                // It's already staged, not "modified" in WT sense
            } else {
                untracked.push(rel.clone());
            }
        }

        // Check for deleted files (in HEAD but not in working tree)
        for name in head_set.keys() {
            if !wt_set.contains_key(*name) {
                modified.push(name.to_string());
            }
        }

        // Staged: files in index that differ from HEAD
        for (path, blob_id) in &index_set {
            match head_set.get(path) {
                Some(head_blob) if *head_blob != *blob_id => staged.push(path.to_string()),
                None => staged.push(path.to_string()),
                _ => {}
            }
        }

        modified.sort();
        untracked.sort();
        staged.sort();

        Ok(VcsStatus {
            modified,
            untracked,
            staged,
        })
    }

    // ── Diff ───────────────────────────────────────────────────────

    /// Path to the pending-resolution sidecar (active merge conflicts).
    pub fn pending_resolution_path(&self) -> PathBuf {
        self.repo_path.join(".codetree").join("pending_resolution.json")
    }

    /// Path to the snapshots sidecar.
    pub fn snapshots_path(&self) -> PathBuf {
        self.repo_path.join(".codetree").join("snapshots.json")
    }



    // ── Push (stub — remote protocol not yet implemented) ───────────

    /// Get the current HEAD commit hash.
    pub fn get_head_hash(&self) -> Result<String> {
        self.repo
            .refs()
            .resolve_head()?
            .context("HEAD does not point to a commit")
    }

    // ── Internal helpers ───────────────────────────────────────────

    /// Read a commit and return (message, author, timestamp).
    fn read_commit_meta(&self, commit_id: &str) -> Result<(String, String, u64)> {
        let commit = self.repo.read_commit(&commit_id.to_string())?;
        Ok((commit.message, commit.author, commit.timestamp))
    }

    /// Get the tree of a commit.
    pub(super) fn commit_tree(&self, commit_id: &str) -> Result<Tree> {
        let commit = self.repo.read_commit(&commit_id.to_string())?;
        self.repo.read_tree(&commit.tree)
    }

    /// Get the HEAD tree (or empty tree if no HEAD).
    pub(super) fn head_tree(&self) -> Result<Tree> {
        let head_id = self
            .repo
            .refs()
            .resolve_head()?
            .unwrap_or_default();
        if head_id.is_empty() {
            return Ok(Tree::new(vec![]));
        }
        self.commit_tree(&head_id)
    }

    /// Get files changed in a commit (diff against first parent).
    pub(super) fn commit_files(&self, commit_id: &str) -> Result<Vec<String>> {
        let commit = self.repo.read_commit(&commit_id.to_string())?;
        let tree = self.repo.read_tree(&commit.tree)?;

        let parent_tree = if !commit.parents.is_empty() {
            let parent = self.repo.read_commit(&commit.parents[0])?;
            self.repo.read_tree(&parent.tree)?
        } else {
            Tree::new(vec![])
        };

        let parent_set: std::collections::HashMap<&String, &String> = parent_tree
            .entries
            .iter()
            .map(|e| (&e.name, &e.id))
            .collect();

        let mut files = Vec::new();
        for entry in &tree.entries {
            match parent_set.get(&entry.name) {
                Some(parent_blob) if **parent_blob != entry.id => files.push(entry.name.clone()),
                None => files.push(entry.name.clone()),
                _ => {}
            }
        }
        // Deleted files
        for name in parent_tree.entries.iter().map(|e| &e.name) {
            if !tree.entries.iter().any(|e| &e.name == name) {
                files.push(name.clone());
            }
        }
        Ok(files)
    }

    /// Walk the working tree and return all files (excluding .codetree/ and hidden dirs).
    pub(super) fn walk_working_tree(&self, dir: &Path) -> Result<Vec<PathBuf>> {
        let mut files = Vec::new();
        self.walk_dir_recursive(dir, &mut files)?;
        Ok(files)
    }

    fn walk_dir_recursive(&self, dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            // Skip .codetree, .git, target, node_modules
            if name_str == ".codetree" || name_str == ".git" || name_str == "target" || name_str == "node_modules" {
                continue;
            }

            let file_type = entry.file_type()?;
            if file_type.is_dir() {
                self.walk_dir_recursive(&path, files)?;
            } else if file_type.is_file() {
                files.push(path);
            }
        }
        Ok(())
    }

    /// Restore working tree to match a commit's tree.
    pub fn restore_working_tree_pub(&self, commit_id: &str) -> Result<()> {
        self.restore_working_tree(commit_id)
    }

    /// Restore working tree to match a commit's tree.
    ///
    /// Files whose content already matches the target tree are not rewritten:
    /// first via the index stat cache (no read at all), then by hashing the
    /// existing file (read but no blob read + write).
    pub(super) fn restore_working_tree(&self, commit_id: &str) -> Result<()> {
        let tree = self.commit_tree(commit_id)?;

        // Collect existing files in working tree (excluding .codetree/)
        let existing = self.walk_working_tree(&self.repo_path)?;
        let existing_set: std::collections::HashSet<String> = existing
            .iter()
            .map(|p| {
                p.strip_prefix(&self.repo_path)
                    .unwrap_or(p)
                    .to_string_lossy()
                    .to_string()
            })
            .collect();

        // Write all files from the tree
        let tree_set: std::collections::HashSet<String> = tree
            .entries
            .iter()
            .map(|e| e.name.clone())
            .collect();

        let index = self.repo.load_index()?;

        for entry in &tree.entries {
            let file_path = self.repo_path.join(&entry.name);

            // Fast path 1: index stat cache proves the file matches the target.
            let mut matches = false;
            if let Some(ie) = index.entry(&entry.name)
                && ie.blob_id == entry.id
                && let Ok(meta) = std::fs::metadata(&file_path)
            {
                let (secs, nanos, size, ino) = stat_fingerprint(&meta);
                matches = ie.matches_stat(secs, nanos, size, ino);
            }
            // Fast path 2: existing content already hashes to the target blob.
            if !matches
                && let Ok(content) = std::fs::read(&file_path)
            {
                let id = hash_object(ObjectType::Blob, &content);
                matches = id == entry.id;
            }
            if matches {
                continue;
            }

            let blob = self.repo.read_blob(&entry.id)?;
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&file_path, &blob.content)?;
        }

        // Remove files that exist in working tree but not in the tree
        for file in &existing_set {
            if !tree_set.contains(file) {
                let path = self.repo_path.join(file);
                let _ = std::fs::remove_file(&path);
            }
        }

        Ok(())
    }

    /// Sync the index to match HEAD.
    pub(super) fn sync_index_to_head(&self) -> Result<()> {
        let tree = self.head_tree()?;
        let mut index = self.repo.load_index()?;
        index.clear();
        for entry in &tree.entries {
            index.add(&entry.name, &entry.id);
        }
        index.save()?;
        Ok(())
    }

    /// Sync the index to match a specific commit's tree.
    pub fn sync_index_to_commit(&self, commit_id: &str) -> Result<()> {
        let tree = self.commit_tree(commit_id)?;
        let mut index = self.repo.load_index()?;
        index.clear();
        for entry in &tree.entries {
            index.add(&entry.name, &entry.id);
        }
        index.save()?;
        Ok(())
    }

}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolution::{PendingResolution, ResolutionCache};
    use tempfile::TempDir;

    fn setup_repo() -> (TempDir, VcsManager) {
        let tmp = TempDir::new().unwrap();
        let mgr = VcsManager::init_at(tmp.path()).unwrap();
        (tmp, mgr)
    }

    #[tokio::test]
    async fn test_create_and_checkout_branch() {
        let (tmp, mgr) = setup_repo();

        // Write a file and commit
        std::fs::write(tmp.path().join("file.txt"), "hello").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Add file.txt").await.unwrap();

        // Create a branch
        mgr.create_branch("feature", Some("main")).await.unwrap();
        assert!(mgr.branch_exists("feature"));

        // Checkout the branch
        mgr.checkout_branch("feature").await.unwrap();
        let current = mgr.get_current_branch().await.unwrap();
        assert_eq!(current, "feature");
    }

    #[tokio::test]
    async fn test_status() {
        let (tmp, mgr) = setup_repo();

        // Write a file and commit
        std::fs::write(tmp.path().join("file.txt"), "hello").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Add file.txt").await.unwrap();

        // Modify the file
        std::fs::write(tmp.path().join("file.txt"), "hello world").unwrap();
        // Add untracked file
        std::fs::write(tmp.path().join("new.txt"), "new").unwrap();

        let status = mgr.get_status().await.unwrap();
        assert!(status.modified.contains(&"file.txt".to_string()));
        assert!(status.untracked.contains(&"new.txt".to_string()));
    }

    #[tokio::test]
    async fn test_commit_history() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("First").await.unwrap();

        std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Second").await.unwrap();

        let history = mgr.get_commit_history("main", 10).unwrap();
        assert_eq!(history.len(), 3); // init + first + second
        assert_eq!(history[0].message, "Second");
        assert_eq!(history[1].message, "First");
    }

    #[tokio::test]
    async fn test_merge_no_conflicts() {
        let (tmp, mgr) = setup_repo();

        // Create initial content
        std::fs::write(tmp.path().join("base.txt"), "base").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Base commit").await.unwrap();

        // Create a feature branch with a new file
        mgr.create_branch("feature", Some("main")).await.unwrap();
        mgr.checkout_branch("feature").await.unwrap();
        std::fs::write(tmp.path().join("feature.txt"), "feature").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Feature commit").await.unwrap();

        // Switch back to main and add a different file
        mgr.checkout_branch("main").await.unwrap();
        std::fs::write(tmp.path().join("main.txt"), "main").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Main commit").await.unwrap();

        // Merge feature into main
        let mut cache = ResolutionCache::default();
        let result = mgr.merge_branch_with_cache("feature", &mut cache).await.unwrap();
        assert!(!result.resolved_from_cache);
        assert!(result.conflicts.is_empty());

        // Verify both files exist
        assert!(tmp.path().join("feature.txt").exists());
        assert!(tmp.path().join("main.txt").exists());
    }

    #[tokio::test]
    async fn test_merge_with_conflict() {
        let (tmp, mgr) = setup_repo();

        // Create initial content
        std::fs::write(tmp.path().join("file.txt"), "base").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Base commit").await.unwrap();

        // Create a feature branch that modifies the file
        mgr.create_branch("feature", Some("main")).await.unwrap();
        mgr.checkout_branch("feature").await.unwrap();
        std::fs::write(tmp.path().join("file.txt"), "feature version").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Feature change").await.unwrap();

        // Switch back to main and modify the same file differently
        mgr.checkout_branch("main").await.unwrap();
        std::fs::write(tmp.path().join("file.txt"), "main version").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Main change").await.unwrap();

        // Merge commits with first-class conflicts (jj-style): no abort.
        let mut cache = ResolutionCache::default();
        let result = mgr.merge_branch_with_cache("feature", &mut cache).await.unwrap();
        assert!(!result.resolved_from_cache);
        assert_eq!(result.conflicts.len(), 1);
        assert_eq!(result.conflicts[0].path, "file.txt");

        // Pending resolution sidecar should be recorded.
        let pending = PendingResolution::load(&mgr.pending_resolution_path())
            .await
            .unwrap()
            .expect("pending resolution should be written");
        assert_eq!(pending.branch, "feature");
        assert_eq!(pending.conflicts.len(), 1);

        // The merge commit should have two parents.
        let head = mgr.repo.refs().resolve_head().unwrap().unwrap();
        let head_commit = mgr.repo.read_commit(&head).unwrap();
        assert_eq!(head_commit.parents.len(), 2);

        // Working tree should hold "our" side of the conflict.
        let content = std::fs::read_to_string(tmp.path().join("file.txt")).unwrap();
        assert_eq!(content, "main version");
    }

    #[tokio::test]
    async fn test_amend_commit() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
        mgr.add_all().await.unwrap();
        let first_hash = mgr.commit("First").await.unwrap();

        // Add more content and amend
        std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
        mgr.add_all().await.unwrap();
        let amended_hash = mgr.amend_commit().await.unwrap();

        // Hashes should differ
        assert_ne!(first_hash, amended_hash);

        // Should still have 2 commits (init + amended)
        let history = mgr.get_commit_history("main", 10).unwrap();
        assert_eq!(history.len(), 2);
        assert_eq!(history[0].message, "First");
    }

    #[tokio::test]
    async fn test_reset_soft_parent() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("First").await.unwrap();

        std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Second").await.unwrap();

        // Reset soft
        mgr.reset_soft_parent().await.unwrap();

        // Should have 2 commits now (init + first)
        let history = mgr.get_commit_history("main", 10).unwrap();
        assert_eq!(history.len(), 2);
        assert_eq!(history[0].message, "First");
    }

    #[tokio::test]
    async fn test_divergence() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("base.txt"), "base").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Base").await.unwrap();

        // Create feature branch with a commit
        mgr.create_branch("feature", Some("main")).await.unwrap();
        mgr.checkout_branch("feature").await.unwrap();
        std::fs::write(tmp.path().join("feat.txt"), "feat").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Feature").await.unwrap();

        // Main also gets a commit
        mgr.checkout_branch("main").await.unwrap();
        std::fs::write(tmp.path().join("main.txt"), "main").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Main update").await.unwrap();

        let (ahead, behind) = mgr.get_branch_divergence("feature", "main").unwrap();
        assert_eq!(ahead, 1); // feature has 1 commit ahead of merge base
        assert_eq!(behind, 1); // feature is 1 commit behind main
    }

    #[tokio::test]
    async fn test_delete_branch() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("file.txt"), "content").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Initial").await.unwrap();

        mgr.create_branch("feature", Some("main")).await.unwrap();
        assert!(mgr.branch_exists("feature"));

        mgr.delete_branch("feature", false).await.unwrap();
        assert!(!mgr.branch_exists("feature"));
    }

    #[tokio::test]
    async fn test_rebase() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("base.txt"), "base").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Base").await.unwrap();

        // Create feature branch with a commit
        mgr.create_branch("feature", Some("main")).await.unwrap();
        mgr.checkout_branch("feature").await.unwrap();
        std::fs::write(tmp.path().join("feat.txt"), "feat").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Feature").await.unwrap();

        // Main gets a new commit
        mgr.checkout_branch("main").await.unwrap();
        std::fs::write(tmp.path().join("main.txt"), "main").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Main update").await.unwrap();

        // Rebase feature onto main
        mgr.rebase_branch("feature", "main").await.unwrap();

        // Feature should now be ahead of main by 1, behind by 0
        let (ahead, behind) = mgr.get_branch_divergence("feature", "main").unwrap();
        assert_eq!(ahead, 1);
        assert_eq!(behind, 0);
    }

    #[tokio::test]
    async fn test_get_diff() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("file.txt"), "line1\n").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Add file").await.unwrap();

        // Modify the file
        std::fs::write(tmp.path().join("file.txt"), "line1\nline2\n").unwrap();

        let diff = mgr.get_diff().unwrap();
        assert!(diff.contains("diff --git"));
        assert!(diff.contains("+line2"));
    }

    #[tokio::test]
    async fn test_worktree() {
        let (tmp, mgr) = setup_repo();

        std::fs::write(tmp.path().join("file.txt"), "content").unwrap();
        mgr.add_all().await.unwrap();
        mgr.commit("Initial").await.unwrap();

        let wt_path = tmp.path().join(".codetree").join("worktrees").join("feature");
        mgr.add_worktree_new_branch("feature", &wt_path, "main").await.unwrap();

        assert!(wt_path.exists());
        assert!(wt_path.join("file.txt").exists());

        let worktrees = mgr.list_worktrees().await.unwrap();
        assert!(!worktrees.is_empty());

        mgr.remove_worktree(&wt_path).await.unwrap();
        assert!(!wt_path.exists());
    }
}