agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
//! Backup status and the file changes still waiting to be backed up.
use super::*;
use std::collections::BTreeSet;

#[derive(Debug, Clone, serde::Serialize)]
pub struct GitBackupStatus {
    /// Whether the skills directory is a git repository
    pub is_repo: bool,
    /// The configured remote URL (if any)
    pub remote_url: Option<String>,
    /// Current branch name
    pub branch: Option<String>,
    /// Whether there are uncommitted changes
    pub has_changes: bool,
    /// Number of distinct skill directories with changes pending backup.
    /// Drives the "N skills have unbacked changes" status copy; 0 when only
    /// metadata or root files changed.
    pub changed_skill_count: u32,
    /// File changes, including local commits not yet pushed to the upstream.
    pub changes: Vec<GitBackupChange>,
    /// Number of commits ahead of remote
    pub ahead: u32,
    /// Number of commits behind remote
    pub behind: u32,
    /// Last commit message
    pub last_commit: Option<String>,
    /// Last commit timestamp (ISO 8601)
    pub last_commit_time: Option<String>,
    /// Snapshot tag that points at current HEAD (if any)
    pub current_snapshot_tag: Option<String>,
    /// Snapshot tag restored most recently (when HEAD is a restore commit)
    pub restored_from_tag: Option<String>,
    /// Health of the relationship to the configured remote.
    /// One of: "healthy", "no_remote", "no_upstream", "unrelated_histories", "detached".
    pub upstream_health: String,
}

#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BackupChangeKind {
    Added,
    Modified,
    Deleted,
    Renamed,
    Conflicted,
}

#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
pub struct GitBackupChange {
    /// Repository-relative path, never an absolute local path.
    pub path: String,
    pub previous_path: Option<String>,
    pub kind: BackupChangeKind,
}

/// Get the current git status of the skills directory.
pub fn get_status(skills_dir: &Path) -> Result<GitBackupStatus> {
    if !skills_dir.join(".git").exists() {
        return Ok(GitBackupStatus {
            is_repo: false,
            remote_url: None,
            branch: None,
            has_changes: false,
            changed_skill_count: 0,
            changes: Vec::new(),
            ahead: 0,
            behind: 0,
            last_commit: None,
            last_commit_time: None,
            current_snapshot_tag: None,
            restored_from_tag: None,
            upstream_health: "no_remote".to_string(),
        });
    }

    let remote_url = run_git(skills_dir, &["remote", "get-url", "origin"])
        .ok()
        .map(|url| redact_url(&url));

    let branch = run_git(skills_dir, &["rev-parse", "--abbrev-ref", "HEAD"]).ok();

    let repo = git2::Repository::open(skills_dir).context("Cannot read backup repository")?;
    let has_changes = !repo.statuses(None)?.is_empty();

    let (ahead, behind) = get_ahead_behind(skills_dir).unwrap_or((0, 0));

    let last_commit = run_git(skills_dir, &["log", "-1", "--format=%s"]).ok();

    let last_commit_time = run_git(skills_dir, &["log", "-1", "--format=%cI"]).ok();

    let current_snapshot_tag = run_git(
        skills_dir,
        &[
            "tag",
            "--points-at",
            "HEAD",
            "--list",
            "sm-v-*",
            "--sort=-creatordate",
        ],
    )
    .ok()
    .and_then(|output| {
        output
            .lines()
            .map(str::trim)
            .find(|line| !line.is_empty())
            .map(|line| line.to_string())
    });

    let restored_from_tag = last_commit
        .as_deref()
        .and_then(parse_restored_from_tag_message);

    let upstream_health = detect_upstream_health(skills_dir, remote_url.is_some());

    let changes = pending_changes(&repo, ahead, &upstream_health)?;
    let changed_skill_count = count_changed_skills(&changes);

    Ok(GitBackupStatus {
        is_repo: true,
        remote_url,
        branch,
        has_changes,
        changed_skill_count,
        changes,
        ahead,
        behind,
        last_commit,
        last_commit_time,
        current_snapshot_tag,
        restored_from_tag,
        upstream_health,
    })
}

/// Compare with HEAD for working changes, or the common ancestor for unpushed
/// commits. Using the ancestor avoids listing remote-only updates as local edits.
fn pending_changes(
    repo: &git2::Repository,
    ahead: u32,
    upstream_health: &str,
) -> Result<Vec<GitBackupChange>> {
    let baseline = resolve_baseline(repo, ahead, upstream_health)?;
    let mut options = git2::DiffOptions::new();
    options
        .include_untracked(true)
        .recurse_untracked_dirs(true)
        .include_typechange(true);
    let mut diff = repo.diff_tree_to_workdir_with_index(baseline.as_ref(), Some(&mut options))?;
    diff.find_similar(Some(git2::DiffFindOptions::new().renames(true)))?;
    let mut changes = Vec::new();
    for delta in diff.deltas() {
        let kind = match delta.status() {
            git2::Delta::Added | git2::Delta::Untracked => BackupChangeKind::Added,
            git2::Delta::Deleted => BackupChangeKind::Deleted,
            git2::Delta::Renamed => BackupChangeKind::Renamed,
            git2::Delta::Conflicted => BackupChangeKind::Conflicted,
            git2::Delta::Modified | git2::Delta::Typechange | git2::Delta::Copied => {
                BackupChangeKind::Modified
            }
            _ => continue,
        };
        let path = delta
            .new_file()
            .path()
            .or_else(|| delta.old_file().path())
            .context("Backup change has no path")?
            .to_string_lossy()
            .into_owned();
        let previous_path = if kind == BackupChangeKind::Renamed {
            delta
                .old_file()
                .path()
                .map(|path| path.to_string_lossy().into_owned())
        } else {
            None
        };
        changes.push(GitBackupChange {
            path,
            previous_path,
            kind,
        });
    }
    changes.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(changes)
}

const MAX_DIFF_SIZE: usize = 1_048_576; // 1 MiB

#[derive(Debug, Clone, serde::Serialize)]
pub struct GitBackupFileDiff {
    pub path: String,
    pub status: BackupChangeKind,
    /// "text" | "binary" | "too_large"
    pub content_kind: String,
    pub original_text: Option<String>,
    pub updated_text: Option<String>,
}

fn resolve_baseline<'a>(
    repo: &'a git2::Repository,
    ahead: u32,
    upstream_health: &str,
) -> Result<Option<git2::Tree<'a>>> {
    let head = match repo.head() {
        Ok(head) => Some(head.peel_to_commit()?),
        Err(error)
            if matches!(
                error.code(),
                git2::ErrorCode::UnbornBranch | git2::ErrorCode::NotFound
            ) =>
        {
            None
        }
        Err(error) => return Err(error.into()),
    };
    if upstream_health == "no_upstream" {
        Ok(None)
    } else if ahead > 0 {
        let head = head.as_ref().context("Backup HEAD is missing")?;
        let upstream = repo.revparse_single("@{upstream}")?.peel_to_commit()?;
        Ok(Some(
            repo.find_commit(repo.merge_base(head.id(), upstream.id())?)?
                .tree()?,
        ))
    } else {
        Ok(head.map(|h| h.tree()).transpose()?)
    }
}

pub fn get_file_diff(skills_dir: &Path, file_path: &str) -> Result<GitBackupFileDiff> {
    let repo = git2::Repository::open(skills_dir).context("Cannot read backup repository")?;
    let (ahead, _) = get_ahead_behind(skills_dir).unwrap_or((0, 0));
    let upstream_health = detect_upstream_health(skills_dir, false);
    let baseline = resolve_baseline(&repo, ahead, &upstream_health)?;

    let original_blob = baseline.as_ref().and_then(|tree| {
        tree.get_path(Path::new(file_path))
            .ok()
            .and_then(|entry| entry.to_object(&repo).ok())
            .and_then(|obj| obj.into_blob().ok())
    });

    let workdir_path = skills_dir.join(file_path);
    let workdir_content = std::fs::read(&workdir_path).ok();

    let is_binary = |data: &[u8]| data.contains(&0);

    let orig_binary = original_blob
        .as_ref()
        .is_some_and(|b| is_binary(b.content()));
    let work_binary = workdir_content.as_ref().is_some_and(|c| is_binary(c));
    if orig_binary || work_binary {
        let status = if original_blob.is_none() {
            BackupChangeKind::Added
        } else if workdir_content.is_none() {
            BackupChangeKind::Deleted
        } else {
            BackupChangeKind::Modified
        };
        return Ok(GitBackupFileDiff {
            path: file_path.to_string(),
            status,
            content_kind: "binary".to_string(),
            original_text: None,
            updated_text: None,
        });
    }

    let orig_size = original_blob.as_ref().map_or(0, |b| b.content().len());
    let work_size = workdir_content.as_ref().map_or(0, |c| c.len());
    if orig_size > MAX_DIFF_SIZE || work_size > MAX_DIFF_SIZE {
        return Ok(GitBackupFileDiff {
            path: file_path.to_string(),
            status: BackupChangeKind::Modified,
            content_kind: "too_large".to_string(),
            original_text: None,
            updated_text: None,
        });
    }

    let original_text = original_blob.map(|b| String::from_utf8_lossy(b.content()).into_owned());
    let updated_text = workdir_content.map(|c| String::from_utf8_lossy(&c).into_owned());

    let status = if original_text.is_none() {
        BackupChangeKind::Added
    } else if updated_text.is_none() {
        BackupChangeKind::Deleted
    } else {
        BackupChangeKind::Modified
    };

    Ok(GitBackupFileDiff {
        path: file_path.to_string(),
        status,
        content_kind: "text".to_string(),
        original_text,
        updated_text,
    })
}

fn count_changed_skills(changes: &[GitBackupChange]) -> u32 {
    changes
        .iter()
        .flat_map(|change| {
            std::iter::once(change.path.as_str()).chain(change.previous_path.as_deref())
        })
        .filter_map(|path| {
            if path.starts_with("automations/") || path.starts_with("user-config/") {
                return None;
            }
            let path = path.strip_prefix("skills/").unwrap_or(path);
            let (name, _) = path.split_once('/')?;
            (!name.starts_with('.')).then_some(name)
        })
        .collect::<BTreeSet<_>>()
        .len() as u32
}

#[cfg(test)]
mod tests;