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