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
//! Read-only exploration: diffs, logs, blame, search, forks, verify, gc,
//! and working-tree cleanup on VcsManager.

use crate::error::{Context, Result};
use super::objects::{Blob, Tree, TreeEntry};
use super::manager::{CommitInfo, VcsManager};

impl VcsManager {
    /// Get unified diff of a branch against HEAD.
    pub fn get_branch_diff(&self, branch_name: &str) -> Result<String> {
        let branch_commit_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        let branch_tree = self.commit_tree(&branch_commit_id)?;
        let head_tree = self.head_tree().unwrap_or(Tree::new(vec![]));

        let diff = self.diff_trees(&head_tree, &branch_tree);
        Ok(diff)
    }

    /// Get unified diff of working tree changes against HEAD.
    pub fn get_diff(&self) -> Result<String> {
        let head_tree = self.head_tree().unwrap_or(Tree::new(vec![]));
        let wt_files = self.walk_working_tree(&self.repo_path)?;

        let mut wt_entries: std::collections::HashMap<String, Vec<u8>> = std::collections::HashMap::new();
        for path in &wt_files {
            let rel = path.strip_prefix(&self.repo_path).unwrap_or(path);
            let rel_str = rel.to_string_lossy().to_string();
            if let Ok(content) = std::fs::read(path) {
                wt_entries.insert(rel_str, content);
            }
        }

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

        // Added / modified files
        for (path, content) in &wt_entries {
            let blob = Blob::new(content.clone());
            if let Some(head_blob_id) = head_set.get(path) {
                if &blob.id() != *head_blob_id {
                    diff.push_str(&format!("diff --git a/{} b/{}\n", path, path));
                    let old_content = self.repo.read_blob(head_blob_id)?.content;
                    diff.push_str(&self.unified_diff(path, &old_content, content));
                }
            } else {
                diff.push_str(&format!("diff --git a/{} b/{}\n", path, path));
                diff.push_str("new file\n");
                diff.push_str(&self.unified_diff(path, &[], content));
            }
        }

        // Deleted files
        for (name, blob_id) in &head_set {
            if !wt_entries.contains_key(*name) {
                diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
                diff.push_str("deleted file\n");
                let old_content = self.repo.read_blob(blob_id)?.content;
                diff.push_str(&self.unified_diff(name, &old_content, &[]));
            }
        }

        Ok(diff)
    }

    // ── Commit history ─────────────────────────────────────────────

    /// Get commit history for a branch (limited to `limit` entries).
    pub fn get_commit_history(&self, branch_name: &str, limit: usize) -> Result<Vec<CommitInfo>> {
        let mut commit_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        let mut commits = Vec::new();
        for _ in 0..limit {
            let commit = self.repo.read_commit(&commit_id)?;
            let files = self.commit_files(&commit_id)?;
            commits.push(CommitInfo {
                hash: commit_id.clone(),
                message: commit.message.clone(),
                author: commit.author.clone(),
                timestamp: commit.timestamp as i64,
                files_changed: files,
            });
            if commit.parents.is_empty() {
                break;
            }
            commit_id = commit.parents[0].clone();
        }
        Ok(commits)
    }

    /// Get commits between a branch and a base (exclusive of base).
    pub fn get_commits_between(&self, branch_name: &str, base_branch: &str) -> Result<Vec<CommitInfo>> {
        let branch_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;
        let base_id = self
            .repo
            .refs()
            .get_branch(base_branch)?
            .with_context(|| format!("Base branch '{}' not found", base_branch))?;

        // Walk branch commits until we reach base_id
        let mut commits = Vec::new();
        let mut current = branch_id.clone();
        while current != base_id {
            let commit = self.repo.read_commit(&current)?;
            let files = self.commit_files(&current)?;
            commits.push(CommitInfo {
                hash: current.clone(),
                message: commit.message.clone(),
                author: commit.author.clone(),
                timestamp: commit.timestamp as i64,
                files_changed: files,
            });
            if commit.parents.is_empty() {
                break;
            }
            current = commit.parents[0].clone();
        }
        Ok(commits)
    }

    // ── Divergence / ancestry ──────────────────────────────────────

    /// Produce a simple unified diff between two byte contents.
    fn unified_diff(&self, path: &str, old: &[u8], new: &[u8]) -> String {
        let old_text = String::from_utf8_lossy(old);
        let new_text = String::from_utf8_lossy(new);
        let old_lines: Vec<&str> = old_text.lines().collect();
        let new_lines: Vec<&str> = new_text.lines().collect();

        let mut diff = String::new();
        diff.push_str(&format!("--- a/{}\n", path));
        diff.push_str(&format!("+++ b/{}\n", path));

        // Simple line-by-line diff (not a full LCS, but sufficient for display)
        let max_len = old_lines.len().max(new_lines.len());
        for i in 0..max_len {
            let old_line = old_lines.get(i);
            let new_line = new_lines.get(i);
            match (old_line, new_line) {
                (Some(o), Some(n)) if o == n => {
                    diff.push_str(&format!(" {}\n", o));
                }
                (Some(o), Some(n)) => {
                    diff.push_str(&format!("-{}\n", o));
                    diff.push_str(&format!("+{}\n", n));
                }
                (Some(o), None) => {
                    diff.push_str(&format!("-{}\n", o));
                }
                (None, Some(n)) => {
                    diff.push_str(&format!("+{}\n", n));
                }
                (None, None) => {}
            }
        }
        diff
    }

    /// Show a commit's diff (what changed in that commit vs its parent).
    /// Returns the unified diff text.
    pub fn show_commit_diff(&self, commit_id: &str) -> Result<String> {
        let commit = self.repo.read_commit(&commit_id.to_string())?;
        let new_tree = self.repo.read_tree(&commit.tree)?;
        let old_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![])
        };
        Ok(self.diff_trees(&old_tree, &new_tree))
    }

    /// Show the diff between two arbitrary commits (jj interdiff).
    /// Returns the unified diff text.
    pub fn interdiff(&self, commit_a: &str, commit_b: &str) -> Result<String> {
        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let a_id = self.resolve_commit_pub(commit_a, &head_id)?;
        let b_id = self.resolve_commit_pub(commit_b, &head_id)?;
        let a_commit = self.repo.read_commit(&a_id)?;
        let b_commit = self.repo.read_commit(&b_id)?;
        let a_tree = self.repo.read_tree(&a_commit.tree)?;
        let b_tree = self.repo.read_tree(&b_commit.tree)?;
        Ok(self.diff_trees(&a_tree, &b_tree))
    }

    /// Show diff between working tree and HEAD (or a specified commit).
    /// Returns the unified diff text.
    pub fn diff_working_tree(&self, commit_id: Option<&str>) -> Result<String> {
        let base_tree = if let Some(id) = commit_id {
            let commit = self.repo.read_commit(&id.to_string())?;
            self.repo.read_tree(&commit.tree)?
        } else {
            self.head_tree()?
        };

        let base_map: std::collections::HashMap<String, String> = base_tree
            .entries.iter().map(|e| (e.name.clone(), e.id.clone())).collect();

        let wt_files = self.walk_working_tree(&self.repo_path)?;
        let mut wt_entries: Vec<TreeEntry> = Vec::new();
        for file in &wt_files {
            let relative = file.strip_prefix(&self.repo_path).unwrap_or(file);
            let relative_str = relative.to_string_lossy().to_string();
            let content = std::fs::read(file)?;
            let blob_id = self.repo.write_blob(&content)?;
            wt_entries.push(TreeEntry { mode: 0o100644, name: relative_str, id: blob_id });
        }
        // Include deleted files (in base but not in working tree).
        let wt_names: std::collections::HashSet<&str> =
            wt_entries.iter().map(|e| e.name.as_str()).collect();
        for name in base_map.keys() {
            if !wt_names.contains(name.as_str()) {
                // File was deleted — don't add to wt_entries (diff will show deletion)
            }
        }

        let wt_tree = Tree::new(wt_entries);
        Ok(self.diff_trees(&base_tree, &wt_tree))
    }

    /// Search file contents in HEAD's tree for a pattern. Returns
    /// (file_path, line_number, line_content) for each match.
    pub fn file_search(&self, pattern: &str) -> Result<Vec<(String, usize, String)>> {
        let tree = self.head_tree()?;
        let mut results = Vec::new();
        let pattern_lower = pattern.to_lowercase();

        for entry in &tree.entries {
            if let Ok(blob) = self.repo.read_blob(&entry.id) {
                let content = String::from_utf8_lossy(&blob.content);
                for (i, line) in content.lines().enumerate() {
                    if line.to_lowercase().contains(&pattern_lower) {
                        results.push((entry.name.clone(), i + 1, line.to_string()));
                    }
                }
            }
        }

        Ok(results)
    }

    /// Search file names in HEAD's tree for a pattern. Returns matching file paths.
    pub fn file_search_names(&self, pattern: &str) -> Result<Vec<String>> {
        let tree = self.head_tree()?;
        let pattern_lower = pattern.to_lowercase();
        Ok(tree.entries.iter()
            .filter(|e| e.name.to_lowercase().contains(&pattern_lower))
            .map(|e| e.name.clone())
            .collect())
    }

    /// Find fork points: commits with multiple children across all branches.
    pub fn forks(&self) -> Result<Vec<(String, String)>> {
        let branches = self.repo.refs().list_branches()?;
        let mut child_count: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
        let mut commit_msgs: std::collections::HashMap<String, String> = std::collections::HashMap::new();

        for branch in &branches {
            if let Some(tip) = self.repo.refs().get_branch(branch)? {
                let mut current = tip;
                loop {
                    let commit = self.repo.read_commit(&current)?;
                    commit_msgs.entry(current.clone()).or_insert_with(|| commit.message.lines().next().unwrap_or("").to_string());
                    if commit.parents.is_empty() {
                        break;
                    }
                    let parent = &commit.parents[0];
                    *child_count.entry(parent.clone()).or_insert(0) += 1;
                    commit_msgs.entry(parent.clone()).or_insert_with(|| {
                        self.repo.read_commit(parent).ok()
                            .and_then(|c| c.message.lines().next().map(|s| s.to_string()))
                            .unwrap_or_default()
                    });
                    current = parent.clone();
                }
            }
        }

        let mut forks: Vec<(String, String)> = child_count.iter()
            .filter(|&(_, &count)| count > 1)
            .map(|(hash, _)| (hash.clone(), commit_msgs.get(hash).cloned().unwrap_or_default()))
            .collect();
        forks.sort();
        Ok(forks)
    }

    /// Find the merge point (common ancestor) of two commits.
    pub fn merge_point(&self, commit_a: &str, commit_b: &str) -> Result<Option<String>> {
        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let a_id = self.resolve_commit_pub(commit_a, &head_id)?;
        let b_id = self.resolve_commit_pub(commit_b, &head_id)?;

        // Collect all ancestors of A.
        let mut ancestors_a: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut current = a_id.clone();
        loop {
            ancestors_a.insert(current.clone());
            let commit = self.repo.read_commit(&current)?;
            if commit.parents.is_empty() {
                break;
            }
            current = commit.parents[0].clone();
        }

        // Walk B's ancestors and find the first one in A's set.
        let mut current = b_id.clone();
        loop {
            if ancestors_a.contains(&current) {
                return Ok(Some(current));
            }
            let commit = self.repo.read_commit(&current)?;
            if commit.parents.is_empty() {
                break;
            }
            current = commit.parents[0].clone();
        }

        Ok(None)
    }

    /// Verify a commit's integrity: check that its hash matches, tree exists,
    /// and parent commits exist.
    pub fn verify_commit(&self, commit_spec: &str) -> Result<Vec<String>> {
        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let commit_id = self.resolve_commit_pub(commit_spec, &head_id)?;
        let mut issues = Vec::new();

        // Check commit exists.
        let commit = match self.repo.read_commit(&commit_id) {
            Ok(c) => c,
            Err(_) => {
                issues.push(format!("Commit {} not found in object store", commit_spec));
                return Ok(issues);
            }
        };

        // Check tree exists.
        if self.repo.read_tree(&commit.tree).is_err() {
            issues.push(format!("Tree {} not found for commit {}", commit.tree, commit_spec));
        }

        // Check parents exist.
        for (i, parent) in commit.parents.iter().enumerate() {
            if self.repo.read_commit(parent).is_err() {
                issues.push(format!("Parent {} ({}) not found for commit {}", i, parent, commit_spec));
            }
        }

        // Check tree entries have valid blobs.
        if let Ok(tree) = self.repo.read_tree(&commit.tree) {
            for entry in &tree.entries {
                if self.repo.read_blob(&entry.id).is_err() {
                    issues.push(format!("Blob {} not found for file '{}' in commit {}", entry.id, entry.name, commit_spec));
                }
            }
        }

        Ok(issues)
    }

    /// Run a command across each commit in a range (from HEAD~N to HEAD).
    /// Returns (commit_hash, success) for each commit.
    pub async fn run_across_commits(&self, from_spec: &str, command: &[String]) -> Result<Vec<(String, bool)>> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let from_spec = from_spec.to_string();
        let command = command.to_vec();
        tokio::task::spawn_blocking(move || -> Result<Vec<(String, bool)>> {
            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 from_id = mgr.resolve_commit(&from_spec, &head_id)?;

            // Collect commits from HEAD to from (inclusive).
            let mut commits: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                commits.push(current.clone());
                if current == from_id {
                    break;
                }
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    break;
                }
                current = commit.parents[0].clone();
            }
            commits.reverse(); // oldest first

            let mut results = Vec::new();
            for commit_hash in &commits {
                // Restore working tree to this commit.
                mgr.sync_index_to_commit(commit_hash)?;
                mgr.restore_working_tree_pub(commit_hash)?;

                // Run the command.
                if command.is_empty() {
                    results.push((commit_hash.clone(), false));
                    continue;
                }
                let status = std::process::Command::new(&command[0])
                    .args(&command[1..])
                    .current_dir(&repo_path)
                    .status();
                let success = status.map(|s| s.success()).unwrap_or(false);
                results.push((commit_hash.clone(), success));
            }

            // Restore original HEAD.
            mgr.sync_index_to_commit(&head_id)?;
            mgr.restore_working_tree_pub(&head_id)?;

            Ok(results)
        })
        .await?
    }

    /// List all files in a commit's tree (default: HEAD).
    pub fn file_list(&self, commit_spec: Option<&str>) -> Result<Vec<String>> {
        let tree = if let Some(spec) = commit_spec {
            let head_id = self.repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let commit_id = self.resolve_commit_pub(spec, &head_id)?;
            let commit = self.repo.read_commit(&commit_id)?;
            self.repo.read_tree(&commit.tree)?
        } else {
            self.head_tree()?
        };

        Ok(tree.entries.iter().map(|e| e.name.clone()).collect())
    }

    /// List all branch heads (branch name + commit hash).
    pub fn heads(&self) -> Result<Vec<(String, String)>> {
        let branches = self.repo.refs().list_branches()?;
        let mut result = Vec::new();
        for branch in &branches {
            if let Some(commit_id) = self.repo.refs().get_branch(branch)? {
                result.push((branch.clone(), commit_id));
            }
        }
        Ok(result)
    }

    /// Show the commit history for a specific file. Returns a list of
    /// (commit_hash, timestamp, message_first_line) entries, newest first.
    pub fn file_log(&self, file_path: &str) -> Result<Vec<(String, u64, String)>> {
        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;

        let mut results = Vec::new();
        let mut current = head_id;
        let mut prev_blob: Option<String> = None;

        loop {
            let commit = self.repo.read_commit(&current)?;
            let tree = self.repo.read_tree(&commit.tree)?;
            let current_blob = tree.entries.iter()
                .find(|e| e.name == file_path)
                .map(|e| e.id.clone());

            // If the blob changed (or file was added/removed), this commit touched the file.
            if current_blob != prev_blob {
                let first_line = commit.message.lines().next().unwrap_or("").to_string();
                results.push((current.clone(), commit.timestamp, first_line));
                prev_blob = current_blob;
            }

            if commit.parents.is_empty() {
                break;
            }
            current = commit.parents[0].clone();
        }

        Ok(results)
    }

    /// Annotate a file: for each line, find the commit that last introduced it.
    /// Returns a list of (line_number, commit_hash_short, line_content).
    pub fn blame(&self, file_path: &str) -> Result<Vec<(usize, String, String)>> {
        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;

        // Get the current file content from HEAD.
        let head_commit = self.repo.read_commit(&head_id)?;
        let head_tree = self.repo.read_tree(&head_commit.tree)?;
        let blob_id = head_tree.entries.iter()
            .find(|e| e.name == file_path)
            .map(|e| e.id.clone())
            .context(format!("File '{}' not found in HEAD", file_path))?;

        let content = self.repo.read_blob(&blob_id)?.content;
        let text = String::from_utf8_lossy(&content);
        let lines: Vec<&str> = text.lines().collect();

        // Walk back through commits to find when each line was introduced.
        // For each line, find the oldest commit where the line exists at the same position.
        // Simplified: track which commit last changed each line by walking backwards.
        let mut line_commits: Vec<String> = vec![head_id.clone(); lines.len()];
        let mut current = head_id.clone();
        let mut prev_lines: Option<Vec<String>> = None;

        loop {
            let commit = self.repo.read_commit(&current)?;
            let tree = self.repo.read_tree(&commit.tree)?;
            let current_blob = tree.entries.iter()
                .find(|e| e.name == file_path)
                .map(|e| e.id.clone());

            if let Some(blob_id) = &current_blob {
                let c = self.repo.read_blob(blob_id)?.content;
                let c_text = String::from_utf8_lossy(&c);
                let c_lines: Vec<String> = c_text.lines().map(|s| s.to_string()).collect();

                if let Some(ref prev) = prev_lines {
                    // Compare: if a line changed, mark it with this commit.
                    for (i, line) in c_lines.iter().enumerate() {
                        if i < line_commits.len()
                            && prev.get(i).map(|s| s.as_str()) != Some(line.as_str())
                        {
                            line_commits[i] = current.clone();
                        }
                    }
                }
                prev_lines = Some(c_lines);
            } else {
                prev_lines = None;
            }

            if commit.parents.is_empty() {
                break;
            }
            current = commit.parents[0].clone();
        }

        let mut result = Vec::new();
        for (i, line) in lines.iter().enumerate() {
            let short = &line_commits[i][..7.min(line_commits[i].len())];
            result.push((i + 1, short.to_string(), line.to_string()));
        }

        Ok(result)
    }

    /// Remove untracked files from the working tree (except .codetree/).
    /// Returns the list of removed file paths.
    pub fn clean(&self) -> Result<Vec<String>> {
        let head_tree = self.head_tree()?;
        let tracked: std::collections::HashSet<String> = head_tree
            .entries.iter().map(|e| e.name.clone()).collect();

        let wt_files = self.walk_working_tree(&self.repo_path)?;
        let mut removed = Vec::new();
        for file in &wt_files {
            let relative = file.strip_prefix(&self.repo_path).unwrap_or(file);
            let relative_str = relative.to_string_lossy().to_string();
            if !tracked.contains(&relative_str) {
                std::fs::remove_file(file)?;
                removed.push(relative_str);
            }
        }
        Ok(removed)
    }

    /// Garbage collect unreachable objects. Removes objects not reachable
    /// from any branch ref. Returns the count of removed objects.
    pub fn gc(&self) -> Result<usize> {
        // Collect all reachable commit hashes from all branches.
        let branches = self.repo.refs().list_branches()?;
        let mut reachable: std::collections::HashSet<String> = std::collections::HashSet::new();

        for branch in &branches {
            if let Ok(Some(commit_id)) = self.repo.refs().get_branch(branch) {
                let mut current = commit_id;
                loop {
                    if reachable.contains(&current) {
                        break;
                    }
                    reachable.insert(current.clone());
                    let commit = match self.repo.read_commit(&current) {
                        Ok(c) => c,
                        Err(_) => break,
                    };
                    // Also mark the tree and blobs as reachable.
                    reachable.insert(commit.tree.clone());
                    if let Ok(tree) = self.repo.read_tree(&commit.tree) {
                        for entry in &tree.entries {
                            reachable.insert(entry.id.clone());
                        }
                    }
                    if commit.parents.is_empty() {
                        break;
                    }
                    current = commit.parents[0].clone();
                }
            }
        }

        // Walk the object store and remove unreachable objects.
        let objects_dir = self.repo.root().join("objects");
        let mut removed = 0;
        if !objects_dir.exists() {
            return Ok(0);
        }
        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 !reachable.contains(&hash) {
                    std::fs::remove_file(file_entry.path())?;
                    removed += 1;
                }
            }
        }
        Ok(removed)
    }

    /// Diff two trees and return unified diff text.
    fn diff_trees(&self, old: &Tree, new: &Tree) -> String {
        let old_map: std::collections::HashMap<&String, &String> = old
            .entries
            .iter()
            .map(|e| (&e.name, &e.id))
            .collect();
        let new_map: std::collections::HashMap<&String, &String> = new
            .entries
            .iter()
            .map(|e| (&e.name, &e.id))
            .collect();

        let all_names: std::collections::BTreeSet<&String> = old_map.keys().chain(new_map.keys()).copied().collect();

        let mut diff = String::new();
        for name in all_names {
            let old_blob = old_map.get(name);
            let new_blob = new_map.get(name);
            match (old_blob, new_blob) {
                (Some(o), Some(n)) if o == n => continue,
                (Some(o), Some(n)) => {
                    diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
                    let old_content = self.repo.read_blob(o).map(|b| b.content).unwrap_or_default();
                    let new_content = self.repo.read_blob(n).map(|b| b.content).unwrap_or_default();
                    diff.push_str(&self.unified_diff(name, &old_content, &new_content));
                }
                (None, Some(n)) => {
                    diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
                    diff.push_str("new file\n");
                    let new_content = self.repo.read_blob(n).map(|b| b.content).unwrap_or_default();
                    diff.push_str(&self.unified_diff(name, &[], &new_content));
                }
                (Some(o), None) => {
                    diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
                    diff.push_str("deleted file\n");
                    let old_content = self.repo.read_blob(o).map(|b| b.content).unwrap_or_default();
                    diff.push_str(&self.unified_diff(name, &old_content, &[]));
                }
                (None, None) => {}
            }
        }
        diff
    }
}