Skip to main content

contextgraph_core/
merge.rs

1//! `merge`: reconciling two branches representing alternative continuations.
2//!
3//! Merging conversation branches is fundamentally different from merging
4//! code: two forked branches are usually alternative continuations, not
5//! compatible edits to reconcile line-by-line. There is no automatic
6//! content merging of divergent natural-language turns here, and this
7//! module does not attempt to invent one. Instead, `merge` always creates
8//! an explicit merge commit referencing both parents for audit/lineage,
9//! and its materialized view is defined purely by parent order:
10//! `RecordOnly` puts `branch_a`'s head first (so it materializes as
11//! `branch_a`'s view, with `branch_b` linked as an alternative), and
12//! `PreferOther` puts `branch_b`'s head first instead. Both strategies are
13//! "no silent merging" — the untaken branch's content never appears in the
14//! merged view; it's only reachable by checking it out directly.
15
16use crate::commit::{Author, Commit, CommitId, Delta, MergeStrategy, Metadata};
17use crate::error::{GraphError, Result};
18use crate::store::{CommitStore, RefStore};
19use chrono::Utc;
20
21/// Merges `branch_b` into `branch_a`: creates a merge commit referencing
22/// both branches' current heads (order determined by `strategy`), advances
23/// `branch_a` to point at it, and leaves `branch_b` untouched. Fails if
24/// either branch doesn't exist, or if both heads are the same commit
25/// (nothing to merge).
26pub async fn merge<S: CommitStore + RefStore>(
27    store: &S,
28    branch_a: &str,
29    branch_b: &str,
30    strategy: MergeStrategy,
31) -> Result<CommitId> {
32    let a_head = store
33        .get_branch(branch_a)
34        .await?
35        .ok_or_else(|| GraphError::BranchNotFound(branch_a.to_string()))?;
36    let b_head = store
37        .get_branch(branch_b)
38        .await?
39        .ok_or_else(|| GraphError::BranchNotFound(branch_b.to_string()))?;
40
41    if a_head == b_head {
42        return Err(GraphError::InvalidMergeParents);
43    }
44
45    let parent_ids = match strategy {
46        MergeStrategy::RecordOnly => vec![a_head, b_head],
47        MergeStrategy::PreferOther => vec![b_head, a_head],
48    };
49
50    let commit = Commit::new(
51        parent_ids,
52        Author::System,
53        Delta::Merge { strategy },
54        Metadata::new(Utc::now()),
55    );
56    let id = store.put(commit).await?;
57    store.set_branch(branch_a, id).await?;
58    Ok(id)
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use crate::commit::Delta as D;
65    use crate::materialize::materialize;
66    use crate::mem::InMemoryGraphStore;
67    use crate::store::CommitStore;
68
69    fn text(s: &str) -> Delta {
70        D::Message {
71            content: s.to_string(),
72        }
73    }
74
75    async fn setup_diverged(store: &InMemoryGraphStore) -> (CommitId, CommitId, CommitId) {
76        let root = Commit::new(
77            vec![],
78            Author::User,
79            text("root"),
80            Metadata::new(Utc::now()),
81        );
82        let root_id = store.put(root).await.unwrap();
83        store.set_branch("a", root_id).await.unwrap();
84        store.set_branch("b", root_id).await.unwrap();
85
86        let a_turn = Commit::new(
87            vec![root_id],
88            Author::Assistant,
89            text("a-turn"),
90            Metadata::new(Utc::now()),
91        );
92        let a_id = store.put(a_turn).await.unwrap();
93        store.set_branch("a", a_id).await.unwrap();
94
95        let b_turn = Commit::new(
96            vec![root_id],
97            Author::Assistant,
98            text("b-turn"),
99            Metadata::new(Utc::now()),
100        );
101        let b_id = store.put(b_turn).await.unwrap();
102        store.set_branch("b", b_id).await.unwrap();
103
104        (root_id, a_id, b_id)
105    }
106
107    #[tokio::test]
108    async fn record_only_merge_materializes_as_branch_a_view() {
109        let store = InMemoryGraphStore::new();
110        let (root_id, a_id, b_id) = setup_diverged(&store).await;
111
112        let merge_id = merge(&store, "a", "b", MergeStrategy::RecordOnly)
113            .await
114            .unwrap();
115
116        let ctx = materialize(&store, merge_id).await.unwrap();
117        // Branch a's content ("a-turn") is present; branch b's ("b-turn") never is.
118        let texts: Vec<String> = ctx
119            .messages
120            .iter()
121            .filter_map(|m| match &m.delta {
122                D::Message { content } => Some(content.clone()),
123                _ => None,
124            })
125            .collect();
126        assert_eq!(texts, vec!["root", "a-turn"]);
127
128        // But the manifest records the merge commit's lineage, including
129        // that b's head is linked as the alternative parent.
130        assert_eq!(ctx.manifest, vec![root_id, a_id, merge_id]);
131        let merge_commit = store.get(&merge_id).await.unwrap().unwrap();
132        assert_eq!(merge_commit.parent_ids, vec![a_id, b_id]);
133    }
134
135    #[tokio::test]
136    async fn prefer_other_merge_materializes_as_branch_b_view() {
137        let store = InMemoryGraphStore::new();
138        let (_, _, b_id) = setup_diverged(&store).await;
139
140        let merge_id = merge(&store, "a", "b", MergeStrategy::PreferOther)
141            .await
142            .unwrap();
143
144        let ctx = materialize(&store, merge_id).await.unwrap();
145        let texts: Vec<String> = ctx
146            .messages
147            .iter()
148            .filter_map(|m| match &m.delta {
149                D::Message { content } => Some(content.clone()),
150                _ => None,
151            })
152            .collect();
153        assert_eq!(texts, vec!["root", "b-turn"]);
154
155        let merge_commit = store.get(&merge_id).await.unwrap().unwrap();
156        assert_eq!(
157            merge_commit.parent_ids,
158            vec![b_id, merge_commit.parent_ids[1]]
159        );
160    }
161
162    #[tokio::test]
163    async fn merge_advances_branch_a_but_leaves_branch_b_untouched() {
164        let store = InMemoryGraphStore::new();
165        let (_, a_id, b_id) = setup_diverged(&store).await;
166
167        let merge_id = merge(&store, "a", "b", MergeStrategy::RecordOnly)
168            .await
169            .unwrap();
170
171        assert_eq!(store.get_branch("a").await.unwrap(), Some(merge_id));
172        assert_eq!(store.get_branch("b").await.unwrap(), Some(b_id));
173        // Both original heads remain independently checkoutable.
174        assert!(store.contains(&a_id).await.unwrap());
175        assert!(store.contains(&b_id).await.unwrap());
176    }
177
178    #[tokio::test]
179    async fn merging_branches_with_no_common_ancestor_still_succeeds() {
180        let store = InMemoryGraphStore::new();
181        let a_root = Commit::new(
182            vec![],
183            Author::User,
184            text("a-root"),
185            Metadata::new(Utc::now()),
186        );
187        let a_id = store.put(a_root).await.unwrap();
188        store.set_branch("a", a_id).await.unwrap();
189
190        let b_root = Commit::new(
191            vec![],
192            Author::User,
193            text("b-root"),
194            Metadata::new(Utc::now()),
195        );
196        let b_id = store.put(b_root).await.unwrap();
197        store.set_branch("b", b_id).await.unwrap();
198
199        let merge_id = merge(&store, "a", "b", MergeStrategy::RecordOnly)
200            .await
201            .unwrap();
202        let ctx = materialize(&store, merge_id).await.unwrap();
203        assert_eq!(ctx.messages.len(), 1); // just a-root; no shared history, no error
204    }
205
206    #[tokio::test]
207    async fn merging_a_branch_with_itself_fails() {
208        let store = InMemoryGraphStore::new();
209        let root = Commit::new(
210            vec![],
211            Author::User,
212            text("root"),
213            Metadata::new(Utc::now()),
214        );
215        let id = store.put(root).await.unwrap();
216        store.set_branch("a", id).await.unwrap();
217        store.set_branch("b", id).await.unwrap();
218
219        let err = merge(&store, "a", "b", MergeStrategy::RecordOnly)
220            .await
221            .unwrap_err();
222        assert!(matches!(err, GraphError::InvalidMergeParents));
223    }
224
225    #[tokio::test]
226    async fn merging_a_nonexistent_branch_fails() {
227        let store = InMemoryGraphStore::new();
228        let root = Commit::new(
229            vec![],
230            Author::User,
231            text("root"),
232            Metadata::new(Utc::now()),
233        );
234        let id = store.put(root).await.unwrap();
235        store.set_branch("a", id).await.unwrap();
236
237        let err = merge(&store, "a", "nope", MergeStrategy::RecordOnly)
238            .await
239            .unwrap_err();
240        assert!(matches!(err, GraphError::BranchNotFound(_)));
241    }
242}