Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat: add machine identity and capture diagnostics
Éverton Toffanetto8610e87c7b3f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ce62d08..d2bc8370 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added machine-authenticated `GET /identity`, available with the web UI+ disabled, and `ai-memory doctor` diagnostics for caller identity, external+ capture ownership and sessions with multiple capture sources (native events+ or distinct extensions, including backfill).+ Mixed-source counts preserve scope, session ownership and time-window filters;+ older servers leave unsupported fields unknown. (#1010)+## [2.5.2] - 2026-10-01### Addeddiff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex a1c240b9..c64b0bd6 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -77,6 +77,7 @@ pub(crate) struct CoverageRow {/// True when the harness ran here recently but captured nothing — the/// high-confidence "hook is missing" signal.uncaptured: bool,+ mixed_capture_sessions: Option<u64>,}impl CoverageRow {@@ -104,6 +105,27 @@ struct ByAgentResponse {struct AgentCount {agent: String,sessions: u64,+ #[serde(default)]+ mixed_capture_sessions: Option<u64>,+}++#[derive(Debug, Deserialize, Serialize)]+struct OperatorIdentity {+ version: String,+ level: String,+ operator: Option<String>,+ distinguishes_operators: bool,+}++async fn read_identity(ep: &ServerEndpoint) -> Option<OperatorIdentity> {+ match get_json::<OperatorIdentity>(ep, "/identity", &[]).await {+ Ok(identity) => Some(identity),+ Err(error) if super::is_scope_not_found(&error) => None,+ Err(_) => {+ eprintln!("Machine identity is unavailable; showing capture coverage only.");+ None+ }+ }}/// The full report, also the JSON output shape.@@ -116,6 +138,8 @@ struct DoctorReport {rows: Vec<CoverageRow>,/// The agent kinds (kebab form) flagged as uncaptured, for quick scripting.uncaptured: Vec<String>,+ capture_owner_active: bool,+ identity: Option<OperatorIdentity>,}/// Fold the raw per-harness local scans and the server's captured counts into@@ -157,6 +181,7 @@ pub(crate) fn build_rows(local_recent,captured,uncaptured,+ mixed_capture_sessions: None,}}).filter(|row| row.local_total > 0 || row.captured > 0)@@ -256,7 +281,7 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {super::run::native_home(config).context("locating the local harness session stores")?;let ep = ServerEndpoint::from_config_resolving_auth(config).await;- let captured: BTreeMap<String, u64> = match get_json::<ByAgentResponse>(+ let captured = match get_json::<ByAgentResponse>(&ep,"/admin/sessions/by-agent",&[@@ -266,15 +291,11 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {).await{- Ok(response) => response- .by_agent- .into_iter()- .map(|c| (c.agent, c.sessions))- .collect(),+ Ok(response) => response.by_agent,// A project that has never been captured into does not exist// server-side yet (404) — that is "nothing captured", not an error, so// every local harness correctly reads as uncaptured.- Err(error) if super::is_scope_not_found(&error) => BTreeMap::new(),+ Err(error) if super::is_scope_not_found(&error) => Vec::new(),Err(error) => {return Err(error).with_context(|| {format!("asking the server for captured session counts for {workspace}/{project}")@@ -282,8 +303,20 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {}};+ let identity = read_identity(&ep).await;+let local = scan_local(&home, &cwd, args.since_days).await;- let rows = build_rows(&local, &captured);+ let counts = captured+ .iter()+ .map(|count| (count.agent.clone(), count.sessions))+ .collect();+ let mut rows = build_rows(&local, &counts);+ for row in &mut rows {+ row.mixed_capture_sessions = captured+ .iter()+ .find(|count| count.agent == row.agent)+ .and_then(|count| count.mixed_capture_sessions);+ }let uncaptured: Vec<String> = rows.iter().filter(|r| r.uncaptured)@@ -297,6 +330,8 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {since_days: args.since_days,rows,uncaptured,+ capture_owner_active: config.runtime_env.capture_owner_active(),+ identity,};if args.json {@@ -312,6 +347,22 @@ fn render_human(report: &DoctorReport) {"Capture coverage for {}/{} (server {})",report.workspace, report.project, report.server);+ if let Some(identity) = &report.identity {+ println!(+ " identity: {} ({}, server {})",+ identity.operator.as_deref().unwrap_or("anonymous"),+ identity.level,+ identity.version+ );+ } else {+ println!(" identity: unavailable");+ }+ if report.capture_owner_active {+ println!(+ " AI_MEMORY_CAPTURE_OWNER is active: native capture is suppressed in this process.\n \+ Confirm the external producer is delivering events."+ );+ }if report.since_days == 0 {println!(" recent window: all on-disk sessions\n");} else {@@ -330,10 +381,22 @@ fn render_human(report: &DoctorReport) {row.agent, row.local_total, row.local_recent, row.captured);if row.uncaptured {+ if report.capture_owner_active {+ println!(+ " No captured session: check the external producer and repository policy."+ );+ } else {+ println!(+ " └ ran here but nothing was captured — install its hook:\n \+ ai-memory install-hooks --agent {} --apply",+ row.agent+ );+ }+ }+ if let Some(count) = row.mixed_capture_sessions.filter(|count| *count > 0) {println!(- " └ ran here but nothing was captured — install its hook:\n \- ai-memory install-hooks --agent {} --apply",- row.agent+ " {count} session(s) contain events from multiple capture sources.\n \+ Backfill can also mix source metadata; this does not prove duplicate capture.");}}@@ -341,9 +404,13 @@ fn render_human(report: &DoctorReport) {if report.uncaptured.is_empty() {println!("\n✓ Every harness that ran in this project recently is captured on the server.");} else {+ let remedy = if report.capture_owner_active {+ "Check the external producer and repository policy, then re-run `ai-memory doctor`."+ } else {+ "Install the hook(s) above, then re-run `ai-memory doctor` to confirm."+ };println!(- "\n⚠ {} harness(es) ran here recently with no captured sessions: {}.\n \- Install the hook(s) above, then re-run `ai-memory doctor` to confirm.",+ "\n⚠ {} harness(es) ran here recently with no captured sessions: {}.\n {remedy}",report.uncaptured.len(),report.uncaptured.join(", "));@@ -354,6 +421,55 @@ fn render_human(report: &DoctorReport) {mod tests {use super::*;+ #[tokio::test]+ async fn identity_diagnostics_degrade_on_server_and_decode_errors() {+ for (status, body, available) in [+ (500, "unavailable", false),+ (403, "forbidden", false),+ (200, "<html>legacy SPA</html>", false),+ (404, "missing", false),+ (+ 200,+ r#"{"version":"2.5.0","level":"anonymous","operator":null,"distinguishes_operators":false}"#,+ true,+ ),+ ] {+ let app = axum::Router::new().route(+ "/identity",+ axum::routing::get(move || async move {+ (axum::http::StatusCode::from_u16(status).unwrap(), body)+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let ep = ServerEndpoint::from_pair(+ Some(format!("http://{}", listener.local_addr().unwrap())),+ None,+ );+ let task = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ assert_eq!(+ read_identity(&ep).await.is_some(),+ available,+ "status {status}"+ );+ task.abort();+ }+ }++ #[test]+ fn an_older_server_leaves_provenance_unknown() {+ let legacy: ByAgentResponse =+ serde_json::from_str(r#"{"by_agent":[{"agent":"codex","sessions":2}]}"#).unwrap();+ assert_eq!(legacy.by_agent[0].sessions, 2);+ assert_eq!(legacy.by_agent[0].mixed_capture_sessions, None);+ let current: ByAgentResponse = serde_json::from_str(+ r#"{"by_agent":[{"agent":"codex","sessions":2,"mixed_capture_sessions":1}]}"#,+ )+ .unwrap();+ assert_eq!(current.by_agent[0].mixed_capture_sessions, Some(1));+ }+fn scan(agent: AgentKind, total: usize, recent: usize) -> LocalScan {LocalScan {agent,diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex cad09650..d1678042 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -666,6 +666,20 @@ fn validate_trusted_proxy_auth(auth: &AuthSettings) -> Result<()> {Ok(())}+fn mount_machine_routes(+ machine: axum::Router,+ reader: ai_memory_store::ReaderPool,+ auth: Arc<AuthState>,+) -> axum::Router {+ machine+ .merge(ai_memory_mcp::identity::router(+ reader,+ auth.actor_proxy_bearer().is_some(),+ ))+ .layer(DefaultBodyLimit::max(MAX_BODY_BYTES))+ .layer(axum::middleware::from_fn_with_state(auth, require_bearer))+}+/// Can a trusted proxy actually assert identities on this server?////// The MCP admin gates read this to know that distinct operators are in play@@ -1493,15 +1507,14 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {);let auth_state = Arc::new(auth_state);let auth_enabled = auth_state.enabled();- let machine = axum::Router::new()- .nest_service("/mcp", mcp_service)- .merge(hooks)- .merge(workstreams)- .layer(DefaultBodyLimit::max(MAX_BODY_BYTES))- .layer(axum::middleware::from_fn_with_state(- auth_state.clone(),- require_bearer,- ));+ let machine = mount_machine_routes(+ axum::Router::new()+ .nest_service("/mcp", mcp_service)+ .merge(hooks)+ .merge(workstreams),+ store.reader.clone(),+ auth_state.clone(),+ );let admin = admin.layer(DefaultBodyLimit::max(BOOTSTRAP_MAX_BODY_BYTES)).layer(axum::middleware::from_fn_with_state(@@ -4377,6 +4390,103 @@ mod tests {assert!(validate_existing_users_auth(true, false, true, &auth).is_ok());}+ #[tokio::test]+ async fn machine_identity_remains_authenticated_with_web_disabled_and_expired_keys() {+ use ai_memory_core::{ApiCredentialId, NewUser, UserRole};+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let web = split_web_routers(+ false,+ store.reader.clone(),+ wiki,+ WebMountSpec {+ web_ui_dir: None,+ cors_origins: &[],+ web_slug: "/web",+ base_href: "/web/",+ base_path: "",+ trusted_proxy_identity: false,+ },+ )+ .unwrap();+ let pepper = ai_memory_store::TokenPepper::new("identity-mount-test");+ let user = store+ .writer+ .create_human_user(+ NewUser {+ username: "alice".into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ let id = ApiCredentialId::new();+ store+ .writer+ .create_api_credential(+ id,+ user,+ "test".into(),+ ai_memory_store::hash_token("expired-test-token", &pepper),+ None,+ )+ .await+ .unwrap();+ let auth = Arc::new(+ AuthState::new(Some("root-test-token".into())).with_multiuser(+ pepper,+ store.reader.clone(),+ store.writer.clone(),+ ),+ );+ let app = mount_machine_routes(axum::Router::new(), store.reader.clone(), auth)+ .merge(web.protected)+ .merge(web.public);+ for (token, status) in [+ (None, StatusCode::UNAUTHORIZED),+ (Some("invalid-test-token"), StatusCode::UNAUTHORIZED),+ (Some("root-test-token"), StatusCode::OK),+ (Some("expired-test-token"), StatusCode::OK),+ ] {+ let mut request = Request::builder().uri("/identity");+ if let Some(token) = token {+ request = request.header("authorization", format!("Bearer {token}"));+ }+ assert_eq!(+ app.clone()+ .oneshot(request.body(Body::empty()).unwrap())+ .await+ .unwrap()+ .status(),+ status+ );+ }+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();+ conn.execute(+ "UPDATE api_credentials SET expires_at = 1 WHERE id = ?1",+ [id.as_bytes()],+ )+ .unwrap();+ assert_eq!(+ app.oneshot(+ Request::builder()+ .uri("/identity")+ .header("authorization", "Bearer expired-test-token")+ .body(Body::empty())+ .unwrap()+ )+ .await+ .unwrap()+ .status(),+ StatusCode::UNAUTHORIZED+ );+ }+#[tokio::test]async fn web_routes_are_inside_auth_layer() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 71e57798..7a7a1ecb 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -631,6 +631,7 @@ pub struct RuntimeEnv {scope_cwd: Option<String>,ignore_marker: bool,project_strategy: Option<String>,+ capture_owner_active: bool,claude_code_session_id: Option<String>,anthropic_api_key: Option<SecretString>,anthropic_oauth_token: Option<SecretString>,@@ -673,6 +674,8 @@ impl RuntimeEnv {// --project-strategy` bakes into the generated hook commands.// Consulted only when a marker does not pin one.project_strategy: env_string("AI_MEMORY_PROJECT_STRATEGY"),+ capture_owner_active: env_string("AI_MEMORY_CAPTURE_OWNER")+ .is_some_and(|value| !value.trim().is_empty()),claude_code_session_id: env_string("CLAUDE_CODE_SESSION_ID"),anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),// CLAUDE_CODE_OAUTH_TOKEN is what `claude setup-token` writes;@@ -731,6 +734,12 @@ impl RuntimeEnv {self.project_strategy.as_deref()}+ /// Whether this invocation delegates native capture to an external producer.+ #[must_use]+ pub fn capture_owner_active(&self) -> bool {+ self.capture_owner_active+ }+/// Claude Code lifecycle session id inherited by an stdio MCP subprocess.#[must_use]pub fn claude_code_session_id(&self) -> Option<&str> {diff --git a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs b/crates/ai-memory-cli/tests/suite/doctor_e2e.rsindex 74846569..ca2db8ed 100644--- a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs@@ -144,6 +144,9 @@ mod slow {&base,)).expect("doctor --json report");+ assert_eq!(report["capture_owner_active"], false);+ assert_eq!(report["identity"]["level"], "anonymous");+ assert_eq!(report["identity"]["version"], env!("CARGO_PKG_VERSION"));let claude = find_row(&report, "claude-code").unwrap_or_else(|| panic!("expected a claude-code row: {report}"));@@ -284,6 +287,74 @@ mod slow {"a captured harness must not get an install-hooks nag: {human2}");+ // Backfill uses canonical user events and its own namespace for+ // assistant events. Mixed provenance alone does not mean duplication.+ assert_eq!(claude2["mixed_capture_sessions"], 1);+ let diagnostic_session = "doctor-native-external-control";+ let native_ack: Value = client.post(format!("{base}/hook/batch"))+ .json(&json!([{+ "url": format!("/hook?event=user-prompt-submit&agent=claude-code&workspace={WORKSPACE}&project={PROJECT}&ingest_key=doctor-native-prompt-1"),+ "body": {"session_id":diagnostic_session,"cwd":cwd,"prompt":"Native capture control"}+ }]))+ .send().await.unwrap().error_for_status().unwrap().json().await.unwrap();+ assert_eq!(native_ack["accepted"], 1);+ let ack: Value = client.post(format!("{base}/hook/batch"))+ .json(&json!([{+ "url": format!("/hook?event=user-prompt-submit&agent=claude-code&workspace={WORKSPACE}&project={PROJECT}&extension=example.runtime&source_event=user-prompt-submit&ingest_key=doctor-external-prompt-1"),+ "body": {"session_id":diagnostic_session,"cwd":cwd,"prompt":"External capture control"}+ }]))+ .send().await.unwrap().error_for_status().unwrap().json().await.unwrap();+ assert_eq!(ack["accepted"], 1);++ let output = hermetic(BIN)+ .args([+ "doctor",+ "--workspace",+ WORKSPACE,+ "--project",+ PROJECT,+ "--since-days",+ "0",+ "--json",+ ])+ .env("AI_MEMORY_DATA_DIR", data_dir.path())+ .env("AI_MEMORY_HOME", home.path())+ .env("AI_MEMORY_SERVER_URL", &base)+ .env("AI_MEMORY_CAPTURE_OWNER", "example.runtime")+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .current_dir(&cwd)+ .output()+ .unwrap();+ assert!(output.status.success(), "{output:?}");+ let mixed: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(mixed["capture_owner_active"], true);+ assert_eq!(+ find_row(&mixed, "claude-code").unwrap()["mixed_capture_sessions"],+ 2+ );+ assert!(!String::from_utf8_lossy(&output.stdout).contains("example.runtime"));++ let human3 = run_cli(+ &[+ "doctor",+ "--workspace",+ WORKSPACE,+ "--project",+ PROJECT,+ "--since-days",+ "0",+ ],+ data_dir.path(),+ home.path(),+ Some(&cwd),+ &base,+ );+ assert!(human3.contains("multiple capture sources"), "{human3}");+ assert!(+ human3.contains("does not prove duplicate capture"),+ "{human3}"+ );+drop(server);}}diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 71f2b2d1..401a5048 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -9278,8 +9278,8 @@ mod tests {assert_eq!(json["by_agent"],serde_json::json!([- { "agent": "claude-code", "sessions": 2 },- { "agent": "cursor", "sessions": 1 },+ { "agent": "claude-code", "sessions": 2, "mixed_capture_sessions": 0 },+ { "agent": "cursor", "sessions": 1, "mixed_capture_sessions": 0 },]),"counts are per agent, scoped, count-desc: {json}");@@ -9306,8 +9306,8 @@ mod tests {assert_eq!(json["by_agent"],serde_json::json!([- { "agent": "claude-code", "sessions": 3 },- { "agent": "cursor", "sessions": 1 },+ { "agent": "claude-code", "sessions": 3, "mixed_capture_sessions": 0 },+ { "agent": "cursor", "sessions": 1, "mixed_capture_sessions": 0 },]),"named callers see own plus shared sessions only: {json}");@@ -9334,9 +9334,9 @@ mod tests {assert_eq!(json["by_agent"],serde_json::json!([- { "agent": "claude-code", "sessions": 3 },- { "agent": "codex", "sessions": 1 },- { "agent": "cursor", "sessions": 1 },+ { "agent": "claude-code", "sessions": 3, "mixed_capture_sessions": 0 },+ { "agent": "codex", "sessions": 1, "mixed_capture_sessions": 0 },+ { "agent": "cursor", "sessions": 1, "mixed_capture_sessions": 0 },]),"all_owners includes every operator: {json}");diff --git a/crates/ai-memory-mcp/src/identity.rs b/crates/ai-memory-mcp/src/identity.rsnew file mode 100644index 00000000..13965418--- /dev/null+++ b/crates/ai-memory-mcp/src/identity.rs@@ -0,0 +1,221 @@+//! Machine identity introspection, mounted behind the machine auth middleware.++use std::sync::Arc;++use ai_memory_core::{ActorContext, AuthLevel, Capability};+use ai_memory_store::ReaderPool;+use axum::{+ Extension, Json, Router,+ extract::State,+ http::{StatusCode, header},+ response::{IntoResponse, Response},+ routing::get,+};+use serde::Serialize;++#[derive(Clone)]+struct IdentityState {+ reader: ReaderPool,+ trusted_proxy_identity: bool,+}++/// Build the always-mounted machine identity router.+/// The caller must apply `require_bearer`, just as for MCP and hooks.+pub fn router(reader: ReaderPool, trusted_proxy_identity: bool) -> Router {+ Router::new()+ .route("/identity", get(identity))+ .with_state(Arc::new(IdentityState {+ reader,+ trusted_proxy_identity,+ }))+}++#[derive(Serialize)]+struct IdentityResponse {+ version: &'static str,+ level: &'static str,+ operator: Option<String>,+ distinguishes_operators: bool,+}++async fn identity(+ State(state): State<Arc<IdentityState>>,+ Extension(level): Extension<AuthLevel>,+ Extension(actor): Extension<ActorContext>,+) -> Result<Response, StatusCode> {+ let distinguishes_operators = state+ .reader+ .distinguishes_operators(state.trusted_proxy_identity)+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ level+ .authorize(Capability::NormalRead, distinguishes_operators)+ .map_err(|_| StatusCode::FORBIDDEN)?;+ let body = IdentityResponse {+ version: env!("CARGO_PKG_VERSION"),+ level: match level {+ AuthLevel::Anonymous => "anonymous",+ AuthLevel::User => "user",+ AuthLevel::Root => "root",+ },+ operator: actor.identity_key().map(|key| key.storage_key()),+ distinguishes_operators,+ };+ Ok(([(header::CACHE_CONTROL, "private, no-store")], Json(body)).into_response())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::auth::{AuthState, require_bearer};+ use ai_memory_core::{ApiCredentialId, NewUser, UserRole};+ use ai_memory_store::{Store, TokenPepper};+ use axum::{body::Body, http::Request};+ use tower::ServiceExt;++ async fn ask(app: Router, token: Option<&str>) -> Response {+ let mut req = Request::builder()+ .uri("/identity")+ .header("x-memory-actor-user", "forged");+ if let Some(token) = token {+ req = req.header("authorization", format!("Bearer {token}"));+ }+ app.oneshot(req.body(Body::empty()).unwrap()).await.unwrap()+ }++ #[tokio::test]+ async fn identity_real_auth_isolates_users_root_and_revoked_keys() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let pepper = TokenPepper::new("identity-test");+ let state = AuthState::new(Some("root-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root".into()),+ ..ActorContext::default()+ })+ .with_multiuser(pepper.clone(), store.reader.clone(), store.writer.clone());+ let app = router(store.reader.clone(), false).layer(axum::middleware::from_fn_with_state(+ Arc::new(state),+ require_bearer,+ ));+ let mut credentials = Vec::new();+ for name in ["alice", "bob"] {+ let user = store+ .writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ let id = ApiCredentialId::new();+ let token = format!("identity-{name}-token");+ store+ .writer+ .create_api_credential(+ id,+ user,+ "test".into(),+ ai_memory_store::hash_token(&token, &pepper),+ None,+ )+ .await+ .unwrap();+ credentials.push((id, token));+ }+ for (token, level, name) in [+ (credentials[0].1.as_str(), "user", "alice"),+ (credentials[1].1.as_str(), "user", "bob"),+ ("root-token", "root", "root"),+ ] {+ let response = ask(app.clone(), Some(token)).await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ response.headers()[header::CACHE_CONTROL],+ "private, no-store"+ );+ let bytes = axum::body::to_bytes(response.into_body(), 4096)+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(body["level"], level);+ assert_eq!(+ body["operator"],+ ai_memory_core::IdentityKey::User(name.into()).storage_key()+ );+ assert_eq!(body["distinguishes_operators"], true);+ assert_eq!(body.as_object().unwrap().len(), 4);+ }+ assert_eq!(+ ask(app.clone(), None).await.status(),+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ ask(app.clone(), Some("invalid")).await.status(),+ StatusCode::UNAUTHORIZED+ );+ store+ .writer+ .revoke_api_credential(credentials[0].0)+ .await+ .unwrap();+ assert_eq!(+ ask(app, Some(&credentials[0].1)).await.status(),+ StatusCode::UNAUTHORIZED+ );+ }++ #[tokio::test]+ async fn identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let app = router(store.reader.clone(), false).layer(axum::middleware::from_fn_with_state(+ Arc::new(AuthState::new(None)),+ require_bearer,+ ));+ let response = ask(app, None).await;+ let bytes = axum::body::to_bytes(response.into_body(), 4096)+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(body["level"], "anonymous");+ assert!(body["operator"].is_null());+ assert_eq!(body["distinguishes_operators"], false);+ let app = router(store.reader.clone(), true).layer(axum::middleware::from_fn_with_state(+ Arc::new(AuthState::new(Some("root".into())).with_trusted_proxy_bearer("proxy")),+ require_bearer,+ ));+ let response = app+ .oneshot(+ Request::builder()+ .uri("/identity")+ .header("authorization", "Bearer proxy")+ .header("x-memory-actor-issuer", "https://issuer.example")+ .header("x-memory-actor-sub", "alice")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), 4096)+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(+ body["operator"],+ ai_memory_core::IdentityKey::Subject {+ issuer: "https://issuer.example".into(),+ subject: "alice".into()+ }+ .storage_key()+ );+ assert_eq!(body["distinguishes_operators"], true);+ }+}diff --git a/crates/ai-memory-mcp/src/lib.rs b/crates/ai-memory-mcp/src/lib.rsindex e733be2e..915c4cb0 100644--- a/crates/ai-memory-mcp/src/lib.rs+++ b/crates/ai-memory-mcp/src/lib.rs@@ -12,6 +12,7 @@ pub mod actor;pub mod admin;pub mod auth;pub mod human_auth;+pub mod identity;mod server;pub use actor::actor_from_headers;diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 40136c20..ce2e64e3 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -882,6 +882,8 @@ pub struct AgentSessionCount {pub agent: String,/// Sessions this agent opened in the window, ended or still open.pub sessions: u64,+ /// Sessions with multiple admitted capture namespaces in this scope.+ pub mixed_capture_sessions: u64,}/// How a `SessionEnd` event should treat its target session — see@@ -3164,7 +3166,12 @@ impl ReaderPool {""};let sql = format!(- "SELECT agent_kind, COUNT(*) AS n FROM sessions \+ "SELECT agent_kind, COUNT(*) AS n, \+ SUM((SELECT COUNT(DISTINCT CASE WHEN o.extension IS NULL \+ THEN 'native' ELSE 'extension:' || o.extension END) \+ FROM observations o WHERE o.session_id = sessions.id \+ AND o.workspace_id = :ws AND o.project_id = :proj) > 1) \+ FROM sessions \WHERE workspace_id = :ws AND project_id = :proj\{since_clause}{owner_clause} \GROUP BY agent_kind \@@ -3186,14 +3193,15 @@ impl ReaderPool {let rows = stmt.query_map(named.as_slice(), |row| {let agent: String = row.get(0)?;let n: i64 = row.get(1)?;- Ok((agent, n))+ Ok((agent, n, row.get::<_, i64>(2)?))})?;let mut out = Vec::new();for row in rows {- let (agent, n) = row?;+ let (agent, n, mixed) = row?;out.push(AgentSessionCount {agent,sessions: u64::try_from(n).unwrap_or(0),+ mixed_capture_sessions: u64::try_from(mixed).unwrap_or(0),});}Ok(out)diff --git a/crates/ai-memory-store/tests/suite/session_observations.rs b/crates/ai-memory-store/tests/suite/session_observations.rsindex 8a13f3ff..11322273 100644--- a/crates/ai-memory-store/tests/suite/session_observations.rs+++ b/crates/ai-memory-store/tests/suite/session_observations.rs@@ -566,3 +566,68 @@ async fn session_summary_scoped_narrows_the_listing_predicates() {"unknown id",);}++#[tokio::test]+async fn mixed_capture_count_scopes_observations_and_preserves_owner_and_window() {+ let (_tmp, store) = open_seeded();+ let conn = Connection::open(store.db_path()).unwrap();+ conn.execute(+ "UPDATE observations SET extension = 'external' WHERE id = ?1",+ params![&id(23)[..]],+ )+ .unwrap();+ conn.execute(+ "UPDATE observations SET extension = 'external' WHERE id = ?1",+ params![&id(25)[..]],+ )+ .unwrap();+ // Session 10 has native rows in A and external only in B: neither is mixed.+ let counts = store+ .reader+ .session_counts_by_agent(ws(), proj_a(), OwnerFilter::Any, None)+ .await+ .unwrap();+ assert!(counts.iter().all(|count| count.mixed_capture_sessions == 0));+ conn.execute(+ "UPDATE observations SET extension = 'external' WHERE id = ?1",+ params![&id(22)[..]],+ )+ .unwrap();+ let counts = store+ .reader+ .session_counts_by_agent(ws(), proj_a(), OwnerFilter::Any, None)+ .await+ .unwrap();+ assert_eq!(+ counts+ .iter()+ .find(|c| c.agent == "claude-code")+ .unwrap()+ .mixed_capture_sessions,+ 1+ );+ // Alice's B session has native only there. A's extension cannot mix it.+ let counts = store+ .reader+ .session_counts_by_agent(ws(), proj_b(), filter_for("alice"), None)+ .await+ .unwrap();+ assert_eq!(counts.len(), 1);+ assert_eq!(counts[0].mixed_capture_sessions, 0);+ assert!(+ store+ .reader+ .session_counts_by_agent(ws(), proj_b(), filter_for("bob"), None)+ .await+ .unwrap()+ .is_empty()+ );+ assert!(+ store+ .reader+ .session_counts_by_agent(ws(), proj_a(), OwnerFilter::Any, Some(NOW + 1000))+ .await+ .unwrap()+ .is_empty()+ );+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 05fd1c36..eb03cff9 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -250,6 +250,12 @@ 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.+`GET /identity` is a machine-authenticated route mounted independently of the+web UI. `ai-memory doctor` uses it to show caller identity and capture ownership;+its per-agent counts flag sessions with multiple capture sources (native events+or distinct extensions, including backfill).+The mixed-source count is computed in the same scoped, owner-filtered SQL query.+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/external-lifecycle.md b/docs/external-lifecycle.mdindex b085d80b..eae46acc 100644--- a/docs/external-lifecycle.md+++ b/docs/external-lifecycle.md@@ -53,6 +53,12 @@ installed ai-memory integrations; it must manage finer capture ownership itself.`admits_capture: false` when this context is active. It performs no ingestion orhandoff delivery. The producer namespace itself is not printed or authenticated.+`ai-memory doctor` reports whether this invocation delegates native capture and+shows its authenticated machine identity. Its per-agent counts flag sessions+with multiple capture sources (native events or distinct extensions, including+backfill). An older server leaves those+fields unknown; a mixed count is a diagnostic signal, not proof of duplicates.+## Reuse the public event contractFor a live harness, send its actual wire `agent` (such as `claude-code` or `codex`)diff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex d803d403..691058ac 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -29,7 +29,7 @@Bearer fails closed rather than falling back. Before human auth activates,deprecated Basic/cookie compatibility is evaluated for GET requests; afteractivation, Basic and unknown schemes do not suppress a valid web session.-- `/mcp`, hooks, handoffs, and workstream routes are machine-only. A web-session+- `/mcp`, `/identity`, hooks, handoffs, and workstream routes are machine-only. A web-sessioncookie cannot authenticate them.- A disallowed `Host` header receives `403 Forbidden` before auth evaluation(DNS-rebinding guard).@@ -69,6 +69,18 @@ HTTP Basic and an HttpOnly `ai_memory_auth` cookie. Human activation disablesthat path immediately. See [`docs/users.md`](users.md) for bootstrap, passwordrotation, recovery, roles, session expiry, and API-key lifecycle.+Machine clients can call `GET /identity` with their bearer key, even when the+web UI is disabled. It reports only the authenticated caller and server version:++```json+{"version":"2.5.2","level":"user","operator":"user:alice","distinguishes_operators":true}+```++`level` is `root`, `user` or `anonymous`; `operator` is the qualified identity+key, or `null` on an unauthenticated single-user server. Web-session cookies+cannot authenticate this route. Its response uses `Cache-Control: private,+no-store`. See [users.md](users.md) for machine keys and identity types.+## 3. Error modelAll errors return a JSON body of shape:diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 9027f977..93ae0131 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -22,10 +22,10 @@ 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` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can) | 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 |+| 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`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP | `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`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control) | STRONG || 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed) | STRONG || 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff` | 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 |@@ -55,7 +55,7 @@ boundary not yet built.| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | STRONG || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH || 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |-| 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 |+| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled) | 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 |