use anyhow::{Context, Result};
use git2::{Oid, Repository, Sort};
use std::collections::BTreeMap;
use super::decision::Side;
use super::protocol::{parse_trailer_ids, TRAILER_CONFLICTS, TRAILER_RESOLVED};
use super::snapshot::{skill_identical, Snapshot};
pub const REF_PRE_MERGE: &str = "refs/agent-hub/pre-merge";
pub const REF_APPLYING: &str = "refs/agent-hub/applying";
pub const CONFLICT_REF_PREFIX: &str = "refs/agent-hub/conflict/";
pub const STAGING_REF_PREFIX: &str = "refs/agent-hub/conflict-staging/";
pub const PRE_MERGE_RETENTION_DAYS: i64 = 30;
pub fn conflict_ref(skill_id: &str) -> String {
format!("{CONFLICT_REF_PREFIX}{skill_id}")
}
pub fn staging_ref(attempt_id: &str, skill_id: &str) -> String {
format!("{STAGING_REF_PREFIX}{attempt_id}/{skill_id}")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrailerState {
Active,
Closed,
}
pub fn replay_trailers(
repo: &Repository,
tip: Oid,
hide: Option<Oid>,
) -> Result<BTreeMap<String, TrailerState>> {
let mut walk = repo.revwalk()?;
walk.push(tip)?;
if let Some(hide) = hide {
walk.hide(hide)?;
}
walk.set_sorting(Sort::TOPOLOGICAL | Sort::REVERSE)?;
let mut state = BTreeMap::new();
for oid in walk {
let commit = repo.find_commit(oid?)?;
let message = commit.message().unwrap_or_default();
for id in parse_trailer_ids(message, TRAILER_CONFLICTS) {
state.insert(id, TrailerState::Active);
}
for id in parse_trailer_ids(message, TRAILER_RESOLVED) {
state.insert(id, TrailerState::Closed);
}
}
Ok(state)
}
#[derive(Debug)]
pub enum PendingOutcome {
Pinned(BTreeMap<String, Side>),
Blocked(Vec<String>),
}
pub fn effective_pending(
repo: &Repository,
base: Oid,
ours_tip: Oid,
theirs_tip: Oid,
ours_snap: &Snapshot,
theirs_snap: &Snapshot,
) -> Result<PendingOutcome> {
let full_ours = replay_trailers(repo, ours_tip, None)?;
let full_theirs = replay_trailers(repo, theirs_tip, None)?;
let range_ours = replay_trailers(repo, ours_tip, Some(base))?;
let range_theirs = replay_trailers(repo, theirs_tip, Some(base))?;
let mut pinned: BTreeMap<String, Side> = BTreeMap::new();
let mut blocked: Vec<String> = Vec::new();
let ids: std::collections::BTreeSet<&String> =
full_ours.keys().chain(full_theirs.keys()).collect();
for id in ids {
let a = full_ours.get(id).copied();
let b = full_theirs.get(id).copied();
let declared_a = range_ours.get(id) == Some(&TrailerState::Active);
let declared_b = range_theirs.get(id) == Some(&TrailerState::Active);
match (a, b) {
(Some(TrailerState::Active), Some(TrailerState::Active)) => {
if declared_a && declared_b {
let same = match (ours_snap.skills.get(id), theirs_snap.skills.get(id)) {
(Some(o), Some(t)) => skill_identical(o, t),
(None, None) => true,
_ => false,
};
if same {
pinned.insert(id.clone(), Side::Ours);
} else {
blocked.push(id.clone());
}
} else if declared_b {
pinned.insert(id.clone(), Side::Theirs);
} else {
pinned.insert(id.clone(), Side::Ours);
}
}
(Some(TrailerState::Active), None) => {
pinned.insert(id.clone(), Side::Ours);
}
(None, Some(TrailerState::Active)) => {
pinned.insert(id.clone(), Side::Theirs);
}
(Some(TrailerState::Active), Some(TrailerState::Closed)) if declared_a => {
pinned.insert(id.clone(), Side::Ours);
}
(Some(TrailerState::Closed), Some(TrailerState::Active)) if declared_b => {
pinned.insert(id.clone(), Side::Theirs);
}
_ => {} }
}
if blocked.is_empty() {
Ok(PendingOutcome::Pinned(pinned))
} else {
blocked.sort();
Ok(PendingOutcome::Blocked(blocked))
}
}
pub fn write_ref(repo: &Repository, name: &str, target: Oid, log: &str) -> Result<()> {
repo.reference(name, target, true, log)
.with_context(|| format!("failed to write {name}"))?;
Ok(())
}
pub fn delete_ref(repo: &Repository, name: &str) {
if let Ok(mut r) = repo.find_reference(name) {
let _ = r.delete();
}
}
pub fn ref_target(repo: &Repository, name: &str) -> Option<Oid> {
repo.find_reference(name).ok().and_then(|r| r.target())
}
pub fn list_staging_refs(repo: &Repository) -> Vec<(String, String, Oid)> {
let mut out = Vec::new();
if let Ok(refs) = repo.references_glob(&format!("{STAGING_REF_PREFIX}*")) {
for r in refs.flatten() {
let Some(name) = r.name() else { continue };
let Some(rest) = name.strip_prefix(STAGING_REF_PREFIX) else {
continue;
};
let Some((attempt, skill_id)) = rest.split_once('/') else {
continue;
};
if let Some(target) = r.target() {
out.push((attempt.to_string(), skill_id.to_string(), target));
}
}
}
out
}
pub fn list_conflict_refs(repo: &Repository) -> Vec<(String, Oid)> {
let mut out = Vec::new();
if let Ok(refs) = repo.references_glob(&format!("{CONFLICT_REF_PREFIX}*")) {
for r in refs.flatten() {
let Some(name) = r.name() else { continue };
let Some(skill_id) = name.strip_prefix(CONFLICT_REF_PREFIX) else {
continue;
};
if let Some(target) = r.target() {
out.push((skill_id.to_string(), target));
}
}
}
out
}
pub fn promote_staging(repo: &Repository, attempt_id: &str) -> Result<()> {
for (attempt, skill_id, target) in list_staging_refs(repo) {
if attempt == attempt_id {
write_ref(
repo,
&conflict_ref(&skill_id),
target,
"promote conflict ref",
)?;
}
delete_ref(repo, &staging_ref(&attempt, &skill_id));
}
Ok(())
}
pub fn heal_conflict_refs(repo: &Repository, head: Oid) -> Result<Vec<(String, Oid)>> {
let active: Vec<String> = replay_trailers(repo, head, None)?
.into_iter()
.filter(|(_, s)| *s == TrailerState::Active)
.map(|(id, _)| id)
.collect();
let staging = list_staging_refs(repo);
let mut healed = Vec::new();
for id in &active {
let desired = staging
.iter()
.find(|(_, skill_id, _)| skill_id == id)
.map(|(_, _, t)| *t)
.or_else(|| find_declaring_theirs(repo, head, id));
let Some(desired) = desired else { continue };
let up_to_date = match ref_target(repo, &conflict_ref(id)) {
None => false,
Some(existing) if existing == desired => true,
Some(existing) => repo.graph_descendant_of(existing, desired).unwrap_or(false),
};
if !up_to_date {
write_ref(repo, &conflict_ref(id), desired, "heal conflict ref")?;
healed.push((id.clone(), desired));
}
}
for (attempt, skill_id, _) in staging {
delete_ref(repo, &staging_ref(&attempt, &skill_id));
}
let active_set: std::collections::BTreeSet<&String> = active.iter().collect();
for (skill_id, _) in list_conflict_refs(repo) {
if !active_set.contains(&skill_id) {
delete_ref(repo, &conflict_ref(&skill_id));
}
}
Ok(healed)
}
fn find_declaring_theirs(repo: &Repository, head: Oid, id: &str) -> Option<Oid> {
let mut walk = repo.revwalk().ok()?;
walk.push(head).ok()?;
walk.set_sorting(Sort::TOPOLOGICAL).ok()?;
for oid in walk.flatten() {
let commit = repo.find_commit(oid).ok()?;
let message = commit.message().unwrap_or_default();
if parse_trailer_ids(message, TRAILER_CONFLICTS)
.iter()
.any(|declared| declared == id)
{
return commit.parent_id(1).ok();
}
}
None
}