Skip to content

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

Rust

fix(hooks): align repo-root host resolution across clients

AkitaOnRails903f4350b59c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c9ebf33a..658cd9de 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,12 +12,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
git worktrees whose directory lives outside the main repo tree when the server
runs in a container. The server resolves repo-root via libgit2 on the incoming
`cwd`, which fails when that host path is not visible inside the container, so
- every such worktree became its own project. The POSIX shell hooks (and the
- PowerShell hook) now resolve the main repo root host-side — following the
- worktree commondir pointer with `git rev-parse --git-common-dir` — and send it
- as an explicit `project`, so linked worktrees collapse to one stable project
- regardless of where the worktree directory lives or how the server is
- deployed. git is only touched when `cwd` is inside a real work tree. (issue #110)
+ every such worktree became its own project. Lifecycle hooks and generated
+ TypeScript plugins now resolve the main repo root host-side — following the
+ worktree commondir pointer with `git rev-parse --git-common-dir` (or the same
+ Rust/libgit2 helper for native hooks) — and send it as an explicit `project`,
+ so linked worktrees collapse to one stable project regardless of where the
+ worktree directory lives or how the server is deployed. The hook-side git
+ probe is silent outside real work trees, preserving the existing basename
+ fallback there. (issue #110)
- Unscoped MCP queries could resolve to the wrong project on a shared
install. The cwd-to-project resolver recorded the bare working directory
as a project's `repo_path` whenever the cwd was not inside a git repo
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 386f55bc..ac83fc80 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -44,15 +44,35 @@ pub fn url_encode(s: &str) -> String {
pub fn marker_query_suffix(cwd: &str) -> String {
let mut qs = format!("&cwd={}", url_encode(cwd));
if let Some(marker) = find_marker(cwd) {
- for key in ["workspace", "project", "project_strategy"] {
- if let Some(val) = parse_toml_key(&marker, key) {
- qs.push_str(&format!("&{key}={}", url_encode(&val)));
- }
+ let workspace = parse_toml_key(&marker, "workspace");
+ let mut project = parse_toml_key(&marker, "project");
+ let project_strategy = parse_toml_key(&marker, "project_strategy");
+ if project.is_none()
+ && matches!(project_strategy.as_deref(), Some("repo-root" | "repo_root"))
+ {
+ project = repo_root_project(cwd);
+ }
+ if let Some(val) = workspace {
+ qs.push_str(&format!("&workspace={}", url_encode(&val)));
+ }
+ if let Some(val) = project {
+ qs.push_str(&format!("&project={}", url_encode(&val)));
+ }
+ if let Some(val) = project_strategy {
+ qs.push_str(&format!("&project_strategy={}", url_encode(&val)));
}
}
qs
}
+fn repo_root_project(cwd: &str) -> Option<String> {
+ let root = ai_memory_consolidate::discover_main_repo_root(Path::new(cwd)).ok()?;
+ root.file_name()
+ .and_then(|s| s.to_str())
+ .filter(|s| !s.is_empty())
+ .map(str::to_owned)
+}
+
/// Walk up from `cwd` toward `$HOME` (or the filesystem root) looking
/// for `.ai-memory.toml`. Stops at `$HOME` to avoid leaking a parent
/// user's declaration on shared machines (parity with
@@ -351,4 +371,87 @@ project_strategy = "repo-root"
assert!(qs.contains("&project=infra"), "{qs}");
assert!(qs.contains("&project_strategy=repo-root"), "{qs}");
}
+
+ #[test]
+ fn marker_query_suffix_repo_root_non_git_keeps_project_implicit() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ std::fs::write(
+ tmp.path().join(".ai-memory.toml"),
+ "workspace = \"oss\"\nproject_strategy = \"repo-root\"\n",
+ )
+ .unwrap();
+ let child = tmp.path().join("plain-dir");
+ std::fs::create_dir_all(&child).unwrap();
+ let qs = marker_query_suffix(child.to_str().unwrap());
+ assert!(qs.contains("&workspace=oss"), "{qs}");
+ assert!(!qs.contains("&project="), "{qs}");
+ assert!(qs.contains("&project_strategy=repo-root"), "{qs}");
+ }
+
+ #[test]
+ fn marker_query_suffix_repo_root_collapses_out_of_tree_worktree() {
+ if std::process::Command::new("git")
+ .arg("--version")
+ .status()
+ .is_err()
+ {
+ return;
+ }
+ let tmp = tempfile::TempDir::new().unwrap();
+ let repo = tmp.path().join("repos/acme-api");
+ std::fs::create_dir_all(&repo).unwrap();
+ assert!(
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ assert!(
+ std::process::Command::new("git")
+ .arg("-C")
+ .arg(&repo)
+ .args([
+ "-c",
+ "-c",
+ "user.name=t",
+ "commit",
+ "-q",
+ "--allow-empty",
+ "-m",
+ "init",
+ ])
+ .status()
+ .unwrap()
+ .success()
+ );
+
+ let worktrees = tmp.path().join("worktrees");
+ std::fs::create_dir_all(&worktrees).unwrap();
+ std::fs::write(
+ worktrees.join(".ai-memory.toml"),
+ "workspace = \"oss\"\nproject_strategy = \"repo-root\"\n",
+ )
+ .unwrap();
+ let wt = worktrees.join("acme-api/wt-feature");
+ std::fs::create_dir_all(wt.parent().unwrap()).unwrap();
+ if !std::process::Command::new("git")
+ .arg("-C")
+ .arg(&repo)
+ .args(["worktree", "add", "-q"])
+ .arg(&wt)
+ .status()
+ .unwrap()
+ .success()
+ {
+ return;
+ }
+
+ let qs = marker_query_suffix(wt.to_str().unwrap());
+ assert!(qs.contains("&workspace=oss"), "{qs}");
+ assert!(qs.contains("&project=acme-api"), "{qs}");
+ assert!(qs.contains("&project_strategy=repo-root"), "{qs}");
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 0c5b4cb7..eb20d47c 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -958,6 +958,7 @@ fn build_opencode_plugin(server_url: &str, auth_token: Option<&str>) -> String {
// re-run.
import type {{ Plugin }} from "@opencode-ai/plugin";
+import {{ execFileSync }} from "node:child_process";
import {{ existsSync, readFileSync }} from "node:fs";
import {{ basename, dirname, join, resolve }} from "node:path";
import {{ homedir }} from "node:os";
@@ -998,6 +999,27 @@ function tomlKey(text: string, key: string): string | undefined {{
return undefined;
}}
+
+function repoRootProject(cwd: string | undefined): string | undefined {{
+ if (!cwd) return undefined;
+ try {{
+ const inside = execFileSync("git", ["-C", cwd, "rev-parse", "--is-inside-work-tree"], {{
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }}).trim();
+ if (inside !== "true") return undefined;
+ const common = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {{
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }}).trim();
+ if (!common) return undefined;
+ const root = dirname(common);
+ if (!root || root === dirname(root)) return undefined;
+ return basename(root);
+ }} catch (_e) {{
+ return undefined;
+ }}
+}}
function applyMarkerParams(url: URL, cwd: string | undefined): void {{
const marker = findMarker(cwd);
if (!marker || !cwd) return;
@@ -1010,8 +1032,9 @@ function applyMarkerParams(url: URL, cwd: string | undefined): void {{
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
- if (!project && projectStrategy === "repo-root") {{
- url.searchParams.set("project", basename(dirname(marker)));
+ if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {{
+ const repoProject = repoRootProject(cwd);
+ if (repoProject) url.searchParams.set("project", repoProject);
}}
}} catch (_e) {{
}}
@@ -1245,6 +1268,7 @@ fn build_omp_extension(server_url: &str, auth_token: Option<&str>) -> String {
// will overwrite this file (with a `.bak-<ts>` backup) on each
// re-run.
+import {{ execFileSync }} from "node:child_process";
import {{ existsSync, readFileSync }} from "node:fs";
import {{ basename, dirname, join, resolve }} from "node:path";
import {{ homedir }} from "node:os";
@@ -1285,6 +1309,27 @@ function tomlKey(text: string, key: string): string | undefined {{
return undefined;
}}
+
+function repoRootProject(cwd: string | undefined): string | undefined {{
+ if (!cwd) return undefined;
+ try {{
+ const inside = execFileSync("git", ["-C", cwd, "rev-parse", "--is-inside-work-tree"], {{
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }}).trim();
+ if (inside !== "true") return undefined;
+ const common = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {{
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }}).trim();
+ if (!common) return undefined;
+ const root = dirname(common);
+ if (!root || root === dirname(root)) return undefined;
+ return basename(root);
+ }} catch (_e) {{
+ return undefined;
+ }}
+}}
function applyMarkerParams(url: URL, cwd: string | undefined): void {{
const marker = findMarker(cwd);
if (!marker || !cwd) return;
@@ -1297,8 +1342,9 @@ function applyMarkerParams(url: URL, cwd: string | undefined): void {{
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
- if (!project && projectStrategy === "repo-root") {{
- url.searchParams.set("project", basename(dirname(marker)));
+ if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {{
+ const repoProject = repoRootProject(cwd);
+ if (repoProject) url.searchParams.set("project", repoProject);
}}
}} catch (_e) {{
}}
@@ -2554,8 +2600,15 @@ model = "gpt-5"
!plugin.contains(r#""session.created": async"#),
"OpenCode bus events must be handled through the `event` hook"
);
+ assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));
assert!(plugin.contains("import { basename, dirname, join, resolve } from \"node:path\";"));
- assert!(plugin.contains("basename(dirname(marker))"));
+ assert!(plugin.contains("function repoRootProject"));
+ assert!(plugin.contains("--git-common-dir"));
+ assert!(
+ plugin
+ .contains("projectStrategy === \"repo-root\" || projectStrategy === \"repo_root\"")
+ );
+ assert!(plugin.contains("url.searchParams.set(\"project\", repoProject)"));
}
#[test]
@@ -2607,7 +2660,14 @@ model = "gpt-5"
assert!(
extension.contains("import { basename, dirname, join, resolve } from \"node:path\";")
);
- assert!(extension.contains("basename(dirname(marker))"));
+ assert!(extension.contains("import { execFileSync } from \"node:child_process\";"));
+ assert!(extension.contains("function repoRootProject"));
+ assert!(extension.contains("--git-common-dir"));
+ assert!(
+ extension
+ .contains("projectStrategy === \"repo-root\" || projectStrategy === \"repo_root\"")
+ );
+ assert!(extension.contains("url.searchParams.set(\"project\", repoProject)"));
}
#[test]
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 963a44c4..0acc0774 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -198,8 +198,9 @@ fn build_plugin(server_url: &str, auth_token: Option<&str>) -> String {
// this local OpenClaw plugin package.
import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";
+import {{ execFileSync }} from "node:child_process";
import {{ existsSync, readFileSync }} from "node:fs";
-import {{ dirname, join, resolve }} from "node:path";
+import {{ basename, dirname, join, resolve }} from "node:path";
import {{ homedir }} from "node:os";
const SERVER = {server_literal}.replace(/\/+$/, "");
@@ -238,6 +239,27 @@ function tomlKey(text: string, key: string): string | undefined {{
return undefined;
}}
+
+function repoRootProject(cwd: string | undefined): string | undefined {{
+ if (!cwd) return undefined;
+ try {{
+ const inside = execFileSync("git", ["-C", cwd, "rev-parse", "--is-inside-work-tree"], {{
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }}).trim();
+ if (inside !== "true") return undefined;
+ const common = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {{
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }}).trim();
+ if (!common) return undefined;
+ const root = dirname(common);
+ if (!root || root === dirname(root)) return undefined;
+ return basename(root);
+ }} catch (_e) {{
+ return undefined;
+ }}
+}}
function applyMarkerParams(url: URL, cwd: string | undefined): void {{
if (!cwd) return;
url.searchParams.set("cwd", cwd);
@@ -251,6 +273,10 @@ function applyMarkerParams(url: URL, cwd: string | undefined): void {{
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
+ if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {{
+ const repoProject = repoRootProject(cwd);
+ if (repoProject) url.searchParams.set("project", repoProject);
+ }}
}} catch (_e) {{
}}
}}
@@ -441,6 +467,15 @@ mod tests {
assert!(plugin.contains("postHook(\"user-prompt\""));
assert!(plugin.contains("function applyMarkerParams"));
assert!(plugin.contains("tomlKey(body, \"project_strategy\")"));
+ assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));
+ assert!(plugin.contains("import { basename, dirname, join, resolve } from \"node:path\";"));
+ assert!(plugin.contains("function repoRootProject"));
+ assert!(plugin.contains("--git-common-dir"));
+ assert!(
+ plugin
+ .contains("projectStrategy === \"repo-root\" || projectStrategy === \"repo_root\"")
+ );
+ assert!(plugin.contains("url.searchParams.set(\"project\", repoProject)"));
assert!(plugin.contains(
"applyMarkerParams(url, typeof body.cwd === \"string\" ? body.cwd : undefined);"
));
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 847db89f..90de3c89 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -436,7 +436,10 @@ async fn resolve_project_ids(
.to_string();
let (project_name, repo_path) = match (project_override, cwd_norm.as_deref()) {
- (Some(p), Some(c)) => (p.to_string(), repo_path_from_cwd(c)),
+ (Some(p), Some(c)) => (
+ p.to_string(),
+ repo_path_from_project_override(c, p, project_strategy),
+ ),
(Some(p), None) => (p.to_string(), None),
(None, Some(c)) => match derive_project_from_cwd(c, project_strategy) {
Some(resolved) => resolved,
@@ -506,6 +509,20 @@ async fn resolve_project_ids(
cwd_is_repo_root(path, &repo_root).then(|| repo_root.to_string_lossy().into_owned())
}
+ fn repo_path_from_project_override(
+ cwd: &str,
+ project: &str,
+ strategy: ProjectStrategy,
+ ) -> Option<String> {
+ if matches!(strategy, ProjectStrategy::RepoRoot)
+ && let Some((name, Some(root))) = derive_project_from_cwd(cwd, strategy)
+ && name == project
+ {
+ return Some(root);
+ }
+ repo_path_from_cwd(cwd)
+ }
+
fn cwd_is_repo_root(cwd: &std::path::Path, repo_root: &std::path::Path) -> bool {
// git2's workdir may carry a trailing separator and resolves symlinks;
// canonicalize both before comparing. Fall back to a trailing-slash
@@ -2592,6 +2609,46 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn host_resolved_repo_root_override_records_repo_path_when_visible() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let main_dir = tmp.path().join("repo");
+ init_repo_with_commit(&main_dir);
+ let app_dir = main_dir.join("app");
+ let sibling_dir = main_dir.join("sibling");
+ std::fs::create_dir_all(&app_dir).unwrap();
+ std::fs::create_dir_all(&sibling_dir).unwrap();
+
+ let (_, proj_from_host_override) = resolve_project_ids(
+ &state,
+ Some(app_dir.to_str().unwrap()),
+ None,
+ Some("repo"),
+ ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
+
+ let (_, proj_from_sibling) = resolve_project_ids(
+ &state,
+ Some(sibling_dir.to_str().unwrap()),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ proj_from_sibling, proj_from_host_override,
+ "host-resolved repo-root override should still record repo_path so sibling cwd prefix-matches the repo project",
+ );
+ }
+
#[tokio::test]
async fn cache_does_not_poison_across_project_strategies() {
let tmp = TempDir::new().unwrap();
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 32e2c30a..d9ab4b54 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -100,8 +100,8 @@ Outcome:
### Git worktrees / repo-root identity
```
-~/projects/ai-memory/.ai-memory.toml → workspace = "oss"
- → project_strategy = "repo-root"
+~/projects/.ai-memory.toml → workspace = "oss"
+ → project_strategy = "repo-root"
```
Outcome:
@@ -110,18 +110,24 @@ Outcome:
- `~/projects/ai-memory/crates/cli` → workspace = `oss`, project = `ai-memory`
- `~/projects/ai-memory-feature-branch` → workspace = `oss`, project = `ai-memory`
+If the marker lives inside the main checkout instead (for example
+`~/projects/ai-memory/.ai-memory.toml`), copy or commit it into each
+out-of-tree worktree, or place a shared marker above the worktree parent
+directory as shown here.
+
Without `project_strategy = "repo-root"`, those same paths keep the
default behavior and resolve by their current directory basename.
-Resolution is host-side: the lifecycle hook follows the worktree's
-commondir pointer (`git rev-parse --git-common-dir`) to the main
-repository and sends the resolved name as an explicit `project`. This
-means it works even when the worktree directory lives **outside** the
-main repo tree (some tools keep worktrees in a separate directory, so
-the worktree has no `.ai-memory.toml` ancestor of its own) and even when
-the server runs in a container that cannot see the host checkout. Put
-the marker anywhere on the walk-up path from the worktree — commonly a
-single `~/.ai-memory.toml` — to select the strategy.
+Resolution is host-side: lifecycle hooks and generated TypeScript
+plugins follow the worktree's commondir pointer (`git rev-parse
+--git-common-dir`, or the same Rust/libgit2 helper for native hooks) to
+the main repository and send the resolved name as an explicit `project`.
+This means it works even when the worktree directory lives **outside**
+the main repo tree (some tools keep worktrees in a separate directory,
+so the worktree has no `.ai-memory.toml` ancestor of its own) and even
+when the server runs in a container that cannot see the host checkout.
+Put the marker anywhere on the walk-up path from the worktree — commonly
+a single `~/.ai-memory.toml` — to select the strategy.
### Single workspace, no per-repo overrides
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index fe17a57e..edc39071 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -124,6 +124,24 @@ if command -v git >/dev/null 2>&1; then
assert_eq "explicit project pin beats repo-root" \
"&cwd=$REPO/crates/cli&workspace=oss&project=pinned&project_strategy=repo-root" \
"$QSP"
+
+ PSH=""
+ if command -v pwsh >/dev/null 2>&1; then
+ PSH=$(command -v pwsh)
+ elif command -v powershell >/dev/null 2>&1; then
+ PSH=$(command -v powershell)
+ fi
+ if [ -n "$PSH" ]; then
+ PS_REPO=$($PSH -NoProfile -ExecutionPolicy Bypass -Command \
+ ". '$PWD/hooks/lib/ai-memory-hook.ps1'; Get-AiMemoryRepoRootProject -Cwd '$REPO/crates/cli'")
+ assert_eq "powershell repo-root helper resolves repo basename" "acme-api" "$PS_REPO"
+ else
+ PS_STATIC=$(grep -q 'function Get-AiMemoryRepoRootProject' hooks/lib/ai-memory-hook.ps1 \
+ && grep -q -- '--git-common-dir' hooks/lib/ai-memory-hook.ps1 \
+ && grep -q 'Get-AiMemoryRepoRootProject -Cwd' hooks/lib/ai-memory-hook.ps1 \
+ && printf 'ok' || printf 'missing')
+ assert_eq "powershell repo-root helper has static parity" "ok" "$PS_STATIC"
+ fi
fi
# --- url_encode -------------------------------------------------------