codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Persistent bisect state stored in `.codetree/bisect.json`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BisectState {
    /// The commit known to be bad (HEAD at bisect start, or marked bad).
    pub bad: Option<String>,
    /// The commit known to be good (oldest known-good ancestor).
    pub good: Vec<String>,
    /// The current commit being tested.
    pub current: Option<String>,
    /// The original HEAD to restore after bisect completes.
    pub original_head: Option<String>,
    /// The original branch name to restore after bisect completes.
    pub original_branch: Option<String>,
}

impl BisectState {
    fn path(repo_path: &Path) -> PathBuf {
        repo_path.join(".codetree").join("bisect.json")
    }

    /// Load bisect state from disk, or return default if none exists.
    pub fn load(repo_path: &Path) -> Result<Self> {
        let path = Self::path(repo_path);
        if !path.exists() {
            return Ok(Self::default());
        }
        let content = std::fs::read_to_string(&path)?;
        let state: BisectState = serde_json::from_str(&content)
            .unwrap_or_default();
        Ok(state)
    }

    /// Save bisect state to disk.
    pub fn save(&self, repo_path: &Path) -> Result<()> {
        let path = Self::path(repo_path);
        let content = serde_json::to_string_pretty(self)?;
        crate::atomic::write_atomic(&path, content.as_bytes())?;
        Ok(())
    }

    /// Clear bisect state (remove the file).
    pub fn clear(repo_path: &Path) -> Result<()> {
        let path = Self::path(repo_path);
        if path.exists() {
            std::fs::remove_file(&path)?;
        }
        Ok(())
    }

    /// Check if a bisect session is in progress.
    pub fn is_active(&self) -> bool {
        self.bad.is_some()
    }

    /// Find the midpoint commit between the bad commit and the nearest good
    /// ancestor. Returns None if the range is exhausted (bad's parent is good).
    pub fn midpoint(&self, repo: &crate::vcs::Repository) -> Result<Option<String>> {
        let Some(bad) = &self.bad else {
            return Ok(None);
        };

        // Collect all ancestors of bad until we hit a good commit.
        let mut ancestors: Vec<String> = Vec::new();
        let mut current = bad.clone();
        loop {
            if self.good.contains(&current) {
                break;
            }
            ancestors.push(current.clone());
            let commit = repo.read_commit(&current)?;
            if commit.parents.is_empty() {
                break;
            }
            current = commit.parents[0].clone();
        }

        // If only 1 ancestor (just bad itself) or bad is directly after good, done.
        if ancestors.len() <= 1 {
            return Ok(None);
        }

        // Pick the midpoint (skip index 0 which is bad itself).
        let mid = ancestors.len() / 2;
        Ok(Some(ancestors[mid].clone()))
    }
}