codetree 0.1.1

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
//! Merge engine: three-way merge, merge-base discovery, cached merges,
//! readiness checks, rebase, and speculative merge on VcsManager.

use crate::error::{Context, Result};
use crate::resolution::{ConflictInfo, PendingResolution, ResolutionCache};
use super::objects::{Tree, TreeEntry, Commit};
use super::manager::{MergeResult, ReadyCheck, VcsManager};

impl VcsManager {
    /// Get (ahead, behind) counts between a branch and base.
    pub fn get_branch_divergence(&self, branch_name: &str, base_branch: &str) -> Result<(usize, usize)> {
        let branch_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .unwrap_or_default();
        let base_id = self
            .repo
            .refs()
            .get_branch(base_branch)?
            .unwrap_or_default();

        if branch_id.is_empty() || base_id.is_empty() {
            return Ok((0, 0));
        }

        let merge_base = self.find_merge_base(&branch_id, &base_id)?;

        // ahead = commits from branch to merge_base (exclusive)
        let ahead = self.count_commits_to(&branch_id, &merge_base)?;
        // behind = commits from base to merge_base (exclusive)
        let behind = self.count_commits_to(&base_id, &merge_base)?;

        Ok((ahead, behind))
    }

    /// Check if a branch is behind its base (base has commits not in branch).
    pub fn is_branch_behind(&self, branch_name: &str, base_branch: &str) -> Result<bool> {
        let (_, behind) = self.get_branch_divergence(branch_name, base_branch)?;
        Ok(behind > 0)
    }

    /// Determine the parent branch of a given branch.
    pub fn get_branch_parent(
        &self,
        branch_name: &str,
        base_branch: &str,
        candidate_parents: &[String],
    ) -> Result<String> {
        let branch_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        // Check each candidate: if merge_base(branch, candidate) == candidate's tip, branch is stacked on it
        for parent_name in candidate_parents {
            if parent_name == branch_name || parent_name == base_branch {
                continue;
            }
            if let Ok(Some(parent_id)) = self.repo.refs().get_branch(parent_name)
                && let Ok(mb) = self.find_merge_base(&branch_id, &parent_id)
                && mb == parent_id
            {
                return Ok(parent_name.clone());
            }
        }

        Ok(base_branch.to_string())
    }

    // ── Merge ──────────────────────────────────────────────────────

    /// Check if a branch is ready to merge into its base (read-only).
    /// Returns a `ReadyCheck` with: ahead/behind counts, conflict count,
    /// and whether conflicts would be auto-resolved from the cache.
    pub async fn check_ready(&self, branch_name: &str, base_branch: &str) -> Result<ReadyCheck> {
        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))?;

        let (ahead, behind) = self.get_branch_divergence(branch_name, base_branch)?;

        let merge_base = self.find_merge_base(&base_id, &branch_id)?;
        let base_tree = self.commit_tree(&merge_base)?;
        let our_tree = self.commit_tree(&base_id)?;
        let their_tree = self.commit_tree(&branch_id)?;

        let (_, conflicts) = self.merge_trees(&base_tree, &our_tree, &their_tree)?;

        let cache = ResolutionCache::load(
            &self.repo_path.join(".codetree").join("resolutions.json"),
        ).await?;

        let mut auto_resolvable = true;
        for conflict in &conflicts {
            if cache.get(&conflict.path, &conflict.our_blob, &conflict.their_blob).is_none() {
                auto_resolvable = false;
                break;
            }
        }

        Ok(ReadyCheck {
            ahead,
            behind,
            up_to_date: behind == 0,
            conflict_count: conflicts.len(),
            auto_resolvable: conflicts.is_empty() || auto_resolvable,
            conflict_files: conflicts.iter().map(|c| c.path.clone()).collect(),
        })
    }

    /// Merge a branch into the current branch (with conflict resolution cache).
    pub async fn merge_branch_with_cache(
        &self,
        branch_name: &str,
        cache: &ResolutionCache,
    ) -> Result<MergeResult> {
        let branch_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        let head_id = self
            .repo
            .refs()
            .resolve_head()?
            .context("HEAD does not point to a commit")?;

        let merge_base = self.find_merge_base(&head_id, &branch_id)?;

        let base_tree = self.commit_tree(&merge_base)?;
        let our_tree = self.commit_tree(&head_id)?;
        let their_tree = self.commit_tree(&branch_id)?;

        let (merged_entries, conflicts) = self.merge_trees(&base_tree, &our_tree, &their_tree)?;

        if !conflicts.is_empty() {
            // Try resolving from cache
            let mut resolved = true;
            let mut final_entries = merged_entries.clone();

            for conflict in &conflicts {
                if let Some(resolved_blob) = cache.get(&conflict.path, &conflict.our_blob, &conflict.their_blob) {
                    // Replace entry with resolved blob
                    final_entries.retain(|e: &TreeEntry| e.name != conflict.path);
                    final_entries.push(TreeEntry {
                        mode: 0o100644,
                        name: conflict.path.clone(),
                        id: resolved_blob.to_string(),
                    });
                } else {
                    resolved = false;
                    break;
                }
            }

            if resolved {
                let tree = Tree::new(final_entries);
                let tree_id = self.repo.write_tree(&tree)?;

                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,
                    vec![head_id.clone(), branch_id.clone()],
                    "CodeTree <agent@codetree>".to_string(),
                    format!("Merge branch '{}' (conflicts auto-resolved)", branch_name),
                    timestamp,
                );
                let commit_id = self.repo.write_commit(&commit)?;

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

                self.restore_working_tree(&commit_id)?;
                self.sync_index_to_head()?;

                return Ok(MergeResult {
                    resolved_from_cache: true,
                    conflicts,
                });
            }

            // Could not resolve from cache — commit the merge with the
            // conflicting files left at "our" side (jj-style first-class
            // conflicts). The agent edits the files and runs `codetree resolve`.
            let tree = Tree::new(merged_entries);
            let tree_id = self.repo.write_tree(&tree)?;

            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,
                vec![head_id.clone(), branch_id.clone()],
                "CodeTree <agent@codetree>".to_string(),
                format!("Merge branch '{}' ({} conflict(s) pending resolution)", branch_name, conflicts.len()),
                timestamp,
            );
            let commit_id = self.repo.write_commit(&commit)?;

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

            self.restore_working_tree(&commit_id)?;
            self.sync_index_to_head()?;

            let pending = PendingResolution {
                branch: branch_name.to_string(),
                base_branch: head_id,
                conflicts: conflicts.clone(),
            };
            pending.save(&self.pending_resolution_path()).await?;

            return Ok(MergeResult {
                resolved_from_cache: false,
                conflicts,
            });
        }

        // No conflicts — normal merge
        let tree = Tree::new(merged_entries);
        let tree_id = self.repo.write_tree(&tree)?;

        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,
            vec![head_id.clone(), branch_id.clone()],
            "CodeTree <agent@codetree>".to_string(),
            format!("Merge branch '{}'", branch_name),
            timestamp,
        );
        let commit_id = self.repo.write_commit(&commit)?;

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

        self.restore_working_tree(&commit_id)?;
        self.sync_index_to_head()?;

        Ok(MergeResult {
            resolved_from_cache: false,
            conflicts: vec![],
        })
    }

    /// Squash-merge a branch (single-parent commit).
    pub async fn squash_merge_branch_with_cache(
        &self,
        branch_name: &str,
        cache: &ResolutionCache,
    ) -> Result<MergeResult> {
        let branch_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        let head_id = self
            .repo
            .refs()
            .resolve_head()?
            .context("HEAD does not point to a commit")?;

        let merge_base = self.find_merge_base(&head_id, &branch_id)?;

        let base_tree = self.commit_tree(&merge_base)?;
        let our_tree = self.commit_tree(&head_id)?;
        let their_tree = self.commit_tree(&branch_id)?;

        let (merged_entries, conflicts) = self.merge_trees(&base_tree, &our_tree, &their_tree)?;

        if !conflicts.is_empty() {
            let mut resolved = true;
            let mut final_entries = merged_entries.clone();

            for conflict in &conflicts {
                if let Some(resolved_blob) = cache.get(&conflict.path, &conflict.our_blob, &conflict.their_blob) {
                    final_entries.retain(|e: &TreeEntry| e.name != conflict.path);
                    final_entries.push(TreeEntry {
                        mode: 0o100644,
                        name: conflict.path.clone(),
                        id: resolved_blob.to_string(),
                    });
                } else {
                    resolved = false;
                    break;
                }
            }

            if resolved {
                let tree = Tree::new(final_entries);
                let tree_id = self.repo.write_tree(&tree)?;

                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,
                    vec![head_id.clone()],
                    "CodeTree <agent@codetree>".to_string(),
                    format!("Squashed merge of branch '{}' (conflicts auto-resolved)", branch_name),
                    timestamp,
                );
                let commit_id = self.repo.write_commit(&commit)?;

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

                self.restore_working_tree(&commit_id)?;
                self.sync_index_to_head()?;

                return Ok(MergeResult {
                    resolved_from_cache: true,
                    conflicts,
                });
            }

            // Could not resolve from cache — commit the squash merge with the
            // conflicting files left at "our" side (jj-style first-class
            // conflicts). The agent edits the files and runs `codetree resolve`.
            let tree = Tree::new(merged_entries);
            let tree_id = self.repo.write_tree(&tree)?;

            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,
                vec![head_id.clone()],
                "CodeTree <agent@codetree>".to_string(),
                format!("Squashed merge of branch '{}' ({} conflict(s) pending resolution)", branch_name, conflicts.len()),
                timestamp,
            );
            let commit_id = self.repo.write_commit(&commit)?;

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

            self.restore_working_tree(&commit_id)?;
            self.sync_index_to_head()?;

            let pending = PendingResolution {
                branch: branch_name.to_string(),
                base_branch: head_id,
                conflicts: conflicts.clone(),
            };
            pending.save(&self.pending_resolution_path()).await?;

            return Ok(MergeResult {
                resolved_from_cache: false,
                conflicts,
            });
        }

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

        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,
            vec![head_id.clone()],
            "CodeTree <agent@codetree>".to_string(),
            format!("Squashed merge of branch '{}'", branch_name),
            timestamp,
        );
        let commit_id = self.repo.write_commit(&commit)?;

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

        self.restore_working_tree(&commit_id)?;
        self.sync_index_to_head()?;

        Ok(MergeResult {
            resolved_from_cache: false,
            conflicts: vec![],
        })
    }

    /// Simple merge (no cache support).
    pub async fn merge_branch(&self, branch_name: &str) -> Result<()> {
        let cache = ResolutionCache::default();
        let result = self.merge_branch_with_cache(branch_name, &cache).await?;
        if result.resolved_from_cache {
            // shouldn't happen with empty cache, but handle it
        }
        Ok(())
    }

    /// Simple squash merge (no cache support).
    pub async fn squash_merge_branch(&self, branch_name: &str) -> Result<()> {
        let cache = ResolutionCache::default();
        let _ = self.squash_merge_branch_with_cache(branch_name, &cache).await?;
        Ok(())
    }

    // ── Merge state ────────────────────────────────────────────────

    /// Check if there's a pending merge state (first-class conflicts awaiting resolution).
    pub fn is_in_merge_state(&self) -> bool {
        self.pending_resolution_path().exists()
    }

    /// Get the blob hash for a staged file.
    pub fn get_staged_blob_hash(&self, file_path: &str) -> Result<String> {
        let index = self.repo.load_index()?;
        index
            .get(file_path)
            .map(|s| s.to_string())
            .with_context(|| format!("File '{}' not found in index", file_path))
    }

    // ── Rebase ─────────────────────────────────────────────────────

    /// Rebase a branch onto a base branch.
    pub async fn rebase_branch(&self, branch_name: &str, base_branch: &str) -> Result<()> {
        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))?;

        let merge_base = self.find_merge_base(&branch_id, &base_id)?;

        // Collect commits from branch back to merge_base (exclusive)
        let mut commits_to_replay = Vec::new();
        let mut current = branch_id.clone();
        while current != merge_base {
            let commit = self.repo.read_commit(&current)?;
            let parents = commit.parents.clone();
            commits_to_replay.push(commit);
            if parents.is_empty() {
                break;
            }
            current = parents[0].clone();
        }
        commits_to_replay.reverse(); // oldest first

        // Replay commits onto base
        let mut new_parent = base_id.clone();
        for old_commit in commits_to_replay {
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let new_commit = Commit::new(
                old_commit.tree.clone(),
                vec![new_parent.clone()],
                old_commit.author.clone(),
                old_commit.message.clone(),
                timestamp,
            );
            let new_id = self.repo.write_commit(&new_commit)?;
            new_parent = new_id;
        }

        // Update branch ref to the new tip
        self.repo.refs().set_branch(branch_name, &new_parent)?;

        Ok(())
    }

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

    /// Find the merge base of two commits (lowest common ancestor).
    pub(super) fn find_merge_base(&self, a: &str, b: &str) -> Result<String> {
        // Collect all ancestors of A
        let mut ancestors_a = std::collections::HashSet::new();
        let mut stack = vec![a.to_string()];
        while let Some(id) = stack.pop() {
            if ancestors_a.contains(&id) {
                continue;
            }
            ancestors_a.insert(id.clone());
            if let Ok(commit) = self.repo.read_commit(&id) {
                for p in &commit.parents {
                    stack.push(p.clone());
                }
            }
        }

        // BFS from B — first ancestor that's in ancestors_a is the merge base
        let mut queue = vec![b.to_string()];
        let mut visited = std::collections::HashSet::new();
        while let Some(id) = queue.pop() {
            if visited.contains(&id) {
                continue;
            }
            visited.insert(id.clone());
            if ancestors_a.contains(&id) {
                return Ok(id);
            }
            if let Ok(commit) = self.repo.read_commit(&id) {
                for p in &commit.parents {
                    queue.push(p.clone());
                }
            }
        }

        // No common ancestor — return empty string (shouldn't happen with init commit)
        Ok(String::new())
    }

    /// Count commits from `start` (exclusive) back to `ancestor` (exclusive).
    fn count_commits_to(&self, start: &str, ancestor: &str) -> Result<usize> {
        if start == ancestor {
            return Ok(0);
        }
        let mut count = 0;
        let mut current = start.to_string();
        loop {
            if current == ancestor || current.is_empty() {
                break;
            }
            let commit = self.repo.read_commit(&current)?;
            count += 1;
            if commit.parents.is_empty() {
                break;
            }
            current = commit.parents[0].clone();
        }
        Ok(count)
    }

    /// Merge two trees using a base tree for 3-way merge.
    /// Returns (merged_entries, conflicts).
    pub(super) fn merge_trees(
        &self,
        base: &Tree,
        ours: &Tree,
        theirs: &Tree,
    ) -> Result<(Vec<TreeEntry>, Vec<ConflictInfo>)> {
        let base_map: std::collections::HashMap<&String, &String> = base
            .entries
            .iter()
            .map(|e| (&e.name, &e.id))
            .collect();
        let our_map: std::collections::HashMap<&String, &String> = ours
            .entries
            .iter()
            .map(|e| (&e.name, &e.id))
            .collect();
        let their_map: std::collections::HashMap<&String, &String> = theirs
            .entries
            .iter()
            .map(|e| (&e.name, &e.id))
            .collect();

        let all_names: std::collections::BTreeSet<String> = base
            .entries
            .iter()
            .chain(ours.entries.iter())
            .chain(theirs.entries.iter())
            .map(|e| e.name.clone())
            .collect();

        let mut merged = Vec::new();
        let mut conflicts = Vec::new();

        for name in &all_names {
            let base_blob = base_map.get(name);
            let our_blob = our_map.get(name);
            let their_blob = their_map.get(name);

            match (base_blob, our_blob, their_blob) {
                // Unchanged in both
                (_b, o, t) if o == t => {
                    if let Some(blob) = o {
                        merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: blob.to_string() });
                    }
                }
                // Changed only in ours
                (Some(b), Some(o), Some(t)) if b == t && o != b => {
                    merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
                }
                // Changed only in theirs
                (Some(b), Some(o), Some(t)) if b == o && t != b => {
                    merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: t.to_string() });
                }
                // Added in ours only
                (None, Some(o), None) => {
                    merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
                }
                // Added in theirs only
                (None, None, Some(t)) => {
                    merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: t.to_string() });
                }
                // Both added with same content
                (None, Some(o), Some(t)) if o == t => {
                    merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
                }
                // Deleted in theirs, unchanged in ours → delete
                (Some(b), Some(o), None) if b == o => { /* no entry = deleted */ }
                // Deleted in ours, unchanged in theirs → delete
                (Some(b), None, Some(t)) if b == t => { /* no entry = deleted */ }
                // Deleted in both → no entry
                (Some(_), None, None) => { /* no entry = deleted */ }
                // Conflict: both changed differently
                _ => {
                    conflicts.push(ConflictInfo {
                        path: name.clone(),
                        our_blob: our_blob.map(|s| s.to_string()).unwrap_or_default(),
                        their_blob: their_blob.map(|s| s.to_string()).unwrap_or_default(),
                    });
                    // Take our version as the "ours" side of the conflict
                    if let Some(o) = our_blob {
                        merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
                    }
                }
            }
        }

        Ok((merged, conflicts))
    }

    /// Speculative merge: check if merging a branch into the current branch
    /// would conflict. Returns Ok(()) if clean, or a list of conflicting files.
    pub fn speculative_merge(&self, branch_name: &str) -> Result<Vec<String>> {
        let branch_tip = self.repo.refs().get_branch(branch_name)?
            .context(format!("Branch '{}' not found", branch_name))?;

        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;

        // Find merge base.
        let merge_base = self.merge_point(&head_id, &branch_tip)?
            .context("No common ancestor found")?;

        // Try to merge trees.
        let base_tree = {
            let base_commit = self.repo.read_commit(&merge_base)?;
            self.repo.read_tree(&base_commit.tree)?
        };
        let our_tree = {
            let our_commit = self.repo.read_commit(&head_id)?;
            self.repo.read_tree(&our_commit.tree)?
        };
        let their_tree = {
            let their_commit = self.repo.read_commit(&branch_tip)?;
            self.repo.read_tree(&their_commit.tree)?
        };

        let conflicts = self.find_merge_conflicts(&base_tree, &our_tree, &their_tree);
        Ok(conflicts)
    }

    /// Find files that would conflict in a three-way merge.
    fn find_merge_conflicts(&self, base: &Tree, ours: &Tree, theirs: &Tree) -> Vec<String> {
        let base_map: std::collections::HashMap<&String, &String> = base.entries.iter()
            .map(|e| (&e.name, &e.id)).collect();
        let our_map: std::collections::HashMap<&String, &String> = ours.entries.iter()
            .map(|e| (&e.name, &e.id)).collect();
        let their_map: std::collections::HashMap<&String, &String> = theirs.entries.iter()
            .map(|e| (&e.name, &e.id)).collect();

        let all_files: std::collections::HashSet<&String> = base.entries.iter()
            .map(|e| &e.name)
            .chain(ours.entries.iter().map(|e| &e.name))
            .chain(theirs.entries.iter().map(|e| &e.name))
            .collect();

        let mut conflicts = Vec::new();
        for file in all_files {
            let base_id = base_map.get(file);
            let our_id = our_map.get(file);
            let their_id = their_map.get(file);

            // Conflict: both sides modified the same file differently.
            if our_id != their_id && our_id != base_id && their_id != base_id {
                conflicts.push(file.to_string());
            }
        }
        conflicts.sort();
        conflicts
    }

}