Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust
11.7 KB
Raw Blame
//! Repository/worktree identity and non-mutating boundary checkpoints.

use std::path::{Path, PathBuf};
use std::process::Command;

use ai_memory_core::WorkstreamCheckpoint;
use anyhow::{Context as _, Result};
use sha2::{Digest as _, Sha256};

/// Stable identity used to select a workstream without relying only on CWD.
#[derive(Debug, Clone)]
pub struct RepositoryIdentity {
    /// Canonical host cwd.
    pub cwd: PathBuf,
    /// Repository identity hash shared by linked worktrees.
    pub repo_fingerprint: String,
    /// Worktree-specific identity hash.
    pub worktree_fingerprint: String,
    /// Current non-mutating Git checkpoint.
    pub checkpoint: WorkstreamCheckpoint,
    /// The URL `git push` to `origin` uses (`pushurl`, or `url` after any
    /// `pushInsteadOf`). The ai-jail `ssh` default reads it.
    pub origin_push_url: Option<String>,
    /// Whether the cwd is a linked worktree (its git dir differs from the
    /// repository's common dir), whose metadata ai-jail must mount writable
    /// for the agent to commit.
    pub linked_worktree: bool,
}

/// Stable checkout keys, without scanning files or collecting a checkpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepositoryFingerprints {
    /// Repository identity hash shared by linked worktrees.
    pub repo_fingerprint: String,
    /// Worktree-specific identity hash.
    pub worktree_fingerprint: String,
}

struct RepositoryMetadata {
    cwd: PathBuf,
    fingerprints: RepositoryFingerprints,
    linked_worktree: bool,
}

/// Inspect the current checkout without committing, stashing, resetting, or
/// otherwise changing it.
pub fn inspect_repository(cwd: &Path) -> Result<RepositoryIdentity> {
    let metadata = inspect_metadata(cwd)?;
    Ok(RepositoryIdentity {
        checkpoint: checkpoint(&metadata.cwd),
        origin_push_url: git(&metadata.cwd, &["remote", "get-url", "--push", "origin"])
            .as_deref()
            .and_then(|urls| urls.lines().next())
            .map(str::trim)
            .filter(|url| !url.is_empty())
            .map(str::to_owned),
        cwd: metadata.cwd,
        repo_fingerprint: metadata.fingerprints.repo_fingerprint,
        worktree_fingerprint: metadata.fingerprints.worktree_fingerprint,
        linked_worktree: metadata.linked_worktree,
    })
}

/// Inspect only the stable keys needed to list checkout-local workstreams.
///
/// Listing must not run `git status`: a large working tree or an unavailable
/// filesystem-monitor hook can otherwise block the picker before its first frame.
pub fn inspect_repository_fingerprints(cwd: &Path) -> Result<RepositoryFingerprints> {
    Ok(inspect_metadata(cwd)?.fingerprints)
}

fn inspect_metadata(cwd: &Path) -> Result<RepositoryMetadata> {
    let canonical = cwd
        .canonicalize()
        .with_context(|| format!("canonicalizing managed run cwd {}", cwd.display()))?;
    let git_root = git(&canonical, &["rev-parse", "--show-toplevel"]);
    let common_dir = git(
        &canonical,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    );
    let git_dir = git(
        &canonical,
        &["rev-parse", "--path-format=absolute", "--git-dir"],
    );
    let remotes = git(&canonical, &["remote", "get-url", "--all", "origin"]);

    let repo_seed = match (&git_root, &common_dir, &remotes) {
        (_, _, Some(remotes)) if !remotes.trim().is_empty() => format!("git-remotes\n{remotes}"),
        (_, Some(common), _) => format!("git-common\n{common}"),
        (Some(root), _, _) => format!("git-root\n{root}"),
        _ => format!("directory\n{}", canonical.display()),
    };
    let worktree_seed = match (&git_dir, &git_root) {
        (Some(git_dir), _) => format!("{}\ngit-dir\n{git_dir}", sha256(&repo_seed)),
        (_, Some(root)) => format!("{}\nroot\n{root}", sha256(&repo_seed)),
        _ => format!("{}\ncwd\n{}", sha256(&repo_seed), canonical.display()),
    };
    Ok(RepositoryMetadata {
        cwd: canonical,
        fingerprints: RepositoryFingerprints {
            repo_fingerprint: sha256(&repo_seed),
            worktree_fingerprint: sha256(&worktree_seed),
        },
        linked_worktree: matches!(
            (&git_dir, &common_dir),
            (Some(git_dir), Some(common)) if git_dir != common
        ),
    })
}

fn checkpoint(cwd: &Path) -> WorkstreamCheckpoint {
    let status = git_bytes(cwd, &["status", "--porcelain=v1", "-z"]);
    let changed_paths = status
        .as_deref()
        .map(parse_status_paths)
        .unwrap_or_default();
    WorkstreamCheckpoint {
        head: git(cwd, &["rev-parse", "HEAD"]),
        branch: git(cwd, &["branch", "--show-current"]).map(|branch| {
            if branch.is_empty() {
                "(detached HEAD)".to_string()
            } else {
                branch
            }
        }),
        dirty_hash: status
            .as_deref()
            .and_then(|bytes| (!bytes.is_empty()).then(|| format!("{:x}", Sha256::digest(bytes)))),
        changed_paths,
    }
}

/// The git worktree root above `cwd`, or `None` outside a worktree.
pub(crate) fn worktree_root(cwd: &Path) -> Option<PathBuf> {
    git(cwd, &["rev-parse", "--show-toplevel"])
        .filter(|root| !root.is_empty())
        .map(PathBuf::from)
}

fn git(cwd: &Path, args: &[&str]) -> Option<String> {
    let output = git_bytes(cwd, args)?;
    String::from_utf8(output)
        .ok()
        .map(|value| value.trim().to_string())
}

fn git_bytes(cwd: &Path, args: &[&str]) -> Option<Vec<u8>> {
    let mut command = Command::new("git");
    hide_console(&mut command);
    let output = command.arg("-C").arg(cwd).args(args).output().ok()?;
    output.status.success().then_some(output.stdout)
}

#[cfg(windows)]
fn hide_console(command: &mut Command) {
    use std::os::windows::process::CommandExt as _;

    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
    command.creation_flags(CREATE_NO_WINDOW);
}

#[cfg(not(windows))]
fn hide_console(_command: &mut Command) {}

fn parse_status_paths(status: &[u8]) -> Vec<String> {
    let mut entries = status.split(|byte| *byte == 0).peekable();
    let mut paths = Vec::new();
    while let Some(entry) = entries.next() {
        if entry.len() <= 3 {
            continue;
        }
        if let Ok(path) = String::from_utf8(entry[3..].to_vec()) {
            paths.push(path);
        }
        if entry[..2]
            .iter()
            .any(|status| matches!(*status, b'R' | b'C'))
            && let Some(old_path) = entries.next()
            && let Ok(path) = String::from_utf8(old_path.to_vec())
        {
            paths.push(path);
        }
        if paths.len() >= 256 {
            break;
        }
    }
    paths.truncate(256);
    paths
}

fn sha256(value: &str) -> String {
    format!("{:x}", Sha256::digest(value.as_bytes()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn non_git_directory_has_stable_distinct_fingerprints() {
        let temp = tempfile::tempdir().unwrap();
        let first = inspect_repository(temp.path()).unwrap();
        let second = inspect_repository(temp.path()).unwrap();
        assert_eq!(first.repo_fingerprint, second.repo_fingerprint);
        assert_eq!(first.worktree_fingerprint, second.worktree_fingerprint);
        assert_eq!(first.repo_fingerprint.len(), 64);
        assert_eq!(first.origin_push_url, None);
        assert!(!first.linked_worktree);
        let lightweight = inspect_repository_fingerprints(temp.path()).unwrap();
        assert_eq!(lightweight.repo_fingerprint, first.repo_fingerprint);
        assert_eq!(lightweight.worktree_fingerprint, first.worktree_fingerprint);
    }

    fn git_fixture(cwd: &Path, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(cwd)
            .args([
                "-c",
                "user.name=fixture",
                "-c",
                "[email protected]",
            ])
            .args(args)
            .status()
            .unwrap();
        assert!(status.success(), "git {args:?} failed");
    }

    /// The ai-jail toggle defaults key off these two facts: an SSH-style
    /// `origin` pre-checks `ssh`, and only a linked worktree shows `worktree`.
    #[test]
    fn reports_origin_push_url_and_linked_worktree() {
        let temp = tempfile::tempdir().unwrap();
        let main = temp.path().join("main");
        std::fs::create_dir(&main).unwrap();
        git_fixture(&main, &["init", "-q"]);
        git_fixture(
            &main,
            &["remote", "add", "origin", "[email protected]:example/repo.git"],
        );
        git_fixture(
            &main,
            &[
                "commit",
                "-q",
                "--allow-empty",
                "--no-gpg-sign",
                "-m",
                "init",
            ],
        );
        let primary = inspect_repository(&main).unwrap();
        assert_eq!(
            primary.origin_push_url.as_deref(),
            Some("[email protected]:example/repo.git")
        );
        assert!(!primary.linked_worktree, "the main checkout is not linked");

        let linked = temp.path().join("linked");
        git_fixture(
            &main,
            &[
                "worktree",
                "add",
                "-q",
                "-b",
                "side",
                linked.to_str().unwrap(),
            ],
        );
        let worktree = inspect_repository(&linked).unwrap();
        assert!(worktree.linked_worktree);
        assert_eq!(worktree.origin_push_url, primary.origin_push_url);
        for (path, full) in [(&main, &primary), (&linked, &worktree)] {
            let lightweight = inspect_repository_fingerprints(path).unwrap();
            assert_eq!(lightweight.repo_fingerprint, full.repo_fingerprint);
            assert_eq!(lightweight.worktree_fingerprint, full.worktree_fingerprint);
        }
        assert_eq!(primary.repo_fingerprint, worktree.repo_fingerprint);
        assert_ne!(primary.worktree_fingerprint, worktree.worktree_fingerprint);
    }

    /// The push URL counts, not the fetch URL. The `.invalid` host keeps a
    /// contributor's global `pushInsteadOf` out of the first case.
    #[test]
    fn origin_push_url_follows_push_rewrites() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path();
        git_fixture(repo, &["init", "-q"]);
        git_fixture(
            repo,
            &[
                "remote",
                "add",
                "origin",
                "https://git.example.invalid/example/repo.git",
            ],
        );
        assert_eq!(
            inspect_repository(repo).unwrap().origin_push_url.as_deref(),
            Some("https://git.example.invalid/example/repo.git")
        );

        git_fixture(
            repo,
            &[
                "config",
                "[email protected]:.pushInsteadOf",
                "https://git.example.invalid/",
            ],
        );
        assert_eq!(
            inspect_repository(repo).unwrap().origin_push_url.as_deref(),
            Some("[email protected]:example/repo.git")
        );

        git_fixture(
            repo,
            &[
                "config",
                "remote.origin.pushurl",
                "work-gh:example/repo.git",
            ],
        );
        assert_eq!(
            inspect_repository(repo).unwrap().origin_push_url.as_deref(),
            Some("work-gh:example/repo.git")
        );
    }

    #[test]
    fn status_parser_handles_spaces_without_shell_splitting() {
        let paths = parse_status_paths(b" M path with spaces.rs\0?? new.txt\0");
        assert_eq!(paths, ["path with spaces.rs", "new.txt"]);
    }

    #[test]
    fn status_parser_preserves_both_rename_paths() {
        let paths = parse_status_paths(b"R  new name.rs\0old name.rs\0");
        assert_eq!(paths, ["new name.rs", "old name.rs"]);
    }
}