Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(web): add incremental page reads and client guide
Éverton Toffanetto4ba6f567217e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ce62d08..a6b663f9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added incremental paging to scoped HTTP `recent` reads with `updated_since`+ and an opaque, scope-bound cursor. Queries preserve equal-time ordering,+ exclude expired and superseded pages and recheck authorization on each+ request. Calls without incremental arguments retain their existing array+ response. Added a generic MCP/HTTP integration guide. (#1010)+## [2.5.2] - 2026-10-01### Addeddiff --git a/Cargo.lock b/Cargo.lockindex 0015f62e..c7080669 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -277,6 +277,7 @@ dependencies = ["anyhow","askama","axum",+ "base64 0.22.1","jiff","pulldown-cmark","serde",diff --git a/README.md b/README.mdindex 7326c1df..06a80e33 100644--- a/README.md+++ b/README.md@@ -465,6 +465,7 @@ diagram, crate breakdown, schema notes, and invariants.| [`docs/macos.md`](docs/macos.md) | macOS install paths: menu bar app, native release tarball, source build, Docker wrapper, launchd, and current limitations. || [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, prebuilt native release zip, native source builds, and caveats. || [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes, handoff-injection limits, and community bridge guidance. |+| [`docs/programmatic-memory.md`](docs/programmatic-memory.md) | Use ai-memory from any tool: MCP write/query/handoff calls, scope rules and incremental reads. || [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, pointers to the TLS guide. || [`docs/users.md`](docs/users.md) | **Multi-user attribution and human login.** Four-rung bearer ladder, password sessions, `ai-memory user` / `api-key` walkthrough, brownfield migration. || [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS and when you don't, with copy-paste Caddy / nginx / Cloudflare Tunnel templates and the "secure when you're not" failure modes. |diff --git a/crates/ai-memory-mcp/tests/suite/mcp_stateless_http.rs b/crates/ai-memory-mcp/tests/suite/mcp_stateless_http.rsindex 3a8fb79e..34016c61 100644--- a/crates/ai-memory-mcp/tests/suite/mcp_stateless_http.rs+++ b/crates/ai-memory-mcp/tests/suite/mcp_stateless_http.rs@@ -16,6 +16,7 @@use ai_memory_mcp::AiMemoryServer;use ai_memory_store::Store;+use ai_memory_wiki::Wiki;use axum::Router;use axum::body::Body;use axum::http::{Request, StatusCode};@@ -68,6 +69,7 @@ async fn make_router_with_dialect(.await.unwrap();let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_wiki(Wiki::new(tmp.path(), store.writer.clone()).unwrap()).with_strip_root_combinators(strip_root_combinators).with_gemini_safe_schemas(gemini_safe_schemas);let svc = StreamableHttpService::new(@@ -89,7 +91,7 @@ fn post(body: &'static str) -> Request<Body> {}/// [`post`] against an explicit URI (tests carrying `?flavor=moonshot`).-fn post_to(uri: &str, body: &'static str) -> Request<Body> {+fn post_to(uri: &str, body: impl Into<Body>) -> Request<Body> {Request::builder().method("POST").uri(uri)@@ -99,7 +101,7 @@ fn post_to(uri: &str, body: &'static str) -> Request<Body> {.header("host", "localhost").header("content-type", "application/json").header("accept", "application/json, text/event-stream")- .body(Body::from(body))+ .body(body.into()).unwrap()}@@ -165,6 +167,235 @@ async fn stateless_initialize_returns_json_result() {);}+async fn rpc(router: &Router, token: &str, body: serde_json::Value) -> serde_json::Value {+ let mut request = post_to("/mcp", body.to_string());+ request+ .headers_mut()+ .insert("authorization", format!("Bearer {token}").parse().unwrap());+ let response = router.clone().oneshot(request).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ serde_json::from_str(&body_string(response).await).unwrap()+}++async fn generic_tool(+ router: &Router,+ token: &str,+ name: &str,+ arguments: serde_json::Value,+) -> serde_json::Value {+ let reply = rpc(+ router,+ token,+ serde_json::json!({+ "jsonrpc":"2.0", "id":2, "method":"tools/call",+ "params":{"name":name,"arguments":arguments},+ }),+ )+ .await;+ assert!(reply.get("error").is_none(), "{reply}");+ assert_ne!(reply["result"]["isError"], true, "{reply}");+ let text = reply["result"]["content"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|part| part["text"].as_str())+ .collect::<Vec<_>>()+ .join("\n");+ serde_json::from_str(&text).unwrap()+}++/// The public guide's direct-memory sequence works for a static machine+/// client with a user key, without native hooks or a transport session.+#[tokio::test]+async fn generic_machine_client_writes_queries_and_claims_a_handoff() {+ use ai_memory_core::{ApiCredentialId, NewUser, UserRole};+ use ai_memory_mcp::auth::{AuthState, require_bearer};+ use ai_memory_store::{TokenPepper, api_key_preview, generate_api_key, hash_token};+ use serde_json::json;+ use std::sync::Arc;++ let tmp = TempDir::new().unwrap();+ let (router, store) = make_router(&tmp, false).await;+ let user_id = store+ .writer+ .create_human_user(+ NewUser {+ username: "example-client".into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ let pepper = TokenPepper::new("generic-client-test-pepper");+ let token = generate_api_key().unwrap();+ store+ .writer+ .create_api_credential(+ ApiCredentialId::new(),+ user_id,+ "generic-client".into(),+ hash_token(&token, &pepper),+ Some(api_key_preview(&token)),+ )+ .await+ .unwrap();+ let auth = AuthState::new(Some("generic-client-root-control".into())).with_multiuser(+ pepper,+ store.reader.clone(),+ store.writer.clone(),+ );+ let router = router.layer(axum::middleware::from_fn_with_state(+ Arc::new(auth),+ require_bearer,+ ));+ let initialized = rpc(+ &router,+ &token,+ json!({+ "jsonrpc":"2.0", "id":1, "method":"initialize",+ "params":{"protocolVersion":"2024-11-05","capabilities":{},+ "clientInfo":{"name":"example-client","version":"1.0"}},+ }),+ )+ .await;+ assert_eq!(initialized["result"]["serverInfo"]["name"], "ai-memory");+ let tools = rpc(+ &router,+ &token,+ json!({+ "jsonrpc":"2.0","id":2,"method":"tools/list","params":{},+ }),+ )+ .await;+ for name in [+ "memory_write_page",+ "memory_query",+ "memory_handoff_begin",+ "memory_handoff_accept",+ ] {+ assert!(+ tools["result"]["tools"]+ .as_array()+ .unwrap()+ .iter()+ .any(|tool| tool["name"] == name)+ );+ }++ let written = generic_tool(+ &router,+ &token,+ "memory_write_page",+ json!({+ "workspace":"demo","project":"app","path":"notes/retries.md",+ "body":"# Retry policy\nKeep the same event ID when retrying delivery.",+ }),+ )+ .await;+ assert_eq!(written["path"], "notes/retries.md");+ assert!(written["page_id"].is_string());+ let queried = generic_tool(+ &router,+ &token,+ "memory_query",+ json!({+ "workspace":"demo","project":"app","query":"retry policy",+ }),+ )+ .await;+ assert_eq!(queried["hits"].as_array().unwrap().len(), 1);+ assert_eq!(queried["hits"][0]["path"], "notes/retries.md");++ // A same-named project in another workspace must never become the target.+ generic_tool(+ &router,+ &token,+ "memory_write_page",+ json!({+ "workspace":"other-team","project":"app","path":"notes/foreign.md",+ "body":"# Foreign project\nForeign workspace control.",+ }),+ )+ .await;+ let foreign = generic_tool(+ &router,+ &token,+ "memory_query",+ json!({+ "workspace":"other-team","project":"app","query":"retry policy",+ }),+ )+ .await;+ assert_eq!(foreign["hits"], json!([]));+ let partial = rpc(+ &router,+ &token,+ json!({+ "jsonrpc":"2.0","id":3,"method":"tools/call",+ "params":{"name":"memory_write_page","arguments":{+ "workspace":"demo","path":"notes/partial.md","body":"Must be refused",+ }},+ }),+ )+ .await;+ assert!(+ partial.get("error").is_some() || partial["result"]["isError"] == true,+ "{partial}"+ );++ let pending = generic_tool(+ &router,+ &token,+ "memory_handoff_begin",+ json!({+ "workspace":"demo","project":"app",+ "summary":"The retry policy was saved. Add the delivery test next.",+ "next_steps":["Add a retry regression test."],+ }),+ )+ .await;+ let handoff_id = pending["handoff_id"].as_str().unwrap();+ let foreign_claim = generic_tool(+ &router,+ &token,+ "memory_handoff_accept",+ json!({+ "workspace":"other-team","project":"app","handoff_id":handoff_id,+ }),+ )+ .await;+ assert_eq!(foreign_claim["handoff"], serde_json::Value::Null);+ let claimed = generic_tool(+ &router,+ &token,+ "memory_handoff_accept",+ json!({+ "workspace":"demo","project":"app","handoff_id":handoff_id,+ }),+ )+ .await;+ assert_eq!(claimed["status"], "claimed");+ assert_eq!(+ claimed["handoff"]["summary"],+ "The retry policy was saved. Add the delivery test next."+ );+ let repeated = generic_tool(+ &router,+ &token,+ "memory_handoff_accept",+ json!({+ "workspace":"demo","project":"app","handoff_id":handoff_id,+ }),+ )+ .await;+ assert_eq!(repeated["status"], "none_pending");+ assert_eq!(repeated["handoff"], serde_json::Value::Null);+}+/// Contrast / guard: with `--http-stateful` (session mode), the same/// session-less `tools/call` is rejected with 422 "Unexpected message,/// expect initialize request" — the exact symptom from issue #3. Thisdiff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 40136c20..186c88e1 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -8069,6 +8069,59 @@ impl ReaderPool {.await}+ /// Bounded incremental latest-page summaries, ordered by timestamp and path.+ /// Expired pages are omitted; this is an update listing, not a deletion feed.+ /// `since_us` is exclusive; `after` resumes strictly after a returned pair.+ ///+ /// # Errors+ /// Propagates SQL and pool errors.+ pub async fn incremental_pages(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ since_us: i64,+ after: Option<(i64, String)>,+ limit: usize,+ ) -> StoreResult<Vec<PageSummary>> {+ self.with_conn(move |conn| {+ let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");+ let (after_us, after_path) = after.unwrap_or((since_us, String::new()));+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT pg.path, pg.title, {kind_expr}, pg.tier, pg.updated_at+ FROM pages pg WHERE pg.workspace_id = ?1 AND pg.project_id = ?2+ AND pg.is_latest = 1 AND pg.updated_at > ?3+ AND (pg.updated_at > ?4 OR (pg.updated_at = ?4 AND pg.path > ?5))+ AND (pg.expires_at IS NULL OR pg.expires_at > ?6)+ ORDER BY pg.updated_at ASC, pg.path ASC LIMIT ?7"+ ))?;+ let rows = stmt.query_map(+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ since_us,+ after_us,+ after_path,+ jiff::Timestamp::now().as_microsecond(),+ limit.clamp(1, 100) as i64 + 1+ ],+ |row| {+ let updated_us: i64 = row.get(4)?;+ Ok(PageSummary {+ path: row.get(0)?,+ title: row.get(1)?,+ kind: row.get(2)?,+ tier: row.get(3)?,+ updated_at: jiff::Timestamp::from_microsecond(updated_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default(),+ })+ },+ )?;+ rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)+ })+ .await+ }+/// Full page metadata for the page-view template (body comes from/// `Wiki::read_page`). Returns `None` when no `is_latest = 1` row/// matches the given path.diff --git a/crates/ai-memory-store/tests/suite/session_observations.rs b/crates/ai-memory-store/tests/suite/session_observations.rsindex 8a13f3ff..f3616b9d 100644--- a/crates/ai-memory-store/tests/suite/session_observations.rs+++ b/crates/ai-memory-store/tests/suite/session_observations.rs@@ -566,3 +566,80 @@ async fn session_summary_scoped_narrows_the_listing_predicates() {"unknown id",);}++#[tokio::test]+async fn incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope() {+ let (_tmp, store) = open_seeded();+ let conn = Connection::open(store.db_path()).unwrap();+ for n in 0..125u8 {+ conn.execute("INSERT INTO pages (id, workspace_id, project_id, path, title, tier,+ body, body_sha256, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'Page', 'semantic', '', ?5, ?6, ?6)",+ params![&id(n + 40)[..], ws().as_bytes(), proj_a().as_bytes(), format!("p{n:03}.md"), &[0u8; 32][..], NOW]).unwrap();+ }+ // Expired latest versions remain in the legacy tree listing but are+ // hidden from the incremental update listing even when pinned.+ conn.execute(+ "UPDATE pages SET expires_at = 1, pinned = 1 WHERE path = 'p124.md'",+ [],+ )+ .unwrap();+ conn.execute("INSERT INTO pages (id, workspace_id, project_id, path, title, tier,+ body, body_sha256, created_at, updated_at, is_latest) VALUES (?1, ?2, ?3, 'p000.md', 'Old', 'semantic', '', ?4, ?5, ?5, 0)",+ params![&id(200)[..], ws().as_bytes(), proj_a().as_bytes(), &[0u8;32][..], NOW + 1]).unwrap();+ conn.execute("INSERT INTO pages (id, workspace_id, project_id, path, title, tier,+ body, body_sha256, created_at, updated_at) VALUES (?1, ?2, ?3, 'foreign.md', 'Foreign', 'semantic', '', ?4, ?5, ?5)",+ params![&id(201)[..], ws().as_bytes(), proj_b().as_bytes(), &[0u8;32][..], NOW]).unwrap();+ let mut after = None;+ let mut seen = Vec::new();+ loop {+ let mut pages = store+ .reader+ .incremental_pages(ws(), proj_a(), NOW - 1, after, 37)+ .await+ .unwrap();+ assert!(pages.len() <= 38, "SQL fetches at most limit+1");+ let more = pages.len() > 37;+ pages.truncate(37);+ seen.extend(pages.iter().map(|p| p.path.clone()));+ if !more {+ break;+ }+ let last = pages.last().unwrap();+ after = Some((NOW, last.path.clone()));+ }+ assert_eq!(+ seen,+ (0..124).map(|n| format!("p{n:03}.md")).collect::<Vec<_>>()+ );+ assert!(+ store+ .reader+ .incremental_pages(ws(), proj_a(), NOW, None, 100)+ .await+ .unwrap()+ .is_empty(),+ "exact cutoff is exclusive"+ );+ assert_eq!(+ store+ .reader+ .incremental_pages(ws(), proj_b(), NOW - 1, None, 100)+ .await+ .unwrap()[0]+ .path,+ "foreign.md"+ );+ assert!(+ store+ .reader+ .incremental_pages(WorkspaceId::new(), proj_a(), NOW - 1, None, 100)+ .await+ .unwrap()+ .is_empty()+ );+ assert_eq!(+ store.reader.list_pages("w", "proj-a").await.unwrap().len(),+ 125,+ "legacy expiry behavior stays unchanged"+ );+}diff --git a/crates/ai-memory-web/Cargo.toml b/crates/ai-memory-web/Cargo.tomlindex 6d2eab88..2c00906b 100644--- a/crates/ai-memory-web/Cargo.toml+++ b/crates/ai-memory-web/Cargo.toml@@ -19,6 +19,7 @@ serde_json.workspace = truetokio.workspace = truetracing.workspace = trueaxum.workspace = true+base64.workspace = truejiff.workspace = truesha2.workspace = truetower.workspace = truediff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rsindex 540209d3..6071ce13 100644--- a/crates/ai-memory-web/src/routes/api.rs+++ b/crates/ai-memory-web/src/routes/api.rs@@ -13,6 +13,7 @@ use axum::extract::{Path, Query, RawQuery, State};use axum::http::{HeaderValue, StatusCode, header};use axum::response::{IntoResponse, Response};use axum::{Json, Router};+use base64::Engine as _;use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};@@ -452,21 +453,181 @@ async fn search_scopes(Ok(hits)}+#[derive(Deserialize)]+struct RecentQuery {+ #[serde(default = "default_limit")]+ limit: usize,+ updated_since: Option<String>,+ cursor: Option<String>,+}++// Versioned URL-safe base64 JSON is opaque to callers and bounded before decoding.+// Scope ids are checked after normal authorization, never used to resolve scope.+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct RecentCursor {+ v: u8,+ workspace: WorkspaceId,+ project: ProjectId,+ since: String,+ updated_at: String,+ path: String,+}++fn recent_instant(value: &str) -> ApiParseResult<jiff::Timestamp> {+ let bytes = value.as_bytes();+ let invalid = || ApiFailure::bad_request("invalid RFC3339 timestamp");+ if bytes.len() < 20+ || bytes.len() > 64+ || !value.is_ascii()+ || bytes[4] != b'-'+ || bytes[7] != b'-'+ || !matches!(bytes[10], b'T' | b't')+ || bytes[13] != b':'+ || bytes[16] != b':'+ || ![0..4, 5..7, 8..10, 11..13, 14..16, 17..19]+ .into_iter()+ .all(|range| bytes[range].iter().all(u8::is_ascii_digit))+ {+ return Err(invalid());+ }+ let mut rest = &value[19..];+ if let Some(fraction) = rest.strip_prefix('.') {+ let digits = fraction.bytes().take_while(u8::is_ascii_digit).count();+ if digits == 0 || digits > 9 {+ return Err(invalid());+ }+ rest = &fraction[digits..];+ }+ if rest != "Z" && rest != "z" {+ let zone = rest.as_bytes();+ if zone.len() != 6+ || !matches!(zone[0], b'+' | b'-')+ || zone[3] != b':'+ || !zone[1..3].iter().chain(&zone[4..6]).all(u8::is_ascii_digit)+ {+ return Err(invalid());+ }+ }+ value.parse::<jiff::Timestamp>().map_err(|_| invalid())+}++fn encode_recent_cursor(cursor: &RecentCursor) -> ApiParseResult<String> {+ let bytes = serde_json::to_vec(cursor).map_err(|_| ApiFailure {+ message: "internal server error".into(),+ status: StatusCode::INTERNAL_SERVER_ERROR,+ })?;+ let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes);+ decode_recent_cursor(&raw)?;+ Ok(raw)+}++fn decode_recent_cursor(raw: &str) -> ApiParseResult<RecentCursor> {+ if raw.len() > 8192 || raw.is_empty() {+ return Err(ApiFailure::bad_request("invalid recent cursor"));+ }+ let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .decode(raw)+ .map_err(|_| ApiFailure::bad_request("invalid recent cursor"))?;+ if bytes.len() > 6144 {+ return Err(ApiFailure::bad_request("invalid recent cursor"));+ }+ let cursor: RecentCursor = serde_json::from_slice(&bytes)+ .map_err(|_| ApiFailure::bad_request("invalid recent cursor"))?;+ if cursor.v != 1 || cursor.path.len() > 2048 || PagePath::new(&cursor.path).is_err() {+ return Err(ApiFailure::bad_request("invalid recent cursor"));+ }+ Ok(cursor)+}+async fn recent_handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,Path((workspace, project)): Path<(String, String)>,- Query(query): Query<LimitQuery>,+ Query(query): Query<RecentQuery>,) -> Result<Response, Response> {- let _ = lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;+ let (workspace_id, project_id) =+ lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;+ let limit = query.limit.clamp(1, 100);+ if query.updated_since.is_none() && query.cursor.is_none() {+ let mut pages = state+ .reader+ .list_pages(&workspace, &project)+ .await+ .map_err(internal_error)?;+ pages.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));+ pages.truncate(limit);+ return Ok(with_cache(Json(pages).into_response(), LIST_CACHE_MAX_AGE));+ }+ let cursor = query+ .cursor+ .as_deref()+ .map(decode_recent_cursor)+ .transpose()+ .map_err(ApiFailure::into_response)?;+ let (since, after) = if let Some(cursor) = cursor {+ if cursor.workspace != workspace_id || cursor.project != project_id {+ return Err(+ ApiFailure::bad_request("recent cursor does not match scope").into_response(),+ );+ }+ let since = recent_instant(&cursor.since).map_err(ApiFailure::into_response)?;+ let after = recent_instant(&cursor.updated_at).map_err(ApiFailure::into_response)?;+ if after <= since+ || query+ .updated_since+ .as_deref()+ .map(recent_instant)+ .transpose()+ .map_err(ApiFailure::into_response)?+ .is_some_and(|bound| bound != since)+ {+ return Err(ApiFailure::bad_request("conflicting recent cursor bounds").into_response());+ }+ (since, Some((after.as_microsecond(), cursor.path)))+ } else {+ (+ recent_instant(query.updated_since.as_deref().unwrap_or_default())+ .map_err(ApiFailure::into_response)?,+ None,+ )+ };+ // SQL timestamps have microsecond precision. Flooring a submicrosecond+ // cutoff retains exactly the rows strictly later than the supplied instant.let mut pages = state.reader- .list_pages(&workspace, &project)+ .incremental_pages(+ workspace_id,+ project_id,+ i64::try_from(since.as_nanosecond().div_euclid(1000)).map_err(internal_error)?,+ after,+ limit,+ ).await.map_err(internal_error)?;- pages.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));- pages.truncate(query.limit.clamp(1, 100));- Ok(with_cache(Json(pages).into_response(), LIST_CACHE_MAX_AGE))+ let has_more = pages.len() > limit;+ pages.truncate(limit);+ let next_cursor = if has_more {+ pages+ .last()+ .map(|page| {+ encode_recent_cursor(&RecentCursor {+ v: 1,+ workspace: workspace_id,+ project: project_id,+ since: since.to_string(),+ updated_at: page.updated_at.clone(),+ path: page.path.clone(),+ })+ })+ .transpose()+ .map_err(ApiFailure::into_response)?+ } else {+ None+ };+ Ok(with_no_store(+ Json(serde_json::json!({ "pages": pages, "next_cursor": next_cursor })).into_response(),+ ))}async fn briefing_handler(@@ -1477,6 +1638,47 @@ fn hex_value(byte: u8) -> Option<u8> {#[cfg(test)]mod tests {+ #[test]+ fn recent_cursor_validates_rfc3339_and_bounded_payload() {+ for value in [+ "2026-09-30T10:00:00Z",+ "2026-09-30T10:00:00.123456789-03:00",+ "1969-12-31T23:59:59.999999999Z",+ ] {+ assert!(super::recent_instant(value).is_ok(), "{value}");+ }+ for value in [+ "2026-09-30",+ "2026-09-30 10:00:00Z",+ "2026-09-30T10:00:00",+ "2026-09-30T10:00:00Z[UTC]",+ "2026-09-30T10:00:00+0300",+ "2026-09-30T10:00:00.1234567890Z",+ ] {+ assert!(super::recent_instant(value).is_err(), "{value}");+ }+ let cursor = super::RecentCursor {+ v: 1,+ workspace: super::WorkspaceId::new(),+ project: super::ProjectId::new(),+ since: "2000-01-01T00:00:00Z".into(),+ updated_at: "2026-09-30T10:00:00Z".into(),+ path: "page.md".into(),+ };+ let raw = super::encode_recent_cursor(&cursor).unwrap();+ assert_eq!(super::decode_recent_cursor(&raw).unwrap().path, "page.md");+ let invalid = super::RecentCursor {+ path: "../page.md".into(),+ ..cursor+ };+ assert!(super::encode_recent_cursor(&invalid).is_err());+ assert!(super::decode_recent_cursor(&"a".repeat(8194)).is_err());+ assert!(super::decode_recent_cursor("e30").is_err());+ for invalid in [format!("{raw}="), "+w".into(), "/w".into()] {+ assert!(super::decode_recent_cursor(&invalid).is_err());+ }+ }+use super::{internal_error, serves_handoff_body};use ai_memory_core::{AuthLevel, OwnerFilter};use axum::{Extension, body::to_bytes};diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rsindex ccc8c010..0929d06d 100644--- a/crates/ai-memory-web/tests/suite/routes.rs+++ b/crates/ai-memory-web/tests/suite/routes.rs@@ -3778,3 +3778,250 @@ async fn metadata_shows_only_what_the_viewer_may_read() {assert_eq!(status, StatusCode::OK);assert!(shows(&body, "secrets/rates.md"), "{body}");}++#[tokio::test]+async fn api_recent_incremental_paginates_over_120_pages_and_binds_cursor() {+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(ws, "other", None)+ .await+ .unwrap();+ for n in 0..125 {+ store+ .writer+ .upsert_page(new_page(ws, proj, &format!("p{n:03}.md"), "Page", "body"))+ .await+ .unwrap();+ }+ let app = api_router(store.reader.clone(), wiki);+ let base = "/workspaces/default/projects/scratch/recent";+ let mut url = format!("{base}?updated_since=2000-01-01T00:00:00Z&limit=37");+ let mut paths = Vec::new();+ let mut first_cursor = None;+ loop {+ let response = app+ .clone()+ .oneshot(Request::builder().uri(&url).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ response.headers()[header::CACHE_CONTROL],+ "private, no-store"+ );+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let json: Value = serde_json::from_slice(&body).unwrap();+ let pages = json["pages"].as_array().unwrap();+ assert!(pages.len() <= 37);+ paths.extend(+ pages+ .iter()+ .map(|page| page["path"].as_str().unwrap().to_owned()),+ );+ let Some(cursor) = json["next_cursor"].as_str() else {+ break;+ };+ first_cursor.get_or_insert_with(|| cursor.to_owned());+ url = format!("{base}?cursor={cursor}&limit=37");+ }+ assert_eq!(paths.len(), 125);+ paths.sort();+ paths.dedup();+ assert_eq!(paths.len(), 125);+ let cursor = first_cursor.unwrap();+ let resume = format!("{base}?cursor={cursor}&limit=37");+ let mut replay_bodies = Vec::new();+ for _ in 0..2 {+ let response = app+ .clone()+ .oneshot(Request::builder().uri(&resume).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ replay_bodies.push(+ axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap(),+ );+ }+ assert_eq!(+ replay_bodies[0], replay_bodies[1],+ "unchanged data gives a stable continuation"+ );+ use base64::Engine as _;+ let cursor_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .decode(&cursor)+ .unwrap();+ let cursor_json: Value = serde_json::from_slice(&cursor_bytes).unwrap();+ for (key, value) in [+ ("v", serde_json::json!(2)),+ ("path", serde_json::json!("../escape.md")),+ ("updated_at", cursor_json["since"].clone()),+ ("since", serde_json::json!("invalid")),+ ] {+ let mut malformed = cursor_json.clone();+ malformed[key] = value;+ let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .encode(serde_json::to_vec(&malformed).unwrap());+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .uri(format!("{base}?cursor={raw}"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ }+ for url in [+ format!("/workspaces/default/projects/other/recent?cursor={cursor}"),+ format!("{base}?cursor={cursor}&updated_since=2001-01-01T00:00:00Z"),+ format!("{base}?cursor=zz"),+ format!("{base}?cursor={}", "a".repeat(8194)),+ format!("{base}?updated_since=yesterday"),+ ] {+ let response = app+ .clone()+ .oneshot(Request::builder().uri(url).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ }+ let response = app+ .oneshot(+ Request::builder()+ .uri(format!("{base}?limit=1"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ response.headers()[header::CACHE_CONTROL],+ "private, max-age=30"+ );+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let json: Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(json.as_array().unwrap().len(), 1);+}++#[tokio::test]+async fn api_recent_incremental_rechecks_restricted_scope_on_cursor() {+ use ai_memory_core::{AuthorizedViewer, NewUser, UserRole};+ use ai_memory_store::{AccessMode, GrantLevel};+ let (_tmp, store, wiki) = setup().await;+ store+ .writer+ .set_new_project_mode(AccessMode::Restricted)+ .await+ .unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "private-memory", None)+ .await+ .unwrap();+ for n in 0..2 {+ store+ .writer+ .upsert_page(new_page(ws, proj, &format!("p{n}.md"), "Page", "body"))+ .await+ .unwrap();+ }+ let mut users = Vec::new();+ for name in ["alice", "bob"] {+ users.push(+ store+ .writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap(),+ );+ }+ store+ .writer+ .grant_memory(users[0], proj, GrantLevel::Read, None)+ .await+ .unwrap();+ let app = api_router(store.reader.clone(), wiki);+ let request = |uri: String, user| {+ Request::builder()+ .uri(uri)+ .extension(AuthorizedViewer(user))+ .body(Body::empty())+ .unwrap()+ };+ let base = "/workspaces/default/projects/private-memory/recent";+ let first = app+ .clone()+ .oneshot(request(+ format!("{base}?updated_since=2000-01-01T00:00:00Z&limit=1"),+ users[0],+ ))+ .await+ .unwrap();+ assert_eq!(first.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(first.into_body(), usize::MAX)+ .await+ .unwrap();+ let json: Value = serde_json::from_slice(&bytes).unwrap();+ let url = format!("{base}?cursor={}", json["next_cursor"].as_str().unwrap());+ assert_eq!(+ app.clone()+ .oneshot(request(url.clone(), users[1]))+ .await+ .unwrap()+ .status(),+ StatusCode::FORBIDDEN+ );+ assert_eq!(+ app.clone()+ .oneshot(request(url.clone(), users[0]))+ .await+ .unwrap()+ .status(),+ StatusCode::OK+ );+ assert!(+ store+ .writer+ .revoke_memory(users[0], proj, None)+ .await+ .unwrap()+ );+ assert_eq!(+ app.oneshot(request(url, users[0])).await.unwrap().status(),+ StatusCode::FORBIDDEN,+ "a cursor cannot retain access after its user's grant is revoked"+ );+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 05fd1c36..dab5596a 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -250,6 +250,10 @@ for provenance and stable, namespaced `ingest_key` values for retries. See the[external capture contract](external-lifecycle.md) for batching, identity andthe limits of this cooperative process-scoped mode.+Tools can use MCP directly to write pages, query knowledge and claim handoffs.+With `--enable-web`, incremental `recent` pages use a bounded `(updated_at, path)`+query in the authorized scope. See [programmatic memory](programmatic-memory.md).+Lifecycle bodies have content limits independent of the 10 MiB HTTP requestlimit. User prompts and post-compaction summaries are capped UTF-8-safely at16 KiB; notification and tool excerpts are capped at 2 KB. Nativediff --git a/docs/cookbook.md b/docs/cookbook.mdindex 69e3b7cc..73bbcd82 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -16,6 +16,13 @@ a derived SQLite index for search. Everything is **scoped per project**LLM at all (capture + full-text search + rule-based summaries); adding a providerenables consolidation and auto-improvement.+## Recipe: use ai-memory as your tool's memory++Call the existing MCP tools to save pages, query knowledge and pass a handoff+between executions. Native hooks are optional. The [programmatic memory guide](programmatic-memory.md)+includes complete HTTP requests, scope rules and machine authentication.+If your tool also hosts a harness, follow the [external lifecycle contract](external-lifecycle.md).+## Everyday tasks (through your agent, over MCP)You mostly just talk to your agent; it calls the right tool. Common ones:diff --git a/docs/external-lifecycle.md b/docs/external-lifecycle.mdindex b085d80b..5bd86d8c 100644--- a/docs/external-lifecycle.md+++ b/docs/external-lifecycle.md@@ -4,6 +4,9 @@ An orchestrator that observes its agents can send lifecycle events to one sharedai-memory server through `/hook/batch`. Framework adapters belong outside core;the server continues to own storage, retrieval, consolidation and durable memory.+For deliberate writes, queries and handoffs without lifecycle capture, start+with the [programmatic memory guide](programmatic-memory.md).+## Choose one capture path before launchingSet `AI_MEMORY_CAPTURE_OWNER` to your producer namespace in the environment ofdiff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex d803d403..16891cc1 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -255,7 +255,7 @@ Every reader surface uses the same `kind` contract. An explicit frontmatter`rule`, `slot`, `session`, `decision`, `gotcha`, `concept`, `procedure`, and`note`, respectively. Other paths fall back to `fact`.-**Response:** a bare JSON array, `[BriefingPage, …]`+**Legacy response:** a bare JSON array of `PageSummary` objects.```json[@@ -268,6 +268,30 @@ Every reader surface uses the same `kind` contract. An explicit frontmatter]```+Supply `updated_since` (RFC 3339) or `cursor` to opt into incremental paging:++```http+GET /api/v1/workspaces/{workspace}/projects/{project}/recent?updated_since=2026-09-30T00%3A00%3A00Z&limit=20+```++```json+{"pages": [], "next_cursor": null}+```++The cutoff is exclusive (`updated_at > updated_since`). Results are ordered+by `(updated_at, path)` ascending and fetched with a bounded SQL query. Pass+`next_cursor` unchanged to continue; an optional cutoff must match the cursor's+cutoff. Cursors use versioned URL-safe base64 without padding, are opaque to+clients, and are limited to 8192 characters (6144 decoded bytes). They are bound+to the workspace and project. Invalid, foreign-scope or conflicting cursors+return 400. Each request rechecks authorization and uses+`Cache-Control: private, no-store`.++Incremental results omit superseded and expired pages, including expired pinned+pages. They provide no snapshot or deletion feed: concurrent changes can appear+on a later page, and deleted or expired pages are absent. Calls without either+parameter retain the legacy array, descending order and cache behavior.+### 4.7 Briefing (structured snapshot)```httpdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 305abc48..bcf6692b 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -1,5 +1,8 @@# MCP install guide - additional clients+For a custom tool, start with the [programmatic memory guide](programmatic-memory.md).+It shows direct MCP writes, queries and handoffs without a native hook adapter.+> All snippets below default to `http://127.0.0.1:49374` (local server). For a> remote server (homelab, LAN box) substitute the appropriate URL AND add an> `Authorization: Bearer <token>` header to the `headers` block when bearer authdiff --git a/docs/programmatic-memory.md b/docs/programmatic-memory.mdnew file mode 100644index 00000000..5ffb6d3a--- /dev/null+++ b/docs/programmatic-memory.md@@ -0,0 +1,98 @@+# Use ai-memory from your tool++Any tool can use ai-memory over MCP to save knowledge, search it and pass context+between executions. Native lifecycle hooks are optional. A tool that also hosts+an agent harness can send that harness's lifecycle events through HTTP.++## Connect and choose a scope++Connect to `/mcp` using Streamable HTTP. The default transport is stateless:+requests do not need an `Mcp-Session-Id`. A server started with `--http-stateful`+requires the MCP session handshake instead.++Use a user API key for machine requests. See [users.md](users.md) for issuing+keys and granting project access. A dedicated tool identity suits an independent+client. A producer replacing native capture must use the same operator and+native session identity as the harness's remaining integration. See the+[external lifecycle guide](external-lifecycle.md) when sending those events.++Static MCP clients pass `workspace` and `project` together on every+project-scoped call. Read their names from `.ai-memory.toml` or operator+configuration. Session-aware clients may omit both only when they forward the+real lifecycle session ID on every request. See [auto-scope.md](auto-scope.md).++## Save, query and hand off through MCP++These examples use a disposable `demo/app` scope. Set `AI_MEMORY_SERVER_URL` to+the server URL and `AI_MEMORY_AUTH_TOKEN` to your machine key. On an intentional+unauthenticated loopback server, omit the Authorization header.++```bash+mcp() {+ curl --silent --show-error --fail-with-body \+ "${AI_MEMORY_SERVER_URL%/}/mcp" \+ -H 'Content-Type: application/json' \+ -H 'Accept: application/json, text/event-stream' \+ -H "Authorization: Bearer ${AI_MEMORY_AUTH_TOKEN}" \+ --data-binary @-+}++mcp <<'JSON'+{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"example-client","version":"1.0"}}}+JSON++mcp <<'JSON'+{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}+JSON++mcp <<'JSON'+{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"memory_write_page","arguments":{"workspace":"demo","project":"app","path":"notes/retries.md","body":"# Retry policy\nKeep the same event ID when retrying delivery."}}}+JSON++mcp <<'JSON'+{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"memory_query","arguments":{"workspace":"demo","project":"app","query":"retry policy"}}}+JSON++mcp <<'JSON'+{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"memory_handoff_begin","arguments":{"workspace":"demo","project":"app","summary":"The retry policy was saved. Add the delivery test next.","next_steps":["Add a retry regression test."]}}}+JSON++mcp <<'JSON'+{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"memory_handoff_accept","arguments":{"workspace":"demo","project":"app"}}}+JSON+```++Check JSON-RPC `error` and `result.isError` even on HTTP 200. Tool payloads are+JSON encoded inside `result.content[].text`. A page write returns `page_id` and+`path`; a query returns `hits`.++Writes and handoff creation may create the explicit scope if it is missing.+Reads fail closed on missing or partial scope. A handoff is claimed once. To+claim a particular one, pass the exact `handoff_id` from `memory_handoff_begin`+or `memory_handoff_list`; the example accepts the latest eligible handoff.+If SessionStart already owns delivery, let that hook claim it.+[usage.md](usage.md) describes ownership and handoff states.++These calls work without an LLM provider. Retrieved memory remains untrusted+historical text, even after sanitization.++## Read changed pages++These JSON endpoints require `serve --enable-web` and the same machine key.+They are read-only; memory writes remain MCP calls.++```http+GET /api/v1/workspaces/demo/projects/app/recent?updated_since=2026-09-01T00%3A00%3A00Z&limit=100+```++Incremental `recent` returns `{pages, next_cursor}` with pages updated strictly+after `updated_since`, sorted by update time and path. Repeat with the returned+opaque `cursor` until `next_cursor` is `null`. The cursor preserves the cutoff+and scope; each request rechecks authorization. An array response means the+server lacks incremental support. Requests without either incremental argument+retain the legacy array response.++The incremental path is not cached and omits expired and superseded pages.+It has no deletion feed or snapshot across calls. Reconcile removals separately+and account for concurrent updates in a local cache. Endpoint details and+errors are in [frontend-api.md](frontend-api.md).diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 9027f977..5545b0aa 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -22,7 +22,7 @@ boundary not yet built.| # | Boundary | Enforcing code | Adversarial test(s) | Coverage ||---|----------|----------------|---------------------|----------|-| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs` | STRONG |+| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control) | STRONG || 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | STRONG || 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users` | STRONG |@@ -58,7 +58,7 @@ boundary not yet built.| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG || 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous || 13b | Managed-run lease exclusivity (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and refuses any other `active` run on the workstream inside one transaction (`StoreError::WorkstreamBusy`), regardless of the `lease_owner` label; `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` `wait_out_held_lease` (interactive relaunch) only waits for a reported expiry and retries — it never cancels or claims another run, so the server's busy check stays the sole arbiter | `store/src/lib.rs` `managed_workstream_batches_are_idempotent_and_release_the_lease` (second prepare refused while active); `run.rs` `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over` (renewing holder is reported, never displaced), with controls `interactive_launch_waits_out_a_lapsing_lease_then_proceeds` and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key |-| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |+| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them || 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others || 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) || 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |