Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
refactor(config): read $HOME once in Config::load for resolver guard and heal
Thiago Silva17ae047dd95e
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex eb5a4dfc..7e3fd64b 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -81,10 +81,11 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {// One-shot legacy heal (issue #103): NULL out any project repo_path that// is a known prefix-match catch-all ($HOME or filesystem root) so existing// broken installs self-correct on upgrade. Uses the same $HOME source as- // the router's match-time guard so heal and guard agree on its meaning.+ // the router's match-time guard (captured once in `Config`) so heal and+ // guard agree on its meaning.let healed = store.writer- .heal_catch_all_repo_paths(std::env::var("HOME").ok())+ .heal_catch_all_repo_paths(config.home_dir.clone()).await?;if healed > 0 {tracing::info!(@@ -281,6 +282,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,)),consolidate_on_session_end: config.consolidate_on_session_end,+ home_dir: config.home_dir.clone(),});let admin = admin_router(AdminState {writer: store.writer.clone(),diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 93da4fe4..ceec3513 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -65,6 +65,13 @@ pub struct Config {/// `std::env::var` call (invariant: one config-read path).#[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+ /// 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.+ #[serde(skip)]+ pub home_dir: Option<String>,/// Per-subsystem log filter (overridable by `RUST_LOG`).pub log_level: String,/// Optional LLM provider (`anthropic`, `openai`, `gemini`, `openai-compat`, `openai-oauth`, `copilot`).@@ -339,6 +346,7 @@ impl Default for Config {bind: DEFAULT_BIND.into(),server_url: DEFAULT_SERVER_URL.into(),base_path: String::new(),+ home_dir: None,log_level: "info".into(),llm_provider: None,llm_model: None,@@ -520,6 +528,10 @@ 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.+ config.home_dir = std::env::var("HOME").ok();+// CLI override always wins (figment doesn't see it because clap has// already parsed the flag into `cli_data_dir`).if let Some(dir) = cli_data_dir {@@ -857,6 +869,17 @@ mod tests {);}+ #[test]+ fn load_populates_home_dir_from_env() {+ 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). Reading the env in a test is allowed; this fails if the+ // load-time assignment is dropped while `$HOME` is set.+ assert_eq!(cfg.home_dir, std::env::var("HOME").ok());+ }+#[test]fn config_file_overrides_defaults() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 76cc894f..c90975ed 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -178,6 +178,11 @@ pub struct HookState {/// session close stays cheap; the LLM checkpoint otherwise happens on/// PreCompact and via manual `memory_consolidate`.pub consolidate_on_session_end: bool,+ /// Operator home directory, sourced from `Config` once at startup. The+ /// cwd->project resolver never prefix-matches a stored `repo_path` equal+ /// to this, so `$HOME` cannot become a catch-all (issue #103). `None`+ /// disables the guard. Held here so the hooks crate makes no env reads.+ pub home_dir: Option<String>,}/// Build a router with `POST /hook` (event ingress) and `GET /handoff`@@ -506,12 +511,11 @@ async fn resolve_project_ids(// The match is keyed on the actual cwd (`cwd_norm`), not the stored// `repo_path`: `repo_path` is now the git root or None (issue #103),// whereas cwd->parent matching needs the full deep path.- let home_dir = std::env::var("HOME").ok();let proj = if project_override.is_none()&& let Some(rp) = cwd_norm.as_deref().filter(|s| !s.is_empty())&& let Some((parent_id, parent_name)) = state.reader- .find_project_by_cwd_prefix(ws, rp.to_string(), home_dir.as_deref())+ .find_project_by_cwd_prefix(ws, rp.to_string(), state.home_dir.as_deref()).await.map_err(|e| anyhow::anyhow!("find_project_by_cwd_prefix: {e}"))?&& parent_name != project_name@@ -947,6 +951,7 @@ mod tests {project_cache: Arc::new(tokio::sync::Mutex::new(ProjectCacheStore::default())),active_project: ActiveProject::new(),consolidate_on_session_end: false,+ home_dir: None,ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,)),diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rsindex c6efc93e..2acd7518 100644--- a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs@@ -157,6 +157,7 @@ impl MultiUserHarness {DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,)),consolidate_on_session_end: false,+ home_dir: None,});// Production-equivalent Bearer middleware. Pepper + reader arediff --git a/crates/ai-memory-mcp/tests/autoscope_stress.rs b/crates/ai-memory-mcp/tests/autoscope_stress.rsindex c7d2737b..97b1dc82 100644--- a/crates/ai-memory-mcp/tests/autoscope_stress.rs+++ b/crates/ai-memory-mcp/tests/autoscope_stress.rs@@ -156,6 +156,7 @@ impl Harness {DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,)),consolidate_on_session_end: false,+ home_dir: None,});let router = Router::new()