use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;
pub const MERGE_PROTOCOL_VERSION: u32 = 2;
const PROTOCOL_SCHEMA_VERSION: u32 = 1;
pub const TRAILER_PROTOCOL: &str = "Agent-Hub-Protocol";
pub const TRAILER_CONFLICTS: &str = "Agent-Hub-Conflicts";
pub const TRAILER_RESOLVED: &str = "Agent-Hub-Resolved";
pub const PROTOCOL_FILE_REL: &str = ".agent-hub/protocol.json";
pub const CONFLICTS_TRAILER_CAP: usize = 20;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtocolFile {
pub schema_version: u32,
pub merge_protocol: u32,
}
impl Default for ProtocolFile {
fn default() -> Self {
Self {
schema_version: PROTOCOL_SCHEMA_VERSION,
merge_protocol: MERGE_PROTOCOL_VERSION,
}
}
}
pub fn protocol_file_bytes(file: &ProtocolFile) -> Result<Vec<u8>> {
let mut bytes = serde_json::to_vec_pretty(file)?;
bytes.push(b'\n');
Ok(bytes)
}
pub fn ensure_protocol_file(skills_dir: &Path) -> Result<()> {
let path = skills_dir.join(PROTOCOL_FILE_REL);
if let Ok(raw) = std::fs::read_to_string(&path) {
if let Ok(existing) = serde_json::from_str::<ProtocolFile>(&raw) {
if existing.merge_protocol >= MERGE_PROTOCOL_VERSION {
return Ok(());
}
}
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&path, protocol_file_bytes(&ProtocolFile::default())?)
.with_context(|| format!("failed to write {}", path.display()))?;
Ok(())
}
pub fn app_commit_message(message: &str) -> String {
format!(
"{}\n\n{}: {}",
message.trim_end(),
TRAILER_PROTOCOL,
MERGE_PROTOCOL_VERSION
)
}
pub fn has_protocol_trailer(message: &str) -> bool {
message.lines().any(|line| {
line.trim_start()
.starts_with(&format!("{TRAILER_PROTOCOL}:"))
})
}
pub fn parse_trailer_ids(message: &str, key: &str) -> Vec<String> {
let prefix = format!("{key}:");
let mut ids = Vec::new();
for line in message.lines() {
let line = line.trim_start();
if let Some(rest) = line.strip_prefix(&prefix) {
for id in rest.split(',') {
let id = id.trim();
if !id.is_empty() && !id.starts_with('+') {
ids.push(id.to_string());
}
}
}
}
ids
}
pub fn format_conflicts_trailer(ids: &[String]) -> Option<(String, bool)> {
if ids.is_empty() {
return None;
}
let mut sorted: Vec<&String> = ids.iter().collect();
sorted.sort();
let shown: Vec<&str> = sorted
.iter()
.take(CONFLICTS_TRAILER_CAP)
.map(|s| s.as_str())
.collect();
let overflow = sorted.len().saturating_sub(CONFLICTS_TRAILER_CAP);
let mut line = format!("{TRAILER_CONFLICTS}: {}", shown.join(", "));
if overflow > 0 {
line.push_str(&format!(", +{overflow}"));
}
Some((line, overflow > 0))
}
#[cfg(test)]
mod tests;