codetree 0.1.1

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

use crate::branch::{BranchManager, BranchStatus};
use crate::candidates::CandidateManager;
use crate::config::Config;
use crate::vcs::VcsManager;
use crate::lock::LockManager;
use crate::ops::{Operation, OperationLog};
use crate::snapshot::{SnapshotManager, MAX_SNAPSHOTS};

pub mod agents;
pub mod bisect;
pub mod bundle;
pub mod compare;
pub mod config_cmd;
pub mod tag;
pub mod finish;
pub mod freeze;
pub mod import;
pub mod init;
pub mod lock;
pub mod merge;
pub mod operations;
pub mod rebase;
pub mod save;
pub mod snapshot;
pub mod status;
pub mod undo;
pub mod worktree;

pub use agents::{agents_command, evaluate_command, promote_command};
pub use bundle::{bundle_command, unbundle_command};
pub use compare::{compare_command, publish_command};
pub use finish::{finish_command, withdraw_command};
pub use freeze::{freeze_command, frozen_command, unfreeze_command};
pub use import::{import_command, export_command};
pub use init::init_command;
pub use lock::{locks_command, unlock_command};
pub use merge::{merge_command, ready_command, resolve_command};
pub use operations::{branch_advance_command, branch_rename_command, goto_command, next_command, next_commit_command, prev_command, prev_commit_command, restack_graph_command, start_command, switch_command};
pub use rebase::{rebase_command, restack_command, sync_command};
pub use save::{abandon_command, absorb_command, amend_to_command, describe_command, duplicate_command, fix_command, fold_command, forget_command, revive_command, save_command, new_command, move_command, revert_command, reword_command, squash_command, squash_into_command, split_command, test_command, unsquash_command, watch_command};
pub use snapshot::{snapshot_command, snapshots_command, restore_snapshot_command};
pub use status::{blame_command, clean_command, diff_command, evolog_command, file_list_command, file_search_command, filelog_command, forks_command, gc_command, heads_command, hide_command, interdiff_command, list_command, log_command, merge_point_command, restore_command, run_command, show_command, smartlog_command, speculative_merge_command, status_command, unhide_command, verify_command, whereami_command};
pub use undo::{op_log_command, redo_command, undo_command};
pub use bisect::{bisect_command, BisectAction};
pub use config_cmd::{config_command, ConfigAction};
pub use tag::{tag_command, TagAction, TagAnnotation};
pub use worktree::{worktree_add_command, worktree_list_command, worktree_remove_command};

pub(crate) const STALE_THRESHOLD_DAYS: u64 = 7;

pub(crate) fn staleness_label(updated_at: u64) -> String {
    let now = crate::branch::now_ts();
    let age_secs = now.saturating_sub(updated_at);
    let age_days = age_secs / 86400;
    if age_days >= STALE_THRESHOLD_DAYS {
        format!(" (stale: {}d)", age_days)
    } else {
        String::new()
    }
}

pub(crate) async fn run_hooks(config: &Config, stage: &str, cwd: &std::path::Path) -> Result<()> {
    let hooks = config.hooks.get(stage);
    if hooks.is_empty() {
        return Ok(());
    }
    let is_post = stage.starts_with("post_");
    for cmd in hooks {
        info!("Running {} hook: {}", stage, cmd);
        let output = tokio::process::Command::new("sh")
            .arg("-c")
            .arg(cmd)
            .current_dir(cwd)
            .output()
            .await
            .with_context(|| format!("Failed to run {} hook: {}", stage, cmd))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let msg = format!(
                "{} hook '{}' failed (exit {})\n--- stdout ---\n{}\n--- stderr ---\n{}",
                stage, cmd, output.status.code().unwrap_or(-1),
                stdout.trim(), stderr.trim()
            );
            if is_post {
                warn!("{}", msg);
            } else {
                return Err(msg.into());
            }
        }
    }
    Ok(())
}

pub(crate) async fn load_config(config_path: Option<PathBuf>) -> Result<Config> {
    let config_file_path = match config_path {
        Some(path) => path,
        None => std::env::current_dir()
            .context("Failed to get current directory")?
            .join(".codetree")
            .join("config.toml"),
    };

    if config_file_path.exists() {
        Config::load(&config_file_path).await
            .context("Failed to load configuration")
    } else {
        warn!("Config not found, using defaults");
        Ok(Config::default())
    }
}

pub(crate) fn format_ts(ts: u64) -> String {
    let now = crate::branch::now_ts();
    let diff = now.saturating_sub(ts);
    if diff < 60 {
        format!("{}s ago", diff)
    } else if diff < 3600 {
        format!("{}m ago", diff / 60)
    } else if diff < 86400 {
        format!("{}h ago", diff / 3600)
    } else {
        format!("{}d ago", diff / 86400)
    }
}

pub(crate) async fn get_active_op_branches_sorted(current_dir: &std::path::Path) -> Result<Vec<String>> {
    let branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;
    let mut branches: Vec<String> = branch_manager.list_branches()
        .into_iter()
        .filter(|b| matches!(b.status, BranchStatus::Active) && !b.branchless)
        .map(|b| b.name.clone())
        .collect();
    branches.sort();
    Ok(branches)
}

pub(crate) async fn withdraw_single(branch_name: &str) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let mut branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let branch_info = branch_manager.get_branch(branch_name)
        .ok_or_else(|| format!("Branch '{}' is not tracked by codetree", branch_name))?;

    if !matches!(branch_info.status, BranchStatus::Active) {
        return Err(format!("Branch '{}' is not active", branch_name).into());
    }

    let is_branchless = branch_info.branchless;

    if is_branchless {
        branch_manager.archive_branch(branch_name).await?;
        println!("Withdrew branchless bookmark '{}'", branch_name);
    } else {
        let current = git_manager.get_current_branch().await?;
        if current == branch_name && let Ok(config) = load_config(None).await {
            let _ = git_manager.checkout_branch(&config.git.base_branch).await;
        }
        let _ = git_manager.delete_branch(branch_name, true).await;
        branch_manager.archive_branch(branch_name).await?;
        println!("Withdrew operation '{}'", branch_name);
    }

    cleanup_after_finish(&current_dir, branch_name, Operation::Withdraw {
        branch: branch_name.to_string(),
        timestamp: crate::branch::now_ts(),
    }).await?;

    Ok(())
}

/// Shared cleanup logic used by both merge_command and withdraw_single.
/// Releases file locks, removes from candidate groups, and pushes to the operation log.
pub(crate) async fn cleanup_after_finish(
    current_dir: &std::path::Path,
    branch_name: &str,
    op: Operation,
) -> Result<()> {
    let locks_path = current_dir.join(".codetree").join("locks.json");
    // Atomic RMW so a concurrent agent's acquire is never lost. Best-effort:
    // cleanup proceeds even if the lockfile is momentarily contended.
    let _ = LockManager::update_atomically(locks_path, |m| {
        m.release_for_operation(branch_name);
        Ok(())
    });

    let candidates_path = current_dir.join(".codetree").join("candidates.json");
    if let Ok(mut cand_mgr) = CandidateManager::load(candidates_path) {
        for group in cand_mgr.list_groups() {
            cand_mgr.remove_candidate(&group, branch_name);
        }
        let _ = cand_mgr.save();
    }

    let ops_path = current_dir.join(".codetree").join("ops.json");
    let mut op_log = OperationLog::new(&ops_path).await?;
    op_log.push(op);
    op_log.save(&ops_path).await?;

    Ok(())
}

/// Auto-snapshot the working tree before a risky command. Creates a snapshot
/// only if the working tree has uncommitted changes (dirty vs HEAD). Failures
/// are logged but never block the calling command — the snapshot is a safety
/// net, not a gate.
pub(crate) async fn auto_snapshot() {
    let current_dir = match std::env::current_dir() {
        Ok(d) => d,
        Err(_) => return,
    };
    let git_manager = match VcsManager::new(current_dir.clone()) {
        Ok(m) => m,
        Err(_) => return,
    };
    let result = match git_manager.snapshot_working_tree().await {
        Ok(Some(snap)) => snap,
        Ok(None) => return, // clean — no snapshot needed
        Err(e) => {
            warn!("Auto-snapshot failed: {}", e);
            return;
        }
    };
    let snapshots_path = git_manager.snapshots_path();
    match SnapshotManager::load(&snapshots_path).await {
        Ok(mut mgr) => {
            mgr.add(result.commit_hash, result.timestamp, result.branch, result.file_count);
            mgr.prune(MAX_SNAPSHOTS);
            if let Err(e) = mgr.save(&snapshots_path).await {
                warn!("Failed to save auto-snapshot: {}", e);
            }
        }
        Err(e) => {
            warn!("Failed to load snapshot manager: {}", e);
        }
    }
}

/// Clear all snapshots — called when `save` succeeds (the real commit
/// supersedes any pending snapshots).
pub(crate) async fn clear_snapshots() {
    let current_dir = match std::env::current_dir() {
        Ok(d) => d,
        Err(_) => return,
    };
    let codetree_dir = current_dir.join(".codetree").join("snapshots.json");
    if codetree_dir.exists() {
        let _ = tokio::fs::remove_file(&codetree_dir).await;
    }
}