Skip to content

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

Rust

fix(mcp): honor explicit local queries over recall defaults

Samir Hanna Verzaa7ab35d3e9b3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e65cba04..0480041e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,10 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
+- `memory_query(global=false)` now overrides a project's
+ `[recall] default_global` marker and uses the resolved project's normal
+ search. Previously the explicit opt-out still returned cross-project
+ `global_hits` and disabled project-only query options (#PR).
- Refused empty and whitespace-only `--workspace` and `--project` flags at the
shared CLI scope-resolution choke point (`resolve_scope`,
`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, and
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 08d3baf9..60dcdfff 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -2876,7 +2876,7 @@ impl AiMemoryServer {
));
}
let recall_global = !explicit_scoping
- && !args.global.unwrap_or(false)
+ && args.global.is_none()
&& !as_of_present
&& self.active_project.default_global_for(&aps_actor);
if args.global.unwrap_or(false) || recall_global {
@@ -15385,7 +15385,7 @@ mod tests {
}
#[tokio::test]
- async fn memory_query_default_global_marker_broadens_unscoped_query() {
+ async fn memory_query_default_global_marker_honours_explicit_arguments() {
let (_tmp, store, server, ws, _pj) = setup_server().await;
let infra = store
.writer
@@ -15428,92 +15428,90 @@ mod tests {
.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 {
- kind: None,
- tier: None,
- path_prefix: None,
- tag: None,
- query: "recall_token".into(),
- limit: Some(10),
- project: None,
- scopes: Vec::new(),
- workspace: None,
- global: None,
- include_expired: None,
- include_superseded: None,
- pin_first: None,
- explain: None,
- as_of: None,
- answer: None,
- reasoning: 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 {
- kind: None,
- tier: None,
- path_prefix: None,
- tag: None,
- query: "recall_token".into(),
- limit: Some(10),
- project: Some("runbooks".into()),
- scopes: Vec::new(),
- workspace: Some("ops".into()),
- global: None,
- include_expired: None,
- include_superseded: None,
- pin_first: None,
- explain: None,
- as_of: None,
- answer: None,
- reasoning: 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}"
- );
+ // The marker is only a default: an explicit false keeps the current
+ // project, while named scopes override either marker value.
+ for default_global in [false, true] {
+ server.active_project.set_for(
+ &ai_memory_core::ActorKey::default(),
+ ws,
+ infra,
+ default_global,
+ );
+ for (label, extra, global, expected_path) in [
+ (
+ "omitted",
+ serde_json::json!({}),
+ default_global,
+ "cluster.md",
+ ),
+ (
+ "false",
+ serde_json::json!({"global": false}),
+ false,
+ "cluster.md",
+ ),
+ ("true", serde_json::json!({"global": true}), true, ""),
+ (
+ "named scope",
+ serde_json::json!({"workspace": "ops", "project": "runbooks"}),
+ false,
+ "deploy.md",
+ ),
+ (
+ "named scope with false",
+ serde_json::json!({"workspace": "ops", "project": "runbooks", "global": false}),
+ false,
+ "deploy.md",
+ ),
+ (
+ "scope list",
+ serde_json::json!({"scopes": [{"workspace": "ops", "project": "runbooks"}]}),
+ false,
+ "deploy.md",
+ ),
+ (
+ "scope list with false",
+ serde_json::json!({"scopes": [{"workspace": "ops", "project": "runbooks"}], "global": false}),
+ false,
+ "deploy.md",
+ ),
+ ] {
+ let mut args = serde_json::json!({"query": "recall_token"});
+ args.as_object_mut()
+ .unwrap()
+ .extend(extra.as_object().unwrap().clone());
+ let result = server
+ .memory_query(
+ Parameters(serde_json::from_value(args).unwrap()),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ let response: serde_json::Value =
+ serde_json::from_str(&result.content.first().unwrap().as_text().unwrap().text)
+ .unwrap();
+ let context = format!("marker={default_global}, {label}: {response}");
+ if global {
+ let paths: BTreeSet<_> = response["global_hits"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|hit| hit["path"].as_str().unwrap())
+ .collect();
+ assert_eq!(
+ paths,
+ BTreeSet::from(["cluster.md", "deploy.md"]),
+ "{context}"
+ );
+ assert_eq!(response["hits"], serde_json::json!([]), "{context}");
+ } else {
+ assert!(response.get("global_hits").is_none(), "{context}");
+ let hits = response["hits"].as_array().unwrap();
+ assert_eq!(hits.len(), 1, "{context}");
+ assert_eq!(hits[0]["path"], expected_path, "{context}");
+ }
+ }
+ }
// `as_of` wins over default_global too: the time-travel lookup reads
// the current project (infra) instead of being broadened to a global
@@ -18806,10 +18804,10 @@ mod tests {
.map(|t| t.text.clone())
.unwrap()
};
- let found_by_query = |user, authorized| {
+ let query = |user, authorized, global| {
let server = &server;
async move {
- let result = server
+ server
.memory_query(
Parameters(QueryArgs {
kind: None,
@@ -18825,7 +18823,7 @@ mod tests {
project: None,
workspace: None,
scopes: Vec::new(),
- global: Some(true),
+ global: Some(global),
include_expired: None,
explain: None,
as_of: None,
@@ -18833,8 +18831,7 @@ mod tests {
OptionalParts(as_user(user, authorized)),
)
.await
- .unwrap();
- text(result).contains("secrets/rates.md")
+ .map(text)
}
};
let found_by_recent = |user, authorized| {
@@ -18857,15 +18854,48 @@ mod tests {
// Authorization on: bob holds nothing on alice's repository, so a
// global search and the global recent listing do not surface it...
- assert!(!found_by_query(bob, true).await, "bob found it by search");
+ assert!(
+ !query(bob, true, true)
+ .await
+ .unwrap()
+ .contains("secrets/rates.md")
+ );
assert!(!found_by_recent(bob, true).await, "bob found it in recent");
// ...while alice, who holds a grant, still finds her own page.
- assert!(found_by_query(alice, true).await);
+ assert!(
+ query(alice, true, true)
+ .await
+ .unwrap()
+ .contains("secrets/rates.md")
+ );
assert!(found_by_recent(alice, true).await);
// No viewer is stamped and nothing changes.
- assert!(found_by_query(bob, false).await);
+ assert!(
+ query(bob, false, true)
+ .await
+ .unwrap()
+ .contains("secrets/rates.md")
+ );
assert!(found_by_recent(bob, false).await);
+
+ // Turning off the marker's global default must use the scoped read
+ // gate, even if the active pointer names a project the caller cannot
+ // read. It must not silently fall back to a filtered global search.
+ let refused = query(bob, true, false).await.unwrap_err();
+ assert!(!refused.to_string().contains("secrets/rates.md"));
+ assert!(
+ query(alice, true, false)
+ .await
+ .unwrap()
+ .contains("secrets/rates.md")
+ );
+ assert!(
+ query(bob, false, false)
+ .await
+ .unwrap()
+ .contains("secrets/rates.md")
+ );
}
/// R1 observation stream, per-project authorization (row 14) and pages
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 9e34c917..54932db6 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -294,8 +294,10 @@ falsy (`false` / `0` / `no` / `off`, quoted or bare). A marker that sets only
`[profile]` keys is a settings boundary, like one with `[briefing]` keys.
`[recall] default_global` applies to an agent's unscoped `memory_query` and
-`memory_recent` calls. A `memory_query` with `as_of` is not broadened: it
-reads the current project as it stood at that instant, and an explicit
+`memory_recent` calls. On `memory_query`, an explicit `global: false` keeps
+the resolved project, even when the marker enables global recall. Explicit
+`workspace` + `project` or `scopes` also override the marker. A query with
+`as_of` reads the current project as it stood at that instant, and an explicit
`global=true` with `as_of` is refused. The `ai-memory search` and
`ai-memory recent` terminal commands do not read it: those commands stay
scoped to the current project and cover every project only when you pass
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 23b2d5a6..81a50701 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -72,7 +72,7 @@ the legitimate restricted-project control and the failed-query cases.
| 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI |
| 5e | Conditional page mutation (#986, invariant #16) | `ai-memory-store/src/ops.rs` `upsert_page_if` reads the latest version and writes in one transaction, the authority; `ai-memory-wiki/src/wiki.rs` `write_page_if` pre-checks under the per-page lock before touching disk and restores the file when the store check fails; conditional deletes reuse `delete_page_if_latest` (exclusive mutation lock plus an in-transaction check). `ai-memory-mcp/src/server.rs` checks the precondition only after scope resolution and the write grant, against the resolved scope's own latest row, and returns `precondition_failed` with no write, checkpoint or webhook dispatch. The agentmemory importer (`agentmemory/mod.rs` `apply_page`) resumes from a conflicting destination only when its complete body equals a planned version; a retained attribution key alone cannot supply the next write's expected version. `companions/ai-memory-wikisync/src/bidi.rs` `build_plan` reads the full page for an edited repository file, keeping classification and `expected_page_id` on the same server version | `multi_session.rs` `conditional_writers_on_one_base_exactly_one_wins_and_nothing_is_destroyed` (two writers from one version: one wins, the base stays reachable, no loser row; fails with the store check removed); `server.rs` `conditional_page_writes::*` (stale id, `create_only` on an existing page, a version id from another project, and conditional deletes are refused and change nothing, with and without the wiki pre-check; the store check proven to bite with the reader pre-check off); `a_reader_may_read_everything_and_change_nothing` (a read-only user's conditional write or delete, with the right id or a wrong one, gets the authorization error and no version data; the page is unchanged); importer `resume_refuses_an_edited_body_even_with_the_original_ingest_key` and `e2e_export_import_rebuilds_chains_and_honours_ttl` (an edited destination body keeps its attribution key but cannot be superseded by a resumed import; both fail with marker-only matching); `resume_after_an_injected_failure_writes_no_duplicates` and `a_foreign_page_at_the_destination_is_never_replaced` are the legitimate-resume and foreign-page controls; wikisync `tests/api_server.rs` `sync_does_not_rebase_an_import_onto_a_concurrent_server_edit` (an edit after the read snapshot is refused by the original version precondition, preserving server, repository and baseline; fails without the conditional-read guard), `sync_imports_a_repo_edit_with_its_metadata` and `sync_exports_metadata_and_round_trips_without_writes` (ordinary import and unchanged-file ETag controls) | STRONG. Importer resumption compares bodies, not frontmatter-only edits; custom server sanitation that changes the planned body fails closed |
| 5f | Wiki-sync companion destination confinement | `companions/ai-memory-wikisync/src/paths.rs` `prepare_dest` compares canonical and lexical destination components without resolving the lexical path; Windows disk and UNC verbatim prefixes compare as equivalent spellings, while changed directory components are refused. `secure_join` keeps validated page paths below that root and refuses existing symlink components | `paths.rs` `prepare_dest_refuses_windows_junctions_without_touching_the_target` refuses a junction and a destination reached through it, leaves an outside canary unchanged, and accepts the real directory; `windows_destination_prefixes_do_not_hide_different_paths` refuses different drives, shares and directory components with ordinary/verbatim controls; `prepare_dest_refuses_symlinks_and_files` and `secure_join_stays_under_root_and_refuses_symlink_components` retain the Unix link controls | Static path checks; no descriptor-relative protection against a concurrently malicious same-user process. The dedicated `windows.yml` wiki sync companion job runs the prefix and junction tests on companion/workflow changes, `windows` or `full-ci` labels, nightly runs and dispatch |
-| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`); `ai-memory-cli/src/commands/mcp_bridge.rs` `bridge_session_id`: the session-less bridge (`--no-session-id`, every non-Claude stdio client on a token-file install) never forwards an inherited `CLAUDE_CODE_SESSION_ID`, so a client launched from a Claude Code terminal cannot steer that session's per-session pointer; the session-aware bridge reads only the variable its `--agent` names (`CLAUDE_CODE_SESSION_ID`, or `MUSE_SESSION_ID` for Meta Muse Code), so neither harness's id stands in for the other's | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed`; `multi_session.rs` `same_operator_multiple_sessions_isolate_active_project_pointers_and_resolution` (concurrent sessions of one operator under `AccessMode::Restricted` resolve unscoped reads/writes to their own active project without cross-session clobber, while an unbound session of the same operator fails closed on unscoped write with `AmbiguousUnscopedWrite` and falls back to `DefaultAfterMismatch` on read); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id` (an inherited id is dropped in session-less mode; the session-aware control forwards it and still fails closed without one), `each_harness_forwards_only_its_own_session_id` (a Muse bridge never forwards an inherited Claude id and fails closed without its own, a Claude bridge never forwards an inherited Muse id; controls forward each harness's own id) and `a_session_less_upstream_config_carries_no_session_header`; `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (the built `mcp-bridge --agent muse` refuses to start with only `CLAUDE_CODE_SESSION_ID` set) | STRONG |
+| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`); `ai-memory-mcp/src/server.rs` `memory_query` applies the pointer's `default_global` only when `global` is absent and no explicit scope or `as_of` is supplied; `ai-memory-cli/src/commands/mcp_bridge.rs` `bridge_session_id`: the session-less bridge (`--no-session-id`, every non-Claude stdio client on a token-file install) never forwards an inherited `CLAUDE_CODE_SESSION_ID`, so a client launched from a Claude Code terminal cannot steer that session's per-session pointer; the session-aware bridge reads only the variable its `--agent` names (`CLAUDE_CODE_SESSION_ID`, or `MUSE_SESSION_ID` for Meta Muse Code), so neither harness's id stands in for the other's | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed`; `multi_session.rs` `same_operator_multiple_sessions_isolate_active_project_pointers_and_resolution` (concurrent sessions of one operator under `AccessMode::Restricted` resolve unscoped reads/writes to their own active project without cross-session clobber, while an unbound session of the same operator fails closed on unscoped write with `AmbiguousUnscopedWrite` and falls back to `DefaultAfterMismatch` on read); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id` (an inherited id is dropped in session-less mode; the session-aware control forwards it and still fails closed without one), `each_harness_forwards_only_its_own_session_id` (a Muse bridge never forwards an inherited Claude id and fails closed without its own, a Claude bridge never forwards an inherited Muse id; controls forward each harness's own id) and `a_session_less_upstream_config_carries_no_session_header`; `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (the built `mcp-bridge --agent muse` refuses to start with only `CLAUDE_CODE_SESSION_ID` set); `server.rs` `memory_query_default_global_marker_honours_explicit_arguments` (both marker values with omitted/false/true `global`, named scopes and scope lists: explicit false never adds another project; fails with the opt-out guard removed), `bob_cannot_find_alices_page_by_searching_in_a_restricted_project` (explicit false still refuses an ungranted restricted active project, with granted and unrestricted controls; global searches retain their visibility filter) | STRONG |
| 6b | Native `_meta` routing coordinate is routing-only (never grants identity) | `ai-memory-mcp/src/server.rs` `attach_native_session` reads only `_meta["ai.opencode/sessionID"]` into `ActorKey.session_id` (trimmed, non-empty-string-validated); `user` still comes from the authenticated `ActorContext`, so a forged `_meta` cannot cross a user/scope boundary — it only selects a session slot behind the existing `active_project` guard | `server.rs` `native_session_metadata_is_routing_only_and_preserves_precedence`, `native_session_metadata_validates_strings_without_granting_identity`; `autoscope_multiuser.rs` `native_metadata_routes_concurrent_reads_and_writes_to_hook_workspaces` (#864) | STRONG |
| 6c | Per-user slot namespaces stay per operator (`[slots] per_user`) | `ai-memory-mcp/src/server.rs` `place_slot_mutation`, shared by `place_slot_write` (`memory_write_page`) and `place_slot_delete` (`memory_delete_page`): a non-admin's generic `_slots/<name>.md` is redirected to their own `_slots/u-<operator>/` namespace, a path inside another operator's namespace is refused, admins bypass, and nothing changes with the flag off (#1083) | `slot_identity.rs` `oidc_operator_cannot_delete_another_operators_personal_slot`, `oidc_operator_deleting_shared_slot_path_deletes_their_personal_slot` (shared slot survives), legitimate controls `oidc_operator_can_delete_their_own_personal_slot_explicitly`, `admin_can_delete_shared_and_personal_slots` | STRONG |
| 6d | MCP page restore is admin-only and cannot bypass the write boundary | `ai-memory-mcp/src/server.rs` `memory_restore_page`: `require_admin_capability` gates listing and restoring alike (git keeps text a root deleted, purged or let expire), the same rung as `/admin/restore-page`; scope resolves once with the no-create mutation resolver (`effective_ids_for_mutation_args_with_actor`), so a restricted project needs a write grant even past the gate; a restore writes through `write_page_in_scope` (the `memory_write_page` body) into that resolved scope, so the sanitizer, admission chain, slot placement, attribution and supersession apply, and `checkpoint_write_metadata` re-validates the checkpoint's metadata | `tests/suite/restore_page_authz.rs`: `a_db_user_with_a_write_grant_cannot_list_or_restore` (an `aim_` user who can write the project is refused for both; root control restores), `a_foreign_restricted_project_is_refused_without_a_grant` (no grant on a restricted project, plus an unknown bearer, refused without leaking the version; root control), `a_personal_slot_restores_to_its_exact_path_and_only_for_root` (the slot owner is refused; root restores the exact `_slots/u-…` path, never the shared slot); `server.rs` `memory_restore_page_refuses_unknown_explicit_scope_and_bad_rev`, `memory_restore_page_round_trips_frontmatter_metadata`, legitimate control `memory_restore_page_lists_checkpoints_and_brings_back_a_deleted_page` | STRONG. Bite checks: removing the admin gate fails the write-grant and slot tests; removing it and also resolving without the viewer fails the restricted-project test; dropping the checkpoint metadata fails the round-trip test |