mur-common 2.91.9

Shared types and traits for the MUR ecosystem
Documentation
//! Canonical project identity for skill `scope: Project` matching.
//!
//! A project == its git repo root. Harvest stamps a learned skill with the
//! repo root it was learned in; injection computes the repo root of the current
//! working dir; the two match iff you're in the same repo. Using the repo root
//! (not the cwd) means a skill learned in a subdir of repo X still applies
//! anywhere in X.

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

/// Walk up from `start` to the directory containing a `.git` entry (the repo
/// root). `None` if `start` isn't inside a git repo.
///
/// Note: a `git worktree` has its own `.git` *file*, so it resolves to the
/// worktree's own root — a worktree and its main checkout get distinct project
/// ids (project-scoped skills don't cross between them). Acceptable for now.
pub fn repo_root_of(start: &Path) -> Option<PathBuf> {
    let mut dir = Some(start);
    while let Some(d) = dir {
        if d.join(".git").exists() {
            return Some(d.to_path_buf());
        }
        dir = d.parent();
    }
    None
}

/// Canonical project id (repo-root path string) for scope matching, or `None`
/// if not in a repo. Canonicalized so two entry points into the same repo
/// (subdir, symlink, relative path) produce the same id.
pub fn project_id(start: &Path) -> Option<String> {
    let root = repo_root_of(start)?;
    let canon = std::fs::canonicalize(&root).unwrap_or(root);
    // Non-UTF-8 repo path → None (treated as "not in a project" → global) so a
    // lossy id can never silently mismatch between stamp and inject time.
    canon.to_str().map(str::to_owned)
}

/// The active project id for scope matching: `MUR_ACTIVE_PROJECT` env override,
/// else the current working dir's repo root. `None` when neither resolves
/// (→ only user/enterprise skills inject). Single source used by both the CLI
/// injection hook and the agent runtime injector so they can't diverge.
pub fn active_project_id() -> Option<String> {
    active_project_id_from(std::env::current_dir().ok().as_deref())
}

/// The active project id as seen from `start`, which is the directory the
/// *caller* considers current — for the agent runtime that is the turn's
/// session cwd, not the process cwd.
///
/// The distinction is the whole point: a long-lived runtime process sits in
/// the agent home (`~/.mur/agents/<name>`, never a repo) while its turns work
/// in the user's project. Resolving from [`std::env::current_dir`] there
/// answers "is the *daemon* in a repo", which is always no, so project scope
/// silently degraded to user scope for every agent. `None` for `start` keeps
/// the env override working and otherwise means "no project".
pub fn active_project_id_from(start: Option<&Path>) -> Option<String> {
    if let Ok(v) = std::env::var("MUR_ACTIVE_PROJECT") {
        let v = v.trim();
        if !v.is_empty() {
            return Some(v.to_string());
        }
    }
    start.and_then(project_id)
}

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

    #[test]
    fn active_project_id_prefers_env_override() {
        let _env = crate::test_env::EnvGuard::set([("MUR_ACTIVE_PROJECT", "/explicit")]);
        assert_eq!(active_project_id().as_deref(), Some("/explicit"));
    }

    /// The caller's directory decides the project, not the process's. This is
    /// the runtime case: the process sits in a non-repo agent home while the
    /// turn works inside a repo, and the repo must win.
    #[test]
    fn active_project_id_from_reads_the_callers_directory_not_the_process() {
        let _env = crate::test_env::EnvGuard::unset(["MUR_ACTIVE_PROJECT"]);
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        let not_repo = tmp.path().join("agent-home");
        fs::create_dir_all(repo.join(".git")).unwrap();
        fs::create_dir_all(&not_repo).unwrap();

        // Process cwd is irrelevant; the passed directory is the answer.
        assert_eq!(active_project_id_from(Some(&repo)), project_id(&repo));
        assert!(active_project_id_from(Some(&not_repo)).is_none());
        assert!(active_project_id_from(None).is_none());
    }

    #[test]
    fn repo_root_found_from_subdir_and_none_outside() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("myrepo");
        let sub = root.join("a").join("b");
        fs::create_dir_all(&sub).unwrap();
        fs::create_dir_all(root.join(".git")).unwrap();

        // from a nested subdir we find the repo root
        assert_eq!(repo_root_of(&sub).as_deref(), Some(root.as_path()));
        // project_id is the canonicalized repo root, stable across entry points
        assert_eq!(project_id(&sub), project_id(&root));
        // a dir with no .git ancestor → None
        let bare = tmp.path().join("not-a-repo");
        fs::create_dir_all(&bare).unwrap();
        assert!(repo_root_of(&bare).is_none());
        assert!(project_id(&bare).is_none());
    }
}