Skip to content

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

Rust

fix(windows): harden native path normalization

AkitaOnRails04d9e585793d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bfd1c62f..e2abaa23 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+- Native Windows/Git Bash installs now normalize hook cwd, stored project
+ `repo_path`, and the home-directory guard consistently across slash styles,
+ including legacy rows persisted with backslashes. `AI_MEMORY_HOME` now feeds
+ the same home guard as `$HOME`, and Git-backed helpers preserve bare-repo
+ fallback semantics while limiting CLI git fallbacks to path/open failures.
+
## [1.4.1] - 2026-06-28
## [1.4.0] - 2026-06-26
diff --git a/README.md b/README.md
index 4cdf81ef..1f5d0852 100644
--- a/README.md
+++ b/README.md
@@ -300,8 +300,10 @@ one matching entry.
### Install Notes
- **Windows:** use the Linux path inside WSL2, or the native Windows wrapper
- from PowerShell/cmd. Native Claude Code uses Git Bash `.sh` hooks; other
- script-hook agents use PowerShell defaults. Do not mix path worlds. See
+ from PowerShell/cmd. Native Claude Code uses direct `ai-memory.exe hook`
+ commands by default, with `AI_MEMORY_HOOK_PLATFORM=windows-bash` available for
+ Git Bash `.sh` hooks; other script-hook agents use PowerShell defaults. Do not
+ mix path worlds. See
[`docs/windows.md`](docs/windows.md).
- **Docker compose:** `docker compose -f docker/docker-compose.yml up -d`
is supported; agent setup is the same as step 3 above.
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index d1c1f0e4..6f0538f7 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -66,10 +66,10 @@ pub struct Config {
#[serde(default)]
pub base_path: String,
/// Operator home directory, captured once here (the single config-read
- /// path) from `$HOME`. Used to keep the cwd->project resolver and the
+ /// path) from `AI_MEMORY_HOME` or `$HOME`. Used to keep the cwd->project resolver and the
/// startup heal from treating `$HOME` as a prefix-match catch-all
/// (issue #103) without env reads scattered through the runtime. Not a
- /// config.toml / env key: always derived from `$HOME` at load.
+ /// config.toml key: always derived from the process environment at load.
#[serde(skip)]
pub home_dir: Option<String>,
/// Per-subsystem log filter (overridable by `RUST_LOG`).
@@ -182,6 +182,7 @@ pub struct Config {
#[derive(Debug, Clone, Default)]
pub struct RuntimeEnv {
data_dir: Option<PathBuf>,
+ home_dir: Option<String>,
server_url: Option<String>,
auth_token: Option<String>,
host_cwd: Option<String>,
@@ -202,6 +203,7 @@ impl RuntimeEnv {
fn from_process() -> Self {
Self {
data_dir: env_path("AI_MEMORY_DATA_DIR"),
+ home_dir: env_string("AI_MEMORY_HOME").or_else(|| env_string("HOME")),
server_url: env_string("AI_MEMORY_SERVER_URL"),
auth_token: env_string("AI_MEMORY_AUTH_TOKEN"),
host_cwd: env_string("AI_MEMORY_HOST_CWD"),
@@ -600,13 +602,11 @@ impl Config {
config.admission_webhooks = parsed;
}
- // $HOME read once here (config-read-path invariant); threaded to the
- // resolver guard and startup heal so neither reads the env directly.
- // Normalized so a trailing slash can't slip a catch-all past the
- // exact-match guards.
- config.home_dir = std::env::var("HOME")
- .ok()
- .and_then(|home| normalize_home_dir(&home));
+ // Home is captured once in RuntimeEnv (config-read-path invariant);
+ // threaded to the resolver guard and startup heal so neither reads the
+ // env directly. AI_MEMORY_HOME is accepted for tests/wrappers that need
+ // to emulate a host home distinct from the process HOME.
+ config.home_dir = runtime_env.home_dir.as_deref().and_then(normalize_home_dir);
// CLI override always wins (figment doesn't see it because clap has
// already parsed the flag into `cli_data_dir`).
@@ -892,12 +892,14 @@ fn canonicalise_or_keep(p: &Path) -> PathBuf {
p.to_path_buf()
}
-/// Normalize `$HOME` for prefix-match comparisons: strip trailing separators
+/// Normalize home for prefix-match comparisons: accept either slash spelling,
+/// strip trailing separators,
/// so a stored `repo_path` of `/home/u` still equals a `$HOME` of `/home/u/`
/// (the cwd side is trimmed the same way in `find_project_by_cwd_prefix`).
/// All-separator or empty input yields `None` (no usable home).
fn normalize_home_dir(home: &str) -> Option<String> {
- let trimmed = home.trim_end_matches('/');
+ let normalized = home.replace('\\', "/");
+ let trimmed = normalized.trim_end_matches('/');
(!trimmed.is_empty()).then(|| trimmed.to_string())
}
@@ -975,13 +977,15 @@ mod tests {
let tmp = TempDir::new().unwrap();
let cli_dir = tmp.path().join("override");
let cfg = Config::load(None, Some(cli_dir)).unwrap();
- // `home_dir` is derived from `$HOME` at load (the single config-read
- // path), normalized so a trailing slash can't bypass the catch-all
- // guards. Reading the env in a test is allowed; this fails if the
- // load-time assignment is dropped while `$HOME` is set.
+ // `home_dir` is derived from AI_MEMORY_HOME or `$HOME` at load (the
+ // single config-read path), normalized so a trailing slash can't bypass
+ // the catch-all guards. Reading the env in a test is allowed; this
+ // fails if the load-time assignment is dropped while either env var is
+ // set.
assert_eq!(
cfg.home_dir,
- std::env::var("HOME")
+ std::env::var("AI_MEMORY_HOME")
+ .or_else(|_| std::env::var("HOME"))
.ok()
.and_then(|h| normalize_home_dir(&h))
);
@@ -995,6 +999,10 @@ mod tests {
normalize_home_dir("/home/u///"),
Some("/home/u".to_string())
);
+ assert_eq!(
+ normalize_home_dir(r"C:\Users\tester\"),
+ Some("C:/Users/tester".to_string())
+ );
// Degenerate inputs yield no usable home rather than an empty or
// root-collapsing prefix key.
assert_eq!(normalize_home_dir("/"), None);
diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rs
index 29ee844d..7dea1d8c 100644
--- a/crates/ai-memory-consolidate/src/bootstrap.rs
+++ b/crates/ai-memory-consolidate/src/bootstrap.rs
@@ -578,6 +578,17 @@ pub fn discover_main_repo_root(start: &Path) -> Result<PathBuf, BootstrapError>
#[cfg(windows)]
fn discover_main_repo_root_fallback(start: &Path) -> Result<PathBuf, BootstrapError> {
+ let is_bare = std::process::Command::new("git")
+ .arg("-C")
+ .arg(start)
+ .args(["rev-parse", "--is-bare-repository"])
+ .output()
+ .map_err(|_| BootstrapError::NotARepo(start.to_path_buf()))?;
+ if !is_bare.status.success() {
+ return Err(BootstrapError::NotARepo(start.to_path_buf()));
+ }
+ let is_bare = String::from_utf8_lossy(&is_bare.stdout).trim() == "true";
+
let output = std::process::Command::new("git")
.arg("-C")
.arg(start)
@@ -592,10 +603,7 @@ fn discover_main_repo_root_fallback(start: &Path) -> Result<PathBuf, BootstrapEr
if common_dir.is_empty() {
return Err(BootstrapError::NotARepo(start.to_path_buf()));
}
- Path::new(common_dir)
- .parent()
- .map(Path::to_path_buf)
- .ok_or_else(|| BootstrapError::NotARepo(start.to_path_buf()))
+ main_root_from_common_dir(Path::new(common_dir), is_bare, start)
}
#[cfg(not(windows))]
@@ -603,6 +611,21 @@ fn discover_main_repo_root_fallback(start: &Path) -> Result<PathBuf, BootstrapEr
Err(BootstrapError::NotARepo(start.to_path_buf()))
}
+#[cfg(any(windows, test))]
+fn main_root_from_common_dir(
+ common_dir: &Path,
+ is_bare: bool,
+ start: &Path,
+) -> Result<PathBuf, BootstrapError> {
+ if is_bare {
+ return Err(BootstrapError::NotARepo(start.to_path_buf()));
+ }
+ common_dir
+ .parent()
+ .map(Path::to_path_buf)
+ .ok_or_else(|| BootstrapError::NotARepo(start.to_path_buf()))
+}
+
/// Strategy for [`derive_project_name`]: which path "wins" when a
/// `cwd` lives inside a git repo. Both the CLI's `resolve_project_name`
/// and the hook router's `resolve_project_ids` call through this
@@ -1588,6 +1611,20 @@ mod tests {
assert_eq!(name, "my-app");
}
+ #[test]
+ fn main_root_from_common_dir_rejects_bare_repositories() {
+ let start = Path::new("/tmp/repo.git");
+ assert!(main_root_from_common_dir(Path::new("/tmp/repo.git"), true, start).is_err());
+ }
+
+ #[test]
+ fn main_root_from_common_dir_returns_parent_for_worktree_common_dir() {
+ let root =
+ main_root_from_common_dir(Path::new("/tmp/repo/.git"), false, Path::new("/tmp/repo"))
+ .unwrap();
+ assert_eq!(root, PathBuf::from("/tmp/repo"));
+ }
+
/// Degenerate input (root, empty) returns None instead of
/// returning an empty project name that would later fail
/// `get_or_create_project`'s validation.
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 938b514a..b222cb4b 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -1606,12 +1606,12 @@ mod tests {
.get_or_create_workspace(String::from(DEFAULT_WORKSPACE_NAME))
.await
.unwrap();
- // Three poison rows that would each match too broadly without
- // the safety filters.
+ // Poison rows that would match too broadly without the safety filters.
+ // New trailing-slash repo paths are normalized at the store write
+ // boundary; legacy raw trailing separators are covered in store tests.
for (name, repo) in [
("empty-repo", String::new()),
("root-repo", String::from("/")),
- ("trailing-repo", String::from("/repo/foo/")),
] {
state
.writer
@@ -1620,7 +1620,7 @@ mod tests {
.unwrap();
}
- // Resolve a cwd that the three poison rows would each match
+ // Resolve a cwd that the poison rows would each match
// pre-fix. Expect: a NEW project created by basename.
let (resolved_ws, resolved) = resolve_project_ids(
&state,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 798b38b2..307a397e 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -113,6 +113,7 @@ pub fn get_or_create_project(
name: &str,
repo_path: Option<&str>,
) -> StoreResult<ai_memory_core::ProjectId> {
+ let repo_path = repo_path.map(normalize_repo_path_key);
let tx = conn.transaction()?;
let existing: Option<Vec<u8>> = tx
.query_row(
@@ -132,7 +133,7 @@ pub fn get_or_create_project(
id.as_bytes(),
workspace_id.as_bytes(),
name,
- repo_path,
+ repo_path.as_deref(),
Timestamp::now().as_microsecond()
],
)?;
@@ -165,6 +166,7 @@ pub fn get_or_create_project(
/// temporarily unmounted drive, and destroying it would wipe a valid prefix
/// key. This safety rule is mandatory.
pub fn heal_catch_all_repo_paths(conn: &mut Connection, home: Option<&str>) -> StoreResult<u64> {
+ let home = home.map(normalize_repo_path_key);
let candidates: Vec<(Vec<u8>, String)> = {
let mut stmt =
conn.prepare("SELECT id, repo_path FROM projects WHERE repo_path IS NOT NULL")?;
@@ -175,7 +177,7 @@ pub fn heal_catch_all_repo_paths(conn: &mut Connection, home: Option<&str>) -> S
};
let to_null: Vec<Vec<u8>> = candidates
.into_iter()
- .filter(|(_, repo_path)| should_heal_repo_path(repo_path, home))
+ .filter(|(_, repo_path)| should_heal_repo_path(repo_path, home.as_deref()))
.map(|(id, _)| id)
.collect();
let tx = conn.transaction()?;
@@ -192,7 +194,8 @@ pub fn heal_catch_all_repo_paths(conn: &mut Connection, home: Option<&str>) -> S
/// Decide whether a non-NULL `repo_path` is a prefix-match catch-all that
/// should be NULLed. See [`heal_catch_all_repo_paths`] for the full rule.
fn should_heal_repo_path(repo_path: &str, home: Option<&str>) -> bool {
- if repo_path == "/" || home == Some(repo_path) {
+ let repo_path_key = normalize_repo_path_key(repo_path);
+ if repo_path_key == "/" || home == Some(repo_path_key.as_str()) {
return true; // broad sentinels, healed even if they look like git roots
}
let p = std::path::Path::new(repo_path);
@@ -204,6 +207,15 @@ fn should_heal_repo_path(repo_path: &str, home: Option<&str>) -> bool {
matches!(p.try_exists(), Ok(true)) && matches!(p.join(".git").try_exists(), Ok(false))
}
+fn normalize_repo_path_key(path: &str) -> String {
+ let normalized = path.replace('\\', "/");
+ if normalized.len() > 1 {
+ normalized.trim_end_matches('/').to_string()
+ } else {
+ normalized
+ }
+}
+
fn scheduler_state_table_exists(conn: &Connection) -> StoreResult<bool> {
Ok(conn
.query_row(
@@ -259,6 +271,7 @@ pub fn ensure_project_with_id(
name: &str,
repo_path: Option<&str>,
) -> StoreResult<()> {
+ let repo_path = repo_path.map(normalize_repo_path_key);
conn.execute(
"INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(id) DO NOTHING",
@@ -266,7 +279,7 @@ pub fn ensure_project_with_id(
id.as_bytes(),
workspace_id.as_bytes(),
name,
- repo_path,
+ repo_path.as_deref(),
Timestamp::now().as_microsecond()
],
)?;
@@ -282,7 +295,7 @@ pub fn ensure_project_with_id(
Some((existing_ws, existing_name, existing_repo_path))
if existing_ws.as_slice() == workspace_id.as_bytes()
&& existing_name == name
- && existing_repo_path.as_deref() == repo_path =>
+ && existing_repo_path.as_deref() == repo_path.as_deref() =>
{
Ok(())
}
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 5615ca7a..931f9fc1 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -3465,15 +3465,13 @@ impl ReaderPool {
///
/// - `workspace_id = ?1` — never matches a project in another
/// workspace.
- /// - `repo_path IS NOT NULL AND length(repo_path) > 1 AND repo_path
- /// NOT LIKE '%/'` — rejects stored values that would match too
- /// broadly (`NULL`, `''`, `/`) or fail the `<repo_path>/%`
- /// boundary (trailing slash).
- /// - Stored `repo_path` wildcards (`%`, `_`) are escaped in the
- /// generated `LIKE` pattern, so they stay literal path bytes
- /// instead of matching unintended siblings.
- /// - `?3 IS NULL OR repo_path <> ?3` — never matches a stored
- /// `repo_path` equal to the operator's home directory (`home`).
+ /// - `repo_path IS NOT NULL` plus Rust-side normalization rejects stored
+ /// values that would match too broadly (`NULL`, `''`, `/`) or fail the
+ /// `<repo_path>/%` boundary (trailing slash/backslash).
+ /// - Stored `repo_path` wildcards (`%`, `_`) are compared as literal path
+ /// bytes in Rust, not as SQL `LIKE` wildcards.
+ /// - A normalized stored `repo_path` equal to the operator's home
+ /// directory (`home`) is never matched.
/// Such a row would be a prefix catch-all for every project
/// beneath `$HOME`; the caller passes the server's own `$HOME`
/// (filesystem root `/` is already excluded by the
@@ -3495,38 +3493,49 @@ impl ReaderPool {
cwd: String,
home: Option<&str>,
) -> StoreResult<Option<(ProjectId, String)>> {
- let home = home.map(str::to_owned);
- let cwd_norm = cwd.trim_end_matches('/').to_string();
+ let home = home.map(|h| normalize_cwd(h).into_owned());
+ let cwd_norm = normalize_cwd(&cwd).into_owned();
if !is_safe_cwd_for_prefix_match(&cwd_norm) {
return Ok(None);
}
self.with_conn(move |conn| {
- // Two-condition LIKE: exact match OR descendant (prefix +
- // `/`). The boundary `/` on the descendant arm stops
- // `/foo/bar` from matching `/foo/ba`. The LIKE arm escapes
- // stored wildcard characters so real paths containing `%` or
- // `_` stay literal instead of turning into broad matches.
- let row_opt = conn
- .query_row(
- "SELECT id, name FROM projects \
- WHERE workspace_id = ?1 \
- AND repo_path IS NOT NULL \
- AND length(repo_path) > 1 \
- AND repo_path NOT LIKE '%/' \
- AND (?3 IS NULL OR repo_path <> ?3) \
- AND (?2 = repo_path OR ?2 LIKE replace(replace(replace(repo_path, '\\', '\\\\'), '%', '\\%'), '_', '\\_') || '/%' ESCAPE '\\') \
- ORDER BY length(repo_path) DESC \
- LIMIT 1",
- params![workspace_id.as_bytes(), cwd_norm, home],
- |row| {
- let bytes: Vec<u8> = row.get(0)?;
- let name: String = row.get(1)?;
- Ok((bytes, name))
- },
- )
- .optional()?;
- row_opt
- .map(|(bytes, name)| {
+ // Compare in Rust instead of SQL LIKE so stored `%`/`_` bytes stay
+ // literal and legacy Windows rows with backslashes keep matching a
+ // slash-normalized hook cwd. New writes normalize `repo_path`, but
+ // this compatibility read path protects existing databases.
+ let mut stmt = conn.prepare(
+ "SELECT id, name, repo_path FROM projects \
+ WHERE workspace_id = ?1 AND repo_path IS NOT NULL",
+ )?;
+ let rows = stmt.query_map(params![workspace_id.as_bytes()], |row| {
+ Ok((
+ row.get::<_, Vec<u8>>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ ))
+ })?;
+ let mut matches = Vec::new();
+ for row in rows {
+ let (bytes, name, repo_path) = row?;
+ if has_trailing_path_separator(&repo_path) {
+ continue;
+ }
+ let repo_norm = normalize_cwd(&repo_path).into_owned();
+ if repo_norm.len() <= 1
+ || !is_safe_cwd_for_prefix_match(&repo_norm)
+ || home.as_deref() == Some(repo_norm.as_str())
+ {
+ continue;
+ }
+ if cwd_within(&repo_norm, &cwd_norm) {
+ matches.push((bytes, name, repo_norm.len()));
+ }
+ }
+ matches.sort_by_key(|entry| std::cmp::Reverse(entry.2));
+ matches
+ .into_iter()
+ .next()
+ .map(|(bytes, name, _)| {
ProjectId::from_slice(&bytes)
.map(|id| (id, name))
.map_err(StoreError::from)
@@ -3560,7 +3569,7 @@ impl ReaderPool {
home: Option<&str>,
) -> StoreResult<ContaminationReport> {
let scoped = scope.is_some();
- let home = home.map(str::to_owned);
+ let home = home.map(|h| normalize_cwd(h).into_owned());
let scope_params: Vec<Value> = match &scope {
Some((ws, proj)) => vec![
Value::Blob(ws.as_bytes().to_vec()),
@@ -3686,7 +3695,14 @@ impl ReaderPool {
})?;
for r in rows {
let (ws_b, proj_b, name, repo_path) = r?;
- if home.as_deref() == Some(repo_path.as_str()) {
+ if has_trailing_path_separator(&repo_path) {
+ continue;
+ }
+ let repo_path = normalize_cwd(&repo_path).into_owned();
+ if repo_path.len() <= 1
+ || !is_safe_cwd_for_prefix_match(&repo_path)
+ || home.as_deref() == Some(repo_path.as_str())
+ {
continue;
}
prefixes.push((
@@ -3707,7 +3723,14 @@ impl ReaderPool {
})?;
for r in rows {
let (ws_b, proj_b, name, repo_path) = r?;
- if home.as_deref() == Some(repo_path.as_str()) {
+ if has_trailing_path_separator(&repo_path) {
+ continue;
+ }
+ let repo_path = normalize_cwd(&repo_path).into_owned();
+ if repo_path.len() <= 1
+ || !is_safe_cwd_for_prefix_match(&repo_path)
+ || home.as_deref() == Some(repo_path.as_str())
+ {
continue;
}
prefixes.push((
@@ -3727,13 +3750,12 @@ impl ReaderPool {
// CHECK A: resolve each session's cwd against preloaded valid prefixes
// and flag a bucket mismatch.
for (id, ws, landed_proj, landed_ws_name, landed_proj_name, cwd) in candidates {
- let cwd_norm = cwd.trim_end_matches('/').to_string();
+ let cwd_norm = normalize_cwd(&cwd).into_owned();
if !is_safe_cwd_for_prefix_match(&cwd_norm) {
continue;
}
let resolved = prefixes.iter().find(|(prefix_ws, _, _, repo_path)| {
- *prefix_ws == ws
- && (cwd_norm == *repo_path || cwd_norm.starts_with(&format!("{repo_path}/")))
+ *prefix_ws == ws && cwd_within(repo_path, &cwd_norm)
});
if let Some((_, resolved_proj, resolved_name, _)) = resolved
&& *resolved_proj != landed_proj
@@ -4738,6 +4760,10 @@ fn is_safe_cwd_for_prefix_match(cwd: &str) -> bool {
true
}
+fn has_trailing_path_separator(path: &str) -> bool {
+ path.len() > 1 && path.ends_with(['/', '\\'])
+}
+
fn checkout(inner: &Inner) -> StoreResult<Connection> {
if let Some(conn) = inner.pool.lock().pop() {
return Ok(conn);
@@ -5118,4 +5144,76 @@ mod tests {
.unwrap();
assert_eq!(widened, None, "wildcards in repo_path must stay literal");
}
+
+ #[tokio::test]
+ async fn prefix_match_handles_legacy_windows_backslash_repo_path() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let project_id = ProjectId::new();
+ let conn =
+ rusqlite::Connection::open(tmp.path().join("db").join(crate::DB_FILENAME)).unwrap();
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ rusqlite::params![
+ project_id.as_bytes(),
+ ws.as_bytes(),
+ "app",
+ r"C:\Users\tester\app",
+ jiff::Timestamp::now().as_microsecond()
+ ],
+ )
+ .unwrap();
+
+ let matched = store
+ .reader
+ .find_project_by_cwd_prefix(
+ ws,
+ String::from("C:/Users/tester/app/crates/core"),
+ Some(r"C:\Users\tester"),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(matched.map(|(id, _)| id), Some(project_id));
+ }
+
+ #[tokio::test]
+ async fn prefix_match_ignores_legacy_trailing_separator_repo_path() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let project_id = ProjectId::new();
+ let conn =
+ rusqlite::Connection::open(tmp.path().join("db").join(crate::DB_FILENAME)).unwrap();
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ rusqlite::params![
+ project_id.as_bytes(),
+ ws.as_bytes(),
+ "legacy-trailing",
+ "/repo/foo/",
+ jiff::Timestamp::now().as_microsecond()
+ ],
+ )
+ .unwrap();
+
+ let matched = store
+ .reader
+ .find_project_by_cwd_prefix(ws, String::from("/repo/foo/bar"), None)
+ .await
+ .unwrap();
+
+ assert_eq!(matched, None, "legacy trailing separator must not match");
+ }
}
diff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rs
index a13c4162..36f236de 100644
--- a/crates/ai-memory-wiki/src/git.rs
+++ b/crates/ai-memory-wiki/src/git.rs
@@ -7,7 +7,7 @@
use std::path::{Path, PathBuf};
-use git2::{IndexAddOption, ObjectType, Repository, Signature};
+use git2::{ErrorCode, IndexAddOption, ObjectType, Repository, Signature};
use tracing::{debug, warn};
use crate::error::{WikiError, WikiResult};
@@ -35,6 +35,11 @@ pub struct Checkpoint {
pub time: i64,
}
+enum CommitGit2Error {
+ Open(git2::Error),
+ Other(git2::Error),
+}
+
impl GitAdapter {
/// Open or initialise the repo at `root`. Idempotent: if the
/// directory is already a git repo, leaves it alone.
@@ -70,22 +75,25 @@ impl GitAdapter {
pub fn commit_all(&self, message: &str) -> WikiResult<Option<git2::Oid>> {
match self.commit_all_git2(message) {
Ok(result) => Ok(result),
- Err(e) => commit_all_fallback(&self.root, message, e),
+ Err(CommitGit2Error::Open(e)) if should_try_commit_cli_fallback(&e) => {
+ commit_all_fallback(&self.root, message, e)
+ }
+ Err(CommitGit2Error::Open(e) | CommitGit2Error::Other(e)) => Err(map_git_err(e)),
}
}
- fn commit_all_git2(&self, message: &str) -> WikiResult<Option<git2::Oid>> {
- let repo = Repository::open(&self.root).map_err(map_git_err)?;
+ fn commit_all_git2(&self, message: &str) -> Result<Option<git2::Oid>, CommitGit2Error> {
+ let repo = Repository::open(&self.root).map_err(CommitGit2Error::Open)?;
// Stage everything (including deletions).
- let mut index = repo.index().map_err(map_git_err)?;
+ let mut index = repo.index().map_err(CommitGit2Error::Other)?;
index
.add_all(["*"].iter(), IndexAddOption::DEFAULT, None)
- .map_err(map_git_err)?;
- index.write().map_err(map_git_err)?;
+ .map_err(CommitGit2Error::Other)?;
+ index.write().map_err(CommitGit2Error::Other)?;
// If the index matches HEAD, there is nothing to commit.
- let tree_oid = index.write_tree().map_err(map_git_err)?;
+ let tree_oid = index.write_tree().map_err(CommitGit2Error::Other)?;
if let Ok(head) = repo.head()
&& let Some(target) = head.target()
&& let Ok(parent_commit) = repo.find_commit(target)
@@ -102,12 +110,13 @@ impl GitAdapter {
debug!("fresh repo, empty index; no commit");
return Ok(None);
}
- let tree = repo.find_tree(tree_oid).map_err(map_git_err)?;
- let sig = Signature::now(COMMIT_AUTHOR_NAME, COMMIT_AUTHOR_EMAIL).map_err(map_git_err)?;
+ let tree = repo.find_tree(tree_oid).map_err(CommitGit2Error::Other)?;
+ let sig = Signature::now(COMMIT_AUTHOR_NAME, COMMIT_AUTHOR_EMAIL)
+ .map_err(CommitGit2Error::Other)?;
let parents: Vec<git2::Commit<'_>> = match repo.head() {
Ok(head) => match head.target() {
- Some(oid) => vec![repo.find_commit(oid).map_err(map_git_err)?],
+ Some(oid) => vec![repo.find_commit(oid).map_err(CommitGit2Error::Other)?],
None => Vec::new(),
},
Err(_) => Vec::new(),
@@ -115,7 +124,7 @@ impl GitAdapter {
let parent_refs: Vec<&git2::Commit<'_>> = parents.iter().collect();
let oid = repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &parent_refs)
- .map_err(map_git_err)?;
+ .map_err(CommitGit2Error::Other)?;
debug!(oid = %oid, "wiki commit");
Ok(Some(oid))
}
@@ -207,7 +216,7 @@ impl GitAdapter {
fn commit_all_fallback(
root: &Path,
message: &str,
- original: WikiError,
+ original: git2::Error,
) -> WikiResult<Option<git2::Oid>> {
warn!(error = %original, root = %root.display(), "libgit2 commit failed; trying git CLI fallback");
run_git(root, ["add", "-A"])?;
@@ -248,9 +257,13 @@ fn commit_all_fallback(
fn commit_all_fallback(
_root: &Path,
_message: &str,
- original: WikiError,
+ original: git2::Error,
) -> WikiResult<Option<git2::Oid>> {
- Err(original)
+ Err(map_git_err(original))
+}
+
+fn should_try_commit_cli_fallback(error: &git2::Error) -> bool {
+ matches!(error.code(), ErrorCode::NotFound)
}
#[cfg(windows)]
diff --git a/docs/install.md b/docs/install.md
index 80f1095c..e9f5232c 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -481,8 +481,9 @@ Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw have lifecycle
> bundled scripts to your home dir, (2) `docker run --rm install-hooks`
> to render the config snippet.
> On native Windows, Claude Code is the exception to the PowerShell default:
-> it runs hooks through Git Bash, so ai-memory renders `bash -c` commands for
-> the `.sh` scripts.
+> it uses direct `ai-memory.exe hook` commands by default. Set
+> `AI_MEMORY_HOOK_PLATFORM=windows-bash` before `install-hooks` to opt back into
+> Git Bash `bash -c` commands for the `.sh` scripts.
> OpenClaw, OpenCode, and OMP are different: they use generated
> TypeScript plugin/extension files, so no shell-script extraction is
> needed for those clients.
diff --git a/docs/windows.md b/docs/windows.md
index ca9a1c4b..1de92e0b 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -224,6 +224,12 @@ native on an i7-6700HQ). Notes:
Set the env var before running `install-hooks` so the chosen platform
is baked into the rendered hook commands.
+Project auto-scope treats Windows backslashes and POSIX slashes as the same path
+separator when comparing hook `cwd`, stored `repo_path`, and the home-directory
+catch-all guard. Wrappers or tests that need a host home different from the
+process `HOME` can set `AI_MEMORY_HOME`; it is normalized through the same path
+boundary before startup healing or cwd-prefix matching.
+
### Tuning the spool timings (high-latency instances)
The native hook spools events locally and drains them to the server at session