Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge adjusted PR #1075 into PR #1079
AkitaOnRailsb2725dd9dfd5
diff --cc CHANGELOG.mdindex 60418a3d,3a9674ac..bf5c79b9--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -116,16 -128,65 +128,70 @@@ and this project adheres to [Semantic Vor distinct extensions, including backfill).Mixed-source counts preserve scope, session ownership and time-window filters;older servers leave unsupported fields unknown. (#1016)+ - Added bounded, sanitized native-record and adapter correlation provenance to+ managed-workstream search/tail results and the CLI's text/JSON output, with+ compatible optional fields and sanitization of legacy provenance on reads. (#1057)+ - Added Portuguese history phrases to the existing opt-in session-recall+ router (`[retrieval] query_intent`), including accented and unaccented spellings of+ "última sessão", "onde paramos ontem", and "decisão anterior". Word+ boundaries and explicit history phrases keep technical session queries+ unchanged; routing remains off by default. (#1056)+ - Added shared, typed and bounded `entities`, `abstract`, and `relations`+ metadata to MCP `memory_write_page` and admin `/admin/write-page`, plus bounded+ MCP `kind` while preserving the admin's legacy `kind` adapter. Kept existing+ request shapes, entity normalization, authenticated attribution and the wiki+ write pipeline. Documented whole-page replacement, raw-input metadata bounds+ and trimmed relation scope components. (#1055)+ - Added structured results for the existing auto-improvement eval execution in+ review reports, staged run metadata, and accepted proposal sidecars, with+ server-generated eval IDs, evaluated request/body digests, checker invocation+ identity, observed success/rejection/failure/timeout, and sanitized bounded+ reasons. Report deserialization discarded supplied eval observations. (#1053)+ - Added `grizzybot` as a recognised agent (wire value `grizzybot`, alias+ `grizzy-bot`), so GrizzyBot's lifecycle events are attributed to it instead+ of `other` and its tool calls are captured as closed-schema tool families,+ like other Claude Code-shaped agents. GrizzyBot posts to `/hook` and+ `/mcp` itself, so there is nothing to install. Adds migration V72 to extend+ the `sessions.agent_kind` CHECK constraint. (#1036)+ - Added GitHub Copilot CLI as a hooked agent: `install-hooks --agent+ copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (default+ `~/.copilot/hooks/ai-memory.json`) with Copilot's flat, matcher-less entries+ and PascalCase event names, so Copilot sends its VS Code/Claude-compatible+ payload. Ten events — Claude Code's nine plus `PostToolUseFailure` — with+ native commands enforcing capture exclusions; tool output is read from+ `tool_result.text_result_for_llm` and the outcome from+ `tool_result.result_type`. The `SessionStart` hook delivers the prior+ session's handoff through Copilot's top-level `additionalContext` (ported+ from #1069). There is deliberately no `--scope project`. The bare+ `install-mcp --client copilot` alias keeps meaning VS Code Copilot;+ `ai-memory run copilot` follows separately. (#1040)+ - Added `install-mcp --client copilot-cli`, which merges ai-memory's remote+ entry (`type: "http"`, `url`, bearer `headers`, `tools: ["*"]`) into the root+ `mcpServers` map of `$COPILOT_HOME/mcp-config.json` (default+ `~/.copilot/mcp-config.json`), preserving other servers. `install-hooks+ --agent copilot-cli` without `--server-url` now reads the server URL and+ bearer back from that entry, and `uninstall` removes it. (#1040)+ - Added an optional `session_id` to `memory_write_page`, so an agent can+ write a session's page with its own model and keep it traceable to the+ session. The session must belong to the project the page is written to, and+ the page records it as session evidence. A page that cites a session does+ not overwrite a pinned page. Writing `sessions/<id>.md` also stamps the+ frontmatter `memory_consolidate` writes there (`session_id`, `agent`,+ `consolidated`, plus `consolidated_by: agent`), defaults the tier to+ `episodic`, applies the same duplicate-title suffix, and marks the session's+ queued SessionEnd consolidation job completed. (#1038)### 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. (#1079)- - Required managed-run finish imports and finished retries to pass an- authenticated owner check and current project access checks, repeated in the- writer transaction. Database users required current Write access; trusted+ - Required managed-run finish imports and finished retries, and the cancel,+ heartbeat, native-session link and context-acceptance routes, to pass an+ authenticated owner check and current project access checks (repeated in+ finish's writer transaction), so another operator cannot release or rebind a+ run. Database users required current Write access; trustedproxy operators retained their existing project policy. Active API keysremained valid after human login was disabled. Shared, unattributed runs andlate finishes of still-active runs retained their existing behavior. (#1075)diff --cc crates/ai-memory-cli/src/commands/run.rsindex 1f81cdf8,b2a6dccc..1ea58576--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@@ -720,8 -734,19 +745,19 @@@ async fn run_once_with_wiring&repository.cwd,);}+ // A Kiro v3 resume that dropped `KIRO_HOME` runs against the default store.+ let linked_store = effective_store(+ harness,+ &home,+ &repository.cwd,+ if remove_kiro_home {+ None+ } else {+ plan.session_dir.as_deref()+ },+ );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(@@@ -734,6 -759,31 +770,37 @@@.await.context("linking the managed native session; the agent was not started"));- remember_session_store(config, &endpoint, harness, native_session_id, &linked_store);++ remember_session_store(++ config,++ &endpoint,++ harness,++ native_identity.as_str(),++ &linked_store,++ );+ }+ // Claude refuses `--resume` on a background session that is still running+ // and points at `claude attach`, so open it that way instead. The 2.1.288+ // lifecycle check observed no new SessionStart from the attach client;+ // native flags are omitted because it connects to the existing session.+ let attached_background = if harness == ManagedHarness::Claude+ && plan.mode == LaunchMode::Session+ && resumes_linked_session+ && let Some(native_session_id) = plan.expected_session_id.as_deref()+ {+ claude_background_attach_id(&plan, &home, &repository.cwd, &run_env, native_session_id)+ .await+ } else {+ None+ };+ if let Some(attach_id) = &attached_background {+ eprintln!(+ "ai-memory: Claude session {} is still running in the background; attaching to it (`claude attach {attach_id}`). Native arguments and the workstream context packet do not reach an attached session",+ plan.expected_session_id+ .as_deref()+ .map(display_session_id)+ .unwrap_or_default()+ );+ plan.args = vec![OsString::from("attach"), OsString::from(attach_id)];}let crush_context = if harness == ManagedHarness::Crush && plan.mode == LaunchMode::Session {@@@ -1622,7 -1673,47 +1698,48 @@@ fn own_native_sessionOk(in_checkout.then(|| linked.to_string()))}+ /// A Claude session that attached to a background session (`/resume` on one+ /// the Claude Code daemon hosts) went on in that session's transcript, so the+ /// workstream follows it. Otherwise the next launch resumes the foreground+ /// session, which holds none of the conversation.+ fn follow_claude_background_session(+ plan: &LaunchPlan,+ harness: ManagedHarness,+ home: &Path,+ cwd: &Path,+ own: String,+ started_at: SystemTime,+ ) -> String {+ if harness != ManagedHarness::Claude {+ return own;+ }+ match claude_attached_background_session(+ home,+ cwd,+ plan.session_dir.as_deref(),+ &own,+ started_at,+ ) {+ Ok(Some(background)) => {+ eprintln!(+ "ai-memory: Claude session {} continued in background session {}; the workstream now follows it",+ display_session_id(&own),+ display_session_id(&background)+ );+ background+ }+ Ok(None) => own,+ Err(error) => {+ eprintln!(+ "ai-memory: could not check whether Claude session {} moved to a background session ({error}); keeping it",+ display_session_id(&own)+ );+ own+ }+ }+ }++#[allow(clippy::too_many_arguments)]async fn resolve_native_session_after_run(plan: &LaunchPlan,harness: ManagedHarness,@@@ -1635,11 -1725,10 +1752,13 @@@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));+ return Ok(Some(follow_claude_background_session(+ plan, harness, home, cwd, own, started_at,+ )));}let linked = server_status.filter(|status| status.native_session_linked)@@@ -1672,16 -1761,14 +1791,20 @@@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>> {+ async fn list_auto_sessions(+ home: &Path,+ cwd: &Path,+ env_overrides: &[(String, String)],+ ) -> Result<Vec<AutoSessionCandidate>> {let mut found = Vec::new();let mut failures = Vec::new();for harness in AUTO_HARNESSES {@@@ -4879,6 -5462,58 +5508,59 @@@ mod testsassert!(error.to_string().contains("--fresh cannot be combined"));}+ #[tokio::test]+ async fn a_claude_run_that_attached_to_a_background_session_follows_it() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let project = temp.path().join(".claude/projects/-repo");+ std::fs::create_dir_all(&cwd).unwrap();+ std::fs::create_dir_all(&project).unwrap();+ let started_at = SystemTime::now() - std::time::Duration::from_secs(60);+ let record = |session: &str, kind: Option<&str>| {+ let mut value = serde_json::json!({+ "type": "user",+ "sessionId": session,+ "session_id": "fg",+ "cwd": cwd,+ });+ if let Some(kind) = kind {+ value["sessionKind"] = serde_json::json!(kind);+ }+ format!("{value}\n")+ };+ std::fs::write(project.join("fg.jsonl"), record("fg", None)).unwrap();+ let mut plan =+ build_launch_plan(ManagedHarness::Claude, None, Vec::new(), Some("fg")).unwrap();+ // CLAUDE_CONFIG_DIR in the developer's environment would point the+ // scan away from the transcripts planted under `temp`.+ plan.session_dir = None;+ assert_eq!(plan.expected_session_id.as_deref(), Some("fg"));+ let resolve = |plan: &LaunchPlan| {+ let plan = plan.clone();+ let home = temp.path().to_path_buf();+ let cwd = cwd.clone();+ async move {+ resolve_native_session_after_run(+ &plan,+ ManagedHarness::Claude,+ &home,+ &cwd,+ started_at,+ None,++ &Sanitizer::builtin(),+ )+ .await+ .unwrap()+ }+ };+ assert_eq!(resolve(&plan).await.as_deref(), Some("fg"));++ // `/resume` on a daemon-hosted session: the conversation continues in+ // that transcript, so the workstream must not stay on "fg".+ std::fs::write(project.join("bg.jsonl"), record("bg", Some("bg"))).unwrap();+ assert_eq!(resolve(&plan).await.as_deref(), Some("bg"));+ }+/// A session linked during the run was reported by this run's child, so/// it wins over a newer session another launch made in the same checkout,/// even when it repeats the session the run was prepared with. A child's@@@ -6092,468 -6844,4 +6897,433 @@@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 --cc crates/ai-memory-cli/tests/suite/main.rsindex a3f3517c,4075e0a9..cdd484ae--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@@ -30,6 -30,5 +30,7 @@@ mod serve_shutdownmod server_profiles;mod shutdown_signals;mod upgrade_e2e;+ mod workstream_provenance;mod yolo_ai_jail;++mod workstream_identity;diff --cc crates/ai-memory-core/src/lib.rsindex 0b6629bf,16cee73d..05afd71a--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@@ -100,8 -100,8 +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,- scrub_workstream_provenance,+ ManagedRunStatus, ManagedWorkstreamSummary, NativeSessionIdentity, NewWorkstreamEvent,+ PrepareManagedRunRequest, PrepareManagedRunResponse, RenameManagedWorkstreamRequest,+ RenamedManagedWorkstream, UNTRUSTED_MEMORY_NOTICE, WorkstreamCheckpoint, WorkstreamEvent,- WorkstreamEventKind,++ WorkstreamEventKind, scrub_workstream_provenance,};diff --cc crates/ai-memory-core/src/workstream.rsindex 0ca2ccd3,ac722595..4051c882--- a/crates/ai-memory-core/src/workstream.rs+++ b/crates/ai-memory-core/src/workstream.rs@@@ -478,85 -502,4 +553,80 @@@ mod testsserde_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 --cc crates/ai-memory-hooks/src/router.rsindex 02f369d2,572b57b1..69867375--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@@ -16292,101 -16754,4 +16763,96 @@@ 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 --cc crates/ai-memory-hooks/src/workstream.rsindex 11a2767f,db3c3201..3ab531eb--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@@ -31,7 -31,7 +31,6 @@@ use tracing::warnconst MAX_EVENTS_PER_FINISH: usize = 4_096;const MAX_EVENT_CONTENT_BYTES: usize = 64 * 1024;const MAX_EVENT_ID_BYTES: usize = 512;- const MAX_METADATA_BYTES: usize = 16 * 1024;-const MAX_NATIVE_SESSION_ID_BYTES: usize = 512;const MAX_NAME_BYTES: usize = 256;const MAX_CWD_BYTES: usize = 16 * 1024;@@@ -746,16 -764,15 +763,21 @@@ async fn search_events}match state.reader- .search_workstream_events(workstream_id, query.q, query.limit.clamp(1, 100))+ .search_workstream_events(+ workstream_id,+ query.q,+ query.limit.clamp(1, 100),+ state.sanitizer.clone(),+ ).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()),}}@@@ -857,18 -852,19 +862,25 @@@ async fn finish_runformat!("at most {MAX_EVENTS_PER_FINISH} events are accepted per finish"),);}+ if request+ .events+ .iter()+ .any(|event| event.event_id.starts_with("managed-run:"))+ {+ return error(StatusCode::BAD_REQUEST, "reserved workstream event id");+ }- 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,@@@ -952,8 -935,9 +965,9 @@@}};let input = FinishWorkstreamRun {+ sanitizer: state.sanitizer.clone(),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,@@@ -2688,313 -3161,4 +3191,297 @@@ 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,++ 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,++ 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)++ .search_workstream_events(run.workstream_id, "".into(), 10, Sanitizer::default())+ .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 --cc crates/ai-memory-store/src/workstream.rsindex fccaef34,61ef3c5f..8528e0b9--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@@ -3,8 -3,8 +3,8 @@@use std::str::FromStr as _;use ai_memory_core::{- AgentKind, ManagedRunId, NewWorkstreamEvent, ProjectId, Sanitizer, WorkspaceId,- WorkstreamEvent, WorkstreamEventKind, WorkstreamId, scrub_workstream_provenance,+ AgentKind, ManagedRunId, NativeSessionIdentity, NewWorkstreamEvent, ProjectId, Sanitizer,- WorkspaceId, WorkstreamEvent, WorkstreamEventKind, WorkstreamId,++ WorkspaceId, WorkstreamEvent, WorkstreamEventKind, WorkstreamId, scrub_workstream_provenance,};use jiff::Timestamp;use rusqlite::{Connection, OptionalExtension as _, Transaction, params};@@@ -1061,8 -1063,8 +1080,8 @@@ pub(crate) fn finish_runlatest,event.event_id,event.agent.as_str(),- event.native_session_id,+ event_identity.as_str(),- event.source_record_id,+ source_record_id,event.kind.as_str(),event.role,content,@@@ -1525,7 -1553,9 +1570,9 @@@ fn stored_event(row: EventRow, sanitizesequence,event_id,agent: AgentKind::from_wire(&agent),- native_session_id,+ native_session_id: NativeSessionIdentity::project(&native_session_id, sanitizer),+ source_record_id,+ metadata,kind: WorkstreamEventKind::from_str(&kind)?,role,content,diff --cc crates/ai-memory-store/tests/suite/multi_session.rsindex 71adb30d,cbe86659..02cdf6dc--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@@ -2057,205 -2058,3 +2058,195 @@@ async fn owner_finish_store_keeps_quali1);}++#[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)++ .search_workstream_events(++ run.workstream_id,++ query.to_owned(),++ 10,++ ai_memory_core::Sanitizer::default(),++ )+ .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)++ .search_workstream_events(++ run.workstream_id,++ "".into(),++ 10,++ ai_memory_core::Sanitizer::default(),++ )+ .await+ .unwrap()[0]+ .native_session_id,+ "vendor-界-01"+ );+}diff --cc crates/ai-memory-workstream/src/harness.rsindex f347e94c,bf755342..f9eecebf--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@@ -3313,62 -3308,4 +3313,57 @@@ 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 --cc crates/ai-memory-workstream/src/transcript.rsindex a10a3ba5,77ef8ee7..20c9f03b--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@@ -6075,30 -6390,4 +6388,25 @@@ mod testsNone);}++ #[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 --cc docs/managed-workstreams.mdindex 378c16a8,66a497e6..d42ce968--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@@ -419,36 -419,45 +419,75 @@@ another shell, pass `--workstream-id <uthe source harness, role, event sequence, and content. Historical tool activityis labelled completed evidence and must never be replayed as a pending call.+ Search and tail also return optional `source_record_id` and `metadata` fields.+ The text CLI prints the source record and correlation metadata as escaped JSON;+ `--json` preserves these fields for consumers. Older server responses without+ them remain readable. Startup context packets keep their existing format and+ omit these additional fields.++ Source labels and string metadata values are scrubbed with the server's+ configured sanitizer **before** the 512-byte UTF-8 cap. The metadata allowlist+ matches the shipped adapters: string `tool`, `tool_call_id`, `tool_use_id`,+ `parent_id`, `summary_type`, and `status`; boolean `is_error`; signed 32-bit+ `exit_code`; and unsigned 64-bit `loss_count`. Unknown keys, nested objects,+ arrays, and wrong scalar types are discarded. Empty metadata is omitted. These+ labels describe untrusted historical evidence; they cannot grant authority,+ choose a project, or prove a tool's success independently.++ The same scrub and allowlist protect legacy SQLite rows during search/tail,+ without rewriting them. Malformed metadata or legacy dumps over 16 KiB return+ no metadata. Existing raw segments are not rewritten by a read. The ledger's+ FTS query, ranking, ordering, and limits remain unchanged; provenance is fetched+ in the existing event query, without additional per-result SQL reads.++ `event_id` remains the deduplication key. Native adapters derive it from the+ original source before provenance redaction; truncating or redacting two source+ labels therefore cannot merge distinct event ids. Repeating an event is a+ no-op when its stable identity (`agent`, `native_session_id`, `kind`) matches.+ The first indexed content, role, timestamp and provenance remain unchanged,+ even if a later upload differs or the sanitizer's patterns have changed. This+ also permits replay of legacy rows above today's write bounds; read-time+ provenance sanitization still applies. Changing the stable identity is rejected+ and the SQL batch rolls back. A rejected immutable raw segment is not indexed;+ a corrected retry can import the valid batch without advancing history for the+ rejected one. Finished runs retain the existing no-op behavior for late events,+ including new event ids; their history and latest sequence do not advance.++ Client event ids beginning with `managed-run:` are refused before raw storage,+ including on retries of a finished run. This namespace belongs to the server's+ checkpoint and extraction-loss events, which it appends when completing an+ active run.++## 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 --cc docs/security-boundaries.mdindex e28e370a,d3787c69..65f0047e--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@@ -59,13 -63,15 +63,16 @@@ boundary not yet built| 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG || 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI || 11g | Cross-project file attribution cannot bypass destination capture or server routing (#932) | `ai-memory-hooks/src/capture_policy.rs` `absolute_file_tool_paths` accepts only bounded, recognized, absolute file-tool candidates; `ai-memory-cli/src/commands/hook.rs` `file_tool_routing_cwd` requires every path to prove the same repository/marker boundary and resolves that destination before capture policy, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths` | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |+ | 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 || 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; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `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); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | 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 |+ | 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments; `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, using an explicitly supplied configured sanitizer; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`; `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |+ | 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; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_attached_background_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050); `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` `claude_attached_background_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`; `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 || 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 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 |+ | 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` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `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 |+ | 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |+ | 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) 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`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). The hook-ingress SessionStart link by `AI_MEMORY_RUN_ID` is a separate server-internal path not covered here. Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |++| 14au | Exact native managed identity and privacy (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` | 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 |