Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Add `ai-memory recent` and GET /admin/recent
Matt Van Hornc8bf11c355ea
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 60f22c28..50e4cc58 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,15 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Added++- Added `ai-memory recent` and `GET /admin/recent` to list the most recently+ updated wiki pages, newest first. The listing is scoped to the current+ project by default (cwd / marker, or `--workspace`/`--project`); `--global`+ covers every project and labels each hit with its workspace and project.+ Each hit carries an RFC 3339 `updated_at` instead of an FTS rank. The admin+ route is root-only on a multi-user server, the same as `/admin/search`.+### Fixed- `ai-memory auth login openai-oauth` and `auth login copilot` no longer printa failed endpoint's whole response body. Error bodies are bounded, scrubbeddiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 467d3949..c8b5783a 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -172,6 +172,8 @@ pub enum Command {AuditContamination(AuditContaminationArgs),/// Full-text search the wiki via FTS5.Search(SearchArgs),+ /// List the most recently updated wiki pages.+ Recent(RecentArgs),/// Fetch and display the full body of a wiki page./// Accepts either `--path` (exact path) or a positional query that/// searches FTS5 and fetches the top matching page.@@ -2134,6 +2136,28 @@ pub struct AuditContaminationArgs {pub json: bool,}+/// Arguments for `recent`.+#[derive(Debug, Args)]+pub struct RecentArgs {+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's+ /// `workspace`, else `default`.+ #[arg(long)]+ pub workspace: Option<String>,+ /// Project name. When omitted, auto-derived from the current project.+ #[arg(long)]+ pub project: Option<String>,+ /// List the most recently updated 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 pages to return.+ #[arg(short = 'n', long, default_value_t = 10)]+ pub limit: usize,+ /// Emit results as JSON.+ #[arg(long)]+ pub json: bool,+}+/// Arguments for `search`.#[derive(Debug, Args)]pub struct SearchArgs {@@ -3646,6 +3670,37 @@ mod tests {}}+ /// `recent --global` drops the scope entirely, so naming one alongside it+ /// is a contradiction clap rejects rather than one flag silently winning.+ #[test]+ fn recent_global_parses_and_conflicts_with_an_explicit_scope() {+ let parsed = Cli::try_parse_from(["ai-memory", "recent", "--global", "-n", "20"])+ .expect("recent --global parses");+ let Command::Recent(args) = parsed.command else {+ panic!("expected recent command");+ };+ assert!(args.global);+ assert_eq!(args.limit, 20);+ assert!(args.workspace.is_none() && args.project.is_none());++ let default = Cli::try_parse_from(["ai-memory", "recent"]).expect("recent parses");+ let Command::Recent(args) = default.command else {+ panic!("expected recent command");+ };+ assert!(!args.global, "global recent stays opt-in");+ assert_eq!(args.limit, 10);++ for flag in [["--workspace", "acme"], ["--project", "api"]] {+ let error = Cli::try_parse_from(["ai-memory", "recent", "--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/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 7f40c3dd..50863fa1 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -85,6 +85,7 @@ pub mod purge_preview;pub mod purge_project;pub mod purge_session;pub mod read_page;+pub mod recent;pub mod reclaim_ledger_versions;pub mod recovery;pub mod reindex;diff --git a/crates/ai-memory-cli/src/commands/recent.rs b/crates/ai-memory-cli/src/commands/recent.rsnew file mode 100644index 00000000..10e794c6--- /dev/null+++ b/crates/ai-memory-cli/src/commands/recent.rs@@ -0,0 +1,148 @@+//! `ai-memory recent` — list the most recently updated wiki pages.+//!+//! Thin HTTP client. Calls `GET /admin/recent?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 lists every+//! project's latest pages, and each hit carries its `workspace`/`project`.++use anyhow::Result;+use serde::{Deserialize, Serialize};++use crate::cli::RecentArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, get_json};++/// Recency hit, mirrors the `/admin/recent` fields used here.+#[derive(Debug, Deserialize, Serialize)]+struct Hit {+ /// Set only on a global listing: the workspace the page lives in.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ workspace: Option<String>,+ /// Set only on a global listing: the project the page lives in.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ project: Option<String>,+ path: String,+ title: String,+ snippet: String,+ updated_at: String,+}++/// Run the `recent` subcommand.+///+/// # Errors+/// Returns an error if the server is unreachable or returns non-2xx.+pub async fn run(config: &Config, args: RecentArgs) -> Result<()> {+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;+ let limit_str = args.limit.to_string();+ let mut query = vec![("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/recent", &query).await?;++ if args.json {+ println!("{}", serde_json::to_string_pretty(&hits)?);+ } else {+ print!("{}", render_text(&hits, jiff::Timestamp::now()));+ }+ Ok(())+}++fn render_text(hits: &[Hit], now: jiff::Timestamp) -> String {+ use std::fmt::Write as _;+ if hits.is_empty() {+ return "no recent pages\n".to_owned();+ }+ let mut out = format!("{} page(s):\n", hits.len());+ for hit in hits {+ let age = age_label(&hit.updated_at, now)+ .map(|age| format!(" ({age})"))+ .unwrap_or_default();+ let _ = match (&hit.workspace, &hit.project) {+ (Some(workspace), Some(project)) => {+ writeln!(+ out,+ " {workspace}/{project} {} {}{age}",+ hit.path, hit.updated_at+ )+ }+ _ => writeln!(out, " {} {}{age}", hit.path, hit.updated_at),+ };+ let _ = writeln!(out, " {}", hit.title);+ let _ = writeln!(out, " {}", hit.snippet);+ }+ out+}++fn age_label(updated_at: &str, now: jiff::Timestamp) -> Option<String> {+ let then: jiff::Timestamp = updated_at.parse().ok()?;+ Some(super::humanize_age_secs((now - then).get_seconds()))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn hit(json: serde_json::Value) -> Hit {+ serde_json::from_value(json).expect("hit deserializes")+ }++ fn now() -> jiff::Timestamp {+ "2026-10-17T15:12:00Z".parse().expect("fixed now")+ }++ #[test]+ fn global_hits_render_with_their_project_and_age() {+ let hits = vec![+ hit(serde_json::json!({+ "id": "ignored", "workspace": "acme", "project": "api",+ "path": "notes/wal.md", "title": "WAL", "snippet": "wal mode",+ "updated_at": "2026-10-17T15:10:00Z"+ })),+ hit(serde_json::json!({+ "workspace": "default", "project": "web",+ "path": "notes/wal.md", "title": "WAL too", "snippet": "also wal",+ "updated_at": "2026-10-17T12:12:00Z"+ })),+ ];+ let text = render_text(&hits, now());+ assert!(+ text.contains(" acme/api notes/wal.md 2026-10-17T15:10:00Z (2 minutes ago)\n"),+ "{text}"+ );+ assert!(+ text.contains(" default/web notes/wal.md 2026-10-17T12:12:00Z (3 hours ago)\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");+ assert!(json[0].get("rank").is_none());+ }++ #[test]+ fn scoped_hits_render_and_serialize_without_scope() {+ let hits = vec![hit(serde_json::json!({+ "id": "ignored", "path": "notes/wal.md", "title": "WAL",+ "snippet": "wal mode", "updated_at": "2026-10-17T15:12:00Z"+ }))];+ let text = render_text(&hits, now());+ assert!(+ text.contains(" notes/wal.md 2026-10-17T15:12:00Z (just now)\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!(json[0]["updated_at"], "2026-10-17T15:12:00Z");+ assert_eq!(render_text(&[], now()), "no recent pages\n");+ }+}diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex ed5dbf88..faaad168 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -136,6 +136,7 @@ pub async fn run() -> Result<()> {commands::audit_contamination::run(&config, args).await}Command::Search(args) => commands::search::run(&config, args).await,+ Command::Recent(args) => commands::recent::run(&config, args).await,Command::ReadPage(args) => commands::read_page::run(&config, args).await,Command::WritePage(args) => commands::write_page::run(&config, args).await,Command::DeletePage(args) => commands::delete_page::run(&config, args).await,diff --git a/crates/ai-memory-cli/tests/suite/completions.rs b/crates/ai-memory-cli/tests/suite/completions.rsindex a81eab68..4c76e39b 100644--- a/crates/ai-memory-cli/tests/suite/completions.rs+++ b/crates/ai-memory-cli/tests/suite/completions.rs@@ -65,6 +65,7 @@ fn scripts_cover_subcommands_from_across_the_tree() {for subcommand in ["init","serve",+ "recent","write-page","purge-project","move-session",diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 0b986268..19647672 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -17,6 +17,7 @@//! - `GET /admin/activity/by-client` — MCP tool-call counts per client (server-wide).//! - `GET /admin/audit-log` — paginated read of the append-only `audit_log`.//! - `GET /admin/search?q=` — FTS5 hits against the wiki index.+//! - `GET /admin/recent` — most recently updated wiki pages.//! - `POST /admin/reorg` — retro-fit sessions to per-cwd projects.//! - `POST /admin/lint` — run the M8 lint pass.//! - `POST /admin/forget-sweep` — run the M8 retention sweep.@@ -598,6 +599,7 @@ fn hex_to_sha256(hex: &str) -> Result<[u8; 32], String> {/// - `GET /admin/activity/by-client`/// - `GET /admin/audit-contamination`/// - `GET /admin/search`+/// - `GET /admin/recent`/// - `GET /admin/read-page`/// - `POST /admin/reorg`/// - `POST /admin/lint`@@ -688,6 +690,7 @@ pub fn admin_router_with_sweep_tuning().route("/admin/audit-log", get(handle_audit_log)).route("/admin/search", get(handle_search))+ .route("/admin/recent", get(handle_recent)).route("/admin/read-page", get(handle_read_page)).route("/admin/reorg", post(handle_reorg)).route("/admin/lint", post(handle_lint))@@ -1793,6 +1796,132 @@ async fn handle_search(}}+// ---------------------------------------------------------------------+// recent+// ---------------------------------------------------------------------++/// Query string for `GET /admin/recent?limit=…`.+#[derive(Debug, Deserialize)]+struct RecentQuery {+ /// Workspace name to list within. Must be provided together with `project`.+ #[serde(default)]+ workspace: Option<String>,+ /// Project name to list within. Must be provided together with `workspace`.+ #[serde(default)]+ project: Option<String>,+ /// Max number of pages to return. Capped at 100 server-side.+ #[serde(default = "default_search_limit")]+ limit: usize,+}++/// One hit of `GET /admin/recent`.+///+/// Recency has no FTS rank, so `updated_at` is RFC 3339 instead of the+/// store's reused `PageHit::rank` (updated_at microseconds as REAL). A+/// global listing also names the workspace and project; a scoped listing+/// omits those fields.+#[derive(Debug, Serialize)]+struct RecentHit {+ id: ai_memory_core::PageId,+ path: ai_memory_core::PagePath,+ title: String,+ snippet: String,+ updated_at: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ workspace: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ project: Option<String>,+}++fn iso_from_rank_us(rank: f64) -> String {+ // `recent_pages_*` store `updated_at` microseconds in `PageHit::rank`.+ // Unix µs in 2026 sit well below the 53-bit integer mantissa.+ #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]+ let us = rank.round() as i64;+ jiff::Timestamp::from_microsecond(us)+ .map(|ts| ts.to_string())+ .unwrap_or_default()+}++impl From<ai_memory_store::PageHit> for RecentHit {+ fn from(hit: ai_memory_store::PageHit) -> Self {+ Self {+ id: hit.id,+ path: hit.path,+ title: hit.title,+ snippet: hit.snippet,+ updated_at: iso_from_rank_us(hit.rank),+ workspace: None,+ project: None,+ }+ }+}++impl From<ai_memory_store::PageHitWithMeta> for RecentHit {+ fn from(hit: ai_memory_store::PageHitWithMeta) -> Self {+ Self {+ id: hit.id,+ path: hit.path,+ title: hit.title,+ snippet: hit.snippet,+ updated_at: iso_from_rank_us(hit.rank),+ workspace: Some(hit.workspace_name),+ project: Some(hit.project_name),+ }+ }+}++async fn handle_recent(+ State(state): State<Arc<AdminState>>,+ Query(query): Query<RecentQuery>,+) -> impl IntoResponse {+ let limit = query.limit.clamp(1, 100);+ let recent_result = match (+ trimmed_opt(query.workspace.as_deref()),+ trimmed_opt(query.project.as_deref()),+ ) {+ (Some(workspace), Some(project)) => {+ match lookup_ws_proj_no_create(&state, workspace, project).await {+ Ok((ws, proj)) => state+ .reader+ .recent_pages_for_project(ws, proj, limit)+ .await+ .and_then(|hits| {+ let hits: Vec<RecentHit> = hits.into_iter().map(Into::into).collect();+ Ok(serde_json::to_value(&hits)?)+ }),+ Err(e) => return e,+ }+ }+ (Some(_), None) | (None, Some(_)) => {+ return (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({+ "error": "workspace and project must be provided together"+ })),+ );+ }+ // 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+ .recent_pages_global(limit, OPERATOR)+ .await+ .and_then(|hits| {+ let hits: Vec<RecentHit> = hits.into_iter().map(Into::into).collect();+ Ok(serde_json::to_value(&hits)?)+ }),+ };+ match recent_result {+ Ok(hits) => (StatusCode::OK, Json(hits)),+ Err(e) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(serde_json::json!({ "error": e.to_string() })),+ ),+ }+}+// ---------------------------------------------------------------------// read-page// ---------------------------------------------------------------------@@ -13862,6 +13991,7 @@ mod tests {("GET", "/admin/audit-contamination", serde_json::Value::Null),("GET", "/admin/audit-log", serde_json::Value::Null),("GET", "/admin/search?q=test", serde_json::Value::Null),+ ("GET", "/admin/recent", serde_json::Value::Null),("GET","/admin/read-page?workspace=default&project=scratch&path=notes/x.md",diff --git a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs b/crates/ai-memory-mcp/tests/suite/admin_status_search.rsindex 3ef12b85..21795016 100644--- a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs@@ -1,4 +1,5 @@-//! Integration tests for `GET /admin/status` and `GET /admin/search`.+//! Integration tests for `GET /admin/status`, `GET /admin/search`, and+//! `GET /admin/recent`.//!//! Exercises the read-only admin surface end-to-end through the axum//! router: build an `AdminState` over a real on-disk store + wiki,@@ -791,3 +792,233 @@ async fn search_limit_is_clamped_to_100() {.unwrap();assert_eq!(resp.status(), StatusCode::OK);}++/// A listing with no scope (`ai-memory recent --global`) covers every+/// project and says where each hit lives; a scoped listing is unchanged.+#[tokio::test]+async fn global_recent_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",+ "recent notes for alpha",+ )+ .await;+ seed_page_in(+ &store,+ "acme",+ "beta",+ "Beta notes",+ "notes/beta.md",+ "recent notes for beta",+ )+ .await;+ // Re-upsert alpha so it is strictly newer than beta.+ seed_page_in(+ &store,+ "default",+ "alpha",+ "Alpha notes",+ "notes/alpha.md",+ "recent notes for alpha, revised",+ )+ .await;+ let app = admin_router(state);++ let (status, body) = get(app.clone(), "/admin/recent", None).await;+ assert_eq!(status, StatusCode::OK);+ let hits: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();+ assert_eq!(hits.len(), 2, "both projects appear on a global listing");+ assert_eq!(hits[0]["path"], "notes/alpha.md");+ assert_eq!(hits[0]["workspace"], "default");+ assert_eq!(hits[0]["project"], "alpha");+ assert_eq!(hits[1]["path"], "notes/beta.md");+ assert_eq!(hits[1]["workspace"], "acme");+ assert_eq!(hits[1]["project"], "beta");+ for hit in &hits {+ assert!(hit["id"].is_string(), "recent hits keep their id: {hit}");+ assert!(hit["title"].is_string() && hit["snippet"].is_string());+ hit["updated_at"]+ .as_str()+ .expect("updated_at is a string")+ .parse::<jiff::Timestamp>()+ .expect("updated_at is RFC 3339");+ assert!(hit.get("rank").is_none(), "recent does not leak FTS rank");+ }++ let (status, body) = get(app, "/admin/recent?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 listing 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 listing 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_recent_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",+ "recent open notes",+ )+ .await;+ let secret = seed_page_in(+ &store,+ "default",+ "secret",+ "Secret notes",+ "notes/secret-sentinel.md",+ "recent restricted notes",+ )+ .await;+ store+ .writer+ .set_access_mode(secret, AccessMode::Restricted)+ .await+ .unwrap();+ if !trusted_proxy {+ 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/recent", 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("restricted notes"),+ "proxy={trusted_proxy} level={level:?} leaked a hit: {body}"+ );+ }++ let (status, body) = get(app, "/admin/recent", 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 recent_with_empty_results_returns_empty_array() {+ let tmp = TempDir::new().unwrap();+ let (state, _store) = make_admin_state(&tmp).await;+ let app = admin_router(state);++ let (status, body) = get(app, "/admin/recent", None).await;+ assert_eq!(status, StatusCode::OK);+ let hits: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();+ assert!(hits.is_empty());+}++#[tokio::test]+async fn recent_rejects_partial_scope_instead_of_global_fallback() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_admin_state(&tmp).await;+ seed_page(+ &store,+ "Secret notes",+ "notes/secret-sentinel.md",+ "must not leak through a partial scope",+ )+ .await;+ let app = admin_router(state);++ let (status, body) = get(app, "/admin/recent?workspace=default", None).await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(+ body["error"]+ .as_str()+ .unwrap_or("")+ .contains("workspace and project must be provided together"),+ "unexpected error body: {body}"+ );+ let rendered = body.to_string();+ assert!(+ !rendered.contains("secret-sentinel"),+ "partial scope must not leak a hit: {rendered}"+ );+}++#[tokio::test]+async fn recent_unknown_scope_is_404_and_does_not_leak_other_projects() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_admin_state(&tmp).await;+ seed_page(+ &store,+ "Secret notes",+ "notes/secret-sentinel.md",+ "must not leak through an unknown project",+ )+ .await;+ let app = admin_router(state);++ let (status, body) = get(app, "/admin/recent?workspace=default&project=missing", None).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+ let rendered = String::from_utf8_lossy(&body);+ assert!(+ !rendered.contains("secret-sentinel"),+ "unknown scope must not leak a hit: {rendered}"+ );+}++#[tokio::test]+async fn recent_limit_is_clamped_to_100() {+ let tmp = TempDir::new().unwrap();+ let (state, _store) = make_admin_state(&tmp).await;+ let app = admin_router(state);++ let (status, _) = get(app, "/admin/recent?limit=9999999", None).await;+ assert_eq!(status, StatusCode::OK);+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 5d905077..0d180695 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -834,7 +834,7 @@ page content and scope names never reach it.init status list-projectsrun show continueresume workstreams rename-workstream-workstream-search audit-contamination search+workstream-search audit-contamination search recentread-page write-page delete-pageserve reset backuprestore reindex install-hooksdiff --git a/docs/cookbook.md b/docs/cookbook.mdindex f8559e15..94b047cd 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -542,6 +542,8 @@ ai-memory list-projects # every workspace/project the server knowsai-memory project init # pin this checkout's scope in a .ai-memory.tomlai-memory doctor # is every harness that ran here captured?ai-memory backfill # import prior local history into an empty store+ai-memory search "wal mode" # FTS5 lookup in this project+ai-memory recent # newest wiki pages in this projectai-memory write-page … # save a durable pageai-memory handoffs # list open handoffs for the projectai-memory message list # cross-project inboxdiff --git a/docs/install.md b/docs/install.mdindex f8550abf..7429c100 100644--- a/docs/install.md+++ b/docs/install.md@@ -3565,7 +3565,7 @@ update or downloads. If no client is installed yet, the wrapper says to runis not blocked. For local loopbackservers, the wrapper automatically bridgesthat helper back to the host's `127.0.0.1:49374`, so `ai-memory status`,-`ai-memory search`, and `ai-memory bootstrap` work with the same default+`ai-memory search`, `ai-memory recent`, and `ai-memory bootstrap` work with the same defaultURL as the generated agent config.#### SELinux-enforcing hostsdiff --git a/docs/marker-file.md b/docs/marker-file.mdindex 4d69a44a..2bc4b3e9 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -294,10 +294,11 @@ 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)).+`memory_recent` calls. 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 `--global` (see+[usage.md](usage.md#search-from-the-terminal) and+[usage.md](usage.md#recent-pages-from-the-terminal)).`default_global` and `inject_on_session_start` accept a truthy value(`true` / `1` / `yes` / `on`, quoted or bare; section-style keys arediff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex e8b7008d..9c1eba4b 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -42,6 +42,7 @@ means the boundary is not built yet.| 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; a request admitted this way carries `ai_memory_core::LegacyBrowserAuth`, which `/web/pending` reads to show CLI commands instead of decision buttons that would post and fail | `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), `only_a_legacy_browser_credential_is_marked_read_only` (Basic and the leftover cookie are marked, a Basic POST is still 401; control: the root bearer is unmarked and its POST is served; bite-checked by removing the insertion); `ai-memory-web` `pending_page_offers_cli_commands_instead_of_buttons_to_a_basic_browser` (bite-checked) | 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) |+| 3i | Cross-project `GET /admin/recent` (no `workspace`/`project`, the `ai-memory recent --global` path) is root-only on a multi-user server | `ai-memory-mcp/src/admin.rs` `handle_recent` runs the no-scope branch through `ReaderPool::recent_pages_global` 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; an unknown scoped project is a 404 and does not leak another project's pages. `ai-memory-cli/src/commands/recent.rs` sends no scope only when `--global` is passed, and clap rejects `--global` with `--workspace`/`--project` | MCP `admin_status_search.rs` `global_recent_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 restricted snippet in the body; root control 200 with both projects' hits), `global_recent_tags_each_hit_with_its_workspace_and_project`, `recent_rejects_partial_scope_instead_of_global_fallback`, `recent_unknown_scope_is_404_and_does_not_leak_other_projects`; the shared `admin.rs` all-admin 403/401 route matrix includes `/admin/recent`; CLI `cli.rs` `recent_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.mdindex 83b2ebe6..2ac0c79e 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -275,6 +275,28 @@ operator can run it. A DB user searches across the projects they may read with`memory_query` reads; it does not change this command, which staysproject-scoped unless you pass `--global`.+## Recent pages from the terminal++`ai-memory recent` lists the most recently updated wiki pages, newest first.+It is the terminal counterpart of the agent's `memory_recent` tool: no query+string, just recency.++```bash+ai-memory recent # current project (cwd / marker)+ai-memory recent --workspace acme --project api+ai-memory recent --global # every project+ai-memory recent --global --json -n 20+```++Each line shows the page path, an RFC 3339 `updated_at`, and a relative age,+then the title and a short snippet. `--global` labels every hit with its+`workspace/project`, and `--json` adds `workspace` and `project` fields to+each hit. `--global` cannot be combined with `--workspace` or `--project`.++The command calls `GET /admin/recent`, so on a multi-user server only the root+operator can run it. `[recall] default_global` does not change this command;+it stays project-scoped unless you pass `--global`.+## Historical memory and live code intelligenceai-memory can run beside CodeGraph, an LSP-backed service, a SCIP/LSIF index,diff --git a/docs/use-cases.md b/docs/use-cases.mdindex 8f47c40a..af57341d 100644--- a/docs/use-cases.md+++ b/docs/use-cases.md@@ -133,6 +133,11 @@`additionalContext`. Without the rule, ask Grok to list and then accept thehandoff. Zero still must call `memory_handoff_list` then`memory_handoff_accept`.+- **"What changed in this project recently?"** From a shell, `ai-memory recent`+ lists the newest wiki pages, with RFC 3339 timestamps and relative ages.+ Add `--global` to cover every project, or `--json` for a machine-readable+ list. The agent's `memory_recent` tool is the same recency listing inside a+ session.- **"What did we decide about X six weeks ago?"** Use `memory_query X` fromthe agent for FTS5 fused with entity matches and linked-page expansion (plusvector similarity when an embedder is configured). For a quick terminal-only