Skip to content

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

Rust

feat(search): add `ai-memory search --global` with project-tagged hits (#1253)

AkitaOnRails05f6dcada32c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a2f8424..f981dde0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,19 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
+### Added
+- Added `ai-memory search --global`, which searches the wiki pages of every
+ project from the terminal instead of only the current one. Each hit shows
+ its `workspace/project` in the text output and carries `workspace` and
+ `project` fields in `--json`. The flag cannot be combined with
+ `--workspace` or `--project`, and a search without it still resolves its
+ scope from the current directory. The server side is `GET /admin/search`
+ with no `workspace`/`project`: its hits now include `workspace` and
+ `project` next to the fields they already had, and the route stays
+ root-only on a multi-user server. Global search covers wiki pages only;
+ raw observations and a search limited to one workspace are not part of
+ this change. (#1253)
+
## [3.0.0] - 2026-10-13
### Added
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 2834f73a..66232bd4 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -2114,6 +2114,10 @@ pub struct SearchArgs {
/// Project name. When omitted, auto-derived from the current project.
#[arg(long)]
pub project: Option<String>,
+ /// Search the wiki pages of every project instead of the current one.
+ /// Each hit is labelled with its `workspace/project`.
+ #[arg(long, conflicts_with_all = ["workspace", "project"])]
+ pub global: bool,
/// Maximum number of hits to return.
#[arg(short = 'n', long, default_value_t = 10)]
pub limit: usize,
@@ -3496,6 +3500,36 @@ mod tests {
assert_eq!(args.enforced_by.as_deref(), Some("pre-push hook"));
}
+ /// `search --global` drops the scope entirely, so naming one alongside it
+ /// is a contradiction clap rejects rather than one flag silently winning.
+ #[test]
+ fn search_global_parses_and_conflicts_with_an_explicit_scope() {
+ let parsed = Cli::try_parse_from(["ai-memory", "search", "wal", "--global"])
+ .expect("search --global parses");
+ let Command::Search(args) = parsed.command else {
+ panic!("expected search command");
+ };
+ assert!(args.global);
+ assert!(args.workspace.is_none() && args.project.is_none());
+
+ let default = Cli::try_parse_from(["ai-memory", "search", "wal"]).expect("search parses");
+ let Command::Search(args) = default.command else {
+ panic!("expected search command");
+ };
+ assert!(!args.global, "global search stays opt-in");
+
+ for flag in [["--workspace", "acme"], ["--project", "api"]] {
+ let error =
+ Cli::try_parse_from(["ai-memory", "search", "wal", "--global", flag[0], flag[1]])
+ .expect_err("--global must conflict with an explicit scope");
+ assert_eq!(
+ error.kind(),
+ clap::error::ErrorKind::ArgumentConflict,
+ "{flag:?}"
+ );
+ }
+ }
+
#[test]
fn serve_api_only_flag_does_not_enable_the_web_ui() {
let parsed =
diff --git a/crates/ai-memory-cli/src/commands/search.rs b/crates/ai-memory-cli/src/commands/search.rs
index e3b0b09a..9a69679a 100644
--- a/crates/ai-memory-cli/src/commands/search.rs
+++ b/crates/ai-memory-cli/src/commands/search.rs
@@ -2,6 +2,10 @@
//!
//! Thin HTTP client. Calls `GET /admin/search?q=…&limit=…`; renders
//! the hits as human text or JSON. Never opens the store directly.
+//!
+//! The scope comes from the cwd (or `--workspace`/`--project`) unless
+//! `--global` is passed: then no scope is sent, the server searches every
+//! project's wiki pages, and each hit carries its `workspace`/`project`.
use anyhow::Result;
use serde::{Deserialize, Serialize};
@@ -10,9 +14,15 @@ use crate::cli::SearchArgs;
use crate::config::Config;
use crate::http_client::{ServerEndpoint, get_json};
-/// FTS5 hit, mirrors `ai_memory_store::PageHit` fields used here.
+/// FTS5 hit, mirrors the `/admin/search` fields used here.
#[derive(Debug, Deserialize, Serialize)]
struct Hit {
+ /// Set only on a global search: the workspace the page lives in.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ workspace: Option<String>,
+ /// Set only on a global search: the project the page lives in.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ project: Option<String>,
path: String,
title: String,
snippet: String,
@@ -25,32 +35,93 @@ struct Hit {
/// Returns an error if the server is unreachable or returns non-2xx.
pub async fn run(config: &Config, args: SearchArgs) -> Result<()> {
let ep = ServerEndpoint::from_config_resolving_auth(config).await;
- let (workspace, project) =
- super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let limit_str = args.limit.to_string();
- let hits: Vec<Hit> = get_json(
- &ep,
- "/admin/search",
- &[
- ("q", args.query.as_str()),
- ("workspace", workspace.as_str()),
- ("project", project.as_str()),
- ("limit", limit_str.as_str()),
- ],
- )
- .await?;
+ let mut query = vec![("q", args.query.clone()), ("limit", limit_str)];
+ if !args.global {
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
+ query.push(("workspace", workspace));
+ query.push(("project", project));
+ }
+ let query: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
+ let hits: Vec<Hit> = get_json(&ep, "/admin/search", &query).await?;
if args.json {
println!("{}", serde_json::to_string_pretty(&hits)?);
- } else if hits.is_empty() {
- println!("no results for {:?}", args.query);
} else {
- println!("{} result(s) for {:?}:", hits.len(), args.query);
- for hit in &hits {
- println!(" {} rank={:.4}", hit.path, hit.rank);
- println!(" {}", hit.title);
- println!(" {}", hit.snippet);
- }
+ print!("{}", render_text(&args.query, &hits));
}
Ok(())
}
+
+fn render_text(query: &str, hits: &[Hit]) -> String {
+ use std::fmt::Write as _;
+ if hits.is_empty() {
+ return format!("no results for {query:?}\n");
+ }
+ let mut out = format!("{} result(s) for {query:?}:\n", hits.len());
+ for hit in hits {
+ let _ = match (&hit.workspace, &hit.project) {
+ (Some(workspace), Some(project)) => writeln!(
+ out,
+ " {workspace}/{project} {} rank={:.4}",
+ hit.path, hit.rank
+ ),
+ _ => writeln!(out, " {} rank={:.4}", hit.path, hit.rank),
+ };
+ let _ = writeln!(out, " {}", hit.title);
+ let _ = writeln!(out, " {}", hit.snippet);
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn hit(json: serde_json::Value) -> Hit {
+ serde_json::from_value(json).expect("hit deserializes")
+ }
+
+ #[test]
+ fn global_hits_render_with_their_project() {
+ let hits = vec![
+ hit(serde_json::json!({
+ "id": "ignored", "workspace": "acme", "project": "api",
+ "path": "notes/wal.md", "title": "WAL", "snippet": "wal mode", "rank": -1.5
+ })),
+ hit(serde_json::json!({
+ "workspace": "default", "project": "web",
+ "path": "notes/wal.md", "title": "WAL too", "snippet": "also wal", "rank": -1.0
+ })),
+ ];
+ let text = render_text("wal", &hits);
+ assert!(
+ text.contains(" acme/api notes/wal.md rank=-1.5000\n"),
+ "{text}"
+ );
+ assert!(
+ text.contains(" default/web notes/wal.md rank=-1.0000\n"),
+ "{text}"
+ );
+
+ let json = serde_json::to_value(&hits).unwrap();
+ assert_eq!(json[0]["workspace"], "acme");
+ assert_eq!(json[0]["project"], "api");
+ assert_eq!(json[1]["project"], "web");
+ }
+
+ #[test]
+ fn scoped_hits_render_and_serialize_as_before() {
+ let hits = vec![hit(serde_json::json!({
+ "id": "ignored", "path": "notes/wal.md", "title": "WAL",
+ "snippet": "wal mode", "rank": -1.5
+ }))];
+ let text = render_text("wal", &hits);
+ assert!(text.contains(" notes/wal.md rank=-1.5000\n"), "{text}");
+ let json = serde_json::to_value(&hits).unwrap();
+ assert!(json[0].get("workspace").is_none());
+ assert!(json[0].get("project").is_none());
+ assert_eq!(render_text("wal", &[]), "no results for \"wal\"\n");
+ }
+}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 389a7d9a..a2f3b8bb 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1702,6 +1702,37 @@ fn default_search_limit() -> usize {
10
}
+/// One hit of a cross-project `GET /admin/search` (no `workspace`/`project`).
+///
+/// The fields a global hit always carried (`id`, `path`, `title`, `snippet`,
+/// `rank`) plus the workspace and project the page lives in, so a caller can
+/// tell which repository each hit came from. A project-scoped search keeps
+/// returning plain [`ai_memory_store::PageHit`]s.
+#[derive(Debug, Serialize)]
+struct GlobalSearchHit {
+ id: ai_memory_core::PageId,
+ path: ai_memory_core::PagePath,
+ title: String,
+ snippet: String,
+ rank: f64,
+ workspace: String,
+ project: String,
+}
+
+impl From<ai_memory_store::PageHitWithMeta> for GlobalSearchHit {
+ fn from(hit: ai_memory_store::PageHitWithMeta) -> Self {
+ Self {
+ id: hit.id,
+ path: hit.path,
+ title: hit.title,
+ snippet: hit.snippet,
+ rank: hit.rank,
+ workspace: hit.workspace_name,
+ project: hit.project_name,
+ }
+ }
+}
+
async fn handle_search(
State(state): State<Arc<AdminState>>,
Query(query): Query<SearchQuery>,
@@ -1713,12 +1744,11 @@ async fn handle_search(
) {
(Some(workspace), Some(project)) => {
match lookup_ws_proj_no_create(&state, workspace, project).await {
- Ok((ws, proj)) => {
- state
- .reader
- .search_pages_for_project(ws, proj, query.q, limit, None)
- .await
- }
+ Ok((ws, proj)) => state
+ .reader
+ .search_pages_for_project(ws, proj, query.q, limit, None)
+ .await
+ .and_then(|hits| Ok(serde_json::to_value(&hits)?)),
Err(e) => return e,
}
}
@@ -1730,13 +1760,20 @@ async fn handle_search(
})),
);
}
- _ => state.reader.search_pages(query.q, limit, OPERATOR).await,
+ // Cross-project: every hit names its repository. `OPERATOR` reads
+ // every project because this route is root-only once the deployment
+ // distinguishes operators (`require_root_for_multiuser_admin`).
+ _ => state
+ .reader
+ .search_pages_with_meta(query.q, limit, None, OPERATOR)
+ .await
+ .and_then(|hits| {
+ let hits: Vec<GlobalSearchHit> = hits.into_iter().map(Into::into).collect();
+ Ok(serde_json::to_value(&hits)?)
+ }),
};
match search_result {
- Ok(hits) => (
- StatusCode::OK,
- Json(serde_json::to_value(&hits).unwrap_or_else(|_| serde_json::json!([]))),
- ),
+ Ok(hits) => (StatusCode::OK, Json(hits)),
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ "error": e.to_string() })),
diff --git a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
index 575be0e5..3ef12b85 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
@@ -46,14 +46,25 @@ async fn make_admin_state(tmp: &TempDir) -> (AdminState, Store) {
}
async fn seed_page(store: &Store, title: &str, path: &str, body: &str) {
+ seed_page_in(store, "default", "scratch", title, path, body).await;
+}
+
+async fn seed_page_in(
+ store: &Store,
+ workspace: &str,
+ project: &str,
+ title: &str,
+ path: &str,
+ body: &str,
+) -> ai_memory_core::ProjectId {
let ws = store
.writer
- .get_or_create_workspace("default".to_string())
+ .get_or_create_workspace(workspace.to_string())
.await
.unwrap();
let proj = store
.writer
- .get_or_create_project(ws, "scratch".to_string(), None)
+ .get_or_create_project(ws, project.to_string(), None)
.await
.unwrap();
let page = NewPage {
@@ -72,6 +83,7 @@ async fn seed_page(store: &Store, title: &str, path: &str, body: &str) {
evidence: Vec::new(),
};
store.writer.upsert_page(page).await.unwrap();
+ proj
}
async fn body_bytes(resp: axum::response::Response) -> Vec<u8> {
@@ -540,6 +552,175 @@ async fn search_returns_matching_hits() {
assert_eq!(hits[0]["title"].as_str().unwrap(), "Storage architecture");
}
+async fn get(app: axum::Router, uri: &str, level: Option<&str>) -> (StatusCode, Vec<u8>) {
+ let mut request = Request::builder().uri(uri);
+ if let Some(level) = level {
+ request = request.header("x-level", level);
+ }
+ let response = app
+ .oneshot(request.body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ (response.status(), body_bytes(response).await)
+}
+
+/// A search with no scope (`ai-memory search --global`, #1253) covers every
+/// project and says where each hit lives; a scoped search is unchanged.
+#[tokio::test]
+async fn global_search_tags_each_hit_with_its_workspace_and_project() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ seed_page_in(
+ &store,
+ "default",
+ "alpha",
+ "Alpha notes",
+ "notes/alpha.md",
+ "zephyrine storage notes for alpha",
+ )
+ .await;
+ seed_page_in(
+ &store,
+ "acme",
+ "beta",
+ "Beta notes",
+ "notes/beta.md",
+ "zephyrine storage notes for beta",
+ )
+ .await;
+ let app = admin_router(state);
+
+ let (status, body) = get(app.clone(), "/admin/search?q=zephyrine", None).await;
+ assert_eq!(status, StatusCode::OK);
+ let hits: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
+ let mut tagged: Vec<(String, String, String)> = hits
+ .iter()
+ .map(|hit| {
+ assert!(hit["id"].is_string(), "global hits keep their id: {hit}");
+ assert!(hit["title"].is_string() && hit["snippet"].is_string());
+ assert!(hit["rank"].is_number());
+ (
+ hit["workspace"].as_str().unwrap().to_owned(),
+ hit["project"].as_str().unwrap().to_owned(),
+ hit["path"].as_str().unwrap().to_owned(),
+ )
+ })
+ .collect();
+ tagged.sort();
+ assert_eq!(
+ tagged,
+ [
+ ("acme".into(), "beta".into(), "notes/beta.md".into()),
+ ("default".into(), "alpha".into(), "notes/alpha.md".into()),
+ ]
+ );
+
+ let (status, body) = get(
+ app,
+ "/admin/search?q=zephyrine&workspace=acme&project=beta",
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ let hits: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
+ assert_eq!(hits.len(), 1, "a scoped search stays in its project");
+ assert_eq!(hits[0]["path"], "notes/beta.md");
+ assert!(hits[0].get("workspace").is_none() && hits[0].get("project").is_none());
+}
+
+/// The global search reads every project as the operator, so it must stay
+/// behind the root-only admin gate once the deployment distinguishes
+/// operators: a DB user or proxy-asserted user who could reach it would read a
+/// restricted project they hold no grant on. Root (the control) still sees it.
+#[tokio::test]
+async fn global_search_never_reaches_a_non_root_caller() {
+ for trusted_proxy in [false, true] {
+ let tmp = TempDir::new().unwrap();
+ let (mut state, store) = make_admin_state(&tmp).await;
+ state.trusted_proxy_identity = trusted_proxy;
+ seed_page_in(
+ &store,
+ "default",
+ "open",
+ "Open notes",
+ "notes/open.md",
+ "zephyrine open notes",
+ )
+ .await;
+ let secret = seed_page_in(
+ &store,
+ "default",
+ "secret",
+ "Secret notes",
+ "notes/secret-sentinel.md",
+ "zephyrine restricted notes",
+ )
+ .await;
+ store
+ .writer
+ .set_access_mode(secret, AccessMode::Restricted)
+ .await
+ .unwrap();
+ if !trusted_proxy {
+ // A DB user exists (no grant on `secret`): the store-level
+ // multi-user switch. The proxy case has no `users` rows at all.
+ store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ }
+ let app = admin_router(state).layer(axum::middleware::from_fn(
+ |mut request: Request<Body>, next: axum::middleware::Next| async move {
+ let level = match request
+ .headers()
+ .get("x-level")
+ .and_then(|value| value.to_str().ok())
+ {
+ Some("root") => AuthLevel::Root,
+ Some("user") => AuthLevel::User,
+ _ => AuthLevel::Anonymous,
+ };
+ request.extensions_mut().insert(level);
+ request.extensions_mut().insert(ActorContext::anonymous());
+ next.run(request).await
+ },
+ ));
+
+ for (level, expected) in [
+ (Some("user"), StatusCode::FORBIDDEN),
+ (None, StatusCode::UNAUTHORIZED),
+ ] {
+ let (status, body) = get(app.clone(), "/admin/search?q=zephyrine", level).await;
+ assert_eq!(status, expected, "proxy={trusted_proxy} level={level:?}");
+ let body = String::from_utf8_lossy(&body);
+ assert!(
+ !body.contains("secret-sentinel") && !body.contains("zephyrine"),
+ "proxy={trusted_proxy} level={level:?} leaked a hit: {body}"
+ );
+ }
+
+ let (status, body) = get(app, "/admin/search?q=zephyrine", Some("root")).await;
+ assert_eq!(status, StatusCode::OK, "proxy={trusted_proxy}");
+ let hits: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
+ let mut projects: Vec<&str> = hits
+ .iter()
+ .map(|hit| hit["project"].as_str().unwrap())
+ .collect();
+ projects.sort_unstable();
+ assert_eq!(projects, ["open", "secret"], "proxy={trusted_proxy}");
+ }
+}
+
#[tokio::test]
async fn search_with_empty_results_returns_empty_array() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 33932fd5..fe99199c 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1225,6 +1225,12 @@ pub struct PageVersionBody {
/// per-hit metadata lookups after a global search.
#[derive(Debug, Clone, Serialize)]
pub struct PageHitWithMeta {
+ /// Stable identifier for this page version. Not serialized, so the MCP
+ /// `global_hits` and web shapes stay as they were; `GET /admin/search`
+ /// copies it into its own response to keep the `id` field its global
+ /// branch always returned.
+ #[serde(skip)]
+ pub id: PageId,
/// Name of the workspace containing the page.
pub workspace_name: String,
/// Name of the project containing the page.
@@ -2551,7 +2557,7 @@ impl ReaderPool {
"SELECT workspaces.name, projects.name, pages.path, pages.title, \
snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \
pages_fts.rank, pages.tier, pages.pinned, \
- pages.frontmatter_json, {kind_expr} AS kind \
+ pages.frontmatter_json, {kind_expr} AS kind, pages.id \
FROM pages_fts \
JOIN pages ON pages.rowid = pages_fts.rowid \
JOIN projects ON projects.id = pages.project_id \
@@ -2580,7 +2586,9 @@ impl ReaderPool {
let pinned = row.get::<_, i64>(7)? != 0;
let frontmatter_json: String = row.get(8)?;
let kind: String = row.get(9)?;
+ let id_bytes: Vec<u8> = row.get(10)?;
Ok((
+ id_bytes,
workspace_name,
project_name,
path,
@@ -2597,6 +2605,7 @@ impl ReaderPool {
let mut candidates = Vec::new();
for row in rows {
let (
+ id_bytes,
workspace_name,
project_name,
path,
@@ -2612,6 +2621,7 @@ impl ReaderPool {
PageAuthority::from_stored(&path, &kind, &tier, pinned, &frontmatter_json);
candidates.push((
PageHitWithMeta {
+ id: PageId::from_slice(&id_bytes)?,
workspace_name,
project_name,
path: PagePath::new(path)?,
@@ -3500,7 +3510,7 @@ impl ReaderPool {
let sql = format!(
"SELECT workspaces.name, projects.name, pages.path, pages.title, \
{descriptor} AS snip, \
- CAST(pages.updated_at AS REAL) AS rank \
+ CAST(pages.updated_at AS REAL) AS rank, pages.id \
FROM pages \
JOIN projects ON projects.id = pages.project_id \
JOIN workspaces ON workspaces.id = pages.workspace_id \
@@ -3521,12 +3531,22 @@ impl ReaderPool {
let title: String = row.get(3)?;
let snippet = page_descriptor(&row.get::<_, String>(4)?, &title);
let rank: f64 = row.get(5)?;
- Ok((workspace_name, project_name, path, title, snippet, rank))
+ let id_bytes: Vec<u8> = row.get(6)?;
+ Ok((
+ id_bytes,
+ workspace_name,
+ project_name,
+ path,
+ title,
+ snippet,
+ rank,
+ ))
})?;
let mut hits = Vec::new();
for row in rows {
- let (workspace_name, project_name, path, title, snippet, rank) = row?;
+ let (id_bytes, workspace_name, project_name, path, title, snippet, rank) = row?;
hits.push(PageHitWithMeta {
+ id: PageId::from_slice(&id_bytes)?,
workspace_name,
project_name,
path: PagePath::new(path)?,
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 658a4c8c..af249bdc 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -288,6 +288,12 @@ values are ignored and behave like the default `basename(cwd)` strategy.
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. The `ai-memory search` terminal command does not read
+it: that command stays scoped to the current project and searches every
+project only when you pass `--global` (see
+[usage.md](usage.md#search-from-the-terminal)).
+
`default_global` and `inject_on_session_start` accept a truthy value
(`true` / `1` / `yes` / `on`, quoted or bare; section-style keys are
parsed leniently); anything else behaves as absent. `max_chars` is a
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 074bc464..2d71a10b 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -39,6 +39,7 @@ means the boundary is not built yet.
| 3e | The web health panel is root-only on a multi-user server, read-only and content-free | `ai-memory-web/src/routes/mod.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, shared with `/web/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect) gates `GET {web_slug}/health`, a GET-only route; `routes/health.rs` renders only counters, timestamps and configured provider/model labels, `provider_line` leaves out `last_error_message` (it can quote a response body), and the process side comes through `health::HealthProbe` as counts (`ServeHealthProbe` in `ai-memory-cli/src/commands/serve.rs` drops the journal's error text); the response is `Cache-Control: private, no-store` | `ai-memory-web` `tests/suite/health.rs` — `health_page_refuses_anonymous_once_operators_are_distinguished` (401, login redirect on navigation, no counters or fix lines), `health_page_refuses_a_db_user_and_admits_root` (403 "Root access required", no redirect, no counters; root control 200), `health_page_follows_the_admin_gate_on_a_single_operator_server` (control), `health_page_carries_no_secret_material` (secret-shaped strings planted in a failed LLM call's and a failed embed's provider error body, a page body, a page title and the project name never appear), `health_page_has_no_write_route` (POST/PUT/DELETE 405), plus a fixture per rendered check (`health_page_renders_each_failing_check_with_its_fix_line`, `health_page_renders_pending_spool_and_journal_checks`, `health_page_reports_a_healthy_server_as_passing`, and `src/health.rs` unit tests for every check id) | STRONG. Bite checks: with the `require_admin` call removed from the handler, the anonymous and DB-user tests fail; with `last_error_message` appended to the provider line, the planted-secret test fails |
| 3f | The 1.x token-management surface stays removed, and tokens it issued stay ordinary API keys (3.0) | `ai-memory-mcp/src/admin.rs` mounts only `GET /admin/users` on that path and no `/admin/users/{name}/expire`, `/revive` or `/rotate-token` route; `ai-memory-store` migration `V79__drop_legacy_user_token_columns.sql` drops `users.token_hash` / `token_expired_at` and the V55 mirror triggers, with a guard that aborts the migration if the `users` rebuild would lose any resolving reference to a user (credentials, sessions, grants, authors); authentication reads only `api_credentials` (`api_credentials.rs` `find_active_user_by_token_hash`, `revoked_at` and `expires_at` honored) | `admin.rs` `removed_legacy_token_routes_are_gone_for_every_tier` (production `require_dual_auth`; each removed route as root: 405 on `POST /admin/users`, 404 on the rest; as a DB user and as a legacy-token holder: 403 on `POST /admin/users`, 404 on the rest; anonymous 401; afterwards no user was created, no credential revoked, and the legacy token still authenticates), `legacy_user_token_is_managed_as_an_api_key` (an unprefixed legacy token authenticates as a non-root user, an expired one is 401, `api-key list` shows it as `legacy-user-token`, rotate retires the old secret, revoke refuses the new one); `ai-memory-store` `api_credentials.rs` `v79_upgrade_keeps_legacy_tokens_as_api_keys` (a V78 database seeded the 2.x way with active, expired and rotated tokens plus a web session: after V79 the active and rotated tokens authenticate, the expired and superseded ones do not, all three list as `legacy-user-token`, rotate/revoke work, the session survives, no FK violation) and `v79_rolls_back_rather_than_cascade_delete_credentials` (run with foreign keys on, V79 aborts and leaves the V78 schema and the token intact); `ai-memory-cli` `removed_user_token_commands_no_longer_parse` | STRONG. Bite checks: with a stub `POST /admin/users/{name}/expire` route mounted the route test fails; without V79 the upgrade test and the schema pin fail; without the guard the rollback test fails |
| 3g | A Basic browser sign-in on a server without human accounts never persists the root bearer in a cookie | `ai-memory-mcp/src/human_auth.rs` `require_dual_auth` accepts Basic (or an `ai_memory_auth` cookie an older build set) for GET only before human auth exists and sets no cookie on success; the browser resends Basic itself; `expire_legacy_cookie_mw` retires a leftover cookie once human auth is active | `human_auth.rs` `a_basic_sign_in_mints_no_cookie_holding_the_root_bearer` (no `Set-Cookie` carries the token, no `ai_memory_auth` is set; control: the Basic GET is served and the bearer still authenticates; bite-checked against the old cookie minting), `legacy_browser_credentials_stop_when_human_bootstrap_completes` (Basic and a leftover cookie both stop at bootstrap) | STRONG |
+| 3h | Cross-project `GET /admin/search` (no `workspace`/`project`, the `ai-memory search --global` path, #1253) is root-only on a multi-user server | `ai-memory-mcp/src/admin.rs` `handle_search` runs the no-scope branch through `ReaderPool::search_pages_with_meta` as `OPERATOR` (every project, each hit tagged with its workspace and project); the route sits in the operational router under `require_root_for_multiuser_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`), so a DB user or proxy-asserted user never reaches the unfiltered read. A partial scope is still a 400, never a silent global fallback. `ai-memory-cli/src/commands/search.rs` sends no scope only when `--global` is passed, and clap rejects `--global` with `--workspace`/`--project` | MCP `admin_status_search.rs` `global_search_never_reaches_a_non_root_caller` (a restricted project the user holds no grant on, for both a DB-user deployment and a trusted-proxy deployment with no `users` rows: user 403 and anonymous 401 with neither the sentinel path nor the query term in the body; root control 200 with both projects' hits), `global_search_tags_each_hit_with_its_workspace_and_project`, `search_rejects_partial_scope_instead_of_global_fallback`; the shared `admin.rs` all-admin 403/401 route matrix includes `/admin/search`; CLI `cli.rs` `search_global_parses_and_conflicts_with_an_explicit_scope` | STRONG. Bite check: with the gate's operator test forced off (`authorize(Capability::Admin, false)`) the refusal test fails on the DB-user case (200 instead of 403) |
| 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS; the receiver-session check, which requires the receiving session to exist in the claim's own workspace, project and agent kind and refuses with `InvalidState` before the handoff row is touched; an ended receiver is final EXCEPT for the agents where `AgentKind::reuses_session_id_after_end()` holds — Grok and Kimi Code, whose harnesses reuse the native session id across SessionEnd→resume, so accepting reopens `ended_at` only after the claim-once guard) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff`; `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (receivers from a sibling project, another workspace, a different agent kind, and a nonexistent session are each refused as `InvalidState` with the handoff left open and every `accepted_*` column NULL; the matching receiver claims it; the same receiver retrying and a second matching session get `false` with the first claim intact; fails with the `project_id` or `agent_kind` predicate, or the missing-session refusal, removed. The `workspace_id` predicate is redundant defence in depth: project ids are globally unique, so the cross-workspace receiver is already caught by `project_id`); `multi_session.rs` `accept_reopens_an_ended_receiver_session_but_keeps_claim_once` (Grok reopen + no-steal) and `accept_reopens_an_ended_kimi_receiver_but_keeps_every_guard` (Kimi Code resume claims and reopens `ended_at`; adversarial controls: an ended claude-code receiver stays refused, a kimi-code receiver in another project stays refused, and the already-claimed guard still refuses the resumed kimi session a second baton) | STRONG |
| 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG |
| 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865) | STRONG |
diff --git a/docs/usage.md b/docs/usage.md
index edab69a1..3f2fc565 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -200,6 +200,33 @@ a page: a query aimed at a session-specific term can still return that session.
`pinned` remains primarily a retention and automation-mutation control, not an
unconditional search override.
+## Search from the terminal
+
+`ai-memory search` runs an FTS5 query against the wiki from a shell. It skips
+the entity, vector and graph streams and the raw-observation fallback that the
+agent's hybrid `memory_query` uses.
+
+```bash
+ai-memory search "wal mode" # current project (cwd / marker)
+ai-memory search "wal mode" --workspace acme --project api
+ai-memory search "wal mode" --global # every project
+ai-memory search "wal mode" --global --json -n 20
+```
+
+Without a flag the scope comes from the current directory, the same way as
+every other client command (see [marker-file.md](marker-file.md)).
+`--global` sends no scope and searches the wiki pages of every project; each
+hit is printed with its `workspace/project`, and `--json` adds `workspace` and
+`project` fields to each hit. `--global` cannot be combined with `--workspace`
+or `--project`. It covers compiled wiki pages only, not raw observations.
+
+The command calls `GET /admin/search`, so on a multi-user server only the root
+operator can run it. A DB user searches across the projects they may read with
+`memory_query(global=true)` or the web search page instead. A repository's
+`[recall] default_global` marker setting changes what an agent's unscoped
+`memory_query` reads; it does not change this command, which stays
+project-scoped unless you pass `--global`.
+
## Historical memory and live code intelligence
ai-memory can run beside CodeGraph, an LSP-backed service, a SCIP/LSIF index,
diff --git a/docs/use-cases.md b/docs/use-cases.md
index 9e75f776..3543a89c 100644
--- a/docs/use-cases.md
+++ b/docs/use-cases.md
@@ -126,8 +126,8 @@
- **"What did we decide about X six weeks ago?"** Use `memory_query X` from
the agent for FTS5 fused with entity matches and linked-page expansion (plus
vector similarity when an embedder is configured). For a quick terminal-only
- FTS5 lookup, use `ai-memory search X`; that admin command does not run the
- hybrid streams. Pages are
+ FTS5 lookup, use `ai-memory search X` (add `--global` to search every
+ project); that admin command does not run the hybrid streams. Pages are
LLM-consolidated, so the hit is a coherent decision page, not a raw
chat log. Pass `explain: true` to see why each hit ranked where it
did in project or explicit-scope retrieval. Cross-project