Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: validate native workstream identities before binding
Éverton Toffanettof36f33638ee3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5b221e33..9d355a0e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -118,6 +118,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0older servers leave unsupported fields unknown. (#1016)### Changed+- Required new managed native-session bindings and imports to preserve the+ exact original identity within 512 UTF-8 bytes and pass privacy validation+ before use or persistence. Invalid historical identities were projected as+ unknown (`native_session_id: ""`) in workstream search without rewriting+ stored history; the CLI also protected reads from older servers. (#987)- Required managed-run finish imports and finished retries to pass anauthenticated owner check and current project access checks, repeated in thewriter transaction. Database users required current Write access; trusteddiff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 6c4a9619..1f81cdf8 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -8,8 +8,8 @@ use std::time::{Duration, SystemTime};use ai_memory_core::{AgentKind, FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,- ManagedRunContextResponse, ManagedRunStatus, PrepareManagedRunRequest,- PrepareManagedRunResponse, SessionId,+ ManagedRunContextResponse, ManagedRunStatus, NativeSessionIdentity, PrepareManagedRunRequest,+ PrepareManagedRunResponse, Sanitizer, SessionId,};use ai_memory_workstream::{AmbiguousNativeSession, ExportedTranscript, FORWARDED_ENV_NAMES, JailChecklistItem,@@ -476,6 +476,10 @@ async fn run_once_with_wiring("managed run interrupted before the agent started")));}+ let privacy = acquired_try!(Sanitizer::new(&config.sanitize).map_err(anyhow::Error::from));+ if let Some(id) = prepared.native_session_id.as_deref() {+ acquired_try!(NativeSessionIdentity::parse(id, &privacy).map_err(anyhow::Error::from));+ }let resolved_harness = if automatic_harness {let resolved = prepared.resolved_agent.unwrap_or_else(|| {eprintln!(@@ -658,6 +662,13 @@ async fn run_once_with_wiring(if yolo_modes.claude_true_yolo && harness == ManagedHarness::Claude {apply_claude_true_yolo(harness, &mut plan.args);}+ let planned_native_identity = acquired_try!(+ plan.expected_session_id+ .as_deref()+ .map(|id| NativeSessionIdentity::parse(id, &privacy))+ .transpose()+ .map_err(anyhow::Error::from)+ );let remove_kiro_home = if harness == ManagedHarness::KiroV3&& let Some(native_session_id) = plan.expected_session_id.as_deref(){@@ -710,14 +721,14 @@ async fn run_once_with_wiring();}if plan.mode == LaunchMode::Session- && let Some(native_session_id) = &plan.expected_session_id+ && let Some(native_identity) = &planned_native_identity{acquired_try!(post_json_no_content(&endpoint,&format!("{run_path}/link"),&LinkManagedRunRequest {- native_session_id: native_session_id.clone(),+ native_session_id: native_identity.as_str().to_owned(),},).await@@ -868,6 +879,7 @@ async fn run_once_with_wiring(&home,&repository.cwd,server_status.as_ref(),+ &privacy,) {Ok(own) => own,Err(error) => {@@ -897,6 +909,7 @@ async fn run_once_with_wiring(&repository.cwd,started_at,server_status.as_ref(),+ &privacy,).await);@@ -929,6 +942,7 @@ async fn run_once_with_wiring(transcript,checkpoint,Some(exit_code),+ &privacy,).await);@@ -1584,12 +1598,15 @@ fn own_native_session(home: &Path,cwd: &Path,server_status: Option<&ManagedRunStatus>,+ sanitizer: &Sanitizer,) -> Result<Option<String>> {if plan.mode == LaunchMode::Passthrough {return Ok(None);}if let Some(native_session_id) = &plan.expected_session_id {- return Ok(Some(native_session_id.clone()));+ return Ok(Some(+ NativeSessionIdentity::parse(native_session_id, sanitizer)?.into_string(),+ ));}let Some(linked) = server_status.filter(|status| status.native_session_linked)@@ -1597,12 +1614,15 @@ fn own_native_session(else {return Ok(None);};+ let linked = NativeSessionIdentity::parse(linked, sanitizer)?;+ let linked = linked.as_str();let in_checkout =native_session_in_checkout(harness, home, cwd, plan.session_dir.as_deref(), linked).with_context(|| format!("reading native session {linked}"))?;Ok(in_checkout.then(|| linked.to_string()))}+#[allow(clippy::too_many_arguments)]async fn resolve_native_session_after_run(plan: &LaunchPlan,harness: ManagedHarness,@@ -1610,11 +1630,15 @@ async fn resolve_native_session_after_run(cwd: &Path,started_at: SystemTime,server_status: Option<&ManagedRunStatus>,+ sanitizer: &Sanitizer,) -> Result<Option<String>> {if plan.mode == LaunchMode::Passthrough {return Ok(None);}- if let Ok(Some(own)) = own_native_session(plan, harness, home, cwd, server_status) {+ if let Some(id) = server_status.and_then(|status| status.native_session_id.as_deref()) {+ NativeSessionIdentity::parse(id, sanitizer)?;+ }+ if let Ok(Some(own)) = own_native_session(plan, harness, home, cwd, server_status, sanitizer) {return Ok(Some(own));}let linked = server_status@@ -1644,11 +1668,17 @@ async fn resolve_native_session_after_run(};// A linked session `own_native_session` rejected (not in this checkout,// or its native store could not be read) is no fallback either.- Ok(discovered.or_else(|| {+ let resolved = discovered.or_else(|| {server_status.and_then(|status| status.native_session_id.clone()).filter(|reported| Some(reported.as_str()) != linked)- }))+ });+ Ok(resolved+ .as_deref()+ .map(|id| {+ NativeSessionIdentity::parse(id, sanitizer).map(NativeSessionIdentity::into_string)+ })+ .transpose()?)}async fn list_auto_sessions(home: &Path, cwd: &Path) -> Result<Vec<AutoSessionCandidate>> {@@ -1976,6 +2006,9 @@ fn build_preflighted_launch_plan(cwd: &Path,env_overrides: &[(String, String)],) -> Result<(LaunchPlan, Option<String>)> {+ if let Some(id) = linked_session_id {+ NativeSessionIdentity::parse(id, &Sanitizer::builtin())?;+ }let explicit_selector = has_native_session_selector(harness, &native_args);if force_fresh && explicit_selector {return Err(anyhow!(@@ -2464,13 +2497,20 @@ async fn import_batches(transcript: ExportedTranscript,checkpoint: ai_memory_core::WorkstreamCheckpoint,exit_code: Option<i32>,+ sanitizer: &Sanitizer,) -> Result<usize> {+ let native_identity = nonempty_session(&transcript.native_session_id)+ .map(|id| NativeSessionIdentity::parse(&id, sanitizer))+ .transpose()?;+ for event in &transcript.events {+ NativeSessionIdentity::parse(&event.native_session_id, sanitizer)?;+ }let mut imported = 0;let mut batches = event_batches(transcript.events).into_iter().peekable();while let Some(batch) = batches.next() {let complete = batches.peek().is_none();let request = FinishManagedRunRequest {- native_session_id: nonempty_session(&transcript.native_session_id),+ native_session_id: native_identity.as_ref().map(|id| id.as_str().to_owned()),source_cursor: complete.then(|| transcript.source_cursor.clone()).flatten(),events: batch,complete,@@ -4895,7 +4935,8 @@ mod tests {ManagedHarness::Codex,temp.path(),&cwd,- Some(&status)+ Some(&status),+ &Sanitizer::builtin(),).unwrap().as_deref(),@@ -4910,6 +4951,7 @@ mod tests {&cwd,started_at,Some(&status),+ &Sanitizer::builtin(),).await.unwrap()@@ -4932,6 +4974,7 @@ mod tests {&empty,started_at,Some(&status),+ &Sanitizer::builtin(),).await.unwrap()@@ -4983,6 +5026,7 @@ mod tests {&cwd,started_at,None,+ &Sanitizer::builtin(),).await.unwrap()@@ -4999,6 +5043,7 @@ mod tests {&cwd,started_at,None,+ &Sanitizer::builtin(),).await.unwrap()@@ -5065,6 +5110,7 @@ mod tests {&cwd,started_at,Some(&status),+ &Sanitizer::builtin(),).await.unwrap()@@ -6046,4 +6092,468 @@ mod tests {drop(seen);server.abort();}++ #[test]+ fn native_identity_run_preflight_refuses_before_resume_or_private_path() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let home = tempfile::tempdir().unwrap();+ for id in [+ "sk-abcdefghijklmnopqrstuvwx",+ "native\u{202e}tail",+ "native\u{200b}tail",+ ] {+ let result = build_preflighted_launch_plan(+ ManagedHarness::Codex,+ None,+ Vec::new(),+ Some(id),+ false,+ home.path(),+ home.path(),+ &[],+ );+ assert!(+ result.is_err(),+ "dirty server identity must be refused before resume"+ );+ assert!(!format!("{:#}", result.unwrap_err()).contains(id));+ }+ assert!(+ build_preflighted_launch_plan(+ ManagedHarness::Claude,+ None,+ Vec::new(),+ Some("sk-abcdefghijklmnopqrstuvwx"),+ true,+ home.path(),+ home.path(),+ &[]+ )+ .is_err(),+ "fresh mode must validate the original prepared identity before discarding it"+ );+ let (plan, _) = build_preflighted_launch_plan(+ ManagedHarness::Claude,+ None,+ Vec::new(),+ None,+ false,+ home.path(),+ home.path(),+ &[],+ )+ .unwrap();+ assert!(uuid::Uuid::parse_str(plan.expected_session_id.as_deref().unwrap()).is_ok());+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn native_identity_run_old_server_refusal_prevents_child_and_transport() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let (address, server) = mock_workstream_server(Some("private-vendor")).await;+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "AI_MEMORY_MANAGED_RUN");+ let mut config = launch_config(home.path(), data.path(), address);+ config.run_autowire = false;+ config.sanitize.extra_patterns.push("private-vendor".into());+ let result = run_from(+ &config,+ run_args(RunHarnessChoice::Claude, script, Vec::new(), &[]),+ repo.path(),+ )+ .await;+ assert!(+ result.is_err(),+ "old server dirty identity must refuse the actual launch"+ );+ assert!(!captured.exists(), "child must not start");+ assert!(!format!("{:#}", result.unwrap_err()).contains("private-vendor"));+ server.abort();+ }+ #[tokio::test]+ async fn native_identity_finish_transport_refuses_before_request_and_preserves_exact_control() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let requests = Arc::new(std::sync::Mutex::new(Vec::<FinishManagedRunRequest>::new()));+ let captured = requests.clone();+ let app = Router::new().route(+ "/workstream/runs/{id}/finish",+ post(+ move |axum::Json(request): axum::Json<FinishManagedRunRequest>| {+ let captured = captured.clone();+ async move {+ captured.lock().unwrap().push(request);+ axum::Json(FinishManagedRunResponse {+ imported_events: 1,+ latest_sequence: 1,+ })+ }+ },+ ),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let home = tempfile::tempdir().unwrap();+ let config = launch_config(home.path(), home.path(), address);+ let endpoint = ServerEndpoint::from_config_resolving_auth(&config).await;+ let sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-vendor".into()],+ ..Default::default()+ })+ .unwrap();+ let transcript = |id: &str| ExportedTranscript {+ native_session_id: id.into(),+ source_cursor: Some("cursor".into()),+ events: Vec::new(),+ losses: Vec::new(),+ };+ for bad in ["sk-abcdefghijklmnopqrstuvwx", "private-vendor"] {+ assert!(+ import_batches(+ &endpoint,+ "/workstream/runs/test",+ transcript(bad),+ Default::default(),+ Some(0),+ &sanitizer,+ )+ .await+ .is_err(),+ "dirty finish identity must not reach transport"+ );+ assert!(requests.lock().unwrap().is_empty());+ let mut with_event = transcript("vendor-界-01");+ with_event.events.push(ai_memory_core::NewWorkstreamEvent {+ event_id: "e".into(),+ agent: AgentKind::Codex,+ native_session_id: bad.into(),+ source_record_id: None,+ kind: ai_memory_core::WorkstreamEventKind::Message,+ role: None,+ content: "shared history".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ });+ assert!(+ import_batches(+ &endpoint,+ "/workstream/runs/test",+ with_event,+ Default::default(),+ Some(0),+ &sanitizer,+ )+ .await+ .is_err(),+ "dirty event identity must not reach transport"+ );+ assert!(requests.lock().unwrap().is_empty());+ }+ assert_eq!(+ import_batches(+ &endpoint,+ "/workstream/runs/test",+ transcript("vendor-界-01"),+ Default::default(),+ Some(0),+ &sanitizer,+ )+ .await+ .unwrap(),+ 1+ );+ assert_eq!(+ requests.lock().unwrap()[0].native_session_id.as_deref(),+ Some("vendor-界-01")+ );+ assert_eq!(+ requests.lock().unwrap()[0].source_cursor.as_deref(),+ Some("cursor")+ );+ server.abort();+ }++ #[tokio::test]+ async fn native_identity_run_status_and_expected_refuse_before_discovery() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let home = tempfile::tempdir().unwrap();+ let mut plan = build_launch_plan(ManagedHarness::Codex, None, Vec::new(), None).unwrap();+ plan.session_dir = None;+ let sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-vendor".into()],+ ..Default::default()+ })+ .unwrap();+ for bad in ["sk-abcdefghijklmnopqrstuvwx", "private-vendor"] {+ plan.expected_session_id = Some(bad.into());+ assert!(+ own_native_session(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ None,+ &sanitizer+ )+ .is_err(),+ "expected identity must refuse before use"+ );+ plan.expected_session_id = None;+ let status = ManagedRunStatus {+ run_id: ManagedRunId::new(),+ workstream_id: WorkstreamId::new(),+ agent: AgentKind::Codex,+ native_session_id: Some(bad.into()),+ native_session_linked: true,+ context_delivered: false,+ state: "active".into(),+ };+ assert!(+ own_native_session(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ Some(&status),+ &sanitizer,+ )+ .is_err(),+ "linked status must refuse before native IO"+ );+ assert!(+ resolve_native_session_after_run(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ SystemTime::now(),+ Some(&status),+ &sanitizer,+ )+ .await+ .is_err(),+ "dirty old-server status must not fall back to discovery"+ );+ plan.expected_session_id = Some("vendor-界-01".into());+ assert_eq!(+ own_native_session(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ None,+ &sanitizer+ )+ .unwrap()+ .as_deref(),+ Some("vendor-界-01")+ );+ }+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn native_identity_run_configured_selector_refuses_before_link_or_child() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let (address, server) = mock_workstream_server(None).await;+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "AI_MEMORY_MANAGED_RUN");+ let mut config = launch_config(home.path(), data.path(), address);+ config.run_autowire = false;+ config.sanitize.extra_patterns.push("private-vendor".into());+ let result = run_from(+ &config,+ run_args(+ RunHarnessChoice::Claude,+ script,+ Vec::new(),+ &["--session-id", "private-vendor"],+ ),+ repo.path(),+ )+ .await;+ assert!(+ result.is_err(),+ "configured selector must refuse before link and spawn"+ );+ assert!(!captured.exists());+ assert!(!format!("{:#}", result.unwrap_err()).contains("private-vendor"));+ server.abort();+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn native_identity_run_configured_old_status_refuses_before_native_io_and_finish() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ for id in ["private-vendor", "vendor-界-01"] {+ let finishes = Arc::new(std::sync::Mutex::new(Vec::<FinishManagedRunRequest>::new()));+ let captured_finishes = finishes.clone();+ let app = Router::new()+ .route(+ "/workstream/runs",+ post(|| async {+ axum::Json(PrepareManagedRunResponse {+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: None,+ native_session_id: None,+ source_cursor: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,+ })+ }),+ )+ .route(+ "/workstream/runs/{id}",+ axum::routing::get(move || async move {+ axum::Json(ManagedRunStatus {+ run_id: ManagedRunId::new(),+ workstream_id: WorkstreamId::new(),+ agent: AgentKind::Codex,+ native_session_id: Some(id.into()),+ native_session_linked: false,+ context_delivered: false,+ state: "active".into(),+ })+ }),+ )+ .route(+ "/workstream/runs/{id}/finish",+ post(+ move |axum::Json(request): axum::Json<FinishManagedRunRequest>| {+ let captured_finishes = captured_finishes.clone();+ async move {+ captured_finishes.lock().unwrap().push(request);+ axum::Json(FinishManagedRunResponse {+ imported_events: 0,+ latest_sequence: 0,+ })+ }+ },+ ),+ )+ .route(+ "/workstream/runs/{id}/cancel",+ post(|| async { StatusCode::NO_CONTENT }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let home = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, child_capture) = capture_env_script(repo.path(), "AI_MEMORY_MANAGED_RUN");+ let mut config = launch_config(home.path(), home.path(), address);+ config.run_autowire = false;+ config.sanitize.extra_patterns.push("private-vendor".into());+ let result = run_from(+ &config,+ run_args(RunHarnessChoice::Codex, script, Vec::new(), &[]),+ repo.path(),+ )+ .await;+ assert!(+ child_capture.exists(),+ "the status is returned after the child exits"+ );+ if id == "private-vendor" {+ assert!(+ result.is_err(),+ "configured old status must refuse before native IO and finish"+ );+ assert!(!format!("{:#}", result.unwrap_err()).contains(id));+ assert!(finishes.lock().unwrap().is_empty());+ } else {+ assert_eq!(result.unwrap(), 0);+ assert_eq!(+ finishes.lock().unwrap()[0].native_session_id.as_deref(),+ Some(id)+ );+ }+ server.abort();+ }+ }++ #[tokio::test]+ async fn native_identity_run_configured_discovery_refuses_before_export() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-vendor".into()],+ ..Default::default()+ })+ .unwrap();+ for id in ["private-vendor", "vendor-界-01"] {+ let home = tempfile::tempdir().unwrap();+ let cwd = home.path().join("repo");+ let root = home.path().join(".codex/sessions/2026/01/01");+ std::fs::create_dir_all(&cwd).unwrap();+ std::fs::create_dir_all(&root).unwrap();+ let started_at = SystemTime::now();+ std::fs::write(+ root.join("rollout-current.jsonl"),+ format!(+ "{}\n",+ serde_json::json!({+ "type": "session_meta", "payload": {"id": id, "cwd": cwd}+ })+ ),+ )+ .unwrap();+ let mut plan =+ build_launch_plan(ManagedHarness::Codex, None, Vec::new(), None).unwrap();+ plan.session_dir = None;+ let result = resolve_native_session_after_run(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ &cwd,+ started_at,+ None,+ &sanitizer,+ )+ .await;+ if id == "private-vendor" {+ assert!(+ result.is_err(),+ "configured discovered identity must refuse before export"+ );+ assert!(!format!("{:#}", result.unwrap_err()).contains(id));+ } else {+ assert_eq!(result.unwrap().as_deref(), Some(id));+ }+ }+ }}diff --git a/crates/ai-memory-cli/src/commands/workstream_search.rs b/crates/ai-memory-cli/src/commands/workstream_search.rsindex 25e7cad7..8b1aef31 100644--- a/crates/ai-memory-cli/src/commands/workstream_search.rs+++ b/crates/ai-memory-cli/src/commands/workstream_search.rs@@ -1,6 +1,6 @@//! Explicit retrieval for history older than a managed startup packet.-use ai_memory_core::WorkstreamEvent;+use ai_memory_core::{NativeSessionIdentity, Sanitizer, WorkstreamEvent};use anyhow::Result;use crate::cli::WorkstreamSearchArgs;@@ -12,12 +12,17 @@ pub async fn run(config: &Config, args: WorkstreamSearchArgs) -> Result<()> {let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;let path = format!("/workstream/{}/events", args.workstream_id);let limit = args.limit.to_string();- let events: Vec<WorkstreamEvent> = get_json(+ let mut events: Vec<WorkstreamEvent> = get_json(&endpoint,&path,&[("q", args.query.as_str()), ("limit", limit.as_str())],).await?;+ let sanitizer = Sanitizer::new(&config.sanitize)?;+ for event in &mut events {+ event.native_session_id =+ NativeSessionIdentity::project(&event.native_session_id, &sanitizer);+ }if args.json {println!("{}", serde_json::to_string_pretty(&events)?);return Ok(());diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 78aac145..a3f3517c 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -31,3 +31,5 @@ mod server_profiles;mod shutdown_signals;mod upgrade_e2e;mod yolo_ai_jail;++mod workstream_identity;diff --git a/crates/ai-memory-cli/tests/suite/workstream_identity.rs b/crates/ai-memory-cli/tests/suite/workstream_identity.rsnew file mode 100644index 00000000..0920135a--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/workstream_identity.rs@@ -0,0 +1,58 @@+//! Privacy projection through the existing CLI search against an older server.++#[tokio::test]+async fn native_identity_search_old_server_json_projects_unknown_and_keeps_history() {+ use axum::{Json, Router, routing::get};+ use serde_json::{Value, json};+ let dirty = "sk-abcdefghijklmnopqrstuvwx";+ let app = Router::new().route("/workstream/{id}/events", get(move || async move {+ Json(json!([+ {"sequence": 1, "event_id": "legacy", "agent": "codex", "native_session_id": dirty, "kind": "message", "content": "shared history"},+ {"sequence": 2, "event_id": "valid", "agent": "codex", "native_session_id": "vendor-界-01", "kind": "message", "content": "shared control"}+ ]))+ }));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let data = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let task_data = data.path().to_owned();+ let task_home = home.path().to_owned();+ let output = tokio::task::spawn_blocking(move || {+ let mut cmd = crate::e2e_support::hermetic(env!("CARGO_BIN_EXE_ai-memory"));+ cmd.env("HOME", &task_home)+ .env("USERPROFILE", &task_home)+ .env("AI_MEMORY_SERVER_URL", format!("http://{address}"))+ .arg("--data-dir")+ .arg(task_data)+ .args([+ "workstream-search",+ "--workstream-id",+ "018f0000-0000-7000-8000-000000000001",+ "--json",+ ]);+ cmd.stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped());+ let child = cmd.spawn().unwrap();+ println!("NATIVE_CLI_PID {}", child.id());+ child.wait_with_output().unwrap()+ })+ .await+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8(output.stdout).unwrap();+ let events: Value = serde_json::from_str(&stdout).unwrap();+ assert_eq!(+ events[0]["native_session_id"], "",+ "CLI JSON must project a dirty old-server identity to UNKNOWN"+ );+ assert!(!stdout.contains(dirty));+ assert_eq!(events[0]["content"], "shared history");+ assert_eq!(events[0]["sequence"], 1);+ assert_eq!(events[1]["native_session_id"], "vendor-界-01");+ server.abort();+}diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex ded98d7f..0b6629bf 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -100,7 +100,8 @@ pub use user::{pub use workstream::{FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,ListManagedWorkstreamsRequest, MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunContextResponse,- ManagedRunStatus, ManagedWorkstreamSummary, NewWorkstreamEvent, PrepareManagedRunRequest,- PrepareManagedRunResponse, RenameManagedWorkstreamRequest, RenamedManagedWorkstream,- UNTRUSTED_MEMORY_NOTICE, WorkstreamCheckpoint, WorkstreamEvent, WorkstreamEventKind,+ ManagedRunStatus, ManagedWorkstreamSummary, NativeSessionIdentity, NewWorkstreamEvent,+ PrepareManagedRunRequest, PrepareManagedRunResponse, RenameManagedWorkstreamRequest,+ RenamedManagedWorkstream, UNTRUSTED_MEMORY_NOTICE, WorkstreamCheckpoint, WorkstreamEvent,+ WorkstreamEventKind,};diff --git a/crates/ai-memory-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rsindex 035de2a4..0ca2ccd3 100644--- a/crates/ai-memory-core/src/workstream.rs+++ b/crates/ai-memory-core/src/workstream.rs@@ -72,6 +72,57 @@ impl std::str::FromStr for WorkstreamEventKind {}}+/// Exact original native identity accepted for a managed binding.+///+/// This validates privacy and representation only, not native authenticity,+/// transcript existence, or association with a particular run.+#[derive(Clone, PartialEq, Eq)]+pub struct NativeSessionIdentity(String);++impl NativeSessionIdentity {+ /// Validate the original UTF-8 bytes without rewriting them.+ ///+ /// # Errors+ /// Refuses empty/oversized identities, controls, invisible formatting,+ /// redaction placeholders, and any change made by the privacy scrubber.+ pub fn parse(original: &str, sanitizer: &crate::Sanitizer) -> Result<Self, crate::MemoryError> {+ if original.trim().is_empty()+ || original.len() > 512+ || original.chars().any(|c| {+ c.is_control()+ || matches!(c,+ '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}'+ | '\u{2060}'..='\u{2069}' | '\u{feff}')+ })+ || original.contains("[REDACTED:")+ || sanitizer.scrub(original) != original+ {+ return Err(crate::MemoryError::MalformedRecord(+ "native session identity is UNKNOWN; refusing managed binding".into(),+ ));+ }+ Ok(Self(original.to_owned()))+ }++ /// Borrow exactly the accepted original bytes.+ #[must_use]+ pub fn as_str(&self) -> &str {+ &self.0+ }++ /// Carry exactly the accepted original bytes into existing wire/storage fields.+ #[must_use]+ pub fn into_string(self) -> String {+ self.0+ }++ /// Compatible privacy projection for history: invalid identities are UNKNOWN.+ #[must_use]+ pub fn project(original: &str, sanitizer: &crate::Sanitizer) -> String {+ Self::parse(original, sanitizer).map_or_else(|_| String::new(), Self::into_string)+ }+}+/// One normalized event uploaded from a native harness transcript.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct NewWorkstreamEvent {@@ -427,4 +478,85 @@ mod tests {serde_json::json!(true));}++ #[test]+ fn native_identity_original_bytes_limits_privacy_and_collisions() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let sanitizer = crate::Sanitizer::builtin();+ for id in [+ "vendor-session_01".into(),+ "x".repeat(501),+ "x".repeat(512),+ "界".repeat(170) + "ab",+ "café".into(),+ "cafe\u{301}".into(),+ " vendor ".into(),+ ] {+ assert_eq!(+ NativeSessionIdentity::parse(&id, &sanitizer)+ .unwrap()+ .as_str(),+ id+ );+ assert_eq!(NativeSessionIdentity::project(&id, &sanitizer), id);+ }+ let unsafe_ids = [+ "".into(),+ " ".into(),+ "x".repeat(513),+ "界".repeat(171),+ "x\0y".into(),+ "x\u{1b}[31my".into(),+ "x\ny".into(),+ "x\ty".into(),+ "x\u{85}y".into(),+ "x\u{202e}y".into(),+ "x\u{200b}y".into(),+ "x\u{feff}y".into(),+ "[REDACTED:api_key]".into(),+ "sk-abcdefghijklmnopqrstuvwx".into(),+ ];+ for id in unsafe_ids {+ assert!(+ NativeSessionIdentity::parse(&id, &sanitizer).is_err(),+ "dirty native identity must be refused"+ );+ assert_eq!(NativeSessionIdentity::project(&id, &sanitizer), "");+ assert!(+ !NativeSessionIdentity::parse(&id, &sanitizer)+ .err()+ .unwrap()+ .to_string()+ .contains(&id)+ || id.is_empty()+ || id == " "+ );+ }+ let a = "sk-abcdefghijklmnopqrstuvwx";+ let b = "sk-zyxwvutsrqponmlkjihgfedcba";+ assert_eq!(sanitizer.scrub(a), sanitizer.scrub(b));+ assert!(NativeSessionIdentity::parse(a, &sanitizer).is_err());+ assert!(NativeSessionIdentity::parse(b, &sanitizer).is_err());+ let a = "x".repeat(512) + "a";+ let b = "x".repeat(512) + "b";+ assert_eq!(&a[..512], &b[..512]);+ assert!(NativeSessionIdentity::parse(&a, &sanitizer).is_err());+ assert!(NativeSessionIdentity::parse(&b, &sanitizer).is_err());+ let cfg = crate::SanitizeConfig {+ extra_patterns: vec!["vendor-private".into()],+ ..Default::default()+ };+ assert!(+ NativeSessionIdentity::parse("vendor-private", &crate::Sanitizer::new(&cfg).unwrap())+ .is_err()+ );+ assert_eq!(+ crate::SessionId::from_native("vendor-id"),+ crate::SessionId::from_native("vendor-id")+ );+ }}diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex d18fa64c..02f369d2 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1738,6 +1738,16 @@ async fn fetch_managed_context(warn!(managed_run = %run_id, "managed SessionStart has no native session id");return Ok(None);};+ let native_identity = match ai_memory_core::NativeSessionIdentity::parse(+ native_session_id,+ &state.sanitizer,+ ) {+ Ok(id) => id,+ Err(_) => {+ warn!(managed_run = %run_id, "managed SessionStart native identity is UNKNOWN; binding refused");+ return Ok(None);+ }+ };let Some(cwd) = query.cwd.as_deref()@@ -1760,7 +1770,7 @@ async fn fetch_managed_context(project_id,cwd: cwd.to_owned(),agent,- native_session_id: native_session_id.to_owned(),+ native_session_id: native_identity.into_string(),owner_user,}).await?;@@ -3290,14 +3300,13 @@ async fn process_authorized(ws = admitted.workspace_id();proj = admitted.project_id();if let Some(run_id) = managed_run- && let Some(native_session_id) = env- .session_id- .as_deref()- .filter(|value| !value.trim().is_empty())+ && let Some(native_session_id) = env.session_id.as_deref().and_then(|value| {+ ai_memory_core::NativeSessionIdentity::parse(value, &state.sanitizer).ok()+ }){let _ = state.writer- .link_managed_run_session(run_id, env.agent, native_session_id)+ .link_managed_run_session(run_id, env.agent, native_session_id.into_string()).await?;}if publishable_scope {@@ -16283,4 +16292,101 @@ mod tests {"created_at must come from the observation's own occurred_at");}++ #[tokio::test]+ async fn native_identity_managed_start_refuses_but_keeps_shared_legacy_capture() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ for start_path in [true, false] {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ let privacy = ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-vendor".into()],+ ..Default::default()+ };+ state.sanitizer = Sanitizer::new(&privacy).unwrap();+ let cwd = tmp.path().to_string_lossy().into_owned();+ let run = state+ .writer+ .prepare_workstream_run(ai_memory_store::PrepareWorkstreamRun {+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: cwd.clone(),+ agent: AgentKind::ClaudeCode,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: ai_memory_store::WorkstreamSelection::Current,+ lease_owner: "launcher".into(),+ })+ .await+ .unwrap();+ if start_path {+ let query = HandoffQuery {+ managed_run: Some(run.run_id.to_string()),+ session_id: Some("private-vendor".into()),+ cwd: Some(cwd.clone()),+ ..Default::default()+ };+ assert!(+ fetch_managed_context(+ &state,+ &query,+ AgentKind::ClaudeCode,+ state.workspace_id,+ state.project_id,+ None+ )+ .await+ .unwrap()+ .is_none(),+ "dirty original must not bind SessionStart"+ );+ } else {+ let mut env = session_envelope("user-prompt", "private-vendor", &cwd);+ env.managed_run = Some(run.run_id.to_string());+ env.body_excerpt = Some("shared privacy-safe prompt".into());+ let sid = resolve_session_id(&env).unwrap();+ assert_eq!(sid, SessionId::from_native("private-vendor"));+ process(&state, env, None, Vec::new()).await.unwrap();+ let observations = state.reader.observations_for_session(sid).await.unwrap();+ assert_eq!(+ observations.len(),+ 1,+ "binding refusal must keep regular observation capture"+ );+ assert_eq!(observations[0].body, "shared privacy-safe prompt");+ }+ let status = state+ .reader+ .managed_run_status(run.run_id)+ .await+ .unwrap()+ .unwrap();+ assert!(+ status.native_session_id.is_none(),+ "dirty original must not reach auto-link SQL"+ );+ assert!(!status.context_delivered);+ let mut env = session_envelope("user-prompt", "vendor-界-01", &cwd);+ env.managed_run = Some(run.run_id.to_string());+ env.body_excerpt = Some("valid control".into());+ process(&state, env, None, Vec::new()).await.unwrap();+ assert_eq!(+ state+ .reader+ .managed_run_status(run.run_id)+ .await+ .unwrap()+ .unwrap()+ .native_session_id+ .as_deref(),+ Some("vendor-界-01")+ );+ }+ }}diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 072040b3..11a2767f 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -9,9 +9,9 @@ use std::str::FromStr as _;use ai_memory_core::{AgentKind, AuthLevel, Capability, FinishManagedRunRequest, FinishManagedRunResponse,LinkManagedRunRequest, ListManagedWorkstreamsRequest, ManagedRunContextResponse, ManagedRunId,- ManagedRunStatus, ManagedWorkstreamSummary, NewWorkstreamEvent, PrepareManagedRunRequest,- PrepareManagedRunResponse, RenameManagedWorkstreamRequest, RenamedManagedWorkstream, Sanitizer,- WorkstreamEventKind, WorkstreamId,+ ManagedRunStatus, ManagedWorkstreamSummary, NativeSessionIdentity, NewWorkstreamEvent,+ PrepareManagedRunRequest, PrepareManagedRunResponse, RenameManagedWorkstreamRequest,+ RenamedManagedWorkstream, Sanitizer, WorkstreamEventKind, WorkstreamId,};use ai_memory_store::{FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, RenameWorkstream, ScopeResolutionError,@@ -31,7 +31,6 @@ use tracing::warn;const MAX_EVENTS_PER_FINISH: usize = 4_096;const MAX_EVENT_CONTENT_BYTES: usize = 64 * 1024;const MAX_EVENT_ID_BYTES: usize = 512;-const MAX_NATIVE_SESSION_ID_BYTES: usize = 512;const MAX_METADATA_BYTES: usize = 16 * 1024;const MAX_NAME_BYTES: usize = 256;const MAX_CWD_BYTES: usize = 16 * 1024;@@ -750,7 +749,13 @@ async fn search_events(.search_workstream_events(workstream_id, query.q, query.limit.clamp(1, 100)).await{- Ok(events) => Json(events).into_response(),+ Ok(mut events) => {+ for event in &mut events {+ event.native_session_id =+ NativeSessionIdentity::project(&event.native_session_id, &state.sanitizer);+ }+ Json(events).into_response()+ }Err(failure) => error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),}}@@ -779,11 +784,16 @@ async fn link_run({return response;}- if request.native_session_id.trim().is_empty()- || request.native_session_id.len() > MAX_NATIVE_SESSION_ID_BYTES- {- return error(StatusCode::BAD_REQUEST, "invalid native session id");- }+ let native_identity =+ match NativeSessionIdentity::parse(&request.native_session_id, &state.sanitizer) {+ Ok(id) => id,+ Err(_) => {+ return error(+ StatusCode::BAD_REQUEST,+ "native session identity is UNKNOWN; refusing managed binding",+ );+ }+ };let status = match state.reader.managed_run_status(run_id).await {Ok(Some(status)) => status,Ok(None) => return error(StatusCode::NOT_FOUND, "managed run not found"),@@ -794,7 +804,7 @@ async fn link_run(}match state.writer- .link_managed_run_session(run_id, status.agent, request.native_session_id)+ .link_managed_run_session(run_id, status.agent, native_identity.into_string()).await{Ok(true) => StatusCode::NO_CONTENT.into_response(),@@ -847,12 +857,18 @@ async fn finish_run(format!("at most {MAX_EVENTS_PER_FINISH} events are accepted per finish"),);}- if request- .native_session_id- .as_deref()- .is_some_and(|id| id.trim().is_empty() || id.len() > MAX_NATIVE_SESSION_ID_BYTES)- {- return error(StatusCode::BAD_REQUEST, "invalid native session id");+ for id in request.native_session_id.as_deref().into_iter().chain(+ request+ .events+ .iter()+ .map(|event| event.native_session_id.as_str()),+ ) {+ if NativeSessionIdentity::parse(id, &state.sanitizer).is_err() {+ return error(+ StatusCode::BAD_REQUEST,+ "native session identity is UNKNOWN; refusing managed binding",+ );+ }}let status = match state.reader.managed_run_status(run_id).await {Ok(Some(status)) => status,@@ -887,10 +903,24 @@ async fn finish_run(if status.state != "active" {return error(StatusCode::CONFLICT, "managed run is not active");}- let native_session_id = request+ let native_identity = match request.native_session_id- .clone()- .or(status.native_session_id.clone())+ .as_deref()+ .or(status.native_session_id.as_deref())+ .map(|id| NativeSessionIdentity::parse(id, &state.sanitizer))+ .transpose()+ {+ Ok(id) => id,+ Err(_) => {+ return error(+ StatusCode::BAD_REQUEST,+ "native session identity is UNKNOWN; refusing managed binding",+ );+ }+ };+ let native_session_id = native_identity+ .as_ref()+ .map(|id| id.as_str().to_owned()).unwrap_or_else(|| format!("unresolved:{run_id}"));if let Err(message) = sanitize_events(&state.sanitizer,@@ -923,7 +953,7 @@ async fn finish_run(};let input = FinishWorkstreamRun {run_id,- native_session_id: request.native_session_id.or(status.native_session_id),+ native_session_id: native_identity.map(NativeSessionIdentity::into_string),source_cursor: request.source_cursor,events: request.events,complete: request.complete,@@ -2658,4 +2688,313 @@ mod tests {);}}++ #[tokio::test]+ async fn native_identity_http_link_refuses_before_status_or_sql() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let mut state = test_state(&store, temp.path());+ let mut privacy = ai_memory_core::SanitizeConfig::default();+ privacy.extra_patterns.push("private-vendor".into());+ state.sanitizer = Sanitizer::new(&privacy).unwrap();+ let (ws, project) = seed_scope(&store).await;+ let run = store+ .writer+ .prepare_workstream_run(prepare_input(ws, project, AgentKind::Codex, "launcher"))+ .await+ .unwrap();+ for id in [+ "private-vendor".to_owned(),+ "native\0tail".into(),+ "native\u{202e}tail".into(),+ "x".repeat(513),+ ] {+ let before = finish_sql_snapshot(&store).await;+ let response = link_run(+ State(state.clone()),+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(LinkManagedRunRequest {+ native_session_id: id,+ }),+ )+ .await;+ assert_eq!(+ response.status(),+ StatusCode::BAD_REQUEST,+ "HTTP must refuse dirty original native identity"+ );+ assert_eq!(finish_sql_snapshot(&store).await, before);+ assert!(!temp.path().join("raw/workstreams").exists());+ }+ let response = link_run(+ State(state),+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(LinkManagedRunRequest {+ native_session_id: "vendor-界-01".into(),+ }),+ )+ .await;+ assert_eq!(response.status(), StatusCode::NO_CONTENT);+ assert_eq!(+ store+ .reader+ .managed_run_status(run.run_id)+ .await+ .unwrap()+ .unwrap()+ .native_session_id+ .as_deref(),+ Some("vendor-界-01")+ );+ }++ #[tokio::test]+ async fn native_identity_http_finish_refuses_before_segment_or_sql() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let (ws, project) = seed_scope(&store).await;+ let run = store+ .writer+ .prepare_workstream_run(prepare_input(ws, project, AgentKind::Codex, "launcher"))+ .await+ .unwrap();+ let request = |id: &str| FinishManagedRunRequest {+ native_session_id: Some(id.into()),+ source_cursor: Some("cursor-attack".into()),+ events: vec![NewWorkstreamEvent {+ event_id: "event-attack".into(),+ agent: AgentKind::Codex,+ native_session_id: id.into(),+ source_record_id: None,+ kind: WorkstreamEventKind::Message,+ role: None,+ content: "legitimate content".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ }],+ complete: true,+ checkpoint: Default::default(),+ losses: Vec::new(),+ exit_code: Some(0),+ };+ for id in [+ "sk-abcdefghijklmnopqrstuvwx",+ "native\u{202e}tail",+ "native\u{200b}tail",+ ] {+ let before = finish_sql_snapshot(&store).await;+ let response = finish_run(+ State(state.clone()),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(request(id)),+ )+ .await;+ assert_eq!(+ response.status(),+ StatusCode::BAD_REQUEST,+ "finish must refuse before raw segment"+ );+ let body = to_bytes(response.into_body(), 65536).await.unwrap();+ assert!(!String::from_utf8_lossy(&body).contains(id));+ assert!(!temp.path().join("raw/workstreams").exists());+ assert_eq!(finish_sql_snapshot(&store).await, before);+ }+ let response = finish_run(+ State(state.clone()),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(request("vendor-界-01")),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let events = store+ .reader+ .search_workstream_events(run.workstream_id, "".into(), 10)+ .await+ .unwrap();+ assert!(events.iter().all(|e| e.native_session_id == "vendor-界-01"));+ }+ #[tokio::test]+ async fn native_identity_http_event_guard_and_configured_history_projection() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let mut state = test_state(&store, temp.path());+ let (ws, project) = seed_scope(&store).await;+ let run = store+ .writer+ .prepare_workstream_run(prepare_input(ws, project, AgentKind::Codex, "launcher"))+ .await+ .unwrap();+ let request = |event_native: &str| FinishManagedRunRequest {+ native_session_id: Some("vendor-valid".into()),+ source_cursor: Some("cursor".into()),+ events: vec![NewWorkstreamEvent {+ event_id: "event".into(),+ agent: AgentKind::Codex,+ native_session_id: event_native.into(),+ source_record_id: None,+ kind: WorkstreamEventKind::Message,+ role: None,+ content: "shared history".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ }],+ complete: true,+ checkpoint: Default::default(),+ losses: Vec::new(),+ exit_code: Some(0),+ };+ let before = finish_sql_snapshot(&store).await;+ let response = finish_run(+ State(state.clone()),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(request("sk-abcdefghijklmnopqrstuvwx")),+ )+ .await;+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ let body = to_bytes(response.into_body(), 65536).await.unwrap();+ assert!(+ String::from_utf8_lossy(&body).contains("native session identity is UNKNOWN"),+ "event identity must be checked before mismatch/segment handling"+ );+ assert_eq!(finish_sql_snapshot(&store).await, before);+ assert!(!temp.path().join("raw/workstreams").exists());+ assert_eq!(+ finish_run(+ State(state.clone()),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(request("vendor-valid"))+ )+ .await+ .status(),+ StatusCode::OK+ );+ let privacy = ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["vendor-valid".into()],+ ..Default::default()+ };+ state.sanitizer = Sanitizer::new(&privacy).unwrap();+ let before = finish_sql_snapshot(&store).await;+ let response = search_events(+ State(state),+ None,+ None,+ AxumPath(run.workstream_id.to_string()),+ Query(EventQuery::default()),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let body = to_bytes(response.into_body(), 65536).await.unwrap();+ let events: Vec<ai_memory_core::WorkstreamEvent> = serde_json::from_slice(&body).unwrap();+ assert!(+ events.iter().all(|e| e.native_session_id.is_empty()),+ "HTTP configured privacy must project UNKNOWN"+ );+ assert_eq!(finish_sql_snapshot(&store).await, before);+ }++ #[tokio::test]+ async fn native_identity_http_stored_identity_refuses_before_raw_segment() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let mut state = test_state(&store, temp.path());+ let (ws, project) = seed_scope(&store).await;+ let run = store+ .writer+ .prepare_workstream_run(prepare_input(ws, project, AgentKind::Codex, "launcher"))+ .await+ .unwrap();+ store+ .writer+ .link_managed_run_session(run.run_id, AgentKind::Codex, "private-existing")+ .await+ .unwrap();+ state.sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-existing".into()],+ ..Default::default()+ })+ .unwrap();+ let request = || FinishManagedRunRequest {+ native_session_id: None,+ source_cursor: Some("must-not-advance".into()),+ events: Vec::new(),+ complete: true,+ checkpoint: Default::default(),+ losses: Vec::new(),+ exit_code: Some(0),+ };+ let before = finish_sql_snapshot(&store).await;+ let response = finish_run(+ State(state.clone()),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(request()),+ )+ .await;+ assert_eq!(+ response.status(),+ StatusCode::BAD_REQUEST,+ "stored identity must be validated before segment"+ );+ assert!(!temp.path().join("raw/workstreams").exists());+ assert_eq!(finish_sql_snapshot(&store).await, before);+ state.sanitizer = Sanitizer::builtin();+ assert_eq!(+ finish_run(+ State(state),+ None,+ None,+ None,+ None,+ AxumPath(run.run_id.to_string()),+ Json(request())+ )+ .await+ .status(),+ StatusCode::OK+ );+ }}diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex 6ac46dcc..fccaef34 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -3,8 +3,8 @@use std::str::FromStr as _;use ai_memory_core::{- AgentKind, ManagedRunId, NewWorkstreamEvent, ProjectId, WorkspaceId, WorkstreamEvent,- WorkstreamEventKind, WorkstreamId,+ AgentKind, ManagedRunId, NativeSessionIdentity, NewWorkstreamEvent, ProjectId, Sanitizer,+ WorkspaceId, WorkstreamEvent, WorkstreamEventKind, WorkstreamId,};use jiff::Timestamp;use rusqlite::{Connection, OptionalExtension as _, Transaction, params};@@ -676,12 +676,14 @@ pub(crate) fn link_native_session(agent: AgentKind,native_session_id: &str,) -> StoreResult<bool> {- if native_session_id.trim().is_empty() {- return Ok(false);- }+ let native_identity =+ match NativeSessionIdentity::parse(native_session_id, &Sanitizer::builtin()) {+ Ok(id) => id,+ Err(_) => return Ok(false),+ };let now = Timestamp::now().as_microsecond();let tx = conn.transaction()?;- let linked = link_native_session_in_transaction(&tx, run_id, agent, native_session_id, now)?;+ let linked = link_native_session_in_transaction(&tx, run_id, agent, &native_identity, now)?;tx.commit()?;Ok(linked)}@@ -690,9 +692,10 @@ fn link_native_session_in_transaction(tx: &Transaction<'_>,run_id: ManagedRunId,agent: AgentKind,- native_session_id: &str,+ native_session_id: &NativeSessionIdentity,now: i64,) -> StoreResult<bool> {+ let native_session_id = native_session_id.as_str();let run: Option<LinkRunRow> = tx.query_row("SELECT workstream_id, agent_kind, native_session_id, \@@ -787,6 +790,11 @@ pub(crate) fn link_or_adopt_native_session(return Ok(ManagedRunSessionLink::Refused);}+ let native_identity =+ match NativeSessionIdentity::parse(&input.native_session_id, &Sanitizer::builtin()) {+ Ok(id) => id,+ Err(_) => return Ok(ManagedRunSessionLink::Refused),+ };let now = Timestamp::now().as_microsecond();let tx = conn.transaction()?;let supplied: Option<ManagedRunBoundaryRow> = tx@@ -862,13 +870,7 @@ pub(crate) fn link_or_adopt_native_session(}};- if !link_native_session_in_transaction(- &tx,- selected.0,- input.agent,- &input.native_session_id,- now,- )? {+ if !link_native_session_in_transaction(&tx, selected.0, input.agent, &native_identity, now)? {tx.commit()?;return Ok(ManagedRunSessionLink::Refused);}@@ -995,9 +997,24 @@ pub(crate) fn finish_run(.as_deref().or(linked_session.as_deref());+ let sanitizer = Sanitizer::builtin();+ let validate = |id: &str| {+ NativeSessionIdentity::parse(id, &sanitizer).map_err(|_| {+ StoreError::InvalidState(+ "native session identity is UNKNOWN; refusing managed binding".into(),+ )+ })+ };+ let native_identity = native_session.map(validate).transpose()?;+ let native_session = native_identity.as_ref().map(NativeSessionIdentity::as_str);+ let event_identities = input+ .events+ .iter()+ .map(|event| validate(&event.native_session_id))+ .collect::<StoreResult<Vec<_>>>()?;let mut latest = latest_before;let mut imported = 0_usize;- for event in &input.events {+ for (event, event_identity) in input.events.iter().zip(event_identities) {if event.agent != agent {return Err(StoreError::InvalidState(format!("event {} belongs to {}, managed run expects {}",@@ -1044,7 +1061,7 @@ pub(crate) fn finish_run(latest,event.event_id,event.agent.as_str(),- event.native_session_id,+ event_identity.as_str(),event.source_record_id,event.kind.as_str(),event.role,@@ -1472,10 +1489,11 @@ pub(crate) fn search_events())};let mut events = Vec::new();+ let sanitizer = Sanitizer::builtin();if fts_query.is_empty() {let rows = statement.query_map(params![workstream_id.as_bytes(), limit], read_row)?;for row in rows {- events.push(stored_event(row?)?);+ events.push(stored_event(row?, &sanitizer)?);}} else {let rows = statement.query_map(@@ -1483,7 +1501,7 @@ pub(crate) fn search_events(read_row,)?;for row in rows {- events.push(stored_event(row?)?);+ events.push(stored_event(row?, &sanitizer)?);}}Ok(events)@@ -1500,13 +1518,14 @@ fn stored_event(String,Option<String>,),+ sanitizer: &Sanitizer,) -> StoreResult<WorkstreamEvent> {let (sequence, event_id, agent, native_session_id, kind, role, content, occurred_at) = row;Ok(WorkstreamEvent {sequence,event_id,agent: AgentKind::from_wire(&agent),- native_session_id,+ native_session_id: NativeSessionIdentity::project(&native_session_id, sanitizer),kind: WorkstreamEventKind::from_str(&kind)?,role,content,diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 8901a6d4..71adb30d 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -2057,3 +2057,205 @@ async fn owner_finish_store_keeps_qualified_identity_namespaces() {1);}++#[tokio::test]+async fn native_identity_store_link_refuses_original_dirty_bytes() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let f = FinishFixture::new().await;+ let run = f.run("identity-link", Some(operator("alice"))).await;+ for id in [+ "native\0tail".to_owned(),+ "native\u{202e}tail".into(),+ "sk-abcdefghijklmnopqrstuvwx".into(),+ "x".repeat(513),+ ] {+ let before = finish_snapshot(&f.store).await;+ let result = f+ .store+ .writer+ .link_managed_run_session(run.run_id, AgentKind::Codex, id)+ .await;+ assert!(+ matches!(result, Err(_) | Ok(false)),+ "dirty native identity must not link"+ );+ assert_eq!(finish_snapshot(&f.store).await, before);+ }+ let exact = "界".repeat(170) + "ab";+ assert_eq!(exact.len(), 512);+ assert!(+ f.store+ .writer+ .link_managed_run_session(run.run_id, AgentKind::Codex, exact.clone())+ .await+ .unwrap()+ );+ assert_eq!(+ f.store+ .reader+ .managed_run_status(run.run_id)+ .await+ .unwrap()+ .unwrap()+ .native_session_id,+ Some(exact)+ );+}++#[tokio::test]+async fn native_identity_store_adoption_refuses_before_link() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let f = FinishFixture::new().await;+ let run = f.run("identity-adopt", Some(operator("alice"))).await;+ let input = |id: &str| LinkOrAdoptManagedRunSession {+ supplied_run_id: run.run_id,+ workspace_id: f.ws,+ project_id: f.project,+ cwd: "/repo".into(),+ agent: AgentKind::Codex,+ native_session_id: id.into(),+ owner_user: Some(operator("alice")),+ };+ let before = finish_snapshot(&f.store).await;+ let result = f+ .store+ .writer+ .link_or_adopt_managed_run_session(input("sk-abcdefghijklmnopqrstuvwx"))+ .await;+ assert!(+ matches!(result, Ok(ManagedRunSessionLink::Refused) | Err(_)),+ "dirty native identity must not adopt"+ );+ assert_eq!(finish_snapshot(&f.store).await, before);+ assert_eq!(+ f.store+ .writer+ .link_or_adopt_managed_run_session(input("vendor-session_01"))+ .await+ .unwrap(),+ ManagedRunSessionLink::Exact(run.run_id)+ );+}++#[tokio::test]+async fn native_identity_store_finish_refuses_without_sql_or_index_mutation() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let f = FinishFixture::new().await;+ let run = f.run("identity-finish", Some(operator("alice"))).await;+ for (run_id, event_id) in [+ (+ Some("sk-abcdefghijklmnopqrstuvwx"),+ "sk-abcdefghijklmnopqrstuvwx",+ ),+ (None, "native\u{200b}tail"),+ ] {+ let mut input = finish_input(run.run_id);+ input.native_session_id = run_id.map(str::to_owned);+ input.events[0].native_session_id = event_id.into();+ if run_id.is_some() {+ input.events.clear();+ }+ let before = finish_snapshot(&f.store).await;+ assert!(+ matches!(+ f.store+ .writer+ .finish_workstream_run(f.alice(), input.clone())+ .await,+ Err(StoreError::InvalidState(_))+ ),+ "dirty finish identity must be refused"+ );+ assert_eq!(finish_snapshot(&f.store).await, before);+ let bob = finish_authority(ai_memory_core::AuthLevel::User, Some(f.bob), Some("bob"));+ assert!(+ matches!(+ f.store.writer.finish_workstream_run(bob, input).await,+ Err(StoreError::Forbidden(_))+ ),+ "ownership must precede identity validation"+ );+ assert_eq!(finish_snapshot(&f.store).await, before);+ }+ assert_eq!(+ f.store+ .writer+ .finish_workstream_run(f.alice(), finish_input(run.run_id))+ .await+ .unwrap()+ .imported_events,+ 1+ );+}++#[tokio::test]+async fn native_identity_store_history_projects_unknown_without_rewriting() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let f = FinishFixture::new().await;+ let run = f.run("identity-history", Some(operator("alice"))).await;+ f.store+ .writer+ .finish_workstream_run(f.alice(), finish_input(run.run_id))+ .await+ .unwrap();+ let conn = rusqlite::Connection::open(f.store.db_path()).unwrap();+ let dirty = "sk-abcdefghijklmnopqrstuvwx";+ conn.execute(+ "UPDATE workstream_events SET native_session_id = ?1",+ [dirty],+ )+ .unwrap();+ let before = finish_snapshot(&f.store).await;+ for query in ["", "snapshot"] {+ let events = f+ .store+ .reader+ .search_workstream_events(run.workstream_id, query.to_owned(), 10)+ .await+ .unwrap();+ assert_eq!(events.len(), 1);+ assert_eq!(+ events[0].native_session_id, "",+ "legacy dirty identity must project UNKNOWN"+ );+ assert_eq!(events[0].content, "finish snapshot evidence");+ assert_eq!(events[0].sequence, 1);+ }+ assert_eq!(finish_snapshot(&f.store).await, before);+ let stored: String = conn+ .query_row("SELECT native_session_id FROM workstream_events", [], |r| {+ r.get(0)+ })+ .unwrap();+ assert_eq!(stored, dirty);+ conn.execute(+ "UPDATE workstream_events SET native_session_id = ?1",+ ["vendor-界-01"],+ )+ .unwrap();+ assert_eq!(+ f.store+ .reader+ .search_workstream_events(run.workstream_id, "".into(), 10)+ .await+ .unwrap()[0]+ .native_session_id,+ "vendor-界-01"+ );+}diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsindex bf755342..f347e94c 100644--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@ -286,6 +286,12 @@ pub fn build_launch_plan_with_env(_ => None,});let mut expected = explicit_session_id(harness, &args);+ for id in expected.as_deref().into_iter().chain(linked_session_id) {+ ai_memory_core::NativeSessionIdentity::parse(id, &ai_memory_core::Sanitizer::builtin())?;+ }+ if harness == ManagedHarness::CommandCode {+ expected = expected.filter(|value| Uuid::parse_str(value).is_ok());+ }let mode = launch_mode(harness, &args);if mode == LaunchMode::Session&& harness == ManagedHarness::KiroV3@@ -913,8 +919,7 @@ fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<Str// A bare `--session`/`--resume` opens the picker: `flag_value`// returns `None` when no value follows, as intended.ManagedHarness::Kimi => flag_value(args, &["--session", "-S", "--resume", "-r"]),- ManagedHarness::CommandCode => flag_value(args, &["--session", "--resume", "-r"])- .filter(|value| Uuid::parse_str(value).is_ok()),+ ManagedHarness::CommandCode => flag_value(args, &["--session", "--resume", "-r"]),ManagedHarness::Kiro | ManagedHarness::KiroV3 => flag_value(args, &["--resume-id"]),ManagedHarness::Grok => flag_value(args, &["--resume", "-r", "--session-id", "-s"]),// A bare `--continue` names no conversation: the id is only known@@ -3308,4 +3313,62 @@ mod tests {);}}++ #[test]+ fn native_identity_selector_rejects_original_before_resume_arguments() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ let bad = "sk-abcdefghijklmnopqrstuvwx";+ for (args, linked) in [+ (vec![OsString::from("resume"), OsString::from(bad)], None),+ (Vec::new(), Some(bad)),+ ] {+ let result = build_launch_plan(ManagedHarness::Codex, None, args, linked);+ assert!(+ result.is_err(),+ "selector must refuse dirty original identity"+ );+ assert!(!format!("{:#}", result.unwrap_err()).contains(bad));+ }+ let command_code = build_launch_plan(+ ManagedHarness::CommandCode,+ None,+ vec![OsString::from("--session"), OsString::from(bad)],+ None,+ );+ assert!(+ command_code.is_err(),+ "Command Code must check original privacy before UUID filtering"+ );+ let uuid = "11111111-1111-4111-8111-111111111111";+ let command_code = build_launch_plan(+ ManagedHarness::CommandCode,+ None,+ vec![OsString::from("--session"), OsString::from(uuid)],+ None,+ )+ .unwrap();+ assert_eq!(command_code.expected_session_id.as_deref(), Some(uuid));+ let command_code = build_launch_plan(+ ManagedHarness::CommandCode,+ None,+ vec![OsString::from("--session"), OsString::from("vendor-id")],+ None,+ )+ .unwrap();+ assert!(command_code.expected_session_id.is_none());+ assert!(command_code.args.iter().any(|arg| arg == "vendor-id"));+ let plan = build_launch_plan(+ ManagedHarness::Codex,+ None,+ Vec::new(),+ Some("vendor-界-01"),+ )+ .unwrap();+ assert_eq!(plan.expected_session_id.as_deref(), Some("vendor-界-01"));+ assert!(plan.args.iter().any(|arg| arg == "vendor-界-01"));+ }}diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 6a897868..a10a3ba5 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -7,7 +7,8 @@ use std::path::{Path, PathBuf};use std::time::{Duration, SystemTime, UNIX_EPOCH};use ai_memory_core::{- AgentKind, MANAGED_WORKSTREAM_PACKET_MARKER, NewWorkstreamEvent, WorkstreamEventKind,+ AgentKind, MANAGED_WORKSTREAM_PACKET_MARKER, NativeSessionIdentity, NewWorkstreamEvent,+ Sanitizer, WorkstreamEventKind,};use anyhow::{Context as _, Result, anyhow};use rusqlite::{Connection, OpenFlags, params};@@ -20,7 +21,6 @@ use crate::{ManagedHarness, clean_path};const MAX_SCAN_FILES: usize = 50_000;const MAX_EVENT_BYTES: usize = 128 * 1024;-const MAX_NATIVE_SESSION_ID_BYTES: usize = 512;const LEGACY_MANAGED_WORKSTREAM_PACKET_PREFIX: &str = "> **ai-memory managed workstream:";/// Checkout-local native session that can seed an otherwise-empty workstream.@@ -3595,13 +3595,11 @@ fn modified(path: &Path) -> Option<SystemTime> {}fn valid_native_session_id(value: &str) -> bool {- !value.trim().is_empty()- && value.len() <= MAX_NATIVE_SESSION_ID_BYTES+ NativeSessionIdentity::parse(value, &Sanitizer::builtin()).is_ok()&& !value.starts_with('-')&& value != "."&& value != ".."&& !value.contains(['/', '\\'])- && !value.chars().any(char::is_control)}fn same_path(left: &Path, right: &Path) -> bool {@@ -6077,4 +6075,30 @@ mod tests {None);}++ #[test]+ fn native_identity_adapter_preserves_exact_and_rejects_privacy_changes() {+ println!(+ "NATIVE_TEST_PID {} {:?}",+ std::process::id(),+ std::env::current_exe().unwrap()+ );+ for id in [+ "sk-abcdefghijklmnopqrstuvwx",+ "native\u{202e}tail",+ "native\u{200b}tail",+ "native\u{feff}tail",+ ] {+ assert!(+ !valid_native_session_id(id),+ "adapter must reject dirty identity"+ );+ }+ for id in ["session_vendor-01", "native-界-01"] {+ assert!(valid_native_session_id(id));+ }+ for id in ["../session", "-selector", "a/b", "a\\b", ".", ".."] {+ assert!(!valid_native_session_id(id));+ }+ }}diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex cccb60d7..378c16a8 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -419,6 +419,36 @@ another shell, pass `--workstream-id <uuid>` explicitly. Search results preservethe source harness, role, event sequence, and content. Historical tool activityis labelled completed evidence and must never be replayed as a pending call.+## Native identity privacy++New managed bindings accept the exact original native identity only when it is+nonempty, at most 512 UTF-8 bytes, free of controls and unsafe invisible+formatting, and unchanged by the privacy scrubber. IDs are never trimmed,+normalized, truncated, or replaced with a redaction placeholder to make a+binding succeed. Existing vendor IDs and generated fresh-session UUIDs remain+supported. Each adapter retains its own path and selector restrictions.++The launcher validates prepared and linked IDs from older servers before resume+or native-store use, and validates finish identities before serialization.+Configured privacy rules also apply to post-launch status and discovered IDs+before transcript export and finish transport.+HTTP ingress applies the configured privacy rules before segment writes; the+writer also validates identities before link/import SQL, after the existing+owner and current Write checks on finish. A refused hook auto-link still leaves+regular sanitized shared observation capture and legacy UUID/v5 session routing+intact. A run without a native ID keeps its existing unbound checkpoint behavior.++`workstream-search --json` keeps its existing String field: an invalid historical+`native_session_id` is returned as `""` (UNKNOWN), which cannot be used for a new+managed binding. Valid identities retain their exact bytes. The stored value,+event content, rows, source cursor, and shared history are not rewritten. The+CLI repeats the privacy projection for older-server responses.++This boundary establishes identity representation and privacy only. It does not+prove a native file exists, authenticate a source ID, correlate a run with an+event, or establish a tool outcome. SQL refusal remains transactional; this+change does not add an atomic disk/SQL seal or change lease/retry policy.+## Native adapter behavior| Harness | Fresh native session | Returning native session | Read-only source |diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 5de58448..e28e370a 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -65,6 +65,7 @@ boundary not yet built.| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `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. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users || 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; batch outcomes do not bypass the capture grant or session owner check | `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); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | 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 || 14ap | Managed-run finish owner and current project access | `hooks/src/workstream.rs` derives `WorkstreamFinishAuthority` only from authenticated middleware extensions and checks the real run before status/payload/segment handling; `ReaderPool::authorize_workstream_finish` and `store/src/workstream.rs` `authorize_finish` use a read snapshot and the existing writer transaction, respectively. Strict finish resolution requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within the writer transaction; a revocation after preflight can leave an unindexed raw segment. Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |+| 14au | Exact native managed identity and privacy (P13c0b; invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`; store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history`. Local receipts record failing-first assertions, individual guard neutralization and exact source restoration | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory || 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 |