1use 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#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum CheckoutTarget {
24 Commit(CommitId),
25 Branch(String),
26}
27
28impl CheckoutTarget {
29 pub fn commit(id: CommitId) -> Self {
31 Self::Commit(id)
32 }
33
34 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
46pub 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 g.fork(child, "fork-2").await.unwrap();
461 assert_eq!(g.store().get_branch("fork-2").await.unwrap(), Some(child));
462 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 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}