Skip to main content

contextgraph_core/
graph.rs

1//! `ContextGraph`: the embeddable library entry point combining a
2//! `CommitStore` + `RefStore` (usually the same backing object) with the
3//! guard-clause validation and transaction ordering the spec requires.
4
5use crate::bisect::{bisect as bisect_commits, BisectOutcome};
6use crate::commit::{Author, Commit, CommitId, Delta, MergeStrategy, Metadata};
7use crate::diff::{diff as diff_commits, ContextDiff};
8use crate::error::{GraphError, Result};
9use crate::gc::gc as gc_store;
10use crate::log::{log_ancestors, LogFilter, LogPage};
11use crate::materialize::{materialize, MaterializedContext};
12use crate::merge::merge as merge_branches;
13use crate::store::{CommitStore, RefStore};
14
15/// What to check out: a specific commit, or the current head of a branch.
16///
17/// ```
18/// use contextgraph_core::{CommitId, graph::CheckoutTarget};
19/// let by_id: CheckoutTarget = CommitId::from_bytes([0u8; 32]).into();
20/// let by_branch = CheckoutTarget::branch("main");
21/// ```
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum CheckoutTarget {
24    Commit(CommitId),
25    Branch(String),
26}
27
28impl CheckoutTarget {
29    /// Construct from a specific commit id.
30    pub fn commit(id: CommitId) -> Self {
31        Self::Commit(id)
32    }
33
34    /// Construct from a branch name.
35    pub fn branch(name: impl Into<String>) -> Self {
36        Self::Branch(name.into())
37    }
38}
39
40impl From<CommitId> for CheckoutTarget {
41    fn from(id: CommitId) -> Self {
42        Self::Commit(id)
43    }
44}
45
46/// The embeddable core API: an agent runtime links this directly and calls
47/// `commit`/`checkout` inline per turn.
48pub struct ContextGraph<S> {
49    store: S,
50}
51
52impl<S: CommitStore + RefStore> ContextGraph<S> {
53    pub fn new(store: S) -> Self {
54        Self { store }
55    }
56
57    pub fn store(&self) -> &S {
58        &self.store
59    }
60
61    /// Resolves a checkout target to a concrete commit id, without
62    /// materializing.
63    ///
64    /// # Errors
65    ///
66    /// * [`GraphError::CommitNotFound`] if a commit target does not exist.
67    /// * [`GraphError::BranchNotFound`] if a branch target does not exist.
68    pub async fn resolve(&self, target: &CheckoutTarget) -> Result<CommitId> {
69        match target {
70            CheckoutTarget::Commit(id) => {
71                if !self.store.contains(id).await? {
72                    return Err(GraphError::CommitNotFound(*id));
73                }
74                Ok(*id)
75            }
76            CheckoutTarget::Branch(name) => self
77                .store
78                .get_branch(name)
79                .await?
80                .ok_or_else(|| GraphError::BranchNotFound(name.clone())),
81        }
82    }
83
84    /// Creates a new commit as a child of `parent` (`None` for a root
85    /// commit). Content-addressed and idempotent: identical content always
86    /// returns the same id without creating a duplicate node. Does not move
87    /// any branch pointer — see `commit_advancing_branch` for the combined
88    /// op used by normal per-turn agent loops.
89    ///
90    /// # Errors
91    ///
92    /// * [`GraphError::ParentNotFound`] if `parent` is `Some` and the
93    ///   referenced commit is not in the store.
94    /// * [`GraphError::Storage`] if the underlying store fails to persist.
95    pub async fn commit(
96        &self,
97        parent: Option<CommitId>,
98        author: Author,
99        delta: Delta,
100        metadata: Metadata,
101    ) -> Result<CommitId> {
102        if let Some(p) = parent {
103            if !self.store.contains(&p).await? {
104                return Err(GraphError::ParentNotFound(p));
105            }
106        }
107        let parent_ids = parent.into_iter().collect::<Vec<_>>();
108        let commit = Commit::new(parent_ids, author, delta, metadata);
109        self.store.put(commit).await
110    }
111
112    /// Commits a new turn and advances `branch_name` to point at it in one
113    /// step. The commit is durably written before the branch pointer moves,
114    /// so no reader can ever observe a branch pointing at a not-yet-persisted
115    /// commit.
116    /// Commits a new turn and advances `branch_name` to point at it in one
117    /// step. The commit is durably written before the branch pointer moves,
118    /// so no reader can ever observe a branch pointing at a not-yet-persisted
119    /// commit.
120    ///
121    /// # Errors
122    ///
123    /// Any error returned by [`commit`](Self::commit) (e.g. parent not
124    /// found) or [`store.set_branch`](CommitStore::put).
125    pub async fn commit_advancing_branch(
126        &self,
127        branch_name: &str,
128        author: Author,
129        delta: Delta,
130        metadata: Metadata,
131    ) -> Result<CommitId> {
132        let parent = self.store.get_branch(branch_name).await?;
133        let id = self.commit(parent, author, delta, metadata).await?;
134        self.store.set_branch(branch_name, id).await?;
135        Ok(id)
136    }
137
138    /// Creates a new branch pointer at an existing commit. Fails if the
139    /// branch already exists or the commit does not.
140    ///
141    /// # Errors
142    ///
143    /// * [`GraphError::CommitNotFound`] if `at_commit_id` is not in the store.
144    /// * [`GraphError::BranchAlreadyExists`] if a branch named `name` is
145    ///   already defined.
146    pub async fn branch(&self, name: &str, at_commit_id: CommitId) -> Result<()> {
147        if !self.store.contains(&at_commit_id).await? {
148            return Err(GraphError::CommitNotFound(at_commit_id));
149        }
150        if self.store.get_branch(name).await?.is_some() {
151            return Err(GraphError::BranchAlreadyExists(name.to_string()));
152        }
153        self.store.set_branch(name, at_commit_id).await
154    }
155
156    /// Moves an existing branch pointer to a different (existing) commit.
157    ///
158    /// # Errors
159    ///
160    /// * [`GraphError::BranchNotFound`] if no branch named `name` exists.
161    /// * [`GraphError::CommitNotFound`] if `to_commit_id` is not in the store.
162    pub async fn move_branch(&self, name: &str, to_commit_id: CommitId) -> Result<()> {
163        if self.store.get_branch(name).await?.is_none() {
164            return Err(GraphError::BranchNotFound(name.to_string()));
165        }
166        if !self.store.contains(&to_commit_id).await? {
167            return Err(GraphError::CommitNotFound(to_commit_id));
168        }
169        self.store.set_branch(name, to_commit_id).await
170    }
171
172    pub async fn delete_branch(&self, name: &str) -> Result<()> {
173        self.store.delete_branch(name).await
174    }
175
176    pub async fn list_branches(&self) -> Result<Vec<(String, CommitId)>> {
177        self.store.list_branches().await
178    }
179
180    /// Materializes the ordered message list a model would see at `target`.
181    pub async fn checkout(&self, target: CheckoutTarget) -> Result<MaterializedContext> {
182        let head = self.resolve(&target).await?;
183        materialize(&self.store, head).await
184    }
185
186    /// Explicit speculative-branch creation: "try two continuations from the
187    /// same decision point" in one call. Semantically identical to `branch`
188    /// (a fork *is* a branch at an existing commit) but exposed under its
189    /// own name since it's the primary developer-facing verb for A/B'ing a
190    /// decision point — including forking again from an existing fork.
191    pub async fn fork(&self, from_commit_id: CommitId, new_branch_name: &str) -> Result<()> {
192        self.branch(new_branch_name, from_commit_id).await
193    }
194
195    /// Moves `branch_name` backward to `to_commit_id`. Matches git's `reset`
196    /// semantics: commits "ahead" of the new position are not deleted — they
197    /// remain reachable by hash, or by any other branch still pointing past
198    /// them.
199    pub async fn rollback(&self, branch_name: &str, to_commit_id: CommitId) -> Result<()> {
200        self.move_branch(branch_name, to_commit_id).await
201    }
202
203    /// Walks the ancestry of `target` (a commit, or a branch's current
204    /// head) newest-first, applying `filter` and then offset/limit
205    /// pagination.
206    pub async fn log(
207        &self,
208        target: CheckoutTarget,
209        filter: &LogFilter,
210        offset: usize,
211        limit: usize,
212    ) -> Result<LogPage> {
213        let head = self.resolve(&target).await?;
214        log_ancestors(&self.store, head, filter, offset, limit).await
215    }
216
217    /// Structural diff between two materialized contexts. `from`/`to` can
218    /// each independently be a commit or a branch's current head, so this
219    /// covers both the commit-pair and branch-pair forms.
220    pub async fn diff(&self, from: CheckoutTarget, to: CheckoutTarget) -> Result<ContextDiff> {
221        let from_id = self.resolve(&from).await?;
222        let to_id = self.resolve(&to).await?;
223        diff_commits(&self.store, from_id, to_id).await
224    }
225
226    /// Merges `branch_b` into `branch_a`, creating an explicit merge commit
227    /// and advancing `branch_a` to it. See `crate::merge` for why this never
228    /// silently merges divergent conversation content.
229    pub async fn merge(
230        &self,
231        branch_a: &str,
232        branch_b: &str,
233        strategy: MergeStrategy,
234    ) -> Result<CommitId> {
235        merge_branches(&self.store, branch_a, branch_b, strategy).await
236    }
237
238    /// Binary-searches the ancestry path between `good` and `bad` for the
239    /// exact commit where `predicate` flips from true to false.
240    pub async fn bisect<F>(
241        &self,
242        good: CommitId,
243        bad: CommitId,
244        predicate: F,
245    ) -> Result<BisectOutcome>
246    where
247        F: FnMut(&MaterializedContext) -> bool,
248    {
249        bisect_commits(&self.store, good, bad, predicate).await
250    }
251
252    /// Explicit, opt-in garbage collection: removes every commit not
253    /// reachable from any branch. Never runs implicitly.
254    pub async fn gc(&self) -> Result<Vec<CommitId>> {
255        gc_store(&self.store).await
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use crate::mem::InMemoryGraphStore;
263    use chrono::Utc;
264
265    fn meta() -> Metadata {
266        Metadata::new(Utc::now())
267    }
268
269    fn text(s: &str) -> Delta {
270        Delta::Message {
271            content: s.to_string(),
272        }
273    }
274
275    #[tokio::test]
276    async fn committing_with_no_parent_creates_a_root_commit() {
277        let g = ContextGraph::new(InMemoryGraphStore::new());
278        let id = g
279            .commit(None, Author::User, text("hi"), meta())
280            .await
281            .unwrap();
282        let ctx = g.checkout(CheckoutTarget::commit(id)).await.unwrap();
283        assert_eq!(ctx.messages.len(), 1);
284    }
285
286    #[tokio::test]
287    async fn committing_with_nonexistent_parent_fails() {
288        let g = ContextGraph::new(InMemoryGraphStore::new());
289        let err = g
290            .commit(Some(CommitId::from_bytes([1; 32])), Author::User, text("hi"), meta())
291            .await
292            .unwrap_err();
293        assert!(matches!(err, GraphError::ParentNotFound(_)));
294    }
295
296    #[tokio::test]
297    async fn branching_at_a_nonexistent_commit_fails() {
298        let g = ContextGraph::new(InMemoryGraphStore::new());
299        let err = g.branch("main", CommitId::from_bytes([1; 32])).await.unwrap_err();
300        assert!(matches!(err, GraphError::CommitNotFound(_)));
301    }
302
303    #[tokio::test]
304    async fn branching_with_an_already_used_name_fails() {
305        let g = ContextGraph::new(InMemoryGraphStore::new());
306        let id = g
307            .commit(None, Author::User, text("hi"), meta())
308            .await
309            .unwrap();
310        g.branch("main", id).await.unwrap();
311        let err = g.branch("main", id).await.unwrap_err();
312        assert!(matches!(err, GraphError::BranchAlreadyExists(_)));
313    }
314
315    #[tokio::test]
316    async fn moving_a_nonexistent_branch_fails() {
317        let g = ContextGraph::new(InMemoryGraphStore::new());
318        let id = g
319            .commit(None, Author::User, text("hi"), meta())
320            .await
321            .unwrap();
322        let err = g.move_branch("nope", id).await.unwrap_err();
323        assert!(matches!(err, GraphError::BranchNotFound(_)));
324    }
325
326    #[tokio::test]
327    async fn moving_a_branch_to_a_nonexistent_commit_fails() {
328        let g = ContextGraph::new(InMemoryGraphStore::new());
329        let id = g
330            .commit(None, Author::User, text("hi"), meta())
331            .await
332            .unwrap();
333        g.branch("main", id).await.unwrap();
334        let err = g.move_branch("main", CommitId::from_bytes([9; 32])).await.unwrap_err();
335        assert!(matches!(err, GraphError::CommitNotFound(_)));
336    }
337
338    #[tokio::test]
339    async fn deleting_a_nonexistent_branch_fails() {
340        let g = ContextGraph::new(InMemoryGraphStore::new());
341        let err = g.delete_branch("nope").await.unwrap_err();
342        assert!(matches!(err, GraphError::BranchNotFound(_)));
343    }
344
345    #[tokio::test]
346    async fn checking_out_a_nonexistent_branch_fails() {
347        let g = ContextGraph::new(InMemoryGraphStore::new());
348        let err = g
349            .checkout(CheckoutTarget::branch("nope"))
350            .await
351            .unwrap_err();
352        assert!(matches!(err, GraphError::BranchNotFound(_)));
353    }
354
355    #[tokio::test]
356    async fn checking_out_a_nonexistent_commit_fails() {
357        let g = ContextGraph::new(InMemoryGraphStore::new());
358        let err = g
359            .checkout(CheckoutTarget::commit(CommitId::from_bytes([1; 32])))
360            .await
361            .unwrap_err();
362        assert!(matches!(err, GraphError::CommitNotFound(_)));
363    }
364
365    #[tokio::test]
366    async fn commit_advancing_branch_creates_commit_and_moves_pointer_atomically_in_order() {
367        let g = ContextGraph::new(InMemoryGraphStore::new());
368        let id1 = g
369            .commit_advancing_branch("main", Author::User, text("one"), meta())
370            .await
371            .unwrap();
372        assert_eq!(g.store().get_branch("main").await.unwrap(), Some(id1));
373
374        let id2 = g
375            .commit_advancing_branch("main", Author::Assistant, text("two"), meta())
376            .await
377            .unwrap();
378        assert_eq!(g.store().get_branch("main").await.unwrap(), Some(id2));
379
380        let ctx = g.checkout(CheckoutTarget::branch("main")).await.unwrap();
381        assert_eq!(ctx.messages.len(), 2);
382    }
383
384    #[tokio::test]
385    async fn checking_out_same_commit_twice_yields_byte_identical_materialized_context() {
386        let g = ContextGraph::new(InMemoryGraphStore::new());
387        let root = g
388            .commit(None, Author::User, text("hi"), meta())
389            .await
390            .unwrap();
391        let child = g
392            .commit(Some(root), Author::Assistant, text("there"), meta())
393            .await
394            .unwrap();
395
396        let a = g.checkout(CheckoutTarget::commit(child)).await.unwrap();
397        let b = g.checkout(CheckoutTarget::commit(child)).await.unwrap();
398        assert_eq!(a, b);
399    }
400
401    #[tokio::test]
402    async fn committing_identical_content_via_two_different_parents_paths_still_dedupes() {
403        // Two branches both commit the exact same text on top of the same
404        // parent: this must produce one commit id, referenced from both
405        // branches (free storage dedupe across forks).
406        let g = ContextGraph::new(InMemoryGraphStore::new());
407        let root = g
408            .commit(None, Author::User, text("hi"), meta())
409            .await
410            .unwrap();
411        g.branch("a", root).await.unwrap();
412        g.branch("b", root).await.unwrap();
413
414        let shared_meta = meta();
415        let via_a = g
416            .commit(
417                Some(root),
418                Author::Assistant,
419                text("dup"),
420                shared_meta.clone(),
421            )
422            .await
423            .unwrap();
424        let via_b = g
425            .commit(Some(root), Author::Assistant, text("dup"), shared_meta)
426            .await
427            .unwrap();
428        assert_eq!(via_a, via_b);
429    }
430
431    #[tokio::test]
432    async fn forking_from_an_existing_commit_creates_an_independent_branch() {
433        let g = ContextGraph::new(InMemoryGraphStore::new());
434        let root = g
435            .commit(None, Author::User, text("plan"), meta())
436            .await
437            .unwrap();
438        g.fork(root, "speculative-a").await.unwrap();
439        assert_eq!(
440            g.store().get_branch("speculative-a").await.unwrap(),
441            Some(root)
442        );
443    }
444
445    #[tokio::test]
446    async fn forking_from_a_fork_produces_a_third_independent_branch() {
447        let g = ContextGraph::new(InMemoryGraphStore::new());
448        let root = g
449            .commit(None, Author::User, text("plan"), meta())
450            .await
451            .unwrap();
452        g.fork(root, "fork-1").await.unwrap();
453        let child = g
454            .commit(Some(root), Author::Assistant, text("step"), meta())
455            .await
456            .unwrap();
457        g.move_branch("fork-1", child).await.unwrap();
458
459        // Forking again, from the fork's current head.
460        g.fork(child, "fork-2").await.unwrap();
461        assert_eq!(g.store().get_branch("fork-2").await.unwrap(), Some(child));
462        // The original fork is untouched by the new one.
463        assert_eq!(g.store().get_branch("fork-1").await.unwrap(), Some(child));
464    }
465
466    #[tokio::test]
467    async fn forking_from_a_nonexistent_commit_fails() {
468        let g = ContextGraph::new(InMemoryGraphStore::new());
469        let err = g.fork(CommitId::from_bytes([1; 32]), "x").await.unwrap_err();
470        assert!(matches!(err, GraphError::CommitNotFound(_)));
471    }
472
473    #[tokio::test]
474    async fn rollback_moves_branch_backward_without_deleting_forward_commits() {
475        let g = ContextGraph::new(InMemoryGraphStore::new());
476        let root = g
477            .commit_advancing_branch("main", Author::User, text("one"), meta())
478            .await
479            .unwrap();
480        let ahead = g
481            .commit_advancing_branch("main", Author::Assistant, text("two"), meta())
482            .await
483            .unwrap();
484
485        g.rollback("main", root).await.unwrap();
486        assert_eq!(g.store().get_branch("main").await.unwrap(), Some(root));
487
488        // The commit that was "ahead" is still reachable by hash.
489        assert!(g.store().contains(&ahead).await.unwrap());
490        let ctx = g.checkout(CheckoutTarget::commit(ahead)).await.unwrap();
491        assert_eq!(ctx.messages.len(), 2);
492    }
493
494    #[tokio::test]
495    async fn rollback_of_a_nonexistent_branch_fails() {
496        let g = ContextGraph::new(InMemoryGraphStore::new());
497        let root = g
498            .commit(None, Author::User, text("hi"), meta())
499            .await
500            .unwrap();
501        let err = g.rollback("nope", root).await.unwrap_err();
502        assert!(matches!(err, GraphError::BranchNotFound(_)));
503    }
504
505    #[tokio::test]
506    async fn log_over_a_branch_name_resolves_its_current_head_first() {
507        let g = ContextGraph::new(InMemoryGraphStore::new());
508        g.commit_advancing_branch("main", Author::User, text("one"), meta())
509            .await
510            .unwrap();
511        let second = g
512            .commit_advancing_branch("main", Author::Assistant, text("two"), meta())
513            .await
514            .unwrap();
515
516        let page = g
517            .log(
518                CheckoutTarget::branch("main"),
519                &crate::log::LogFilter::new(),
520                0,
521                10,
522            )
523            .await
524            .unwrap();
525        assert_eq!(page.commits[0].id, second);
526        assert_eq!(page.total_matched, 2);
527    }
528
529    #[tokio::test]
530    async fn diff_between_two_branch_heads_resolves_each_branch_first() {
531        let g = ContextGraph::new(InMemoryGraphStore::new());
532        let root = g
533            .commit(None, Author::User, text("root"), meta())
534            .await
535            .unwrap();
536        g.branch("a", root).await.unwrap();
537        g.branch("b", root).await.unwrap();
538        let a_head = g
539            .commit(Some(root), Author::Assistant, text("a-only"), meta())
540            .await
541            .unwrap();
542        g.move_branch("a", a_head).await.unwrap();
543
544        let d = g
545            .diff(CheckoutTarget::branch("a"), CheckoutTarget::branch("b"))
546            .await
547            .unwrap();
548        assert_eq!(d.added().count(), 0);
549        assert_eq!(d.removed().count(), 1);
550    }
551
552    #[tokio::test]
553    async fn diffing_against_a_nonexistent_branch_fails() {
554        let g = ContextGraph::new(InMemoryGraphStore::new());
555        let root = g
556            .commit(None, Author::User, text("root"), meta())
557            .await
558            .unwrap();
559        g.branch("a", root).await.unwrap();
560        let err = g
561            .diff(CheckoutTarget::branch("a"), CheckoutTarget::branch("nope"))
562            .await
563            .unwrap_err();
564        assert!(matches!(err, GraphError::BranchNotFound(_)));
565    }
566
567    #[tokio::test]
568    async fn merging_two_branches_through_context_graph_advances_branch_a_only() {
569        let g = ContextGraph::new(InMemoryGraphStore::new());
570        let root = g
571            .commit(None, Author::User, text("root"), meta())
572            .await
573            .unwrap();
574        g.branch("a", root).await.unwrap();
575        g.branch("b", root).await.unwrap();
576        let a_head = g
577            .commit(Some(root), Author::Assistant, text("a-turn"), meta())
578            .await
579            .unwrap();
580        g.move_branch("a", a_head).await.unwrap();
581        let b_head = g
582            .commit(Some(root), Author::Assistant, text("b-turn"), meta())
583            .await
584            .unwrap();
585        g.move_branch("b", b_head).await.unwrap();
586
587        let merge_id = g
588            .merge("a", "b", crate::commit::MergeStrategy::RecordOnly)
589            .await
590            .unwrap();
591        assert_eq!(g.store().get_branch("a").await.unwrap(), Some(merge_id));
592        assert_eq!(g.store().get_branch("b").await.unwrap(), Some(b_head));
593    }
594
595    #[tokio::test]
596    async fn log_over_a_nonexistent_branch_fails() {
597        let g = ContextGraph::new(InMemoryGraphStore::new());
598        let err = g
599            .log(
600                CheckoutTarget::branch("nope"),
601                &crate::log::LogFilter::new(),
602                0,
603                10,
604            )
605            .await
606            .unwrap_err();
607        assert!(matches!(err, GraphError::BranchNotFound(_)));
608    }
609}