Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(recall): opt-in `[recall] default_global` to broaden default-scoped queries
Djalma Júniord02943895e2e
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 44ccdcd9..65d2efa1 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -52,12 +52,16 @@ pub fn url_encode(s: &str) -> String {/// server cannot see this checkout.pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String {let mut qs = format!("&cwd={}", url_encode(cwd));- let (mut workspace, mut project, mut strategy, mut drop_subagent) = (None, None, None, None);+ let (mut workspace, mut project, mut strategy, mut drop_subagent, mut default_global) =+ (None, None, None, None, None);if let Some(marker) = find_marker(cwd) {workspace = parse_toml_key(&marker, "workspace");project = parse_toml_key(&marker, "project");strategy = parse_toml_key(&marker, "project_strategy");drop_subagent = parse_toml_key(&marker, "drop_subagent_captures");+ // `[recall] default_global = true` (or top-level; quoted or bare) —+ // a meta-repo opts every default-scoped read into a global search.+ default_global = parse_toml_flag(&marker, "default_global");}if strategy.is_none() {strategy = default_strategy.map(str::to_owned);@@ -80,9 +84,43 @@ pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> Stringif let Some(val) = drop_subagent.filter(|v| !v.is_empty()) {qs.push_str(&format!("&drop_subagent={}", url_encode(&val)));}+ // Per-repo `default_global` opt-in: forward the marker's value so the+ // server can publish it on the ActiveProject and make default-scoped read+ // tools search globally. Truthiness is decided server-side.+ if let Some(val) = default_global.filter(|v| !v.is_empty()) {+ qs.push_str(&format!("&default_global={}", url_encode(&val)));+ }qs}+/// Parse a root-level `key = <value>` line, accepting a quoted string+/// (`key = "true"`) OR a bare token (`key = true` / `key = 1`), so a+/// `[recall] default_global = true` marker works whether or not the operator+/// quotes the value. Line-based like [`parse_toml_key`], so section headers+/// are ignored; strips an optional trailing `# comment`.+fn parse_toml_flag(file: &Path, key: &str) -> Option<String> {+ let text = std::fs::read_to_string(file).ok()?;+ for line in text.lines() {+ let trimmed = line.trim_start();+ let Some(after_key) = trimmed.strip_prefix(key) else {+ continue;+ };+ let Some(rest) = after_key.trim_start().strip_prefix('=') else {+ continue;+ };+ let val = rest+ .split('#')+ .next()+ .unwrap_or("")+ .trim()+ .trim_matches('"');+ if !val.is_empty() {+ return Some(val.to_string());+ }+ }+ None+}+fn repo_root_project(cwd: &str) -> Option<String> {let root = ai_memory_consolidate::discover_main_repo_root(Path::new(cwd)).ok()?;root.file_name()@@ -520,6 +558,32 @@ drop_subagent_captures = "true"assert!(!qs.contains("drop_subagent"), "{qs}");}+ /// A `[recall] default_global` marker (bare `true`, under a section)+ /// forwards the flag so the server can broaden default-scoped reads.+ #[test]+ fn marker_query_suffix_appends_default_global() {+ let tmp = tempfile::TempDir::new().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "workspace = \"acme\"\n[recall]\ndefault_global = true\n",+ )+ .unwrap();+ let qs = marker_query_suffix(tmp.path().to_str().unwrap(), None);+ assert!(qs.contains("&default_global=true"), "{qs}");+ }++ #[test]+ fn marker_query_suffix_omits_default_global_when_unset() {+ let tmp = tempfile::TempDir::new().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "workspace = \"acme\"\nproject = \"infra\"\n",+ )+ .unwrap();+ let qs = marker_query_suffix(tmp.path().to_str().unwrap(), None);+ assert!(!qs.contains("default_global"), "{qs}");+ }+#[test]fn marker_query_suffix_repo_root_non_git_keeps_project_implicit() {let tmp = tempfile::TempDir::new().unwrap();diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rsindex bc184dbc..5494fb66 100644--- a/crates/ai-memory-core/src/active_project.rs+++ b/crates/ai-memory-core/src/active_project.rs@@ -121,9 +121,19 @@ impl ActorKey {}}+/// One per-actor slot: the resolved project plus the actor's opted-in+/// `default_global` recall preference and the insertion time (for TTL).+#[derive(Debug, Clone, Copy)]+struct Entry {+ ws: WorkspaceId,+ proj: ProjectId,+ default_global: bool,+ inserted: Instant,+}+#[derive(Debug)]struct PerActorMap {- entries: HashMap<ActorKey, (WorkspaceId, ProjectId, Instant)>,+ entries: HashMap<ActorKey, Entry>,ttl: Duration,max_entries: usize,}@@ -145,7 +155,7 @@ impl PerActorMap {/// surfaces to a tool handler and the cap below sees an accurate size.fn purge_expired(&mut self, now: Instant) {self.entries- .retain(|_, (_, _, inserted)| now.saturating_duration_since(*inserted) < self.ttl);+ .retain(|_, e| now.saturating_duration_since(e.inserted) < self.ttl);}/// Cap the map at `max_entries`, dropping the oldest insertions first.@@ -156,54 +166,77 @@ impl PerActorMap {return;}let excess = self.entries.len() - self.max_entries;- let mut by_age: Vec<(ActorKey, Instant)> =- self.entries.iter().map(|(k, v)| (k.clone(), v.2)).collect();+ let mut by_age: Vec<(ActorKey, Instant)> = self+ .entries+ .iter()+ .map(|(k, e)| (k.clone(), e.inserted))+ .collect();by_age.sort_by_key(|(_, inserted)| *inserted);for (k, _) in by_age.into_iter().take(excess) {self.entries.remove(&k);}}- fn insert(&mut self, key: ActorKey, ws: WorkspaceId, proj: ProjectId, now: Instant) {+ fn insert(+ &mut self,+ key: ActorKey,+ ws: WorkspaceId,+ proj: ProjectId,+ default_global: bool,+ now: Instant,+ ) {self.purge_expired(now);- self.entries.insert(key, (ws, proj, now));+ self.entries.insert(+ key,+ Entry {+ ws,+ proj,+ default_global,+ inserted: now,+ },+ );self.enforce_cap();}fn get(&mut self, key: &ActorKey, now: Instant) -> Option<(WorkspaceId, ProjectId)> {self.purge_expired(now);- self.entries.get(key).map(|(ws, proj, _)| (*ws, *proj))+ self.entries.get(key).map(|e| (e.ws, e.proj))+ }++ /// The actor's opted-in `default_global` preference, or `false` when no+ /// live entry exists for the key.+ fn get_default_global(&mut self, key: &ActorKey, now: Instant) -> bool {+ self.purge_expired(now);+ self.entries.get(key).is_some_and(|e| e.default_global)}fn retarget_project(&mut self, project_id: ProjectId, workspace_id: WorkspaceId, now: Instant) {self.purge_expired(now);- for (ws, proj, _) in self.entries.values_mut() {- if *proj == project_id {- *ws = workspace_id;+ for e in self.entries.values_mut() {+ if e.proj == project_id {+ e.ws = workspace_id;}}}fn clear_project(&mut self, project_id: ProjectId, now: Instant) {self.purge_expired(now);- self.entries.retain(|_, (_, proj, _)| *proj != project_id);+ self.entries.retain(|_, e| e.proj != project_id);}fn clear_workspace(&mut self, workspace_id: WorkspaceId, now: Instant) {self.purge_expired(now);- self.entries.retain(|_, (ws, _, _)| *ws != workspace_id);+ self.entries.retain(|_, e| e.ws != workspace_id);}fn contains_project(&mut self, project_id: ProjectId, now: Instant) -> bool {self.purge_expired(now);- self.entries- .values()- .any(|(_, proj, _)| *proj == project_id)+ self.entries.values().any(|e| e.proj == project_id)}fn contains_workspace(&mut self, workspace_id: WorkspaceId, now: Instant) -> bool {self.purge_expired(now);- self.entries.values().any(|(ws, _, _)| *ws == workspace_id)+ self.entries.values().any(|e| e.ws == workspace_id)}/// Test-only: live row count in the backing HashMap. Counts all@@ -225,6 +258,11 @@ impl PerActorMap {pub struct ActiveProject {mode: ActiveProjectMode,single: Arc<RwLock<Option<(WorkspaceId, ProjectId)>>>,+ /// `default_global` for the single/fallback slot (Single mode or an actor+ /// with no usable coordinate). Kept beside `single` rather than inside the+ /// tuple so the legacy `set`/`get` API and every existing caller stay+ /// byte-for-byte unchanged.+ single_default_global: Arc<RwLock<bool>>,per_actor: Arc<RwLock<PerActorMap>>,}@@ -259,6 +297,7 @@ impl ActiveProject {Self {mode,single: Arc::new(RwLock::new(None)),+ single_default_global: Arc::new(RwLock::new(false)),per_actor: Arc::new(RwLock::new(PerActorMap::new(ttl, max_entries))),}}@@ -282,8 +321,15 @@ impl ActiveProject {/// - In `PerActor`, a user-only entry is also set when `user` is present./// Requests that carry that user but no session id can still resolve to/// the user's latest project without falling through to the global slot.- pub fn set_for(&self, actor: &ActorKey, workspace_id: WorkspaceId, project_id: ProjectId) {+ pub fn set_for(+ &self,+ actor: &ActorKey,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ default_global: bool,+ ) {self.write_single(workspace_id, project_id);+ self.write_single_default_global(default_global);if self.mode == ActiveProjectMode::Single || actor.is_empty() {return;}@@ -303,10 +349,11 @@ impl ActiveProject {},workspace_id,project_id,+ default_global,Instant::now(),);}- guard.insert(scoped, workspace_id, project_id, Instant::now());+ guard.insert(scoped, workspace_id, project_id, default_global, Instant::now());}/// Read the currently active project for the given actor, if any has@@ -333,6 +380,24 @@ impl ActiveProject {guard.get(&scoped, Instant::now())}+ /// Whether the actor opted this session into `default_global` recall (via+ /// the repo's `[recall] default_global` marker, published by the hook).+ /// Uses the SAME slot-selection as [`Self::get_for`], so the flag tracks+ /// the project pointer it was published alongside. Defaults to `false`+ /// (unchanged behaviour) for any actor/slot that never opted in.+ #[must_use]+ pub fn default_global_for(&self, actor: &ActorKey) -> bool {+ if self.mode == ActiveProjectMode::Single || actor.is_empty() {+ return self.read_single_default_global();+ }+ let scoped = self.scoped_key(actor);+ if scoped.is_empty() {+ return self.read_single_default_global();+ }+ let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());+ guard.get_default_global(&scoped, Instant::now())+ }+/// Project the actor's identity onto only the coordinates the current/// mode uses: `PerSession` keeps `session_id`, `PerActor` keeps both.fn scoped_key(&self, actor: &ActorKey) -> ActorKey {@@ -359,6 +424,22 @@ impl ActiveProject {*guard}+ fn write_single_default_global(&self, value: bool) {+ let mut guard = self+ .single_default_global+ .write()+ .unwrap_or_else(|e| e.into_inner());+ *guard = value;+ }++ fn read_single_default_global(&self) -> bool {+ let guard = self+ .single_default_global+ .read()+ .unwrap_or_else(|e| e.into_inner());+ *guard+ }+/// Legacy single-slot setter — used by tests and by call sites that/// have no actor context yet. Touches the single slot only; the per-key/// map is untouched.@@ -540,7 +621,7 @@ mod tests {let alice = key_actor("alice", "sA");let ws = WorkspaceId::new();let proj = ProjectId::new();- ap.set_for(&alice, ws, proj);+ ap.set_for(&alice, ws, proj, false);assert_eq!(ap.get_for(&alice), Some((ws, proj)));ap.clear();@@ -558,8 +639,8 @@ mod tests {let moved = ProjectId::new();let other = ProjectId::new();- ap.set_for(&alice, old_ws, moved);- ap.set_for(&bob, old_ws, other);+ ap.set_for(&alice, old_ws, moved, false);+ ap.set_for(&bob, old_ws, other, false);ap.set(old_ws, moved);ap.retarget_project_workspace(moved, new_ws);@@ -580,8 +661,8 @@ mod tests {let doomed = ProjectId::new();let kept = ProjectId::new();- ap.set_for(&alice, ws, doomed);- ap.set_for(&bob, ws, kept);+ ap.set_for(&alice, ws, doomed, false);+ ap.set_for(&bob, ws, kept, false);ap.set(ws, doomed);ap.clear_project(doomed);@@ -603,8 +684,8 @@ mod tests {let p1 = ProjectId::new();let p2 = ProjectId::new();- ap.set_for(&alice, doomed_ws, p1);- ap.set_for(&bob, kept_ws, p2);+ ap.set_for(&alice, doomed_ws, p1, false);+ ap.set_for(&bob, kept_ws, p2, false);ap.set(doomed_ws, p1);ap.clear_workspace(doomed_ws);@@ -624,8 +705,8 @@ mod tests {let ws = WorkspaceId::new();let p_alice = ProjectId::new();let p_bob = ProjectId::new();- ap.set_for(&alice, ws, p_alice);- ap.set_for(&bob, ws, p_bob);+ ap.set_for(&alice, ws, p_alice, false);+ ap.set_for(&bob, ws, p_bob, false);// Both reads see the last write; that's the legacy contract.assert_eq!(ap.get_for(&alice), Some((ws, p_bob)));assert_eq!(ap.get_for(&bob), Some((ws, p_bob)));@@ -640,8 +721,8 @@ mod tests {let ws = WorkspaceId::new();let p_a = ProjectId::new();let p_b = ProjectId::new();- ap.set_for(&sess_a, ws, p_a);- ap.set_for(&sess_b, ws, p_b);+ ap.set_for(&sess_a, ws, p_a, false);+ ap.set_for(&sess_b, ws, p_b, false);assert_eq!(ap.get_for(&sess_a), Some((ws, p_a)));assert_eq!(ap.get_for(&sess_b), Some((ws, p_b)));}@@ -653,9 +734,9 @@ mod tests {let p = ProjectId::new();let alice = key_actor("alice", "shared-session");let bob = key_actor("bob", "shared-session");- ap.set_for(&alice, ws, p);+ ap.set_for(&alice, ws, p, false);let p_bob = ProjectId::new();- ap.set_for(&bob, ws, p_bob);+ ap.set_for(&bob, ws, p_bob, false);// Same session_id, different users → still collapses to one entry// (intentional: per_session is the right mode for single-operator,// multi-cwd installs; per_actor is the mode for multi-operator).@@ -672,9 +753,9 @@ mod tests {let p1 = ProjectId::new();let p2 = ProjectId::new();let p3 = ProjectId::new();- ap.set_for(&alice_a, ws, p1);- ap.set_for(&alice_b, ws, p2);- ap.set_for(&bob_a, ws, p3);+ ap.set_for(&alice_a, ws, p1, false);+ ap.set_for(&alice_b, ws, p2, false);+ ap.set_for(&bob_a, ws, p3, false);assert_eq!(ap.get_for(&alice_a), Some((ws, p1)));assert_eq!(ap.get_for(&alice_b), Some((ws, p2)));assert_eq!(ap.get_for(&bob_a), Some((ws, p3)));@@ -688,8 +769,8 @@ mod tests {let ws = WorkspaceId::new();let p_alice = ProjectId::new();let p_bob = ProjectId::new();- ap.set_for(&alice_a, ws, p_alice);- ap.set_for(&bob_a, ws, p_bob);+ ap.set_for(&alice_a, ws, p_alice, false);+ ap.set_for(&bob_a, ws, p_bob, false);assert_eq!(ap.get_for(&ActorKey {@@ -709,8 +790,8 @@ mod tests {let ws = WorkspaceId::new();let p_alice = ProjectId::new();let p_bob = ProjectId::new();- ap.set_for(&alice_a, ws, p_alice);- ap.set_for(&bob_a, ws, p_bob);+ ap.set_for(&alice_a, ws, p_alice, false);+ ap.set_for(&bob_a, ws, p_bob, false);assert_eq!(ap.get_for(&ActorKey {@@ -744,10 +825,43 @@ mod tests {let alice = key_actor("alice", "sA");let ws = WorkspaceId::new();let proj = ProjectId::new();- ap.set_for(&alice, ws, proj);+ ap.set_for(&alice, ws, proj, false);assert_eq!(ap.get(), Some((ws, proj)));}+ #[test]+ fn default_global_round_trips_per_actor_and_defaults_false() {+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);+ let alice = key_actor("alice", "sA");+ let bob = key_actor("bob", "sB");+ let ws = WorkspaceId::new();+ let (pa, pb) = (ProjectId::new(), ProjectId::new());++ ap.set_for(&alice, ws, pa, true); // alice opted in+ ap.set_for(&bob, ws, pb, false); // bob did not++ assert!(ap.default_global_for(&alice), "alice opted in");+ assert!(!ap.default_global_for(&bob), "bob did not");+ // The project-pointer resolution is unaffected by the recall flag.+ assert_eq!(ap.get_for(&alice), Some((ws, pa)));+ assert_eq!(ap.get_for(&bob), Some((ws, pb)));+ // An actor that never published defaults to false (unchanged behaviour).+ assert!(!ap.default_global_for(&key_actor("carol", "sC")));+ }++ #[test]+ fn default_global_single_slot_tracks_last_publish() {+ let ap = ActiveProject::with_mode(ActiveProjectMode::Single);+ let ws = WorkspaceId::new();+ let proj = ProjectId::new();+ ap.set_for(&empty_actor(), ws, proj, true);+ assert!(ap.default_global_for(&empty_actor()));+ // A later publish without the flag clears it — the pointer and its+ // preference move together.+ ap.set_for(&empty_actor(), ws, proj, false);+ assert!(!ap.default_global_for(&empty_actor()));+ }+#[test]fn per_actor_max_entries_evicts_oldest() {let ap = ActiveProject::with_config(ActiveProjectMode::PerActor, DEFAULT_PER_KEY_TTL, 2);@@ -758,11 +872,11 @@ mod tests {let k1 = key_session("s1");let k2 = key_session("s2");let k3 = key_session("s3");- ap.set_for(&k1, ws, p1);+ ap.set_for(&k1, ws, p1, false);std::thread::sleep(Duration::from_millis(2));- ap.set_for(&k2, ws, p2);+ ap.set_for(&k2, ws, p2, false);std::thread::sleep(Duration::from_millis(2));- ap.set_for(&k3, ws, p3);+ ap.set_for(&k3, ws, p3, false);// Use the test-only keyed-only getter so the cap assertion targets// the backing map directly.assert!(ap.keyed_only_get(&k1).is_none(), "k1 must be evicted");@@ -780,7 +894,7 @@ mod tests {let k = key_session("s");let ws = WorkspaceId::new();let proj = ProjectId::new();- ap.set_for(&k, ws, proj);+ ap.set_for(&k, ws, proj, false);assert_eq!(ap.get_for(&k), Some((ws, proj)));std::thread::sleep(Duration::from_millis(40));// The per-actor entry must be gone; identified callers with expired@@ -874,7 +988,7 @@ mod tests {match op {Op::Set(i) => {let proj = ProjectId::new();- ap.set_for(&actors[i], ws, proj);+ ap.set_for(&actors[i], ws, proj, false);}Op::Get(i) => {let _ = ap.get_for(&actors[i]);@@ -949,7 +1063,7 @@ mod tests {for step in 0..1_000 {let i = (rng.next() as usize) % pool_size;let proj = ProjectId::new();- ap.set_for(&actors[i], ws, proj);+ ap.set_for(&actors[i], ws, proj, false);let got = ap.keyed_only_get(&actors[i]);assert_eq!(got,@@ -1013,7 +1127,7 @@ mod tests {// Pre-populate every actor; record the write time relative// to the run start.for actor in &actors {- ap.set_for(actor, ws, ProjectId::new());+ ap.set_for(actor, ws, ProjectId::new(), false);}// Wait for TTL plus a margin so every pre-populated entry@@ -1033,7 +1147,7 @@ mod tests {// the map shouldn't go into an unrecoverable state.let i = (rng.next() as usize) % actors.len();let proj = ProjectId::new();- ap.set_for(&actors[i], ws, proj);+ ap.set_for(&actors[i], ws, proj, false);assert_eq!(ap.keyed_only_get(&actors[i]),Some((ws, proj)),diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 51b9f978..948987cc 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -41,6 +41,13 @@ pub struct HookQuery {/// project that asked for it avoids a server-global switch that would shed/// subagent captures for every project on a shared instance.pub drop_subagent: Option<String>,+ /// Per-repo opt-in for `[recall] default_global`, forwarded by the+ /// host-side hook from a project's `.ai-memory.toml`. A truthy value makes+ /// the server publish `default_global` on this actor's `ActiveProject`, so+ /// a default-scoped `memory_query` / `memory_recent` searches every project+ /// instead of just the current one — the meta-repo case (e.g. `ai-memory`+ /// needing to see `ai-memory-ops` / `infra` without passing `global=true`).+ pub default_global: Option<String>,}/// Coalesced view of an incoming hook event after light parsing of the@@ -70,6 +77,11 @@ pub struct HookEnvelope {/// ingest router consults this per-event so the drop is scoped to the/// project that asked for it.pub drop_subagent_requested: bool,+ /// Whether this repo opted into `[recall] default_global` via its+ /// `.ai-memory.toml` (forwarded as the `default_global` query flag). The+ /// router publishes it on the actor's `ActiveProject` so default-scoped+ /// read tools broaden to a global search.+ pub recall_default_global_requested: bool,/// Optional third-party extension namespace.pub extension: Option<String>,/// Optional source event name from the extension vocabulary.@@ -105,7 +117,7 @@ pub(crate) fn body_is_subagent(raw: &serde_json::Value) -> bool {/// Truthy interpretation of a query-string flag (`1`/`true`/`yes`/`on`,/// case-insensitive). Used for the per-project `drop_subagent` opt-in the/// host-side hook forwards from a project's `.ai-memory.toml`.-fn query_flag_truthy(value: Option<&str>) -> bool {+pub(crate) fn query_flag_truthy(value: Option<&str>) -> bool {matches!(value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),Some("1" | "true" | "yes" | "on")@@ -293,6 +305,7 @@ impl HookEnvelope {let project_override = query.project.filter(|s| !s.is_empty());let project_strategy = ProjectStrategy::parse(query.project_strategy.as_deref());let drop_subagent_requested = query_flag_truthy(query.drop_subagent.as_deref());+ let recall_default_global_requested = query_flag_truthy(query.default_global.as_deref());let extension = normalize_extension_name(query.extension.as_deref());let source_event = extension.as_ref().and_then(|_| {let raw_source = query@@ -325,6 +338,7 @@ impl HookEnvelope {project_override,project_strategy,drop_subagent_requested,+ recall_default_global_requested,extension,source_event,title_hint,@@ -713,6 +727,24 @@ mod tests {);}+ #[test]+ fn envelope_maps_default_global_flag() {+ let on = HookEnvelope::from_query_and_body(+ HookQuery {+ default_global: Some("true".into()),+ ..Default::default()+ },+ serde_json::json!({ "session_id": "s1" }),+ );+ assert!(on.recall_default_global_requested);++ let off = HookEnvelope::from_query_and_body(+ HookQuery::default(),+ serde_json::json!({ "session_id": "s1" }),+ );+ assert!(!off.recall_default_global_requested);+ }+#[test]fn envelope_extracts_session_and_cwd() {let q = HookQuery {diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 1b1993a8..9ecb2650 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -654,13 +654,14 @@ async fn should_drop_subagent(state: &HookState, env: &HookEnvelope, actor: &Actlet Ok(session_id) = resolve_session_id(env) else {return false;};- let Ok((workspace_id, project_id)) = resolve_project_ids(+ let Ok((workspace_id, project_id)) = resolve_project_ids_inner(state,env.cwd.as_deref(),env.workspace_override.as_deref(),env.project_override.as_deref(),env.project_strategy,actor,+ env.recall_default_global_requested,).awaitelse {@@ -759,13 +760,16 @@ async fn fetch_and_accept_handoff(user: actor_user,session_id: None,};- let (ws, proj) = resolve_project_ids(+ let (ws, proj) = resolve_project_ids_inner(state,query.cwd.as_deref(),query.workspace.as_deref(),query.project.as_deref(),ProjectStrategy::parse(query.project_strategy.as_deref()),&actor_key,+ // The /handoff query carries no recall preference; the main capture+ // path is what publishes default_global for read tools.+ false,).await?;let handoff = state@@ -881,13 +885,15 @@ fn normalize_project_path_key(path: &str) -> String {/// project_strategy)` so the same `cwd` resolved with and without an/// override (e.g. during a hook-script upgrade window) doesn't poison each/// other's slot.-async fn resolve_project_ids(+#[allow(clippy::too_many_arguments)]+async fn resolve_project_ids_inner(state: &HookState,cwd: Option<&str>,workspace_override: Option<&str>,project_override: Option<&str>,project_strategy: ProjectStrategy,actor: &ai_memory_core::ActorKey,+ default_global: bool,) -> anyhow::Result<(WorkspaceId, ProjectId)> {let cwd_norm = cwd.filter(|s| !s.is_empty())@@ -914,7 +920,9 @@ async fn resolve_project_ids(// MCP read tools need as their default. Keyed by the actor so// opt-in isolation modes (`per_session`/`per_actor`) keep// concurrent callers separated.- state.active_project.set_for(actor, ids.0, ids.1);+ state+ .active_project+ .set_for(actor, ids.0, ids.1, default_global);return Ok(ids);}}@@ -934,7 +942,7 @@ async fn resolve_project_ids(None => {state.active_project- .set_for(actor, state.workspace_id, state.project_id);+ .set_for(actor, state.workspace_id, state.project_id, default_global);return Ok((state.workspace_id, state.project_id));}},@@ -947,7 +955,7 @@ async fn resolve_project_ids(// message.state.active_project- .set_for(actor, state.workspace_id, state.project_id);+ .set_for(actor, state.workspace_id, state.project_id, default_global);return Ok((state.workspace_id, state.project_id));}};@@ -966,7 +974,7 @@ async fn resolve_project_ids();state.active_project- .set_for(actor, state.workspace_id, state.project_id);+ .set_for(actor, state.workspace_id, state.project_id, default_global);return Ok((state.workspace_id, state.project_id));}@@ -1120,10 +1128,37 @@ async fn resolve_project_ids(};let ids = (ws, proj);state.project_cache.lock().await.insert(cache_key, ids);- state.active_project.set_for(actor, ws, proj);+ state+ .active_project+ .set_for(actor, ws, proj, default_global);Ok(ids)}+/// Back-compat wrapper used by tests: resolve without the `default_global`+/// recall preference (equivalent to a repo that never opted into+/// `[recall] default_global`). Production paths call+/// [`resolve_project_ids_inner`] directly with the marker's value.+#[cfg(test)]+async fn resolve_project_ids(+ state: &HookState,+ cwd: Option<&str>,+ workspace_override: Option<&str>,+ project_override: Option<&str>,+ project_strategy: ProjectStrategy,+ actor: &ai_memory_core::ActorKey,+) -> anyhow::Result<(WorkspaceId, ProjectId)> {+ resolve_project_ids_inner(+ state,+ cwd,+ workspace_override,+ project_override,+ project_strategy,+ actor,+ false,+ )+ .await+}+/// Whether session-sticky attribution may apply: the event's cwd must sit/// inside the session's own cwd subtree, and the session's cwd must be a/// meaningful anchor — not missing, not the filesystem root, and not the@@ -1222,19 +1257,23 @@ async fn process(// Publish the pointer like resolve_project_ids does on a cache// hit: this session being active is exactly what the MCP read// tools should default to.- state- .active_project- .set_for(&actor_key, session_ws, session_proj);+ state.active_project.set_for(+ &actor_key,+ session_ws,+ session_proj,+ env.recall_default_global_requested,+ );(session_ws, session_proj)}None => {- resolve_project_ids(+ resolve_project_ids_inner(state,env.cwd.as_deref(),env.workspace_override.as_deref(),env.project_override.as_deref(),env.project_strategy,&actor_key,+ env.recall_default_global_requested,).await?}@@ -1300,13 +1339,14 @@ async fn process(env.project_strategy,);state.project_cache.lock().await.remove(&key);- let refreshed = resolve_project_ids(+ let refreshed = resolve_project_ids_inner(state,env.cwd.as_deref(),env.workspace_override.as_deref(),env.project_override.as_deref(),env.project_strategy,&actor_key,+ env.recall_default_global_requested,).await?;ws = refreshed.0;diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex b79d1fa4..d829cfdc 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -6355,7 +6355,7 @@ mod tests {user: Some("alice".into()),session_id: Some("session-1".into()),};- active.set_for(&actor, src_ws, src_proj);+ active.set_for(&actor, src_ws, src_proj, false);active.set(WorkspaceId::new(), ProjectId::new());let move_body = serde_json::json!({@@ -6437,7 +6437,7 @@ mod tests {user: Some("alice".into()),session_id: Some("session-1".into()),};- active.set_for(&actor, ws, proj);+ active.set_for(&actor, ws, proj, false);active.set(ws, proj);let resp = router@@ -6562,7 +6562,7 @@ mod tests {user: Some("alice".into()),session_id: Some("session-1".into()),};- active.set_for(&actor, src_ws, src_proj);+ active.set_for(&actor, src_ws, src_proj, false);active.set(src_ws, src_proj);let resp = routerdiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 51781ec1..727f19bf 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -1120,7 +1120,24 @@ impl AiMemoryServer {) -> Result<CallToolResult, McpError> {let aps_actor = Self::actor_key_from_parts(Some(&parts));let limit = args.limit.unwrap_or(self.default_limit).clamp(1, 100);- if args.global.unwrap_or(false) {+ // A repo that opted into `[recall] default_global` (published on the+ // ActiveProject by the hook) makes a query with NO explicit scoping+ // behave as `global=true`. Precedence is strict: an explicit+ // `global` / `scopes` / `workspace` / `project` arg always wins, so+ // this only fires when the caller passed none of them.+ let explicit_scoping = !args.scopes.is_empty()+ || args+ .workspace+ .as_deref()+ .is_some_and(|s| !s.trim().is_empty())+ || args+ .project+ .as_deref()+ .is_some_and(|s| !s.trim().is_empty());+ let recall_global = !explicit_scoping+ && !args.global.unwrap_or(false)+ && self.active_project.default_global_for(&aps_actor);+ if args.global.unwrap_or(false) || recall_global {if !args.scopes.is_empty()|| args.workspace@@ -4687,6 +4704,108 @@ mod tests {assert!(text.contains("global_hits"), "global hits field: {text}");}+ #[tokio::test]+ async fn memory_query_default_global_marker_broadens_unscoped_query() {+ let (_tmp, store, server, ws, _pj) = setup_server().await;+ let infra = store+ .writer+ .get_or_create_project(ws, "infra", None)+ .await+ .unwrap();+ let ops_ws = store.writer.get_or_create_workspace("ops").await.unwrap();+ let runbooks = store+ .writer+ .get_or_create_project(ops_ws, "runbooks", None)+ .await+ .unwrap();+ for (w, p, path, body) in [+ (ws, infra, "cluster.md", "recall_token lives in infra"),+ (ops_ws, runbooks, "deploy.md", "recall_token lives in runbooks"),+ ] {+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: w,+ project_id: p,+ path: PagePath::new(path).unwrap(),+ title: path.into(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ })+ .await+ .unwrap();+ }++ // The repo opted into `[recall] default_global` — the hook publishes it+ // on the ActiveProject (single slot here, matching the empty test actor).+ server+ .active_project+ .set_for(&ai_memory_core::ActorKey::default(), ws, infra, true);++ // A query with NO scoping args now behaves as `global=true`.+ let result = server+ .memory_query(+ Parameters(QueryArgs {+ query: "recall_token".into(),+ limit: Some(10),+ project: None,+ scopes: Vec::new(),+ workspace: None,+ global: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let text = result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(+ text.contains("global_hits"),+ "default_global must route the unscoped query to global: {text}"+ );+ assert!(text.contains("cluster.md"), "infra hit expected: {text}");+ assert!(text.contains("deploy.md"), "runbooks hit expected: {text}");++ // Precedence: an EXPLICIT workspace+project still wins over+ // default_global — the query scopes to runbooks only (no infra hit).+ let scoped = server+ .memory_query(+ Parameters(QueryArgs {+ query: "recall_token".into(),+ limit: Some(10),+ project: Some("runbooks".into()),+ scopes: Vec::new(),+ workspace: Some("ops".into()),+ global: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let scoped_text = scoped+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(+ scoped_text.contains("deploy.md"),+ "explicit ops/runbooks hit expected: {scoped_text}"+ );+ assert!(+ !scoped_text.contains("cluster.md"),+ "explicit scope must NOT broaden to infra: {scoped_text}"+ );+ }+#[tokio::test]async fn memory_query_global_rejects_explicit_scope() {let (_tmp, _store, server, _ws, _pj) = setup_server().await;diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex 969c4376..be6b8e95 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -532,7 +532,7 @@ mod tests {user: Some("alice".into()),session_id: Some("s1".into()),};- active_project.set_for(&actor, active_ws, active_scratch);+ active_project.set_for(&actor, active_ws, active_scratch, false);let resolver = ScopeResolver::new(&store.reader, default_ws, default_scratch).with_active_project(&active_project);@@ -579,7 +579,7 @@ mod tests {user: None,session_id: Some("s1".into()),};- active_project.set_for(&actor, active_ws, active_project_id);+ active_project.set_for(&actor, active_ws, active_project_id, false);let resolver = ScopeResolver::new(&store.reader, default_ws, default_project).with_writer(&store.writer).with_active_project(&active_project);