use crate::error::{Context, Result};
use crate::branch::BranchManager;
use crate::provenance::ProvenanceLog;
use crate::vcs::VcsManager;
#[derive(Debug, Clone, serde::Serialize)]
pub struct OperationConvergence {
pub operation: String,
pub heads: Vec<String>,
pub status: String,
pub commit: Option<String>,
pub conflicts: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct ConvergeReport {
pub operations: Vec<OperationConvergence>,
pub dry_run: bool,
}
pub async fn converge_operations(
git_manager: &VcsManager,
branch_manager: &mut BranchManager,
operation: Option<String>,
dry_run: bool,
) -> Result<ConvergeReport> {
let provenance = ProvenanceLog::load(git_manager.repo_path())?;
let mut by_operation: std::collections::HashMap<String, Vec<String>> =
std::collections::HashMap::new();
for entry in &provenance.entries {
by_operation
.entry(entry.operation.clone())
.or_default()
.push(entry.commit.clone());
}
let registered: Vec<crate::branch::BranchInfo> =
branch_manager.list_branches().into_iter().cloned().collect();
for info in ®istered {
if let Some(op) = &operation {
if &info.name != op {
continue;
}
}
if let Some(tip) = git_manager.repo().refs().get_branch(&info.name)? {
if !tip.is_empty() {
by_operation
.entry(info.name.clone())
.or_default()
.push(tip);
}
}
if let Some(last) = &info.last_commit {
by_operation
.entry(info.name.clone())
.or_default()
.push(last.clone());
}
}
let mut operations: Vec<OperationConvergence> = Vec::new();
let mut names: Vec<String> = by_operation.keys().cloned().collect();
names.sort();
for name in names {
if let Some(op) = &operation {
if &name != op {
continue;
}
}
let commits = &by_operation[&name];
let mut heads = git_manager.commit_heads(commits)?;
heads = git_manager.dedupe_heads_by_tree(&heads)?;
if heads.len() < 2 {
continue; }
if dry_run {
operations.push(OperationConvergence {
operation: name.clone(),
heads,
status: "divergent".to_string(),
commit: None,
conflicts: vec![],
});
continue;
}
let outcome = git_manager.converge_heads(&heads)?;
if !outcome.conflicts.is_empty() {
operations.push(OperationConvergence {
operation: name.clone(),
heads,
status: "conflict".to_string(),
commit: None,
conflicts: outcome.conflicts.iter().map(|c| c.path.clone()).collect(),
});
continue;
}
let new_commit = match outcome.commit {
Some(c) => c,
None => continue,
};
let is_branch = git_manager.repo().refs().get_branch(&name)?.is_some();
if is_branch {
git_manager.set_branch_tip(&name, &new_commit)?;
}
if let Some(info) = registered.iter().find(|i| &i.name == &name) {
if info.branchless {
branch_manager.set_branch_last_commit(&name, &new_commit).await?;
}
}
let current = git_manager.get_current_branch().await?;
if current == name {
git_manager.restore_working_tree_pub(&new_commit)?;
git_manager.sync_index_to_commit(&new_commit)?;
}
let agent_id = registered
.iter()
.find(|i| &i.name == &name)
.and_then(|i| i.agent_id.clone());
let mut provenance = ProvenanceLog::load(git_manager.repo_path())?;
provenance.record(&new_commit, &name, agent_id, None);
provenance.save(git_manager.repo_path())?;
operations.push(OperationConvergence {
operation: name.clone(),
heads,
status: "converged".to_string(),
commit: Some(new_commit),
conflicts: vec![],
});
}
Ok(ConvergeReport { operations, dry_run })
}
pub async fn converge_command(operation: Option<String>, dry_run: bool) -> Result<()> {
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 report = converge_operations(&git_manager, &mut branch_manager, operation.clone(), dry_run).await?;
if report.operations.is_empty() {
match &operation {
Some(op) => println!("No divergent commits for operation '{}' — already converged", op),
None => println!("No divergent commits found — all operations are linear"),
}
return Ok(());
}
for result in &report.operations {
let heads: Vec<String> = result.heads.iter().map(|h| h[..7.min(h.len())].to_string()).collect();
match result.status.as_str() {
"converged" => {
let commit = result.commit.as_deref().unwrap_or("");
println!("Converged operation '{}': {} head(s) [{}] → {}",
result.operation, result.heads.len(), heads.join(", "), &commit[..7.min(commit.len())]);
}
"conflict" => {
println!("Operation '{}' has {} divergent head(s) [{}] that conflict on: {}",
result.operation, result.heads.len(), heads.join(", "), result.conflicts.join(", "));
println!(" Resolve the conflicting files manually, then run `codetree converge` again.");
}
_ => {
println!("Operation '{}' has {} divergent head(s): [{}]",
result.operation, result.heads.len(), heads.join(", "));
if dry_run {
println!(" (dry run — no changes made)");
}
}
}
}
Ok(())
}