Skip to main content

mur_common/
project.rs

1//! Canonical project identity for skill `scope: Project` matching.
2//!
3//! A project == its git repo root. Harvest stamps a learned skill with the
4//! repo root it was learned in; injection computes the repo root of the current
5//! working dir; the two match iff you're in the same repo. Using the repo root
6//! (not the cwd) means a skill learned in a subdir of repo X still applies
7//! anywhere in X.
8
9use std::path::{Path, PathBuf};
10
11/// Walk up from `start` to the directory containing a `.git` entry (the repo
12/// root). `None` if `start` isn't inside a git repo.
13///
14/// Note: a `git worktree` has its own `.git` *file*, so it resolves to the
15/// worktree's own root — a worktree and its main checkout get distinct project
16/// ids (project-scoped skills don't cross between them). Acceptable for now.
17///
18/// The walk never climbs out of an agent scratch dir into a git-tracked
19/// `<mur_home>`; see [`crate::repo_walk`].
20pub fn repo_root_of(start: &Path) -> Option<PathBuf> {
21    crate::repo_walk::git_root_of(start)
22}
23
24/// Canonical project id (repo-root path string) for scope matching, or `None`
25/// if not in a repo. Canonicalized so two entry points into the same repo
26/// (subdir, symlink, relative path) produce the same id.
27pub fn project_id(start: &Path) -> Option<String> {
28    let root = repo_root_of(start)?;
29    let canon = std::fs::canonicalize(&root).unwrap_or(root);
30    // Non-UTF-8 repo path → None (treated as "not in a project" → global) so a
31    // lossy id can never silently mismatch between stamp and inject time.
32    canon.to_str().map(str::to_owned)
33}
34
35/// The active project id for scope matching: `MUR_ACTIVE_PROJECT` env override,
36/// else the current working dir's repo root. `None` when neither resolves
37/// (→ only user/enterprise skills inject). Single source used by both the CLI
38/// injection hook and the agent runtime injector so they can't diverge.
39pub fn active_project_id() -> Option<String> {
40    active_project_id_from(std::env::current_dir().ok().as_deref())
41}
42
43/// The active project id as seen from `start`, which is the directory the
44/// *caller* considers current — for the agent runtime that is the turn's
45/// session cwd, not the process cwd.
46///
47/// The distinction is the whole point: a long-lived runtime process sits in
48/// the agent home (`~/.mur/agents/<name>`, never a repo) while its turns work
49/// in the user's project. Resolving from [`std::env::current_dir`] there
50/// answers "is the *daemon* in a repo", which is always no, so project scope
51/// silently degraded to user scope for every agent. `None` for `start` keeps
52/// the env override working and otherwise means "no project".
53pub fn active_project_id_from(start: Option<&Path>) -> Option<String> {
54    if let Ok(v) = std::env::var("MUR_ACTIVE_PROJECT") {
55        let v = v.trim();
56        if !v.is_empty() {
57            return Some(v.to_string());
58        }
59    }
60    start.and_then(project_id)
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use std::fs;
67
68    #[test]
69    fn active_project_id_prefers_env_override() {
70        let _env = crate::test_env::EnvGuard::set([("MUR_ACTIVE_PROJECT", "/explicit")]);
71        assert_eq!(active_project_id().as_deref(), Some("/explicit"));
72    }
73
74    /// The caller's directory decides the project, not the process's. This is
75    /// the runtime case: the process sits in a non-repo agent home while the
76    /// turn works inside a repo, and the repo must win.
77    #[test]
78    fn active_project_id_from_reads_the_callers_directory_not_the_process() {
79        let _env = crate::test_env::EnvGuard::unset(["MUR_ACTIVE_PROJECT"]);
80        let tmp = tempfile::tempdir().unwrap();
81        let repo = tmp.path().join("repo");
82        let not_repo = tmp.path().join("agent-home");
83        fs::create_dir_all(repo.join(".git")).unwrap();
84        fs::create_dir_all(&not_repo).unwrap();
85
86        // Process cwd is irrelevant; the passed directory is the answer.
87        assert_eq!(active_project_id_from(Some(&repo)), project_id(&repo));
88        assert!(active_project_id_from(Some(&not_repo)).is_none());
89        assert!(active_project_id_from(None).is_none());
90    }
91
92    #[test]
93    fn repo_root_found_from_subdir_and_none_outside() {
94        let tmp = tempfile::tempdir().unwrap();
95        let root = tmp.path().join("myrepo");
96        let sub = root.join("a").join("b");
97        fs::create_dir_all(&sub).unwrap();
98        fs::create_dir_all(root.join(".git")).unwrap();
99
100        // from a nested subdir we find the repo root
101        assert_eq!(repo_root_of(&sub).as_deref(), Some(root.as_path()));
102        // project_id is the canonicalized repo root, stable across entry points
103        assert_eq!(project_id(&sub), project_id(&root));
104        // a dir with no .git ancestor → None
105        let bare = tmp.path().join("not-a-repo");
106        fs::create_dir_all(&bare).unwrap();
107        assert!(repo_root_of(&bare).is_none());
108        assert!(project_id(&bare).is_none());
109    }
110}