Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(scope): reserved _global preferences scope with default-read union
AkitaOnRailsddc960cc09b7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 077d2ee6..fe1a6df5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Global preferences scope ([#154]): standing user/team context that+ should apply to every project — technology choices, code style,+ durable personal conventions — now has a dedicated home. Write with+ `memory_write_page` + `scope: "global"`; the page lands in the+ reserved `_global` project (default workspace, following the+ `_meta.md`/`_pending/` reserved-name convention). Default-scoped+ `memory_query` calls union that scope into every project as a new+ `global_scope_hits` response field — one extra scoped search, not the+ O(projects) `global=true` fan-out — while explicitly scoped queries+ (`workspace`/`project`/`scopes`/`global=true`) are unchanged. The+ scope participates by existence: no config, zero effect until the+ first global write. Event capture never creates or attributes to it —+ a directory or marker override named `_global` falls back to the+ server-default project.+### Fixed- A session that is resumed under the same id after an early `SessionEnd`now re-consolidates when it ends again. The end-of-session guard used todiff --git a/README.md b/README.mdindex 747cbf4a..fde922ca 100644--- a/README.md+++ b/README.md@@ -72,6 +72,13 @@ priors are at the [bottom](#influences-and-prior-art).linked git worktrees.Same page path can exist in two projects without collision; arename is one column update; a purge is one `rm -rf`.+- **Global preferences scope.** Standing user/team context — tech+ choices, code style, durable personal rules — lives in the reserved+ `_global` scope (`memory_write_page` with `scope: "global"`). Default+ `memory_query` reads union it into every project as+ `global_scope_hits`, so preferences travel with you into new projects+ without naming a magic project or paying the all-projects+ `global=true` fan-out. Event capture never writes there.- **Karpathy-style LLM wiki.** Pages are compiled from observationsat session-end (or PreCompact; Codex can use `ai-memory finalize-session`for a manual final close), not retrieved over raw logs.diff --git a/crates/ai-memory-consolidate/src/auto_improve.rs b/crates/ai-memory-consolidate/src/auto_improve.rsindex e2a141e5..c2144558 100644--- a/crates/ai-memory-consolidate/src/auto_improve.rs+++ b/crates/ai-memory-consolidate/src/auto_improve.rs@@ -2099,8 +2099,19 @@ mod tests {.await;assert!(proposals.is_empty());- assert_eq!(rejected[0].reason, "eval_gate_error");- assert!(rejected[0].evidence.contains("eval stdout exceeded"));+ // This test has flaked rarely on loaded machines with a different+ // eval_gate_error; print the actual reason/evidence so the next+ // occurrence identifies the real failure mode instead of hiding it.+ assert_eq!(+ rejected[0].reason, "eval_gate_error",+ "evidence: {}",+ rejected[0].evidence+ );+ assert!(+ rejected[0].evidence.contains("eval stdout exceeded"),+ "evidence: {}",+ rejected[0].evidence+ );}#[test]diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 8d98d595..2e339f88 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -23,6 +23,16 @@ pub const DEFAULT_WORKSPACE_NAME: &str = "default";/// Defensive project fallback used only when no cwd/project is available.pub const DEFAULT_PROJECT_NAME: &str = "scratch";+/// Reserved project holding user/team-level standing context — technology+/// preferences, code style, durable decisions that every project should+/// inherit (issue #154). Lives in [`DEFAULT_WORKSPACE_NAME`]. Default+/// `memory_query` reads union this scope with the current project; it is+/// written only through explicit `scope: "global"` requests. The leading+/// underscore follows the wiki's reserved-name convention (`_meta.md`,+/// `_pending/`, `_lint/`) and the hook router refuses to auto-attribute+/// event capture to it.+pub const GLOBAL_SCOPE_PROJECT: &str = "_global";+pub use active_project::{ActiveProject, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES, DEFAULT_PER_KEY_TTL,};diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.mdindex e334eff3..c59a8d00 100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md@@ -30,3 +30,7 @@ Delete only by exact path. If the user gives a vague title or topic, first resol## Scope defaultDefault to the current project. Pass workspace and project together only when the user explicitly names a different project. Never pass scope arguments for phrases like this project, here, we, or our work.++## Standing user/team preferences go to the global scope++When the fact is a standing preference that should apply to EVERY project — technology choices ("always use pnpm workspaces"), code style ("prefer composition over inheritance"), personal conventions ("never `--force` without asking") — call `memory_write_page` with `scope: "global"` instead of the current project. The page lands in the reserved `_global` scope, and default memory reads surface it in every project as `global_scope_hits`. `scope: "global"` cannot be combined with workspace/project arguments. Use it only for genuinely cross-project preferences; project-specific rules stay in the project (or its instruction file, per the section above).diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex 6dcd246e..80791525 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -67,6 +67,12 @@ Many projects use CLAUDE.md for Claude Code andAGENTS.md for Codex / OpenCode / Cursor / Gemini CLI, but if the projectsays one file is canonical, use that file.+If the rule is a standing *user/team* preference that should apply to+every project (tech choices, code style, personal conventions), save it+to ai-memory's reserved global scope instead — the durable-pages skill+covers how. Default memory reads surface global-scope pages in every+project automatically.+### Refreshing this snippetThis block is maintained by ai-memory. Two ways to refresh it with thediff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex acc072d0..fa0d0fff 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -730,6 +730,24 @@ async fn resolve_project_ids(}};+ // The reserved global preferences scope (issue #154) is written only+ // through explicit MCP `scope: "global"` requests — event capture must+ // never create it or leak observations into it, whether the name came+ // from a directory literally called `_global` or a marker-file+ // override. Fall back to the server-default project, same as a+ // cwd-less event.+ if project_name == ai_memory_core::GLOBAL_SCOPE_PROJECT {+ debug!(+ cwd = ?cwd_norm,+ "hook router: refusing to attribute event capture to the reserved \+ global scope; using the server-default project"+ );+ state+ .active_project+ .set_for(actor, state.workspace_id, state.project_id);+ return Ok((state.workspace_id, state.project_id));+ }+fn derive_project_from_cwd(cwd: &str,strategy: ProjectStrategy,@@ -1462,6 +1480,61 @@ mod tests {assert_eq!(state.active_project.get(), Some((ws_b, proj_b)));}+ // Issue #154: event capture must never create or attribute to the+ // reserved `_global` preferences scope — not from a directory that+ // happens to carry the reserved name, and not from a marker-file+ // project override.+ #[tokio::test]+ async fn reserved_global_scope_is_never_auto_attributed() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;++ // cwd whose basename is the reserved name.+ let (ws, proj) = resolve_project_ids(+ &state,+ Some("/home/user/_global"),+ None,+ None,+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ assert_eq!(+ (ws, proj),+ (state.workspace_id, state.project_id),+ "cwd named _global must fall back to the server-default project"+ );++ // Explicit marker-file override naming the reserved scope.+ let (ws, proj) = resolve_project_ids(+ &state,+ Some("/home/user/some-project"),+ None,+ Some(ai_memory_core::GLOBAL_SCOPE_PROJECT),+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ assert_eq!(+ (ws, proj),+ (state.workspace_id, state.project_id),+ "project override _global must fall back to the server-default project"+ );++ // Neither call may have materialised the reserved project row.+ let created = state+ .reader+ .find_project(+ state.workspace_id,+ ai_memory_core::GLOBAL_SCOPE_PROJECT.to_string(),+ )+ .await+ .unwrap();+ assert_eq!(created, None, "event capture must not create _global");+ }+#[tokio::test]async fn handle_hook_returns_429_when_ingest_saturated() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 7bc3e3bb..5f44a216 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -175,7 +175,10 @@ the conversation calls for them:\n\to propose architecture (always check first). Defaults to the \current project; pass `scopes` to search named sibling projects, \or `global=true` to search EVERY project at once when you don't \- know where the knowledge lives.\n\+ know where the knowledge lives. Default-scoped calls also return \+ `global_scope_hits` — standing user/team preferences from the \+ reserved `_global` scope; treat them as context that applies to \+ every project.\n\- `memory_recent` — at session start, or when the user asks 'what's \been going on lately'. Returns the N most-recent pages.\n\- `memory_status` — when the user asks 'is ai-memory healthy' or \@@ -225,7 +228,11 @@ should be proposed from a completed session, or at explicit wrap-up \do NOT use `memory_handoff_begin` for permanent annotations. \Put the title as a `# H1` on the first line of `body` and omit the \`title` argument — ai-memory derives the title automatically and \- passing `title` is a known JSON-escape footgun (issue #67).\n\+ passing `title` is a known JSON-escape footgun (issue #67). When the \+ fact is a standing user/team preference that should apply to EVERY \+ project ('always use pnpm', 'never force-push', code style rules), \+ pass `scope: \"global\"` so it lands in the reserved `_global` scope \+ instead of the current project.\n\- `memory_read_page` — when the user asks to read, open, or show the \full content of a specific page. Accepts a `query` (searches FTS5 and \returns the top hit's full body) or a `path` (direct lookup). Pass \@@ -420,6 +427,13 @@ struct MemoryQueryResponse {/// carrying its workspace + project name.#[serde(skip_serializing_if = "Vec::is_empty")]global_hits: Vec<ai_memory_store::PageHitWithMeta>,+ /// Standing user/team context from the reserved `_global` preferences+ /// scope, unioned into default-scoped queries alongside the current+ /// project's `hits` (issue #154). Empty when the scope doesn't exist or+ /// the query was explicitly scoped (`workspace`/`project`/`scopes`/+ /// `global=true`).+ #[serde(skip_serializing_if = "Vec::is_empty")]+ global_scope_hits: Vec<ai_memory_store::PageHit>,}#[derive(Debug, Serialize)]@@ -704,6 +718,12 @@ struct WritePageArgs {/// `project`; created if it doesn't exist. Omit for the current workspace.#[serde(default)]workspace: Option<String>,+ /// Set to `"global"` to write into the reserved `_global` preferences+ /// scope — standing user/team context (tech preferences, code style,+ /// durable decisions) that default `memory_query` reads union into+ /// every project. Cannot be combined with `workspace`/`project`.+ #[serde(default)]+ scope: Option<String>,}#[tool_router]@@ -1043,7 +1063,10 @@ impl AiMemoryServer {Returns up to `limit` pages with HTML-marked snippets and a rank \score (lower rank = better match). Only latest page versions. \If compiled wiki search misses, `raw_hits` contains bounded raw \- observation fallback matches. Set `global=true` to search EVERY \+ observation fallback matches. Default-scoped calls also return \+ `global_scope_hits`: standing user/team preferences from the \+ reserved `_global` scope that apply across projects. Set \+ `global=true` to search EVERY \project at once (cross-project) when you don't know which project \holds the knowledge — each hit then carries its workspace + \project name.")]@@ -1079,6 +1102,7 @@ impl AiMemoryServer {hits: Vec::new(),raw_hits: Vec::new(),global_hits,+ global_scope_hits: Vec::new(),});}if !args.scopes.is_empty()@@ -1156,10 +1180,57 @@ impl AiMemoryServer {} else {Vec::new()};+ // Default-scoped queries (no workspace/project/scopes/global args)+ // also union the reserved `_global` preferences scope, so standing+ // user/team context travels into every project without the caller+ // knowing a magic project name (issue #154). Explicit scoping means+ // the caller asked for exactly those scopes — leave it alone. One+ // extra scoped search when the scope exists; zero cost when it+ // doesn't.+ let default_scoped = args.scopes.is_empty()+ && args+ .workspace+ .as_deref()+ .is_none_or(|s| s.trim().is_empty())+ && args.project.as_deref().is_none_or(|s| s.trim().is_empty());+ let global_scope_hits = if default_scoped {+ match ai_memory_store::lookup_global_scope(&self.reader).await {+ Ok(Some(scope)) => {+ // If the current project IS the reserved scope (e.g. the+ // actor's active-project pointer lands there after a+ // global write), `hits` already covers it — don't search+ // it twice.+ let current = self+ .effective_ids_for_read_args_with_actor(None, None, &aps_actor)+ .await?;+ if current == scope.as_tuple() {+ Vec::new()+ } else {+ let hits = self+ .search_project(+ scope.workspace_id,+ scope.project_id,+ &args.query,+ query_vec.as_deref(),+ limit,+ )+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ self.spawn_access_bump(hits.iter().map(|h| h.id).collect());+ hits+ }+ }+ Ok(None) => Vec::new(),+ Err(e) => return Err(McpError::internal_error(e.to_string(), None)),+ }+ } else {+ Vec::new()+ };let response = MemoryQueryResponse {hits,raw_hits,global_hits: Vec::new(),+ global_scope_hits,};ok_json(&response)}@@ -1551,6 +1622,10 @@ impl AiMemoryServer {relative path such as `notes/<topic>.md`, `concepts/<topic>.md`, \`decisions/<topic>.md`, or `_rules/<topic>.md`. `tier` defaults \to `semantic`; set `pinned=true` for facts that should never decay. \+ For standing user/team preferences that apply to EVERY project \+ (tech choices, code style, durable personal rules), pass \+ `scope: \"global\"` — the page lands in the reserved `_global` \+ scope and default memory_query calls surface it in every project. \\**Title convention:** start `body` with a `# Some Title` line — \ai-memory derives the title from that H1 automatically. Do NOT \@@ -1576,13 +1651,42 @@ impl AiMemoryServer {.map_err(|_| McpError::internal_error(format!("unknown tier '{tier_name}'"), None))?;let path = PagePath::new(args.path.clone()).map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;- let (ws, proj) = self- .write_target_ids_with_actor(- args.workspace.as_deref(),- args.project.as_deref(),- &aps_actor,- )- .await?;+ let (ws, proj) = match args.scope.as_deref().map(str::trim) {+ None | Some("") => {+ self.write_target_ids_with_actor(+ args.workspace.as_deref(),+ args.project.as_deref(),+ &aps_actor,+ )+ .await?+ }+ Some("global") => {+ if args+ .workspace+ .as_deref()+ .is_some_and(|s| !s.trim().is_empty())+ || args+ .project+ .as_deref()+ .is_some_and(|s| !s.trim().is_empty())+ {+ return Err(McpError::internal_error(+ "scope: \"global\" cannot be combined with workspace/project",+ None,+ ));+ }+ ai_memory_store::create_global_scope(&self.writer)+ .await+ .map_err(Self::scope_error)?+ .as_tuple()+ }+ Some(other) => {+ return Err(McpError::internal_error(+ format!("unknown scope '{other}': the only supported value is \"global\""),+ None,+ ));+ }+ };let mut fm = serde_json::Map::new();if let Some(title) = &args.title {@@ -3230,6 +3334,7 @@ mod tests {pinned: false,project: Some("sibling".to_string()),workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(parts),)@@ -3321,6 +3426,168 @@ mod tests {assert!(text.contains("foo.md"), "expected hit; got {text}");}+ // Issue #154: default-scoped queries union the reserved `_global`+ // preferences scope; explicitly scoped queries do not.+ #[tokio::test]+ async fn default_query_unions_global_scope_and_explicit_scope_skips_it() {+ let (_tmp, store, server, _ws, _proj) = setup_server().await;+ let global = ai_memory_store::create_global_scope(&store.writer)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: global.workspace_id,+ project_id: global.project_id,+ path: PagePath::new("preferences/style.md").unwrap(),+ title: "Style".into(),+ body: "Karpathy approved standing preference: pnpm always.".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ })+ .await+ .unwrap();++ let query = |workspace: Option<&str>, project: Option<&str>| QueryArgs {+ query: "karpathy".into(),+ limit: Some(5),+ project: project.map(str::to_string),+ scopes: Vec::new(),+ workspace: workspace.map(str::to_string),+ global: None,+ };++ let result = server+ .memory_query(+ Parameters(query(None, None)),+ rmcp::handler::server::tool::Extension(test_parts_default()),+ )+ .await+ .unwrap();+ let text = result.content.first().and_then(|c| c.as_text()).unwrap();+ assert!(+ text.text.contains("foo.md"),+ "current-project hit must remain: {}",+ text.text+ );+ assert!(+ text.text.contains("global_scope_hits") && text.text.contains("preferences/style.md"),+ "default query must union the reserved global scope: {}",+ text.text+ );++ let result = server+ .memory_query(+ Parameters(query(Some("default"), Some("scratch"))),+ rmcp::handler::server::tool::Extension(test_parts_default()),+ )+ .await+ .unwrap();+ let text = result.content.first().and_then(|c| c.as_text()).unwrap();+ assert!(+ !text.text.contains("preferences/style.md"),+ "explicitly scoped queries must not union the global scope: {}",+ text.text+ );+ }++ // Issue #154: an absent `_global` scope contributes nothing and is+ // never created by a read.+ #[tokio::test]+ async fn default_query_without_global_scope_is_unchanged() {+ let (_tmp, store, server, _ws, _proj) = setup_server().await;+ let result = server+ .memory_query(+ Parameters(QueryArgs {+ query: "karpathy".into(),+ limit: Some(5),+ project: None,+ scopes: Vec::new(),+ workspace: None,+ global: None,+ }),+ rmcp::handler::server::tool::Extension(test_parts_default()),+ )+ .await+ .unwrap();+ let text = result.content.first().and_then(|c| c.as_text()).unwrap();+ assert!(+ !text.text.contains("global_scope_hits"),+ "no reserved scope -> field elided: {}",+ text.text+ );+ assert_eq!(+ ai_memory_store::lookup_global_scope(&store.reader)+ .await+ .unwrap(),+ None,+ "a read must never create the reserved scope"+ );+ }++ #[tokio::test]+ async fn write_page_scope_global_lands_in_reserved_scope() {+ let (tmp, store, server, _ws, _proj) = setup_server().await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = server.with_wiki(wiki);+ let write_args = |scope: Option<&str>, project: Option<&str>| WritePageArgs {+ path: "preferences/pkg.md".to_string(),+ body: "# Package manager\nAlways pnpm workspaces.".to_string(),+ title: None,+ tier: None,+ tags: Vec::new(),+ pinned: false,+ project: project.map(str::to_string),+ workspace: None,+ scope: scope.map(str::to_string),+ };++ server+ .memory_write_page(+ Parameters(write_args(Some("global"), None)),+ rmcp::handler::server::tool::Extension(test_parts_default()),+ )+ .await+ .unwrap();+ let global = ai_memory_store::lookup_global_scope(&store.reader)+ .await+ .unwrap()+ .expect("scope: global write must create the reserved scope");+ let pages = store+ .reader+ .recent_pages_for_project(global.workspace_id, global.project_id, 10)+ .await+ .unwrap();+ assert!(+ pages+ .iter()+ .any(|p| p.path.as_str() == "preferences/pkg.md"),+ "page must land in the reserved scope; got {:?}",+ pages.iter().map(|p| p.path.as_str()).collect::<Vec<_>>()+ );++ let err = server+ .memory_write_page(+ Parameters(write_args(Some("global"), Some("other"))),+ rmcp::handler::server::tool::Extension(test_parts_default()),+ )+ .await+ .expect_err("scope + project must fail closed");+ assert!(err.to_string().contains("cannot be combined"), "{err}");++ let err = server+ .memory_write_page(+ Parameters(write_args(Some("universe"), None)),+ rmcp::handler::server::tool::Extension(test_parts_default()),+ )+ .await+ .expect_err("unknown scope values must fail closed");+ assert!(err.to_string().contains("unknown scope"), "{err}");+ }+#[tokio::test]async fn memory_query_returns_raw_hits_when_pages_miss() {let (_tmp, store, server, ws, proj) = setup_server().await;@@ -3941,6 +4208,7 @@ mod tests {pinned: true,project: None,workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(parts),)@@ -4006,6 +4274,7 @@ mod tests {pinned: false,project: None,workspace: Some("default".into()),+ scope: None,}),rmcp::handler::server::tool::Extension(test_parts_default()),)@@ -4071,6 +4340,7 @@ mod tests {pinned: false,project: None,workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(parts),)@@ -4118,6 +4388,7 @@ mod tests {pinned: false,project: None,workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(test_parts_default()),)@@ -4180,6 +4451,7 @@ mod tests {pinned: false,project: None,workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(parts()),)@@ -4267,6 +4539,7 @@ mod tests {pinned: false,project: None,workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(test_parts_default()),)@@ -4358,6 +4631,7 @@ mod tests {pinned: false,project: Some("shared".into()),workspace: Some("alpha".into()),+ scope: None,}),rmcp::handler::server::tool::Extension(parts()),)@@ -4374,6 +4648,7 @@ mod tests {pinned: false,project: Some("shared".into()),workspace: Some("beta".into()),+ scope: None,}),rmcp::handler::server::tool::Extension(parts()),)@@ -4471,6 +4746,7 @@ mod tests {pinned: false,project: Some("other".into()),workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(parts()),)@@ -5080,6 +5356,7 @@ mod tests {pinned: false,project: Some("audited".into()),workspace: None,+ scope: None,}),rmcp::handler::server::tool::Extension(parts()),)diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 8a24b094..30f3bfea 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -46,7 +46,8 @@ pub use reader::{};pub use scope::{ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,- create_explicit_scope, lookup_existing_scope, resolve_many_existing_scopes,+ create_explicit_scope, create_global_scope, lookup_existing_scope, lookup_global_scope,+ resolve_many_existing_scopes,};pub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};pub use writer::WriterHandle;diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex a8da5cbe..5f79b822 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -221,6 +221,54 @@ pub async fn create_explicit_scope(})}+/// Look up the reserved global preferences scope+/// ([`ai_memory_core::GLOBAL_SCOPE_PROJECT`] in the default workspace)+/// without creating it. Returns `Ok(None)` when it doesn't exist yet — the+/// scope participates in default reads by existence, so an absent scope+/// means "nothing to union in", never an error (issue #154).+///+/// # Errors+/// Propagates store failures only; a missing workspace or project is `None`.+pub async fn lookup_global_scope(+ reader: &ReaderPool,+) -> Result<Option<ResolvedScope>, ScopeResolutionError> {+ let Some(workspace_id) = reader+ .find_workspace(ai_memory_core::DEFAULT_WORKSPACE_NAME.to_owned())+ .await?+ else {+ return Ok(None);+ };+ let Some(project_id) = reader+ .find_project(+ workspace_id,+ ai_memory_core::GLOBAL_SCOPE_PROJECT.to_owned(),+ )+ .await?+ else {+ return Ok(None);+ };+ Ok(Some(ResolvedScope {+ workspace_id,+ project_id,+ }))+}++/// Create or fetch the reserved global preferences scope. Write-path only —+/// the counterpart of [`lookup_global_scope`] for `scope: "global"` writes.+///+/// # Errors+/// Propagates store failures.+pub async fn create_global_scope(+ writer: &WriterHandle,+) -> Result<ResolvedScope, ScopeResolutionError> {+ create_explicit_scope(+ writer,+ ai_memory_core::DEFAULT_WORKSPACE_NAME,+ ai_memory_core::GLOBAL_SCOPE_PROJECT,+ )+ .await+}+/// Resolve and de-duplicate explicit multi-scope names without creating/// anything. Surfaces that do not have a current-project default (admin/web)/// can call this directly; [`ScopeResolver::resolve_many_existing`] delegates@@ -598,4 +646,27 @@ mod tests {ScopeResolutionError::TooManyScopes { max: 1, actual: 2 });}++ #[tokio::test]+ async fn global_scope_lookup_is_none_until_created_then_stable() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ // Reads never materialise the reserved scope.+ assert_eq!(lookup_global_scope(&store.reader).await.unwrap(), None);+ assert_eq!(+ lookup_global_scope(&store.reader).await.unwrap(),+ None,+ "lookup must stay a pure read"+ );++ // The write path creates it once; lookup then resolves the same ids.+ let created = create_global_scope(&store.writer).await.unwrap();+ let looked_up = lookup_global_scope(&store.reader).await.unwrap();+ assert_eq!(looked_up, Some(created));++ // Idempotent create.+ let again = create_global_scope(&store.writer).await.unwrap();+ assert_eq!(again, created);+ }}