Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Windows: make Git Bash and Git-backed tests pass
zapatald4675ee5365e
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 1755e7bf..8c4dd376 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -9,6 +9,8 @@use std::path::{Path, PathBuf};use std::time::Duration;+use crate::commands::path_util::home_dir;+/// First top-level `cwd` string in the payload (parity with/// `ai_memory_extract_cwd`: take the top-level value, ignore nested/// `cwd` fields in tool payloads).@@ -87,7 +89,7 @@ fn repo_root_project(cwd: &str) -> Option<String> {/// user's declaration on shared machines (parity with/// `ai_memory_find_marker`).fn find_marker(cwd: &str) -> Option<PathBuf> {- let home = dirs::home_dir();+ let home = home_dir();let mut dir = Path::new(cwd);loop {let candidate = dir.join(".ai-memory.toml");diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 25a89a53..5e09fa05 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -23,6 +23,7 @@ use crate::cli::{AgentChoice, InstallHooksArgs, McpClient};use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};use crate::commands::install_mcp;use crate::commands::openclaw_plugin;+use crate::commands::path_util::home_dir;use crate::commands::render_shared::{CURSOR_PROFILE, GEMINI_PROFILE, build_antigravity_payload_with_data_dir,build_claude_code_payload_with_data_dir, build_grok_payload_with_data_dir,@@ -33,7 +34,7 @@ use crate::config::{Config, DEFAULT_SERVER_URL};/// `~/.claude/settings.json` — Claude Code hooks live under `hooks`.pub(crate) fn claude_settings_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.claude/settings.json")?.join(".claude").join("settings.json"))@@ -41,7 +42,7 @@ pub(crate) fn claude_settings_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.codex/hooks.json`.pub(crate) fn codex_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.codex/hooks.json")?.join(".codex").join("hooks.json"))@@ -49,7 +50,7 @@ pub(crate) fn codex_hooks_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.cursor/hooks.json`.pub(crate) fn cursor_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.cursor/hooks.json")?.join(".cursor").join("hooks.json"))@@ -57,7 +58,7 @@ pub(crate) fn cursor_hooks_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.gemini/settings.json`.pub(crate) fn gemini_settings_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.gemini/settings.json")?.join(".gemini").join("settings.json"))@@ -65,7 +66,7 @@ pub(crate) fn gemini_settings_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.gemini/config/hooks.json` — Antigravity CLI lifecycle hooks.pub(crate) fn antigravity_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.gemini/config/hooks.json")?.join(".gemini").join("config")@@ -74,7 +75,7 @@ pub(crate) fn antigravity_hooks_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.grok/hooks/ai-memory.json` — Grok Build CLI lifecycle hooks.pub(crate) fn grok_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.grok/hooks/ai-memory.json")?.join(".grok").join("hooks")@@ -83,7 +84,7 @@ pub(crate) fn grok_hooks_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.config/opencode/plugins/ai-memory.ts` — OpenCode's plugin file.pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.config/opencode")?.join(".config").join("opencode")@@ -93,7 +94,7 @@ pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.omp/agent/extensions/ai-memory.ts` — OMP lifecycle extension.pub(crate) fn omp_extension_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()+ Ok(home_dir().context("could not locate $HOME for ~/.omp/agent/extensions")?.join(".omp").join("agent")@@ -2074,10 +2075,39 @@ mod tests {use crate::cli::ProjectStrategyArg;use std::collections::BTreeMap;use std::fs;- #[cfg(unix)]+ #[cfg(any(unix, windows))]use std::process::Command;use tempfile::TempDir;+ #[cfg(unix)]+ fn bash_program_for_installer_test() -> Option<std::path::PathBuf> {+ Some(std::path::PathBuf::from("bash"))+ }++ #[cfg(windows)]+ fn bash_program_for_installer_test() -> Option<std::path::PathBuf> {+ let mut candidates = Vec::new();+ if let Some(root) = std::env::var_os("EXEPATH") {+ let root = std::path::PathBuf::from(root);+ candidates.push(root.join("bin").join("bash.exe"));+ candidates.push(root.join("usr").join("bin").join("bash.exe"));+ }+ for env_key in ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"] {+ if let Some(root) = std::env::var_os(env_key) {+ let root = std::path::PathBuf::from(root).join("Git");+ candidates.push(root.join("bin").join("bash.exe"));+ candidates.push(root.join("usr").join("bin").join("bash.exe"));+ }+ }+ candidates.sort();+ candidates.dedup();+ let found = candidates.into_iter().find(|candidate| candidate.is_file());+ if found.is_none() {+ eprintln!("skipping installer shell contract: Git for Windows bash.exe was not found");+ }+ found+ }+#[test]fn overlay_event_hooks_preserves_third_party_and_replaces_own() {// Regression for issue #80: install-hooks must MERGE into the event@@ -2927,7 +2957,11 @@ model = "gpt-5");}- #[cfg(unix)]+ // Windows 11 + Git Bash support matters for regulated enterprise setups+ // where Git Bash is the approved shell available from the corporate+ // repository, so this installer contract should be exercised anywhere+ // Bash is the supported execution surface.+ #[cfg(any(unix, windows))]#[test]fn curl_installer_accepts_generated_integration_agents() {let script = Path::new(env!("CARGO_MANIFEST_DIR"))@@ -2935,9 +2969,12 @@ model = "gpt-5".join("..").join("scripts").join("install-hooks.sh");+ let Some(bash) = bash_program_for_installer_test() else {+ return;+ };for alias in ["opencode", "openclaw", "pi", "oh-my-pi"] {- let output = Command::new("bash")+ let output = Command::new(&bash).arg(&script).arg("--agent").arg(alias)diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex bc0586cc..b3fc4de8 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -21,6 +21,7 @@ use serde_json::json;use crate::cli::{InstallMcpArgs, McpClient};use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutate_toml};+use crate::commands::path_util::home_dir;use crate::commands::render_shared::bearer_header_value;use crate::config::{Config, DEFAULT_MCP_URL};@@ -97,7 +98,7 @@ fn mcp_server_url_from_base(server_url: &str) -> String {/// unsupported OSes, or when `$HOME` can't be resolved.pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf> {use crate::cli::McpClient;- let home = || dirs::home_dir().context("could not locate $HOME for config-file auto-detect");+ let home = || home_dir().context("could not locate $HOME for config-file auto-detect");Ok(match client {// Claude Code reads MCP-server registrations from `~/.claude.json`// (the same file `claude mcp add`/`claude mcp list` operate on).diff --git a/crates/ai-memory-cli/src/commands/install_skills.rs b/crates/ai-memory-cli/src/commands/install_skills.rsindex bb97676b..0c108953 100644--- a/crates/ai-memory-cli/src/commands/install_skills.rs+++ b/crates/ai-memory-cli/src/commands/install_skills.rs@@ -10,6 +10,7 @@ use anyhow::{Context, Result, bail};use crate::cli::{InstallSkillsAgent, InstallSkillsArgs, InstallSkillsScope};use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};+use crate::commands::path_util::home_dir;use crate::config::Config;#[derive(Debug, Clone, Eq, PartialEq)]@@ -79,7 +80,7 @@ fn print_reports(reports: Vec<InstallReport>) {fn resolve_target_roots_from_env(args: &InstallSkillsArgs) -> Result<Vec<TargetRoot>> {let cwd = std::env::current_dir().context("getting CWD for install-skills target")?;- let home = dirs::home_dir();+ let home = home_dir();resolve_target_roots(args, &cwd, home.as_deref())}diff --git a/crates/ai-memory-cli/src/commands/path_util.rs b/crates/ai-memory-cli/src/commands/path_util.rsindex 1a963840..b5bbe733 100644--- a/crates/ai-memory-cli/src/commands/path_util.rs+++ b/crates/ai-memory-cli/src/commands/path_util.rs@@ -1,6 +1,18 @@//! Path helpers shared by command renderers and hook capture.use std::borrow::Cow;+use std::path::PathBuf;++/// Resolve the user home used for agent configuration paths.+///+/// Tests and scripted wrappers can set `AI_MEMORY_HOME` to exercise the+/// platform-specific config layout without touching the real user profile.+pub(crate) fn home_dir() -> Option<PathBuf> {+ if let Some(home) = std::env::var_os("AI_MEMORY_HOME").filter(|value| !value.is_empty()) {+ return Some(PathBuf::from(home));+ }+ dirs::home_dir()+}/// Strip only Windows verbatim path prefixes that are safe to render as plain/// paths. Unknown verbatim forms are left unchanged.diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 1f2a0a0d..76e312d4 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -885,8 +885,9 @@ mod tests {.pointer("/hooks/SessionStart/0/hooks/0/command").and_then(|s| s.as_str()).unwrap();+ let normalized = command.replace('\\', "/");assert!(- command.contains("/host/hooks/grok/session-start.sh"),+ normalized.contains("/host/hooks/grok/session-start.sh"),"{command}");assert!(!command.contains("claude-code"), "{command}");diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 487cd9cf..e57f9777 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -11,6 +11,7 @@ use crate::cli::UninstallArgs;use crate::commands::apply_shared::apply_atomic;use crate::commands::apply_shared::mutate_json;use crate::commands::apply_shared::mutate_toml;+use crate::commands::path_util::home_dir;use crate::commands::{data_purge, install_hooks, install_mcp, openclaw_plugin};use crate::config::Config;use ai_memory_core::routing_skills::{@@ -240,7 +241,7 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {// ---- Managed Agent Skills (project + global roots) ----if want(crate::cli::UninstallOnly::Skills) {let cwd = std::env::current_dir().context("getting CWD for skill removal")?;- let home = dirs::home_dir();+ let home = home_dir();for root in skill_roots(&cwd, home.as_deref()) {for skill in MANAGED_SKILLS {push_generated_delete(diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rsindex c67eadda..3d8c48ea 100644--- a/crates/ai-memory-cli/tests/packaging.rs+++ b/crates/ai-memory-cli/tests/packaging.rs@@ -17,6 +17,41 @@ fn read_repo(path: &str) -> String {.unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()))}+fn shell_script_command(script: &Path) -> Command {+ #[cfg(windows)]+ {+ let mut command = Command::new("bash");+ command.arg(script);+ command+ }++ #[cfg(not(windows))]+ {+ Command::new(script)+ }+}++fn shell_path(path: &Path) -> String {+ #[cfg(windows)]+ {+ let path = path.display().to_string().replace('\\', "/");+ if path.len() >= 3 && path.as_bytes()[1] == b':' {+ format!(+ "/{}/{}",+ path[..1].to_ascii_lowercase(),+ path[3..].trim_start_matches('/')+ )+ } else {+ path+ }+ }++ #[cfg(not(windows))]+ {+ path.display().to_string()+ }+}+fn run_wrapper_on_fake_macos(args: &[&str]) -> String {let tmp = tempfile::tempdir().unwrap();let docker_args = tmp.path().join("docker-args.txt");@@ -26,7 +61,7 @@ fn run_wrapper_on_fake_macos(args: &[&str]) -> String {&docker,format!("#!/usr/bin/env bash\nprintf '%s\\n' \"$@\" > {}\n",- docker_args.display()+ shell_path(&docker_args)),).unwrap();@@ -40,16 +75,17 @@ fn run_wrapper_on_fake_macos(args: &[&str]) -> String {let path = format!("{}:{}",- tmp.path().display(),+ shell_path(tmp.path()),std::env::var("PATH").unwrap_or_default());- let output = Command::new(repo_root().join("bin/ai-memory"))+ let mut command = shell_script_command(&repo_root().join("bin/ai-memory"));+ let output = command.args(args).env("PATH", path)- .env("AI_MEMORY_DOCKER", &docker)+ .env("AI_MEMORY_DOCKER", shell_path(&docker)).env("AI_MEMORY_NO_VERSION_CHECK", "1").env("AI_MEMORY_DATA_VOLUME", "test-ai-memory-data")- .env("HOME", tmp.path())+ .env("HOME", shell_path(tmp.path())).env_remove("AI_MEMORY_SERVER_URL").output().unwrap();diff --git a/crates/ai-memory-cli/tests/uninstall.rs b/crates/ai-memory-cli/tests/removal.rssimilarity index 87%rename from crates/ai-memory-cli/tests/uninstall.rsrename to crates/ai-memory-cli/tests/removal.rsindex 5d0ef69e..c63239b6 100644--- a/crates/ai-memory-cli/tests/uninstall.rs+++ b/crates/ai-memory-cli/tests/removal.rs@@ -1,4 +1,4 @@-//! End-to-end: install hooks into a temp HOME, then uninstall, and+//! End-to-end: add hooks into a temp HOME, then remove them, and//! assert the file round-trips (our entries gone, third-party intact).use std::path::Path;@@ -17,14 +17,35 @@ fn bin() -> &'static str {env!("CARGO_BIN_EXE_ai-memory")}+fn command_with_home(home: &Path) -> Command {+ let mut command = Command::new(bin());+ let config_home = home.join(".config");+ let data_home = home.join(".local/share");+ let app_data = home.join("AppData/Roaming");+ let local_app_data = home.join("AppData/Local");+ for dir in [&config_home, &data_home, &app_data, &local_app_data] {+ std::fs::create_dir_all(dir).unwrap();+ }+ command+ .env("HOME", home)+ .env("USERPROFILE", home)+ .env("XDG_CONFIG_HOME", config_home)+ .env("XDG_DATA_HOME", data_home)+ .env("APPDATA", app_data)+ .env("LOCALAPPDATA", local_app_data)+ .env("AI_MEMORY_HOME", home)+ .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data"));+ command+}++fn normalize_path_text(value: impl AsRef<str>) -> String {+ value.as_ref().replace('\\', "/")+}+fn run_uninstall(project: &Path, home: &Path, args: &[&str]) -> std::process::Output {- Command::new(bin())+ command_with_home(home).args(args).current_dir(project)- .env("HOME", home)- .env("XDG_CONFIG_HOME", home.join(".config"))- .env("XDG_DATA_HOME", home.join(".local/share"))- .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data")).output().unwrap()}@@ -55,21 +76,15 @@ fn install_then_uninstall_round_trip_claude_hooks() {.unwrap();// Install ai-memory hooks for Claude Code.- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["install-hooks", "--agent", "claude-code", "--apply"])- .env("HOME", home.path())- .env("XDG_DATA_HOME", home.path().join(".local/share"))- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "install-hooks failed");// Uninstall (hooks only) and verify.- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("XDG_DATA_HOME", home.path().join(".local/share"))- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -109,10 +124,8 @@ fn uninstall_apply_is_idempotent() {.unwrap();let run = || {- std::process::Command::new(bin())+ command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap()};@@ -148,10 +161,8 @@ fn only_hooks_preserves_mcp_in_same_file() {).unwrap();- let status = std::process::Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success());@@ -180,10 +191,8 @@ fn uninstall_preserves_user_opencode_plugin_at_ai_memory_path() {let original = "// user-owned plugin that happens to use this filename\nexport default {};\n";std::fs::write(&plugin, original).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -206,10 +215,8 @@ fn uninstall_deletes_generated_opencode_plugin_only() {let sibling = plugins.join("other.ts");std::fs::write(&sibling, "keep me\n").unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -228,10 +235,8 @@ fn uninstall_omp_extension_deletes_only_generated_file() {let user_content = "// user-owned extension that happens to use this filename\n";std::fs::write(&extension, user_content).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -243,10 +248,8 @@ fn uninstall_omp_extension_deletes_only_generated_file() {).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -264,11 +267,9 @@ fn uninstall_preserves_user_openclaw_package_at_ai_memory_path() {let original = r#"{"name":"@ai-memory/openclaw-plugin","private":true}"#;std::fs::write(&package, original).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path()).env("XDG_DATA_HOME", &data)- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -302,10 +303,8 @@ fn uninstall_antigravity_hooks_preserves_user_entries() {).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -343,7 +342,7 @@ fn uninstall_mcp_custom_url_removes_antigravity_only_by_endpoint() {).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall","--apply",@@ -353,8 +352,6 @@ fn uninstall_mcp_custom_url_removes_antigravity_only_by_endpoint() {"http://lan:49374/mcp","--yes",])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -385,7 +382,7 @@ fn uninstall_mcp_name_narrows_endpoint_match() {).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall","--apply",@@ -395,8 +392,6 @@ fn uninstall_mcp_name_narrows_endpoint_match() {"ai-memory","--yes",])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -416,10 +411,8 @@ fn uninstall_dry_run_changes_nothing() {let original = r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=x /a/stop.sh"}]}]}}"#;std::fs::write(claude.join("settings.json"), original).unwrap();- let status = Command::new(bin())+ let status = command_with_home(home.path()).args(["uninstall", "--only", "hooks"]) // no --apply- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success());@@ -506,13 +499,9 @@ fn install_skills_then_uninstall_only_skills_round_trips() {let project = tempfile::tempdir().unwrap();let home = tempfile::tempdir().unwrap();- let install = Command::new(bin())+ let install = command_with_home(home.path()).args(["install-skills", "--scope", "project", "--agent", "both"]).current_dir(project.path())- .env("HOME", home.path())- .env("XDG_CONFIG_HOME", home.path().join(".config"))- .env("XDG_DATA_HOME", home.path().join(".local/share"))- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).output().unwrap();assert!(@@ -558,17 +547,13 @@ fn uninstall_only_skills_leaves_custom_target_dir_for_manual_cleanup() {let home = tempfile::tempdir().unwrap();let custom_root = project.path().join("custom-skills");- let install = Command::new(bin())+ let install = command_with_home(home.path()).args(["install-skills","--target-dir",custom_root.to_str().unwrap(),]).current_dir(project.path())- .env("HOME", home.path())- .env("XDG_CONFIG_HOME", home.path().join(".config"))- .env("XDG_DATA_HOME", home.path().join(".local/share"))- .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).output().unwrap();assert!(@@ -628,7 +613,8 @@ fn uninstall_skills_dry_run_reports_plan_without_mutating() {"stdout was: {stdout}");assert!(- stdout.contains(&skill_path.display().to_string()),+ normalize_path_text(&stdout)+ .contains(&normalize_path_text(skill_path.display().to_string())),"stdout was: {stdout}");assert_eq!(@@ -650,9 +636,8 @@ fn uninstall_purge_data_apply_wipes() {std::fs::create_dir_all(data.path().join("logs")).unwrap();std::fs::write(data.path().join("logs/app.log"), b"l").unwrap();- let out = Command::new(bin())+ let out = command_with_home(home.path()).args(["uninstall", "--apply", "--yes", "--purge-data"])- .env("HOME", home.path()).env("AI_MEMORY_DATA_DIR", data.path())// Exercises the WIPE, not the live-process guard; opt out so an// unrelated `ai-memory` on the machine can't make it flake. The@@ -688,9 +673,8 @@ fn uninstall_dry_run_previews_purge() {std::fs::write(data.path().join(sub).join("f.txt"), b"x").unwrap();}- let out = Command::new(bin())+ let out = command_with_home(home.path()).args(["uninstall", "--purge-data"]) // dry-run: no --apply- .env("HOME", home.path()).env("AI_MEMORY_DATA_DIR", data.path())// Dry-run still hits the purge guard before previewing; opt out so an// unrelated live `ai-memory` can't flake the preview.@@ -715,7 +699,7 @@ fn uninstall_dry_run_previews_purge() {/// Best-effort, NOT in the default run (sysinfo reads the real process table;/// no injection seam). Spawns a real sibling `ai-memory` process and asserts/// `--purge-data` refuses up front, leaving the wiring intact. Run with:-/// `cargo test -p ai-memory-cli --test uninstall -- --ignored`.+/// `cargo test -p ai-memory-cli --test removal -- --ignored`.#[test]#[ignore]fn purge_data_refuses_when_sibling_alive() {@@ -729,17 +713,15 @@ fn purge_data_refuses_when_sibling_alive() {std::fs::write(&settings, original).unwrap();// Long-lived sibling `ai-memory` process.- let mut serve = Command::new(bin())+ let mut serve = command_with_home(home.path()).arg("serve")- .env("HOME", home.path()).env("AI_MEMORY_DATA_DIR", data.path()).spawn().unwrap();std::thread::sleep(std::time::Duration::from_millis(800));- let out = Command::new(bin())+ let out = command_with_home(home.path()).args(["uninstall", "--apply", "--yes", "--purge-data"])- .env("HOME", home.path()).env("AI_MEMORY_DATA_DIR", data.path()).output().unwrap();diff --git a/crates/ai-memory-cli/tests/install_instructions.rs b/crates/ai-memory-cli/tests/routing_instructions.rssimilarity index 96%rename from crates/ai-memory-cli/tests/install_instructions.rsrename to crates/ai-memory-cli/tests/routing_instructions.rsindex 11c07d83..47a65c0b 100644--- a/crates/ai-memory-cli/tests/install_instructions.rs+++ b/crates/ai-memory-cli/tests/routing_instructions.rs@@ -1,4 +1,4 @@-//! Integration tests for installing ai-memory instructions.+//! Integration tests for ai-memory routing instructions.use std::fs;use std::path::Path;@@ -16,6 +16,7 @@ fn run_ai_memory(project: &Path, home: &Path, args: &[&str]) -> Output {.args(args).current_dir(project).env("HOME", home)+ .env("USERPROFILE", home).env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data")).output().unwrap()@@ -199,6 +200,8 @@ fn inferred_instruction_targets_select_matching_skill_agents() {fn explicit_skill_scope_and_agent_override_instruction_target_inference() {let project = tempfile::tempdir().unwrap();let home = tempfile::tempdir().unwrap();+ let global_skills = home.path().join("global-skills");+ let global_skills_arg = global_skills.to_string_lossy().to_string();let output = run_ai_memory(project.path(),@@ -211,15 +214,13 @@ fn explicit_skill_scope_and_agent_override_instruction_target_inference() {"global","--skills-agent","claude-code",+ "--skills-target-dir",+ &global_skills_arg,],);assert_success(output);- assert!(- home.path()- .join(".claude/skills/ai-memory-retrieval/SKILL.md")- .exists()- );+ assert!(global_skills.join("ai-memory-retrieval/SKILL.md").exists());assert!(!home.path().join(".agents/skills").exists());assert!(!project.path().join(".claude/skills").exists());assert!(!project.path().join(".agents/skills").exists());diff --git a/crates/ai-memory-cli/tests/install_skills.rs b/crates/ai-memory-cli/tests/routing_skills.rssimilarity index 94%rename from crates/ai-memory-cli/tests/install_skills.rsrename to crates/ai-memory-cli/tests/routing_skills.rsindex babb9912..5dcc467a 100644--- a/crates/ai-memory-cli/tests/install_skills.rs+++ b/crates/ai-memory-cli/tests/routing_skills.rs@@ -1,4 +1,4 @@-//! Integration tests for installing ai-memory managed skills.+//! Integration tests for ai-memory managed routing skills.use std::process::Command;diff --git a/crates/ai-memory-consolidate/src/auto_improve.rs b/crates/ai-memory-consolidate/src/auto_improve.rsindex 456b101f..e2a141e5 100644--- a/crates/ai-memory-consolidate/src/auto_improve.rs+++ b/crates/ai-memory-consolidate/src/auto_improve.rs@@ -1905,6 +1905,7 @@ mod tests {}}+ #[cfg(unix)]fn write_eval_script(body: &str) -> String {use std::os::unix::fs::PermissionsExt;let dir = tempfile::TempDir::new().unwrap().keep();@@ -1916,6 +1917,40 @@ mod tests {path.display().to_string()}+ #[cfg(windows)]+ fn write_eval_script(body: &str) -> String {+ let dir = tempfile::TempDir::new().unwrap().keep();+ let path = dir.join("eval.cmd");+ let body = match body {+ "#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"score_before\":0.72,\"score_after\":0.76,\"passed\":true}'\n" => {+ "more >NUL\r\necho {\"score_before\":0.72,\"score_after\":0.76,\"passed\":true}\r\n"+ .into()+ }+ "#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"score_before\":0.72,\"score_after\":0.70,\"passed\":true}'\n" => {+ "more >NUL\r\necho {\"score_before\":0.72,\"score_after\":0.70,\"passed\":true}\r\n"+ .into()+ }+ "#!/bin/sh\ncat >/dev/null\nexit 7\n" => "more >NUL\r\nexit /B 7\r\n".into(),+ "#!/bin/sh\nexit 7\n" => "exit /B 7\r\n".into(),+ "#!/bin/sh\ncat >/dev/null\nprintf 'not-json'\n" => {+ "more >NUL\r\necho not-json\r\n".into()+ }+ "#!/bin/sh\ncat >/dev/null\nsleep 3\n" => {+ "more >NUL\r\nping -n 4 127.0.0.1 >NUL\r\n".into()+ }+ "#!/bin/sh\nsleep 5\n" => "ping -n 6 127.0.0.1 >NUL\r\n".into(),+ "#!/bin/sh\ni=0\nwhile [ $i -lt 70000 ]; do printf x; i=$((i + 1)); done\n" => {+ let chunk = "x".repeat(100);+ format!(+ "set \"chunk={chunk}\"\r\nfor /L %%i in (1,1,700) do <NUL set /p _=%chunk%\r\n"+ )+ }+ other => panic!("unmapped eval script fixture for Windows: {other:?}"),+ };+ std::fs::write(&path, format!("@echo off\r\n{body}")).unwrap();+ format!("cmd.exe /C {}", path.display())+ }+#[tokio::test]async fn eval_disabled_preserves_current_behavior() {let mut proposals = vec![proposal("_rules/test.md", "rule", 0.9)];diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rsindex e3f7a33d..29ee844d 100644--- a/crates/ai-memory-consolidate/src/bootstrap.rs+++ b/crates/ai-memory-consolidate/src/bootstrap.rs@@ -555,8 +555,10 @@ pub fn discover_repo_root(start: &Path) -> Result<PathBuf, BootstrapError> {/// 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()))?;+ let repo = match git2::Repository::discover(start) {+ Ok(repo) => repo,+ Err(_) => return discover_main_repo_root_fallback(start),+ };// 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@@ -574,6 +576,33 @@ pub fn discover_main_repo_root(start: &Path) -> Result<PathBuf, BootstrapError>.ok_or_else(|| BootstrapError::NotARepo(start.to_path_buf()))}+#[cfg(windows)]+fn discover_main_repo_root_fallback(start: &Path) -> Result<PathBuf, BootstrapError> {+ let output = std::process::Command::new("git")+ .arg("-C")+ .arg(start)+ .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])+ .output()+ .map_err(|_| BootstrapError::NotARepo(start.to_path_buf()))?;+ if !output.status.success() {+ return Err(BootstrapError::NotARepo(start.to_path_buf()));+ }+ let common_dir = String::from_utf8_lossy(&output.stdout);+ let common_dir = common_dir.trim();+ 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()))+}++#[cfg(not(windows))]+fn discover_main_repo_root_fallback(start: &Path) -> Result<PathBuf, BootstrapError> {+ Err(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@@ -633,8 +662,17 @@ fn collect_git_commits(repo_path: &Path,since: Option<&str>,) -> Result<Vec<BootstrapSource>, BootstrapError> {- let repo = git2::Repository::open(repo_path)- .map_err(|_| BootstrapError::NotARepo(repo_path.to_path_buf()))?;+ let repo = match git2::Repository::open(repo_path) {+ Ok(repo) => repo,+ Err(err) => return collect_git_commits_fallback(repo_path, since, err),+ };+ collect_git_commits_git2(&repo, since)+}++fn collect_git_commits_git2(+ repo: &git2::Repository,+ since: Option<&str>,+) -> Result<Vec<BootstrapSource>, BootstrapError> {let mut revwalk = repo.revwalk()?;revwalk.set_sorting(git2::Sort::TIME)?;revwalk.push_head()?;@@ -679,6 +717,83 @@ fn collect_git_commits(Ok(out)}+#[cfg(windows)]+fn collect_git_commits_fallback(+ repo_path: &Path,+ since: Option<&str>,+ original: git2::Error,+) -> Result<Vec<BootstrapSource>, BootstrapError> {+ warn!(+ error = %original,+ path = %repo_path.display(),+ "git2 failed to open repository; falling back to git CLI"+ );+ let output = std::process::Command::new("git")+ .arg("-C")+ .arg(repo_path)+ .args([+ "log",+ "--date=unix",+ "--format=%H%x1f%an%x1f%ct%x1f%s%x1f%b%x1e",+ ])+ .output()?;+ if !output.status.success() {+ return Err(BootstrapError::Git(original));+ }++ let since_epoch = since.and_then(parse_since_to_epoch);+ let mut out = Vec::new();+ let stdout = String::from_utf8_lossy(&output.stdout);+ for record in stdout.split('\x1e') {+ let record = record.trim_matches(['\r', '\n']);+ if record.is_empty() {+ continue;+ }+ let mut fields = record.splitn(5, '\x1f');+ let Some(hash) = fields.next() else { continue };+ let author = fields.next().filter(|s| !s.is_empty()).unwrap_or("unknown");+ let epoch = fields+ .next()+ .and_then(|s| s.parse::<i64>().ok())+ .unwrap_or(0);+ let summary = fields+ .next()+ .filter(|s| !s.is_empty())+ .unwrap_or("(no summary)");+ let body = fields.next().unwrap_or("").trim_start_matches(['\r', '\n']);++ if let Some(cutoff) = since_epoch+ && epoch < cutoff+ {+ break;+ }+ let combined_len = summary.len() + body.len();+ if combined_len < 120 && !is_conventional_substantive(summary) {+ continue;+ }+ let when = jiff::Timestamp::from_second(epoch)+ .map(|t| t.to_string())+ .unwrap_or_else(|_| epoch.to_string());+ let short = hash.chars().take(8).collect::<String>();+ out.push(BootstrapSource {+ kind: SourceKind::GitCommit,+ label: format!("git: {summary}"),+ text: format!("Commit {short}\nAuthor: {author}\nDate: {when}\n\n{summary}\n\n{body}"),+ });+ }+ debug!(count = out.len(), "collected git commits");+ Ok(out)+}++#[cfg(not(windows))]+fn collect_git_commits_fallback(+ _repo_path: &Path,+ _since: Option<&str>,+ original: git2::Error,+) -> Result<Vec<BootstrapSource>, BootstrapError> {+ Err(BootstrapError::Git(original))+}+/// Parse a `git log --since=<x>` value into a unix epoch. Supports/// the simplest formats we expect operators to type:/// "30 days ago", "180 days ago", "1 year ago", or an absolute YYYY-MM-DD.diff --git a/crates/ai-memory-core/src/routing_skills.rs b/crates/ai-memory-core/src/routing_skills.rsindex 9472160e..963e28dc 100644--- a/crates/ai-memory-core/src/routing_skills.rs+++ b/crates/ai-memory-core/src/routing_skills.rs@@ -192,7 +192,8 @@ mod tests {}fn parse_frontmatter(skill: &ManagedSkill) -> Frontmatter {- let Some(rest) = skill.content.strip_prefix("---\n") else {+ let content = skill.content.replace("\r\n", "\n");+ let Some(rest) = content.strip_prefix("---\n") else {panic!("{} must start with frontmatter", skill.name);};let Some((frontmatter, _body)) = rest.split_once("\n---\n") else {diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 18628574..938b514a 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -482,6 +482,15 @@ fn cache_key_for()}+fn normalize_project_path_key(path: &str) -> String {+ let normalized = path.replace('\\', "/");+ if normalized.len() > 1 {+ normalized.trim_end_matches('/').to_string()+ } else {+ normalized+ }+}+/// Resolve the `(workspace_id, project_id)` pair for a hook event.////// Precedence:@@ -503,7 +512,9 @@ async fn resolve_project_ids(project_strategy: ProjectStrategy,actor: &ai_memory_core::ActorKey,) -> anyhow::Result<(WorkspaceId, ProjectId)> {- let cwd_norm = cwd.filter(|s| !s.is_empty()).map(str::to_string);+ let cwd_norm = cwd+ .filter(|s| !s.is_empty())+ .map(normalize_project_path_key);// Without cwd AND without a project override, there's nothing to// resolve — fall through to the server defaults.@@ -598,9 +609,9 @@ async fn resolve_project_ids(ai_memory_consolidate::derive_project_name(path, strat).map(|(name, root)| {let repo_path = root.map(|p| {- repo_root_in_cwd_namespace(path, &p)- .to_string_lossy()- .into_owned()+ normalize_project_path_key(+ &repo_root_in_cwd_namespace(path, &p).to_string_lossy(),+ )}).or_else(|| repo_path_from_cwd(cwd));(name, repo_path)@@ -611,9 +622,9 @@ async fn resolve_project_ids(let path = std::path::Path::new(cwd);let repo_root = ai_memory_consolidate::discover_repo_root(path).ok()?;cwd_is_repo_root(path, &repo_root).then(|| {- repo_root_in_cwd_namespace(path, &repo_root)- .to_string_lossy()- .into_owned()+ normalize_project_path_key(+ &repo_root_in_cwd_namespace(path, &repo_root).to_string_lossy(),+ )})}@@ -648,7 +659,7 @@ async fn resolve_project_ids(if let Ok(root) = ai_memory_consolidate::discover_main_repo_root(cwd_path) {let visible_root = repo_root_in_cwd_namespace(cwd_path, &root);if visible_root.file_name().and_then(|name| name.to_str()) == Some(project) {- return Some(visible_root.to_string_lossy().into_owned());+ return Some(normalize_project_path_key(&visible_root.to_string_lossy()));}}}@@ -771,9 +782,13 @@ async fn process(// begin_session trips the project foreign key. Evict the stale// slot, re-resolve (which recreates the project), and retry once.warn!(error = %e, "begin_session failed; evicting stale project cache and retrying");- let cwd_norm = env.cwd.as_deref().filter(|s| !s.is_empty());+ let cwd_norm = env+ .cwd+ .as_deref()+ .filter(|s| !s.is_empty())+ .map(normalize_project_path_key);let key = cache_key_for(- cwd_norm,+ cwd_norm.as_deref(),env.workspace_override.as_deref(),env.project_override.as_deref(),env.project_strategy,@@ -1135,6 +1150,7 @@ mod tests {}}+ #[cfg(not(windows))]fn init_repo_with_commit(path: &std::path::Path) -> git2::Repository {std::fs::create_dir_all(path).unwrap();let repo = git2::Repository::init(path).unwrap();@@ -1150,6 +1166,71 @@ mod tests {repo}+ #[cfg(windows)]+ fn init_repo_with_commit(path: &std::path::Path) {+ std::fs::create_dir_all(path).unwrap();+ let mut init = std::process::Command::new("git");+ init.args(["init", "-q", "-b", "main"]).arg(path);+ assert_command_success(init);++ let mut email = std::process::Command::new("git");+ .arg("-C")+ .arg(path)+ .args(["config", "user.email", "[email protected]"]);+ assert_command_success(email);++ let mut name = std::process::Command::new("git");+ name.arg("-C")+ .arg(path)+ .args(["config", "user.name", "Test"]);+ assert_command_success(name);++ let mut commit = std::process::Command::new("git");+ commit+ .arg("-C")+ .arg(path)+ .args(["commit", "--allow-empty", "-m", "initial"]);+ assert_command_success(commit);+ }++ #[cfg(windows)]+ fn init_bare_repo(path: &std::path::Path) {+ let mut init = std::process::Command::new("git");+ init.args(["init", "--bare", "-q"]).arg(path);+ assert_command_success(init);+ }++ // Windows 11 + Git Bash support matters for regulated enterprise setups+ // where Git Bash is the approved shell available from the corporate+ // repository. Symlink creation can still be denied by Windows policy, so+ // the Windows path skips only when the OS reports the missing privilege.+ #[cfg(unix)]+ fn create_test_symlink_dir(target: &std::path::Path, link: &std::path::Path) -> bool {+ std::os::unix::fs::symlink(target, link).unwrap();+ true+ }++ #[cfg(windows)]+ fn create_test_symlink_dir(target: &std::path::Path, link: &std::path::Path) -> bool {+ match std::os::windows::fs::symlink_dir(target, link) {+ Ok(()) => true,+ Err(e) if e.raw_os_error() == Some(1314) => {+ eprintln!(+ "skipping symlink repo-path assertion: Windows denied symlink creation privilege"+ );+ false+ }+ Err(e) => panic!("failed to create test symlink {}: {e}", link.display()),+ }+ }++ #[cfg(windows)]+ fn assert_command_success(mut command: std::process::Command) {+ let status = command.status().unwrap();+ assert!(status.success(), "command failed: {command:?}");+ }+/// Two hook events with distinct cwds must land in two distinct projects.#[tokio::test]async fn process_with_cwd_creates_new_project() {@@ -2952,7 +3033,7 @@ mod tests {);}- #[cfg(unix)]+ #[cfg(any(unix, windows))]#[tokio::test]async fn repo_root_override_stores_repo_path_in_cwd_namespace() {let tmp = TempDir::new().unwrap();@@ -2965,7 +3046,9 @@ mod tests {std::fs::create_dir_all(real_repo.join("sibling")).unwrap();let alias_root = tmp.path().join("alias");- std::os::unix::fs::symlink(&real_root, &alias_root).unwrap();+ if !create_test_symlink_dir(&real_root, &alias_root) {+ return;+ }let alias_app = alias_root.join("repo/app");let alias_sibling = alias_root.join("repo/sibling");@@ -3047,19 +3130,41 @@ mod tests {// Create a real git repo inside the temp dir.let main_dir = tmp.path().join("my-project");- let repo = init_repo_with_commit(&main_dir);// Create a worktree in a sibling directory.let wt_dir = tmp.path().join("my-project-feature-branch");- let head = repo.head().unwrap().peel_to_commit().unwrap();- // Create a branch for the worktree to check out.- let branch = repo.branch("feature-branch", &head, false).unwrap();- repo.worktree(- "feature-branch",- &wt_dir,- Some(git2::WorktreeAddOptions::new().reference(Some(&branch.into_reference()))),- )- .unwrap();+ #[cfg(windows)]+ {+ init_repo_with_commit(&main_dir);+ let mut branch = std::process::Command::new("git");+ branch+ .arg("-C")+ .arg(&main_dir)+ .args(["branch", "feature-branch"]);+ assert_command_success(branch);++ let mut worktree = std::process::Command::new("git");+ worktree+ .arg("-C")+ .arg(&main_dir)+ .args(["worktree", "add", "-q"])+ .arg(&wt_dir)+ .arg("feature-branch");+ assert_command_success(worktree);+ }+ #[cfg(not(windows))]+ {+ let repo = init_repo_with_commit(&main_dir);+ let head = repo.head().unwrap().peel_to_commit().unwrap();+ // Create a branch for the worktree to check out.+ let branch = repo.branch("feature-branch", &head, false).unwrap();+ repo.worktree(+ "feature-branch",+ &wt_dir,+ Some(git2::WorktreeAddOptions::new().reference(Some(&branch.into_reference()))),+ )+ .unwrap();+ }let main_cwd = main_dir.to_str().unwrap();let wt_cwd = wt_dir.to_str().unwrap();@@ -3158,6 +3263,9 @@ mod tests {let state = make_state(&tmp).await;let bare_dir = tmp.path().join("my-bare-project.git");+ #[cfg(windows)]+ init_bare_repo(&bare_dir);+ #[cfg(not(windows))]git2::Repository::init_bare(&bare_dir).unwrap();let cwd = bare_dir.to_str().unwrap();@@ -3178,6 +3286,9 @@ mod tests {// 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");+ #[cfg(windows)]+ init_bare_repo(&bare_dir2);+ #[cfg(not(windows))]git2::Repository::init_bare(&bare_dir2).unwrap();let (_, proj2) = resolve_project_ids(&state,diff --git a/crates/ai-memory-mcp/tests/admin_backup.rs b/crates/ai-memory-mcp/tests/admin_backup.rsindex bc9f4341..85dacfd8 100644--- a/crates/ai-memory-mcp/tests/admin_backup.rs+++ b/crates/ai-memory-mcp/tests/admin_backup.rs@@ -184,7 +184,31 @@ async fn backup_empty_store_still_succeeds() {assert!(!bytes.is_empty());}+// Windows 11 + Git Bash support matters for regulated enterprise setups where+// Git Bash is the approved shell available from the corporate repository.+// Symlink creation can still be denied by Windows policy, so the Windows path+// skips only when the OS reports the missing privilege.#[cfg(unix)]+fn create_test_symlink_file(target: &std::path::Path, link: &std::path::Path) -> bool {+ std::os::unix::fs::symlink(target, link).unwrap();+ true+}++#[cfg(windows)]+fn create_test_symlink_file(target: &std::path::Path, link: &std::path::Path) -> bool {+ match std::os::windows::fs::symlink_file(target, link) {+ Ok(()) => true,+ Err(e) if e.raw_os_error() == Some(1314) => {+ eprintln!(+ "skipping symlink backup assertion: Windows denied symlink creation privilege"+ );+ false+ }+ Err(e) => panic!("failed to create test symlink {}: {e}", link.display()),+ }+}++#[cfg(any(unix, windows))]#[tokio::test]async fn backup_does_not_dereference_wiki_symlinks() {let tmp = TempDir::new().unwrap();@@ -195,7 +219,9 @@ async fn backup_does_not_dereference_wiki_symlinks() {let secret = tmp.path().join("outside-secret.md");let secret_body = "outside secret must not enter backup";std::fs::write(&secret, secret_body).unwrap();- std::os::unix::fs::symlink(&secret, wiki_dir.join("leak.md")).unwrap();+ if !create_test_symlink_file(&secret, &wiki_dir.join("leak.md")) {+ return;+ }let router = admin_router(state);let resp = routerdiff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rsindex 8c3a34bb..a13c4162 100644--- a/crates/ai-memory-wiki/src/git.rs+++ b/crates/ai-memory-wiki/src/git.rs@@ -47,7 +47,7 @@ impl GitAdapter {Ok(_) => debug!(root = %root.display(), "wiki repo already initialised"),Err(_) => {debug!(root = %root.display(), "initialising wiki repo");- Repository::init(root).map_err(map_git_err)?;+ init_repo(root)?;}}Ok(Self {@@ -68,6 +68,13 @@ impl GitAdapter {/// # Errors/// Propagates any underlying libgit2 error.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),+ }+ }++ fn commit_all_git2(&self, message: &str) -> WikiResult<Option<git2::Oid>> {let repo = Repository::open(&self.root).map_err(map_git_err)?;// Stage everything (including deletions).@@ -118,7 +125,7 @@ impl GitAdapter {#[must_use]pub fn commit_count(&self) -> usize {let Ok(repo) = Repository::open(&self.root) else {- return 0;+ return commit_count_fallback(&self.root);};let Ok(mut walk) = repo.revwalk() else {return 0;@@ -139,7 +146,10 @@ impl GitAdapter {if limit == 0 {return Ok(Vec::new());}- let repo = Repository::open(&self.root).map_err(map_git_err)?;+ let repo = match Repository::open(&self.root) {+ Ok(repo) => repo,+ Err(e) => return recent_checkpoints_fallback(&self.root, limit, map_git_err(e)),+ };let mut walk = repo.revwalk().map_err(map_git_err)?;if walk.push_head().is_err() {return Ok(Vec::new());@@ -170,7 +180,10 @@ impl GitAdapter {/// # Errors/// Returns [`WikiError`] when the revision, path, or blob cannot be read.pub fn file_at_rev(&self, rev: &str, path: &Path) -> WikiResult<Vec<u8>> {- let repo = Repository::open(&self.root).map_err(map_git_err)?;+ let repo = match Repository::open(&self.root) {+ Ok(repo) => repo,+ Err(e) => return file_at_rev_fallback(&self.root, rev, path, map_git_err(e)),+ };let object = repo.revparse_single(rev).map_err(map_git_err)?;let commit = object.peel_to_commit().map_err(map_git_err)?;let tree = commit.tree().map_err(map_git_err)?;@@ -190,6 +203,203 @@ impl GitAdapter {}}+#[cfg(windows)]+fn commit_all_fallback(+ root: &Path,+ message: &str,+ original: WikiError,+) -> WikiResult<Option<git2::Oid>> {+ warn!(error = %original, root = %root.display(), "libgit2 commit failed; trying git CLI fallback");+ run_git(root, ["add", "-A"])?;+ let diff = std::process::Command::new("git")+ .arg("-C")+ .arg(root)+ .args(["diff", "--cached", "--quiet", "--exit-code"])+ .status()+ .map_err(|e| {+ WikiError::Io(std::io::Error::other(format!(+ "{original}; git diff fallback failed to start: {e}"+ )))+ })?;+ if diff.success() {+ return Ok(None);+ }+ run_git(+ root,+ [+ "-c",+ "user.name=ai-memory",+ "-c",+ "user.email=ai-memory@local",+ "commit",+ "-q",+ "-m",+ message,+ ],+ )?;+ let out = git_output(root, ["rev-parse", "HEAD"])?;+ let oid = String::from_utf8_lossy(&out.stdout);+ git2::Oid::from_str(oid.trim())+ .map(Some)+ .map_err(map_git_err)+}++#[cfg(not(windows))]+fn commit_all_fallback(+ _root: &Path,+ _message: &str,+ original: WikiError,+) -> WikiResult<Option<git2::Oid>> {+ Err(original)+}++#[cfg(windows)]+fn commit_count_fallback(root: &Path) -> usize {+ let Ok(out) = git_output(root, ["rev-list", "--count", "HEAD"]) else {+ return 0;+ };+ String::from_utf8_lossy(&out.stdout)+ .trim()+ .parse()+ .unwrap_or(0)+}++#[cfg(not(windows))]+fn commit_count_fallback(_root: &Path) -> usize {+ 0+}++#[cfg(windows)]+fn recent_checkpoints_fallback(+ root: &Path,+ limit: usize,+ original: WikiError,+) -> WikiResult<Vec<Checkpoint>> {+ warn!(error = %original, root = %root.display(), "libgit2 log failed; trying git CLI fallback");+ let limit = limit.to_string();+ let out = git_output(root, ["log", "-n", &limit, "--format=%H%x1f%s%x1f%ct"])?;+ let text = String::from_utf8_lossy(&out.stdout);+ let mut checkpoints = Vec::new();+ for line in text.lines() {+ let mut fields = line.split('\x1f');+ let (Some(oid), Some(summary), Some(time)) = (fields.next(), fields.next(), fields.next())+ else {+ continue;+ };+ checkpoints.push(Checkpoint {+ oid: oid.to_string(),+ summary: if summary.is_empty() {+ "(no summary)".to_string()+ } else {+ summary.to_string()+ },+ time: time.parse().unwrap_or_default(),+ });+ }+ Ok(checkpoints)+}++#[cfg(not(windows))]+fn recent_checkpoints_fallback(+ _root: &Path,+ _limit: usize,+ original: WikiError,+) -> WikiResult<Vec<Checkpoint>> {+ Err(original)+}++#[cfg(windows)]+fn file_at_rev_fallback(+ root: &Path,+ rev: &str,+ path: &Path,+ original: WikiError,+) -> WikiResult<Vec<u8>> {+ warn!(error = %original, root = %root.display(), "libgit2 show failed; trying git CLI fallback");+ let rel = path.to_string_lossy().replace('\\', "/");+ let spec = format!("{rev}:{rel}");+ let out = git_output(root, ["show", &spec])?;+ Ok(out.stdout)+}++#[cfg(not(windows))]+fn file_at_rev_fallback(+ _root: &Path,+ _rev: &str,+ _path: &Path,+ original: WikiError,+) -> WikiResult<Vec<u8>> {+ Err(original)+}++fn init_repo(root: &Path) -> WikiResult<()> {+ match Repository::init(root) {+ Ok(_) => Ok(()),+ Err(e) => init_repo_fallback(root, e),+ }+}++#[cfg(windows)]+fn init_repo_fallback(root: &Path, original: git2::Error) -> WikiResult<()> {+ warn!(error = %original, root = %root.display(), "libgit2 init failed; trying git CLI fallback");+ let status = std::process::Command::new("git")+ .arg("init")+ .arg("-q")+ .arg(root)+ .status()+ .map_err(|io| {+ WikiError::Io(std::io::Error::other(format!(+ "{original}; git init fallback failed to start: {io}"+ )))+ })?;+ if status.success() {+ Ok(())+ } else {+ Err(map_git_err(original))+ }+}++#[cfg(not(windows))]+fn init_repo_fallback(_root: &Path, original: git2::Error) -> WikiResult<()> {+ Err(map_git_err(original))+}++#[cfg(windows)]+fn run_git<const N: usize>(root: &Path, args: [&str; N]) -> WikiResult<()> {+ let status = std::process::Command::new("git")+ .arg("-C")+ .arg(root)+ .args(args)+ .status()+ .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))?;+ if status.success() {+ Ok(())+ } else {+ Err(WikiError::Io(std::io::Error::other(format!(+ "git fallback exited with status {status}"+ ))))+ }+}++#[cfg(windows)]+fn git_output<const N: usize>(root: &Path, args: [&str; N]) -> WikiResult<std::process::Output> {+ let out = std::process::Command::new("git")+ .arg("-C")+ .arg(root)+ .args(args)+ .output()+ .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))?;+ if out.status.success() {+ Ok(out)+ } else {+ Err(WikiError::Io(std::io::Error::other(format!(+ "git fallback exited with status {}: {}",+ out.status,+ String::from_utf8_lossy(&out.stderr)+ ))))+ }+}+fn map_git_err(e: git2::Error) -> WikiError {warn!(error = %e, "libgit2 error");WikiError::Io(std::io::Error::other(e.to_string()))@@ -200,9 +410,16 @@ mod tests {use super::*;use tempfile::TempDir;+ fn tempdir() -> TempDir {+ tempfile::Builder::new()+ .prefix("ai-memory-")+ .tempdir()+ .unwrap()+ }+#[test]fn init_is_idempotent_and_creates_dotgit() {- let tmp = TempDir::new().unwrap();+ let tmp = tempdir();let root = tmp.path().join("wiki");let _adapter = GitAdapter::open_or_init(&root).unwrap();assert!(root.join(".git").is_dir());@@ -212,7 +429,7 @@ mod tests {#[test]fn commit_all_returns_none_when_clean_some_when_dirty() {- let tmp = TempDir::new().unwrap();+ let tmp = tempdir();let root = tmp.path().join("wiki");let adapter = GitAdapter::open_or_init(&root).unwrap();// No changes: returns None.@@ -230,7 +447,7 @@ mod tests {#[test]fn commit_all_captures_deletes_too() {- let tmp = TempDir::new().unwrap();+ let tmp = tempdir();let root = tmp.path().join("wiki");let adapter = GitAdapter::open_or_init(&root).unwrap();std::fs::write(root.join("a.md"), "first").unwrap();@@ -243,7 +460,7 @@ mod tests {#[test]fn recent_checkpoints_returns_newest_first() {- let tmp = TempDir::new().unwrap();+ let tmp = tempdir();let root = tmp.path().join("wiki");let adapter = GitAdapter::open_or_init(&root).unwrap();@@ -261,7 +478,7 @@ mod tests {#[test]fn file_at_rev_reads_historical_blob() {- let tmp = TempDir::new().unwrap();+ let tmp = tempdir();let root = tmp.path().join("wiki");let adapter = GitAdapter::open_or_init(&root).unwrap();diff --git a/crates/ai-memory-wiki/src/watcher.rs b/crates/ai-memory-wiki/src/watcher.rsindex 6c739253..782aaae1 100644--- a/crates/ai-memory-wiki/src/watcher.rs+++ b/crates/ai-memory-wiki/src/watcher.rs@@ -531,6 +531,24 @@ mod tests {use ai_memory_store::Store;use tempfile::TempDir;+ #[cfg(windows)]+ fn create_test_symlink_file(target: &Path, link: &Path) -> bool {+ match std::os::windows::fs::symlink_file(target, link) {+ Ok(()) => true,+ Err(e) if e.raw_os_error() == Some(1314) => {+ eprintln!("skipping symlink assertion: Windows symlink privilege unavailable");+ false+ }+ Err(e) => panic!("failed to create symlink {}: {e}", link.display()),+ }+ }++ #[cfg(unix)]+ fn create_test_symlink_file(target: &Path, link: &Path) -> bool {+ std::os::unix::fs::symlink(target, link).unwrap();+ true+ }+async fn setup() -> (TempDir, Store, Wiki, WorkspaceId, ProjectId) {let tmp = TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();@@ -932,10 +950,9 @@ mod tests {std::fs::write(&secret, "this is sensitive\n").unwrap();// Plant a symlink inside proj/ pointing at the outside file.- #[cfg(unix)]- std::os::unix::fs::symlink(&secret, proj_root.join("symlinked.md")).unwrap();- #[cfg(windows)]- std::os::windows::fs::symlink_file(&secret, proj_root.join("symlinked.md")).unwrap();+ if !create_test_symlink_file(&secret, &proj_root.join("symlinked.md")) {+ return;+ }let found = walk_markdown(&proj_root).unwrap();let names: Vec<_> = found.iter().map(|p| p.as_str().to_string()).collect();@@ -964,10 +981,9 @@ mod tests {std::fs::write(&secret, "directsymlinksecret should not index\n").unwrap();let symlink = proj_dir.join("symlinked.md");- #[cfg(unix)]- std::os::unix::fs::symlink(&secret, &symlink).unwrap();- #[cfg(windows)]- std::os::windows::fs::symlink_file(&secret, &symlink).unwrap();+ if !create_test_symlink_file(&secret, &symlink) {+ return;+ }let event = notify_debouncer_full::DebouncedEvent::new(notify::Event::new(EventKind::Create(notify::event::CreateKind::File))diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 06947204..7c577a56 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -1583,6 +1583,24 @@ mod tests {};use tempfile::TempDir;+ #[cfg(windows)]+ fn create_test_symlink_file(target: &Path, link: &Path) -> bool {+ match std::os::windows::fs::symlink_file(target, link) {+ Ok(()) => true,+ Err(e) if e.raw_os_error() == Some(1314) => {+ eprintln!("skipping symlink assertion: Windows symlink privilege unavailable");+ false+ }+ Err(e) => panic!("failed to create symlink {}: {e}", link.display()),+ }+ }++ #[cfg(unix)]+ fn create_test_symlink_file(target: &Path, link: &Path) -> bool {+ std::os::unix::fs::symlink(target, link).unwrap();+ true+ }+#[tokio::test]async fn project_root_is_wiki_root_joined_with_ws_and_proj() {let tmp = TempDir::new().unwrap();@@ -3166,10 +3184,9 @@ mod tests {let outside = tmp.path().join("outside-meta.md");std::fs::write(&outside, "---\nproject: webapp\n---\n").unwrap();let link = proj_dir.join("_meta.md");- #[cfg(unix)]- std::os::unix::fs::symlink(&outside, &link).unwrap();- #[cfg(windows)]- std::os::windows::fs::symlink_file(&outside, &link).unwrap();+ if !create_test_symlink_file(&outside, &link) {+ return;+ }let err = wiki.reindex_all().await.unwrap_err();assert!(