Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(workstream): route managed runs by the checkout's remote identity (#1182)
victorcescc07585227529
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b43a8edc..9b7d9061 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Settings window behind the frontmost app, so clicking it appeared to donothing. The item now activates the app before opening the window, as**Show Status…** already did. (#1161)+- Fixed `ai-memory run` creating an empty twin project when a repository's+ folder name differs from its git remote (a `new-space-game` checkout of+ `github.com/acme/unknown-system`) and its project predates recorded+ identities: the run asked for the remote-derived name alone, so it missed+ the folder-named project, and once hook capture claimed that project every+ later run failed with `project '…' is ambiguous`. The launcher now sends the+ checkout's remote identity with the derived name and the server routes the+ run by identity, as capture does — which also lets runs in an+ already-affected repository open again. (#1182)## [2.6.2] - 2026-10-08diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 9034d675..f6ffe9be 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -656,6 +656,7 @@ async fn run_once_with_wiring(new_workstream: args.new_workstream,force_unlock,lease_owner: lease_owner(),+ repository_identity: remote_identity_naming(&repository.cwd, &project),};let interrupted_before_spawn = CancellationToken::new();let interrupt_task = tokio::spawn(capture_interrupts(interrupted_before_spawn.clone()));@@ -2376,6 +2377,18 @@ fn auto_session_dir(.session_dir)}+/// The checkout's git-remote identity when `project` is the name it derives,+/// so the server can route the run by identity the way hook capture does. A+/// name from `--project` or a marker that differs from it routes by name.+fn remote_identity_naming(cwd: &Path, project: &str) -> Option<String> {+ crate::marker::discover_remote_identity(&cwd.to_string_lossy())+ .filter(|identity| {+ ai_memory_core::repository_identity::path_style_name(identity).as_deref()+ == Some(project)+ })+ .map(|identity| identity.identity)+}+fn unique_auto_agents(candidates: &[AutoSessionCandidate]) -> Vec<AgentKind> {let mut agents = Vec::new();for candidate in candidates {@@ -3751,6 +3764,41 @@ mod tests {JailPlan { warn, mode }}+ #[test]+ fn run_sends_the_remote_identity_only_for_the_name_it_derives() {+ let tmp = tempfile::TempDir::new().unwrap();+ let repo = tmp.path().join("new-space-game");+ std::fs::create_dir_all(&repo).unwrap();+ for args in [+ &["init", "-q"][..],+ &[+ "remote",+ "add",+ "origin",+ "[email protected]:victorcesc/unknown-system.git",+ ],+ ] {+ assert!(+ std::process::Command::new("git")+ .args(args)+ .current_dir(&repo)+ .status()+ .unwrap()+ .success()+ );+ }+ assert_eq!(+ remote_identity_naming(&repo, "victorcesc-unknown-system").as_deref(),+ Some("github.com/victorcesc/unknown-system")+ );+ // A folder-name, `--project`, or marker name routes by name alone.+ assert_eq!(remote_identity_naming(&repo, "new-space-game"), None);+ assert_eq!(+ remote_identity_naming(tmp.path(), "victorcesc-unknown-system"),+ None+ );+ }+/// The full decision table: request × jailed × yolo × interactive ×/// usable × project `.ai-jail`. `interactive` stands for "stdin and stderr/// are both TTYs".@@ -4743,6 +4791,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "workstation:43".into(),+ repository_identity: None,};let prepared = prepare_managed_run_with_retry(@@ -5014,6 +5063,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "workstation:43".into(),+ repository_identity: None,}}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 60e2d1ac..b0dd7113 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1532,6 +1532,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {sanitizer: sanitizer.clone(),wiki: wiki.clone(),data_dir: config.data_dir.clone(),+ home_dir: config.home_dir.clone(),trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),});let admin = admin_router_with_sweep_tuning(diff --git a/crates/ai-memory-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rsindex 3ba736b8..1414be12 100644--- a/crates/ai-memory-core/src/workstream.rs+++ b/crates/ai-memory-core/src/workstream.rs@@ -259,6 +259,13 @@ pub struct PrepareManagedRunRequest {pub force_unlock: bool,/// Diagnostic owner label (host and process id), not an authorization key.pub lease_owner: String,+ /// The checkout's git-remote identity (`github.com/acme/api`), sent only+ /// when `project` is the name that identity derives. The server then+ /// routes by identity, as hook capture does, so a project created from the+ /// folder name before identities were recorded is claimed instead of+ /// twinned under the derived name. Old servers ignore it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub repository_identity: Option<String>,}/// Result of preparing a managed invocation.diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 56e3b9c4..bca84a7e 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -15,7 +15,7 @@ use ai_memory_core::{};use ai_memory_store::{FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, RenameWorkstream, ScopeResolutionError,- StoreError, WorkstreamSelection, WorkstreamSelector, WriterHandle,+ StoreError, WorkstreamSelection, WorkstreamSelector, WriterHandle, authorize_scope_for,create_explicit_scope_guarded, lookup_existing_scope_guarded,};use ai_memory_wiki::Wiki;@@ -48,6 +48,9 @@ pub struct WorkstreamState {pub wiki: Wiki,/// ai-memory data root containing `raw/workstreams`.pub data_dir: PathBuf,+ /// Operator home directory; a project rooted there never claims a run's+ /// checkout by cwd prefix, as in hook routing.+ pub home_dir: Option<String>,/// Whether a trusted proxy can distinguish operators without DB users.pub trusted_proxy_identity: bool,#[cfg(test)]@@ -210,6 +213,79 @@ fn scope_refusal(failure: ScopeResolutionError) -> Response {}}+/// The scope a managed run opens in, and whether resolving it renamed the+/// project in place.+///+/// A run whose `project` is the name its checkout's git remote derives routes+/// by that identity, through the same writer transaction hook capture uses:+/// the project already carrying the identity wins, else the project whose+/// `repo_path` contains the cwd is claimed. Routing by name alone would miss a+/// project created from the folder name before identities were recorded,+/// create an identity-less twin under the derived name, and leave every later+/// run ambiguous once capture claimed the original. Any other run keeps the+/// explicit-name path.+async fn resolve_run_scope(+ state: &WorkstreamState,+ request: &PrepareManagedRunRequest,+ viewer: Option<ai_memory_core::UserId>,+) -> Result<(ai_memory_store::ResolvedScope, bool), ScopeResolutionError> {+ use ai_memory_core::repository_identity::{+ IdentitySource, IdentityStyle, accept_wire_identity, path_style_name,+ };+ let workspace = request.workspace.trim();+ let project = request.project.trim();+ let identity = request+ .repository_identity+ .as_deref()+ .and_then(|identity| accept_wire_identity(identity, IdentitySource::GitRemote.as_str()))+ .filter(|identity| path_style_name(identity).as_deref() == Some(project))+ .filter(|_| !ai_memory_core::profile::is_reserved_scope_project(project));+ let Some(identity) = identity else {+ let resolved =+ create_explicit_scope_guarded(&state.reader, &state.writer, workspace, project, viewer)+ .await?;+ return Ok((resolved.scope, resolved.promoted_from.is_some()));+ };+ let workspace_id = state+ .writer+ .get_or_create_workspace(workspace.to_owned())+ .await?;+ let candidate = state+ .reader+ .find_project_by_cwd_prefix(workspace_id, request.cwd.clone(), state.home_dir.as_deref())+ .await?+ .map(|(project_id, _)| project_id);+ let (project_id, resolution) = state+ .writer+ .resolve_project_by_identity_for_capture(+ workspace_id,+ identity,+ IdentityStyle::Path,+ project,+ None,+ candidate,+ viewer,+ )+ .await?;+ // The writer claims or renames only for a caller who may write; matching+ // or finding a project is not access to it.+ let scope = authorize_scope_for(+ &state.reader,+ Some(&state.writer),+ ai_memory_store::ResolvedScope {+ workspace_id,+ project_id,+ },+ viewer,+ ai_memory_store::ProjectAccess::Write,+ )+ .await?;+ Ok((+ scope,+ resolution == ai_memory_store::IdentityResolution::Promoted,+ ))+}+async fn prepare_run(State(state): State<WorkstreamState>,level: Option<Extension<AuthLevel>>,@@ -311,36 +387,25 @@ async fn prepare_run(if let Err(failure) = selection.validate() {return store_error_response(failure);}- let resolved_scope = match create_explicit_scope_guarded(- &state.reader,- &state.writer,- request.workspace.trim(),- request.project.trim(),- actor_user(viewer),- )- .await- {- Ok(scope) => scope,+ let (scope, promoted) = match resolve_run_scope(&state, &request, actor_user(viewer)).await {+ Ok(resolved) => resolved,Err(failure) if failure.is_forbidden() => {return error(StatusCode::FORBIDDEN, failure.to_string());}Err(failure) => return error(StatusCode::BAD_REQUEST, failure.to_string()),};- let manifest_warning = if resolved_scope.promoted_from.is_some() {+ let manifest_warning = if promoted {match state.wiki- .refresh_renamed_scope(- resolved_scope.scope.workspace_id,- resolved_scope.scope.project_id,- )+ .refresh_renamed_scope(scope.workspace_id, scope.project_id).await{Ok(_) => None,Err(failure) => {warn!(error = %failure,- workspace_id = %resolved_scope.scope.workspace_id,- project_id = %resolved_scope.scope.project_id,+ workspace_id = %scope.workspace_id,+ project_id = %scope.project_id,"project name promotion committed; manifest refresh/checkpoint failed; startup backfill can repair");Some(@@ -353,7 +418,6 @@ async fn prepare_run(} else {None};- let scope = resolved_scope.scope;let identity = actor.and_then(|Extension(actor)| actor.identity_key());let owner_user = match managed_run_owner_stamp(&state.reader,@@ -1253,6 +1317,7 @@ mod tests {.unwrap().with_store_reader(store.reader.clone()),data_dir: data_dir.to_path_buf(),+ home_dir: None,trusted_proxy_identity: false,finish_barrier: None,}@@ -1355,6 +1420,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "launcher".into(),+ repository_identity: None,};let refused = prepare_run(State(state.clone()),@@ -1462,6 +1528,7 @@ mod tests {new_workstream: Some("new".into()),force_unlock: false,lease_owner: "launcher".into(),+ repository_identity: None,}),).await;@@ -1531,6 +1598,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "launcher".into(),+ repository_identity: None,}),).await;@@ -1626,6 +1694,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "launcher".into(),+ repository_identity: None,}),).await;@@ -1709,6 +1778,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "launcher".into(),+ repository_identity: None,}),).await;@@ -2627,6 +2697,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "automatic".into(),+ repository_identity: None,}),).await;@@ -2665,6 +2736,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "explicit".into(),+ repository_identity: None,}),).await;@@ -2715,6 +2787,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "automatic".into(),+ repository_identity: None,}),).await;@@ -2762,6 +2835,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "alice-launcher".into(),+ repository_identity: None,}),).await;@@ -2864,6 +2938,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "alice:1".into(),+ repository_identity: None,}),).await;@@ -3001,6 +3076,7 @@ mod tests {new_workstream: None,force_unlock,lease_owner: lease_owner.into(),+ repository_identity: None,};let first = prepare_run(@@ -3085,6 +3161,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "explicit".into(),+ repository_identity: None,}),).await;@@ -3134,6 +3211,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "automatic".into(),+ repository_identity: None,}),).await;@@ -3164,6 +3242,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "explicit".into(),+ repository_identity: None,}),).await;@@ -3213,6 +3292,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "automatic".into(),+ repository_identity: None,}),).await;@@ -3243,6 +3323,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "explicit".into(),+ repository_identity: None,}),).await;@@ -3292,6 +3373,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "automatic".into(),+ repository_identity: None,}),).await;@@ -3325,6 +3407,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "explicit".into(),+ repository_identity: None,}),).await;@@ -3374,6 +3457,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "automatic".into(),+ repository_identity: None,}),).await;@@ -3658,6 +3742,7 @@ mod tests {new_workstream: None,force_unlock: false,lease_owner: "alice".into(),+ repository_identity: None,}),).await;@@ -4320,4 +4405,370 @@ mod tests {StatusCode::OK);}++ /// A checkout's run request as `ai-memory run` sends it for a repository+ /// whose folder name differs from its remote's derived name.+ fn identity_run_request(project: &str, identity: Option<&str>) -> PrepareManagedRunRequest {+ PrepareManagedRunRequest {+ workspace: "default".into(),+ project: project.into(),+ cwd: "/repo/new-space-game".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: Vec::new(),+ workstream: None,+ new_workstream: None,+ force_unlock: false,+ lease_owner: "launcher".into(),+ repository_identity: identity.map(str::to_owned),+ }+ }++ fn unknown_system() -> ai_memory_core::repository_identity::RepositoryIdentity {+ ai_memory_core::repository_identity::RepositoryIdentity {+ identity: "github.com/victorcesc/unknown-system".into(),+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,+ }+ }++ async fn run_project(+ store: &Store,+ response: Response,+ ) -> (ai_memory_core::WorkspaceId, ai_memory_core::ProjectId) {+ assert_eq!(response.status(), StatusCode::OK);+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();+ store+ .reader+ .managed_run_scope(prepared.run_id)+ .await+ .unwrap()+ .unwrap()+ }++ async fn project_names(store: &Store) -> Vec<String> {+ let mut names: Vec<String> = store+ .reader+ .list_projects_with_stats_for_workspace("default".into(), None)+ .await+ .unwrap()+ .into_iter()+ .map(|summary| summary.project_name)+ .collect();+ names.sort();+ names+ }++ #[tokio::test]+ async fn managed_run_by_remote_identity_claims_the_folder_named_project() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ // Created from the folder name before identities were recorded.+ let legacy = store+ .writer+ .get_or_create_project(+ workspace_id,+ "new-space-game",+ Some("/repo/new-space-game".into()),+ )+ .await+ .unwrap();++ let response = prepare_run(+ State(state),+ None,+ None,+ None,+ Json(identity_run_request(+ "victorcesc-unknown-system",+ Some("github.com/victorcesc/unknown-system"),+ )),+ )+ .await;++ assert_eq!(run_project(&store, response).await, (workspace_id, legacy));+ assert_eq!(project_names(&store).await, ["victorcesc-unknown-system"]);+ }++ #[tokio::test]+ async fn managed_run_by_remote_identity_routes_past_an_identityless_twin() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let (holder, _) = store+ .writer+ .resolve_project_by_identity(+ workspace_id,+ unknown_system(),+ ai_memory_core::repository_identity::IdentityStyle::HostPath,+ "new-space-game",+ Some("/repo/new-space-game".into()),+ None,+ None,+ )+ .await+ .unwrap();+ // The twin an earlier name-only run created under the derived name.+ store+ .writer+ .get_or_create_project(workspace_id, "victorcesc-unknown-system", None)+ .await+ .unwrap();++ // By name alone the derived name names both projects.+ let by_name = prepare_run(+ State(state.clone()),+ None,+ None,+ None,+ Json(identity_run_request("victorcesc-unknown-system", None)),+ )+ .await;+ assert_eq!(by_name.status(), StatusCode::BAD_REQUEST);++ let by_identity = prepare_run(+ State(state),+ None,+ None,+ None,+ Json(identity_run_request(+ "victorcesc-unknown-system",+ Some("github.com/victorcesc/unknown-system"),+ )),+ )+ .await;+ assert_eq!(+ run_project(&store, by_identity).await,+ (workspace_id, holder)+ );+ assert_eq!(+ project_names(&store).await,+ ["new-space-game", "victorcesc-unknown-system"]+ );+ }++ #[tokio::test]+ async fn managed_run_identity_never_redirects_another_project_name() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let (holder, _) = store+ .writer+ .resolve_project_by_identity(+ workspace_id,+ unknown_system(),+ ai_memory_core::repository_identity::IdentityStyle::Path,+ "new-space-game",+ None,+ None,+ None,+ )+ .await+ .unwrap();++ // An identity that does not derive the requested name is ignored: the+ // run opens the project it names, never the identity's holder.+ let response = prepare_run(+ State(state),+ None,+ None,+ None,+ Json(identity_run_request(+ "scratchpad",+ Some("github.com/victorcesc/unknown-system"),+ )),+ )+ .await;+ let (_, opened) = run_project(&store, response).await;+ assert_ne!(opened, holder);+ assert_eq!(+ store+ .reader+ .project_name_by_id(workspace_id, opened)+ .await+ .unwrap()+ .as_deref(),+ Some("scratchpad")+ );+ }++ #[tokio::test]+ async fn managed_run_by_remote_identity_refuses_a_viewer_without_write() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let (holder, _) = store+ .writer+ .resolve_project_by_identity(+ workspace_id,+ unknown_system(),+ ai_memory_core::repository_identity::IdentityStyle::HostPath,+ "new-space-game",+ Some("/repo/new-space-game".into()),+ None,+ None,+ )+ .await+ .unwrap();+ store+ .writer+ .set_access_mode(holder, ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ let user = |name: &str, seed: u8| {+ store.writer.create_user(+ ai_memory_core::NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ [seed; ai_memory_store::TOKEN_HASH_LEN],+ )+ };+ let outsider = user("outsider", 3).await.unwrap();+ let member = user("member", 4).await.unwrap();+ store+ .writer+ .grant_memory(member, holder, ai_memory_store::GrantLevel::Write, None)+ .await+ .unwrap();+ let request = || {+ Json(identity_run_request(+ "victorcesc-unknown-system",+ Some("github.com/victorcesc/unknown-system"),+ ))+ };++ let refused = prepare_run(+ State(state.clone()),+ Some(Extension(AuthLevel::User)),+ None,+ Some(Extension(ai_memory_core::AuthorizedViewer(outsider))),+ request(),+ )+ .await;+ assert_eq!(refused.status(), StatusCode::FORBIDDEN);+ // Neither a run nor a project to hold one appeared for the outsider.+ assert_eq!(project_names(&store).await, ["new-space-game"]);++ let admitted = prepare_run(+ State(state),+ Some(Extension(AuthLevel::User)),+ None,+ Some(Extension(ai_memory_core::AuthorizedViewer(member))),+ request(),+ )+ .await;+ assert_eq!(run_project(&store, admitted).await, (workspace_id, holder));+ }++ #[tokio::test]+ async fn managed_run_identity_routing_stays_inside_the_requested_workspace() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let default_ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let (holder, _) = store+ .writer+ .resolve_project_by_identity(+ default_ws,+ unknown_system(),+ ai_memory_core::repository_identity::IdentityStyle::HostPath,+ "new-space-game",+ Some("/repo/new-space-game".into()),+ None,+ None,+ )+ .await+ .unwrap();++ let mut request = identity_run_request(+ "victorcesc-unknown-system",+ Some("github.com/victorcesc/unknown-system"),+ );+ request.workspace = "client-work".into();+ let response = prepare_run(State(state), None, None, None, Json(request)).await;++ // Another workspace's identity holder is never the target: the run+ // gets that workspace's own project for the repository.+ let (workspace_id, opened) = run_project(&store, response).await;+ assert_ne!(workspace_id, default_ws);+ assert_ne!(opened, holder);+ assert_eq!(+ store+ .reader+ .project_name_by_id(workspace_id, opened)+ .await+ .unwrap()+ .as_deref(),+ Some("victorcesc-unknown-system")+ );+ assert_eq!(project_names(&store).await, ["new-space-game"]);+ }++ #[tokio::test]+ async fn concurrent_identity_runs_on_a_legacy_project_converge_on_it() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let legacy = store+ .writer+ .get_or_create_project(+ workspace_id,+ "new-space-game",+ Some("/repo/new-space-game".into()),+ )+ .await+ .unwrap();+ let request = |workstream: &str| {+ let mut request = identity_run_request(+ "victorcesc-unknown-system",+ Some("github.com/victorcesc/unknown-system"),+ );+ request.new_workstream = Some(workstream.into());+ Json(request)+ };++ // Two launches in one checkout race the first claim of the row.+ let (first, second) = tokio::join!(+ prepare_run(State(state.clone()), None, None, None, request("market")),+ prepare_run(State(state), None, None, None, request("mine-meshs")),+ );++ assert_eq!(run_project(&store, first).await, (workspace_id, legacy));+ assert_eq!(run_project(&store, second).await, (workspace_id, legacy));+ assert_eq!(project_names(&store).await, ["victorcesc-unknown-system"]);+ }}diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rsindex f5763b6e..4b8cce10 100644--- a/crates/ai-memory-mcp/src/auth.rs+++ b/crates/ai-memory-mcp/src/auth.rs@@ -1787,6 +1787,7 @@ mod tests {.unwrap().with_store_reader(store.reader.clone()),data_dir: root.into(),+ home_dir: None,trusted_proxy_identity: auth.actor_proxy_bearer().is_some(),}).layer(axum::middleware::from_fn_with_state(@@ -1978,6 +1979,7 @@ mod tests {.unwrap().with_store_reader(store.reader.clone()),data_dir: tmp.path().into(),+ home_dir: None,trusted_proxy_identity: false,}).layer(axum::middleware::from_fn_with_state(@@ -2438,6 +2440,7 @@ mod tests {.unwrap().with_store_reader(store.reader.clone()),data_dir: tmp.path().into(),+ home_dir: None,trusted_proxy_identity: false,}).layer(axum::middleware::from_fn(diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 5ba892f9..2c046a7c 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -396,8 +396,15 @@ resume, continue, session, or fork selector.## What happens on each run1. The host client resolves the normal workspace/project scope and a stable- repository plus worktree fingerprint. If an identity-backed project still- carries its legacy basename, this authorized write promotes the same UUID to+ repository plus worktree fingerprint. When the project is the canonical path+ name the checkout's git remote derives, the client also sends that remote+ identity, and the server opens the run in the project hook capture uses for+ the checkout: the one already carrying the identity, else the project whose+ repository path contains the cwd, which a writer claims in place. A project+ created from a different folder name before identities were recorded is+ therefore reused rather than twinned under the derived name (#1182); a name+ from `--project` or a marker routes by name as before. If an+ identity-backed project still carries its legacy basename, this authorized write promotes the same UUID toits canonical path name and refreshes the wiki scope manifest before openingthe lease; a post-commit manifest failure is returned as`manifest_warning` on either success or a later prepare error, retaining thediff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 5360eeb3..2e90179c 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -57,7 +57,7 @@ boundary not yet built.| 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG || 8d | Messaging: inferred-scope read is diagnosed (#854) | `scope.rs` `is_inferred`; `server.rs` `inferred_scope_hint` on empty pop/list | `agent_messages_briefing.rs` `no_scope_pop_that_misses_the_mail_is_diagnosed_not_a_silent_null` | STRONG || 8e | Messaging: admission is the same for MCP and admin sends (#756) | `ai-memory-mcp/src/admin.rs` `handle_send_message` runs `Wiki::authorize_operation(.., AdmissionOp::MessageSend, ..)` at the recipient scope before `insert_message` (a refusal is 403 and stores nothing) and calls `notify_operation_observers` only after a successful commit; skipping webhooks needs `Capability::SkipAdmissionChain` (`skip_webhooks_for_admin_request`); the MCP path is `server.rs` `memory_message_send` | `admin.rs` `admin_message_send_reject_leaves_inbox_empty` (a rejecting webhook gets 403 and an empty inbox; fails with the admission call removed), controls `admin_message_send_observer_sees_commit_without_blocking_response` and `admin_message_send_full_inbox_does_not_notify_observer` | STRONG |-| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; its message names each holder and the key it matched by, but a restricted holder only as "a restricted project", because the lookup runs before any caller is authorized and the project list hides restricted names from callers without a grant; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, `a_slashed_label_reaches_only_a_project_the_caller_may_use` (a `workspace/project` label passed as the project is authorized as the pair it names and creates nothing when refused; granted control), `a_slashed_write_resolves_its_own_pair_and_never_creates`, `an_existing_slashed_project_wins_over_the_split`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `an_ambiguous_name_names_its_holders_but_not_a_restricted_one` (restricted holder unnamed; open holder named as the control), `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG |+| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; its message names each holder and the key it matched by, but a restricted holder only as "a restricted project", because the lookup runs before any caller is authorized and the project list hides restricted names from callers without a grant; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. A managed run whose `project` is the name its checkout's git remote derives (`PrepareManagedRunRequest.repository_identity`, accepted only through `accept_wire_identity` and only when `path_style_name` equals the requested name) resolves through `resolve_project_by_identity_for_capture` — the identity holder, else the cwd-prefix project with `$HOME` excluded, claimed or renamed only for a writer — and then `authorize_scope_for(Write)` on the writer connection, so an identity can neither redirect a differently named run nor open, claim, or create a project the caller may not write; Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, `a_slashed_label_reaches_only_a_project_the_caller_may_use` (a `workspace/project` label passed as the project is authorized as the pair it names and creates nothing when refused; granted control), `a_slashed_write_resolves_its_own_pair_and_never_creates`, `an_existing_slashed_project_wins_over_the_split`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `an_ambiguous_name_names_its_holders_but_not_a_restricted_one` (restricted holder unnamed; open holder named as the control), `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_by_remote_identity_claims_the_folder_named_project`, `managed_run_by_remote_identity_routes_past_an_identityless_twin` (name-only control is ambiguous), `managed_run_identity_never_redirects_another_project_name`, `managed_run_by_remote_identity_refuses_a_viewer_without_write` (outsider refused with no project created; granted member admitted as the control), `managed_run_identity_routing_stays_inside_the_requested_workspace`, `concurrent_identity_runs_on_a_legacy_project_converge_on_it` (invariant #16), `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG || 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it | STRONG || 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control | STRONG || 10c | Ledger reclaim is content-gated, not filename-gated (invariant #16) | `ai-memory-store/src/ops.rs` `reclaim_ledger_versions` — a candidate row must pass `ai_memory_core::log_ledger::body_opens_with_log_ledger` on its own `body`, and only `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned rows stay with `forget-sweep`; confirm gate in `admin.rs` `handle_reclaim_ledger_versions` | `reclaim_ledger_versions.rs` `a_prose_page_wearing_the_ledger_name_keeps_its_whole_version_chain`, `an_ordinary_page_chain_in_another_project_is_untouched`, `a_decay_tombstone_stays_with_the_sweep_that_owns_it`; `admin_reclaim_ledger_versions.rs` `deleting_without_confirm_is_refused_and_changes_nothing` (with dry-run and confirmed controls) | STRONG |@@ -83,7 +83,7 @@ boundary not yet built.| 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). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). 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`, `claude_transcript_is_located_by_the_real_folder_name` (a server-linked Claude id probed across project folders still resolves only to a transcript whose own header names this checkout; another checkout's transcript and a subagent sidechain with the same id are refused); 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`; when a Phase-5 client explicitly sends `IdentityStyle::Path` (#1033) a project it creates takes `path_style_name` only while no different full identity in the workspace claims that canonical key (checked in the same transaction), so the same path on another forge falls back instead of being merged; authorized captures can claim/promote compatible legacy rows in that transaction while preserving UUID, but handoff/static reads never rename; explicit `host_path` remains the opt-out; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity and style; `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`, `the_same_path_on_another_forge_falls_back_instead_of_merging`, `an_unclaimed_project_holding_the_path_name_is_not_taken`, `old_client_omitted_style_stays_host_path_and_does_not_promote`, `explicit_path_capture_claims_and_promotes_an_identityless_legacy_name_in_one_transaction`, `unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_name`, and `explicit_path_capture_falls_back_when_another_identity_claims_the_canonical_key` (controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `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 |+| 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`; when a Phase-5 client explicitly sends `IdentityStyle::Path` (#1033) a project it creates takes `path_style_name` only while no different full identity in the workspace claims that canonical key (checked in the same transaction), so the same path on another forge falls back instead of being merged; authorized captures can claim/promote compatible legacy rows in that transaction while preserving UUID, but handoff/static reads never rename; explicit `host_path` remains the opt-out; `ai-memory-hooks/src/workstream.rs` `resolve_run_scope` sends a managed run through the same transaction (identity holder, else the `$HOME`-guarded cwd-prefix candidate, inside the requested workspace only) only when the wire identity derives the requested name, then authorizes Write (#1182); `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity and style; `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`, `the_same_path_on_another_forge_falls_back_instead_of_merging`, `an_unclaimed_project_holding_the_path_name_is_not_taken`, `old_client_omitted_style_stays_host_path_and_does_not_promote`, `explicit_path_capture_claims_and_promotes_an_identityless_legacy_name_in_one_transaction`, `unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_name`, and `explicit_path_capture_falls_back_when_another_identity_claims_the_canonical_key` (controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; hooks `workstream.rs` `managed_run_by_remote_identity_refuses_a_viewer_without_write`, `managed_run_identity_never_redirects_another_project_name`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `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 || 14bb | Local marker aliases cannot cross repository or workspace boundaries (#1033) | `ai-memory-core/src/repository_identity.rs` owns the bounded `MarkerAliases` type and exact one-line/root-level portable grammar; native/POSIX/PowerShell/generated TypeScript clients forward one normalized JSON-array query value only with marker provenance and a hostful git-remote identity; `ai-memory-store/src/project_coordinates.rs` probes exact names only inside the selected workspace, deduplicates by UUID, and requires the selected row's full stored git-remote identity; `ops.rs` authorizes in the writer transaction and reuses Phase 1 `promotion_target`, additionally requiring marker `project` to equal the canonical path-style name derived from that remote; handoff uses the read-only path and capture uses the write-authorized path; `router.rs` includes aliases, provenance, and read/write mode in its cache key | Core/CLI shared `marker_aliases` fixture parity covers duplicate keys, table placement, multiline arrays, trailing junk/comma, escapes, max length and duplicate-heavy over-count; store `marker_aliases_require_same_remote_identity_and_preserve_uuid`, `marker_aliases_cannot_promote_to_an_arbitrary_marker_project`, `hostile_ambiguous_and_cross_workspace_marker_aliases_fail_closed`; hooks `hook_and_handoff_queries_validate_aliases_identically`, `malformed_aliases_are_rejected_before_subagent_scope_resolution`, `empty_aliases_preserve_marker_project_precedence`, `capture_promotes_an_alias_but_handoff_only_reads_it`, `project_cache_separates_alias_sets`; shell `marker aliases keep canonical project and forward remote identity`; Windows PowerShell parity and capture-only marker transparency run in Windows CI; OpenClaw `openclaw_runtime_preserves_marker_and_home_identity_precedence` proves no-marker remote routing sends explicit `path`, ordinary project markers keep name precedence and omit identity, while alias markers and home identity routes forward it | STRONG: hostile arbitrary-name, different-identity and ambiguous aliases refuse or resolve without rename with a legitimate canonical same-identity control; another workspace is never searched; no alias table or persistent fallback exists || 14bb2 | Operator-home route selectors cannot silently cross repository or path boundaries (#1033) | `ai-memory-cli/src/marker.rs` returns a typed invalid result for malformed/oversized maps; command scope resolution propagates it unless both CLI scope fields are explicit, while native hooks drop before spool/network. The native, POSIX, PowerShell, generated TypeScript and OpenClaw parsers enforce the shared 64-route/64-KiB/512-byte grammar, recognize malformed `[routes`, `routes =`, `routes.`, and orphan `route_*` syntax before any no-routes return, preserve legacy parsing for malformed root-only settings without route syntax, apply global duplicate-field/raw-selector/normalized-path checks, require exact hostful identities (including host-edge-dot refusal), match paths component-wise, and enforce a no-escape boundary for `~/` selectors. A route replaces only routing fields; root privacy/behavior flags survive. Bounded native/PowerShell/TypeScript reads reject before full-file allocation where their APIs permit. | `ai-memory-core/fixtures/home_route_cases.json` is executed by native `marker.rs`, POSIX, PowerShell, generated TypeScript, and OpenClaw runtime parity, including malformed route syntax and root-only malformed legacy behavior; shell `test_lib.sh` also exercises route selection, sibling refusal, root-setting retention and invalid-map drop; Windows `powershell_marker_aliases.rs` executes drive and UNC path routing independently of identity; generated TypeScript runtime tests assert marker versus repo-root `project_src`; CLI tests prove unscoped/partial refusal and complete-explicit bypass. | STRONG for native/POSIX/generated TypeScript/OpenClaw on this platform; PowerShell runtime evidence is enforced on Windows CI and skipped where PowerShell is unavailable || 14bc | Project-coordinate diagnostics are root-only, read-only and credential-safe (#1033) | `ai-memory-store/src/reader.rs` `diagnose_project_coordinate` and `project_coordinates.rs` share one bounded indexed matcher and the write path's canonical-only promotion predicate; `ai-memory-mcp/src/admin.rs` mounts `GET /admin/project-coordinate` behind the shared `Capability::Admin` middleware and returns no stored identity value; `ai-memory-cli/src/marker.rs` and `commands/hook_capture.rs` provide one strict typed local inspection consumed by `doctor`, which reports only marker/source classes, identity source/style and derived names. Ambiguous count lookup keeps local rows and marks captured counts unavailable | Store `identity_resolution.rs` `coordinate_diagnostic_classifies_exact_canonical_legacy_and_missing_without_mutation`, `coordinate_diagnostic_reports_cross_forge_and_identityless_collisions`; `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; MCP `admin_status_search.rs` `project_coordinate_reports_all_statuses_and_never_mutates`, `project_coordinate_is_root_only_after_multiuser_enablement`, `project_coordinate_single_user_admin_contract_remains_open`, plus the shared all-admin 403/401 route matrix; CLI `doctor.rs` `project_coordinate_renders_promotion_and_cross_forge_fallback_concisely`, `local_coordinate_reports_marker_precedence_invalid_toml_and_no_credentials`; `marker.rs` strict inspection tests; `doctor_e2e.rs` `ambiguous_coordinate_keeps_local_sessions_and_marks_capture_unavailable` | STRONG: project/audit/user/grant/page counts, names and manifest bytes are snapshotted; DB-user/anonymous refusal has a root control; sentinel repo paths, identities, users, grants, pages, malformed marker text, absolute marker paths and credential-bearing remotes do not appear in output; an ambiguous preferred candidate remains contextual only and is never rename-eligible |