Skip to content

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

Rust

fix(hooks): resolve worktree cwd to main repo for project identity

Mauro Couto de Paivae98eeb796955
diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rs
index a6c1c453..6f6a6c44 100644
--- a/crates/ai-memory-consolidate/src/bootstrap.rs
+++ b/crates/ai-memory-consolidate/src/bootstrap.rs
@@ -536,6 +536,38 @@ pub fn discover_repo_root(start: &Path) -> Result<PathBuf, BootstrapError> {
.ok_or_else(|| BootstrapError::NotARepo(start.to_path_buf()))
}
+/// Like [`discover_repo_root`], but when `start` is inside a git
+/// worktree the function follows the `.git` commondir pointer back to
+/// the **main** repository root rather than returning the worktree's
+/// own working directory.
+///
+/// This is the right choice when the caller needs a stable identity
+/// for the repository (e.g. deriving a project name) — all worktrees
+/// of the same repo should resolve to the same root.
+///
+/// # Errors
+/// Returns `BootstrapError::NotARepo` when no repository is found
+/// at or above `start`.
+pub fn discover_main_repo_root(start: &Path) -> Result<PathBuf, BootstrapError> {
+ let repo = git2::Repository::discover(start)
+ .map_err(|_| BootstrapError::NotARepo(start.to_path_buf()))?;
+ // Bare repos have no working directory; `commondir()` IS the repo root
+ // (there is no `.git/` subdirectory), so `.parent()` would return the
+ // grandparent — wrong. Fall back to basename(cwd) via NotARepo so the
+ // router handles it safely.
+ if repo.is_bare() {
+ return Err(BootstrapError::NotARepo(start.to_path_buf()));
+ }
+ // `commondir()` returns the shared .git directory. For a regular
+ // checkout it equals `path()` (i.e. `<repo>/.git/`); for a
+ // worktree it points to the *main* repo's `.git/` — so its parent
+ // is always the main repository root.
+ repo.commondir()
+ .parent()
+ .map(Path::to_path_buf)
+ .ok_or_else(|| BootstrapError::NotARepo(start.to_path_buf()))
+}
+
/// Read commits, format each as a one-paragraph entry. We include
/// only commits with a substantive body (more than ~120 chars
/// total) — drive-by typo-fix commits aren't worth tokens.
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index f026881f..adc22dd6 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -16,8 +16,8 @@ pub mod types;
pub use bootstrap::{
Bootstrap, BootstrapConfig, BootstrapError, BootstrapOutcome, BootstrapSource,
- DEFAULT_CHUNK_INPUT_TOKENS, SourceCounts, SourceKind, collect_sources, discover_repo_root,
- effective_chunk_budget, plan_bootstrap_chunks, prune_sources_to_budget,
+ DEFAULT_CHUNK_INPUT_TOKENS, SourceCounts, SourceKind, collect_sources, discover_main_repo_root,
+ discover_repo_root, effective_chunk_budget, plan_bootstrap_chunks, prune_sources_to_budget,
};
pub use consolidator::{
BATCH_SYSTEM_PROMPT, Consolidator, ConsolidatorError, ConsolidatorResult, build_batch_request,
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index c17a2646..80732f0b 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -287,22 +287,32 @@ async fn resolve_project_ids(
let project_name = match (project_override, cwd_norm.as_deref()) {
(Some(p), _) => p.to_string(),
- (None, Some(c)) => match std::path::Path::new(c)
- .file_name()
- .and_then(|s| s.to_str())
- .map(str::to_string)
- .filter(|s| !s.is_empty())
- {
- Some(name) => name,
- None => {
- // Defensive: basename derivation failed (e.g. cwd is "/").
- // Fall back to server defaults rather than hard-erroring.
- state
- .active_project
- .set(state.workspace_id, state.project_id);
- return Ok((state.workspace_id, state.project_id));
+ (None, Some(c)) => {
+ let path = std::path::Path::new(c);
+ // Resolve git repo root first — handles worktrees by following
+ // the .git gitdir pointer back to the main repository.
+ match ai_memory_consolidate::discover_main_repo_root(path)
+ .ok()
+ .and_then(|root| {
+ root.file_name()
+ .and_then(|s| s.to_str())
+ .map(str::to_string)
+ })
+ .or_else(|| {
+ path.file_name()
+ .and_then(|s| s.to_str())
+ .map(str::to_string)
+ .filter(|s| !s.is_empty())
+ }) {
+ Some(name) => name,
+ None => {
+ state
+ .active_project
+ .set(state.workspace_id, state.project_id);
+ return Ok((state.workspace_id, state.project_id));
+ }
}
- },
+ }
(None, None) => {
// The early-return at the top of the function guards
// against this branch; the explicit fallback here keeps
@@ -1186,4 +1196,35 @@ mod tests {
.unwrap();
assert_ne!(proj, proj2, "different basenames → different projects");
}
+
+ /// A bare repository must fall back to basename(cwd), not resolve
+ /// to the grandparent directory via commondir().parent().
+ #[tokio::test]
+ async fn bare_repo_falls_back_to_basename() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let bare_dir = tmp.path().join("my-bare-project.git");
+ git2::Repository::init_bare(&bare_dir).unwrap();
+ let cwd = bare_dir.to_str().unwrap();
+
+ let (_, proj) = resolve_project_ids(&state, Some(cwd), None, None)
+ .await
+ .unwrap();
+
+ // Must NOT be the server-default scratch project — basename should work.
+ assert_ne!(proj, state.project_id);
+
+ // The project name should come from basename, not from the grandparent.
+ // To verify: resolve with a different bare repo name and confirm different project.
+ let bare_dir2 = tmp.path().join("other-bare.git");
+ git2::Repository::init_bare(&bare_dir2).unwrap();
+ let (_, proj2) = resolve_project_ids(&state, Some(bare_dir2.to_str().unwrap()), None, None)
+ .await
+ .unwrap();
+ assert_ne!(
+ proj, proj2,
+ "different bare repo basenames → different projects"
+ );
+ }
}