Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(workstream): recover ambiguous project selections by ID
Éverton Toffanettoaafd5c55be2d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1de0fc27..ca76f96b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,14 @@ version in [`docs/changelog/`](docs/changelog/):### Added+- Added `--project-id` to managed launches and checkout-local discovery to+ recover populated legacy name collisions without moving or merging history.+ An interactive launch offers authorized project choices and remembers the+ selection for that server and checkout. Resumes reuse the binding, and+ ID-selected runs keep startup context and hook capture in the selected scope+ after checking current access, run ownership and native session identity.+ Existing name selectors and legacy runs retain their behavior (#1833).+- Added `ai-memory run --no-exit-prompt`, `[run] exit_prompt = false`, and`AI_MEMORY_RUN_EXIT_PROMPT=false` to skip the switch/rerun menu after asuccessful interactive session. The menu remains enabled by default (#1776).diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex ff7606cb..83f3ec82 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -414,8 +414,12 @@ pub struct RunArgs {#[arg(long)]pub workspace: Option<String>,/// Project override. Defaults to the current repository project.- #[arg(long)]+ #[arg(long, conflicts_with = "project_id")]pub project: Option<String>,+ /// Select an existing project by ID and remember it for this checkout.+ /// Requires a server supporting managed project-ID selection.+ #[arg(long, conflicts_with = "project")]+ pub project_id: Option<ai_memory_core::ProjectId>,/// Select an existing named workstream instead of the current one.#[arg(long, conflicts_with = "new_workstream")]pub workstream: Option<String>,@@ -888,8 +892,11 @@ pub struct WorkstreamsArgs {#[arg(long)]pub workspace: Option<String>,/// Project override. Defaults to the current repository project.- #[arg(long)]+ #[arg(long, conflicts_with = "project_id")]pub project: Option<String>,+ /// Select an existing project by ID instead of a name or cached binding.+ #[arg(long, conflicts_with = "project")]+ pub project_id: Option<ai_memory_core::ProjectId>,/// Maximum workstreams to return, current first then newest activity.#[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(1..=100))]pub limit: u8,@@ -5738,6 +5745,36 @@ mod tests {/// ambiguous request never reaches the server to be guessed at.#[test]fn project_id_flags_parse_and_conflict_with_their_name_flags() {+ let managed_id = ai_memory_core::ProjectId::new();+ let id_text = managed_id.to_string();+ let cli =+ Cli::try_parse_from(["ai-memory", "run", "--project-id", &id_text, "claude"]).unwrap();+ let Command::Run(run) = cli.command else {+ panic!("expected run");+ };+ assert_eq!(run.project_id, Some(managed_id));+ let cli =+ Cli::try_parse_from(["ai-memory", "workstreams", "--project-id", &id_text]).unwrap();+ let Command::Workstreams(workstreams) = cli.command else {+ panic!("expected workstreams");+ };+ assert_eq!(workstreams.project_id, Some(managed_id));+ for command in ["run", "workstreams"] {+ assert!(+ Cli::try_parse_from([+ "ai-memory",+ command,+ "--project",+ "api",+ "--project-id",+ &id_text+ ])+ .is_err()+ );+ assert!(+ Cli::try_parse_from(["ai-memory", command, "--project-id", "not-a-uuid"]).is_err()+ );+ }let id = "11111111-2222-3333-4444-555555555555";let cli = Cli::try_parse_from(["ai-memory", "purge-project", "--project-id", id]).unwrap();diff --git a/crates/ai-memory-cli/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rsindex 0c6dd0b0..f4e94ec1 100644--- a/crates/ai-memory-cli/src/commands/continue_session.rs+++ b/crates/ai-memory-cli/src/commands/continue_session.rs@@ -63,11 +63,20 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {scope_label(&link),terminal_text(&target.to_string_lossy()));+ let project_id = project_registry::project_binding(+ config,+ &endpoint,+ &link.workspace,+ &link.project,+ &target,+ )?+ .map(|scope| scope.project_id);return crate::commands::run::run_from(config,RunArgs {workspace: Some(link.workspace),- project: Some(link.project),+ project: project_id.is_none().then_some(link.project),+ project_id,workstream: None,new_workstream: None,executable: None,@@ -145,6 +154,18 @@ pub(super) fn resolve_target(config: &Config, link: &ProjectLink) -> Result<Pathlet path = validate_registered_path(&link.path)?;let (workspace, project) = super::resolve_scope_for_path(config, &path)?;if workspace != link.workspace || project != link.project {+ let bound = project_registry::project_binding_for_server(+ config,+ &link.server,+ &workspace,+ &project,+ &path,+ )?;+ if bound+ .is_some_and(|scope| scope.workspace == link.workspace && scope.project == link.project)+ {+ return Ok(path);+ }bail!("checkout now resolves to {}/{}",terminal_text(&workspace),diff --git a/crates/ai-memory-cli/src/commands/managed_project.rs b/crates/ai-memory-cli/src/commands/managed_project.rsnew file mode 100644index 00000000..16f7bb05--- /dev/null+++ b/crates/ai-memory-cli/src/commands/managed_project.rs@@ -0,0 +1,205 @@+//! Explicit recovery from ambiguous managed project coordinates.++use std::io::{self, BufRead, Write};++use ai_memory_core::{+ ManagedProjectCandidatesRequest, ManagedProjectCandidatesResponse, ManagedProjectScope,+};+use anyhow::{Context as _, Result, bail};+use tokio_util::sync::CancellationToken;++use crate::http_client::{ServerEndpoint, ServerResponseError, post_json};++pub(super) fn validate_prepared_scope(+ request: &ai_memory_core::PrepareManagedRunRequest,+ response: &ai_memory_core::PrepareManagedRunResponse,+) -> Result<()> {+ if request.project_id.is_some() && response.resolved_project.is_none() {+ bail!(+ "the server did not confirm project-ID selection; upgrade the server before launching"+ );+ }+ if let Some(scope) = &response.resolved_project+ && (scope.workspace != request.workspace.trim()+ || request.project_id.is_some_and(|id| id != scope.project_id))+ {+ bail!("the server returned a different managed project scope; refusing to launch");+ }+ Ok(())+}++pub(super) fn is_ambiguous(error: &anyhow::Error) -> bool {+ error+ .downcast_ref::<ServerResponseError>()+ .is_some_and(|error| {+ error.status() == reqwest::StatusCode::BAD_REQUEST+ && serde_json::from_str::<serde_json::Value>(error.body())+ .ok()+ .and_then(|body| {+ body.get("code")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned)+ })+ .as_deref()+ == Some("ambiguous_project")+ })+}++pub(super) fn is_missing(error: &anyhow::Error) -> bool {+ error+ .downcast_ref::<ServerResponseError>()+ .is_some_and(|error| error.status() == reqwest::StatusCode::NOT_FOUND)+}++pub(super) async fn choose(+ endpoint: &ServerEndpoint,+ workspace: &str,+ project: &str,+ interactive: bool,+ interrupted: &CancellationToken,+) -> Result<ManagedProjectScope> {+ let response: ManagedProjectCandidatesResponse = post_json(+ endpoint,+ "/workstream/project-candidates",+ &ManagedProjectCandidatesRequest {+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ },+ )+ .await+ .context(+ "listing authorized project candidates; upgrade the server if this endpoint is unavailable",+ )?;+ if response.candidates.is_empty() {+ bail!(+ "no writable project candidates are available; ask the operator for an authorized project ID and use --project-id <id>"+ );+ }+ if !interactive {+ let choices = response+ .candidates+ .iter()+ .map(|row| {+ format!(+ "{} ({})",+ row.project_id,+ super::show::terminal_text(&row.project)+ )+ })+ .collect::<Vec<_>>()+ .join(", ");+ bail!(+ "project name is ambiguous; rerun with --project-id <id>. Authorized choices: {choices}"+ );+ }+ let read = tokio::task::spawn_blocking(move || {+ read_choice(&response, &mut io::stdin().lock(), &mut io::stderr())+ });+ tokio::select! {+ () = interrupted.cancelled() => bail!("project selection interrupted; no managed run was opened"),+ result = read => result.context("reading project selection")?,+ }+}++fn read_choice(+ response: &ManagedProjectCandidatesResponse,+ input: &mut impl BufRead,+ output: &mut impl Write,+) -> Result<ManagedProjectScope> {+ writeln!(+ output,+ "This checkout's project name is ambiguous. Select the existing project to use:"+ )?;+ for (index, scope) in response.candidates.iter().enumerate() {+ writeln!(+ output,+ " {}. {}/{} [{}]",+ index + 1,+ super::show::terminal_text(&scope.workspace),+ super::show::terminal_text(&scope.project),+ scope.project_id+ )?;+ }+ if response.truncated {+ writeln!(+ output,+ "More matches exist; use --project-id if your project is not shown."+ )?;+ }+ write!(output, "Select a number, or Enter to cancel: ")?;+ output.flush()?;+ let mut line = String::new();+ std::io::Read::take(&mut *input, 128).read_line(&mut line)?;+ let index = line+ .trim()+ .parse::<usize>()+ .ok()+ .and_then(|number| number.checked_sub(1));+ match index.and_then(|index| response.candidates.get(index)) {+ Some(scope) => Ok(scope.clone()),+ None => bail!("project selection cancelled; no managed run was opened"),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn project_id_noninteractive_ambiguity_is_actionable_without_selecting() {+ let scope = ManagedProjectScope {+ workspace_id: ai_memory_core::WorkspaceId::new(),+ project_id: ai_memory_core::ProjectId::new(),+ workspace: "default".into(),+ project: "acme-api".into(),+ };+ let response = ManagedProjectCandidatesResponse {+ candidates: vec![scope.clone()],+ truncated: false,+ };+ let app = axum::Router::new().route(+ "/workstream/project-candidates",+ axum::routing::post(move || {+ let response = response.clone();+ async move { axum::Json(response) }+ }),+ );+ 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 endpoint = ServerEndpoint::from_pair(Some(format!("http://{address}")), None);+ let error = choose(+ &endpoint,+ "default",+ "api",+ false,+ &CancellationToken::new(),+ )+ .await+ .unwrap_err();+ assert!(error.to_string().contains("--project-id"));+ assert!(error.to_string().contains(&scope.project_id.to_string()));+ server.abort();+ }++ #[test]+ fn project_id_choice_requires_an_explicit_valid_number() {+ let scope = ManagedProjectScope {+ workspace_id: ai_memory_core::WorkspaceId::new(),+ project_id: ai_memory_core::ProjectId::new(),+ workspace: "default".into(),+ project: "acme-api".into(),+ };+ let response = ManagedProjectCandidatesResponse {+ candidates: vec![scope.clone()],+ truncated: false,+ };+ for input in ["", "\n", "0\n", "2\n", "q\n"] {+ assert!(read_choice(&response, &mut input.as_bytes(), &mut Vec::new()).is_err());+ }+ assert_eq!(+ read_choice(&response, &mut "1\n".as_bytes(), &mut Vec::new()).unwrap(),+ scope+ );+ }+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 4305ef1e..8f0e6b86 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -68,6 +68,7 @@ pub mod install_skills;pub mod lint;pub mod list_projects;pub mod llm_test;+mod managed_project;pub mod mcp_bridge;pub mod merge_project;pub mod message;diff --git a/crates/ai-memory-cli/src/commands/project_registry.rs b/crates/ai-memory-cli/src/commands/project_registry.rsindex bb386462..7152c531 100644--- a/crates/ai-memory-cli/src/commands/project_registry.rs+++ b/crates/ai-memory-cli/src/commands/project_registry.rs@@ -10,6 +10,8 @@ use std::collections::HashSet;use std::fs::{self, File, OpenOptions};use std::path::{Path, PathBuf};+use ai_memory_core::ManagedProjectScope;+use ai_memory_workstream::inspect_repository_fingerprints;use anyhow::{Context, Result, bail};use fs2::FileExt as _;use serde::{Deserialize, Serialize};@@ -65,6 +67,19 @@ struct ProjectRegistry {// binaries ignore it and simply drop it on their next write.#[serde(default, skip_serializing_if = "Vec::is_empty")]session_stores: Vec<SessionStore>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ bindings: Vec<CheckoutBinding>,+}++#[derive(Debug, Serialize, Deserialize)]+struct CheckoutBinding {+ server: String,+ workspace: String,+ requested_project: String,+ path: PathBuf,+ repo_fingerprint: String,+ worktree_fingerprint: String,+ scope: ManagedProjectScope,}impl Default for ProjectRegistry {@@ -73,6 +88,7 @@ impl Default for ProjectRegistry {version: REGISTRY_VERSION,links: Vec::new(),session_stores: Vec::new(),+ bindings: Vec::new(),}}}@@ -90,6 +106,96 @@ pub(super) fn links_for_server(.collect())}+/// Reuse only a binding for this server, scope and unchanged checkout identity.+/// The server still validates the ID and current permissions on every request.+pub(super) fn project_binding(+ config: &Config,+ endpoint: &ServerEndpoint,+ workspace: &str,+ project: &str,+ path: &Path,+) -> Result<Option<ManagedProjectScope>> {+ project_binding_for_server(config, &endpoint.identity(), workspace, project, path)+}++pub(super) fn project_binding_for_server(+ config: &Config,+ server: &str,+ workspace: &str,+ project: &str,+ path: &Path,+) -> Result<Option<ManagedProjectScope>> {+ let canonical = path+ .canonicalize()+ .context("canonicalizing project binding checkout")?;+ let fingerprints = inspect_repository_fingerprints(&canonical)?;+ let registry = match load_registry(®istry_path(config)) {+ Ok(registry) => registry,+ Err(error) => {+ // A damaged optional registry must not break ordinary checkout+ // discovery. Select no ID and leave the file untouched; the server+ // still refuses ambiguous names and an explicit choice is required.+ eprintln!(+ "ai-memory: could not read the checkout binding ({error:#}); using guarded project-name resolution"+ );+ return Ok(None);+ }+ };+ Ok(registry+ .bindings+ .into_iter()+ .find(|binding| {+ binding.server == server+ && binding.workspace == workspace+ && (binding.requested_project == project || binding.scope.project == project)+ && binding.scope.workspace == workspace+ && binding.path == canonical+ && binding.repo_fingerprint == fingerprints.repo_fingerprint+ && binding.worktree_fingerprint == fingerprints.worktree_fingerprint+ })+ .map(|binding| binding.scope))+}++/// Persist only a server-confirmed scope or an explicit authorized selection.+pub(super) fn record_project_binding(+ config: &Config,+ endpoint: &ServerEndpoint,+ requested_project: &str,+ path: &Path,+ scope: &ManagedProjectScope,+ expected: &ai_memory_workstream::RepositoryFingerprints,+) -> Result<()> {+ let canonical = path+ .canonicalize()+ .context("canonicalizing project binding checkout")?;+ let fingerprints = inspect_repository_fingerprints(&canonical)?;+ if &fingerprints != expected {+ bail!(+ "checkout identity changed while selecting the project; refusing to remember a stale selection"+ );+ }+ let server = endpoint.identity();+ update_registry(config, |registry| {+ // One current choice per checkout and workspace, including a deliberate+ // replacement via --project-id. Never choose the first of stale peers.+ registry.bindings.retain(|binding| {+ !(binding.server == server+ && binding.workspace == scope.workspace+ && binding.path == canonical)+ });+ registry.bindings.push(CheckoutBinding {+ server,+ workspace: scope.workspace.clone(),+ requested_project: requested_project.to_owned(),+ path: canonical,+ repo_fingerprint: fingerprints.repo_fingerprint,+ worktree_fingerprint: fingerprints.worktree_fingerprint,+ scope: scope.clone(),+ });+ Ok(true)+ })+}+/// Record the checkout only after the server accepted a managed run prepare.////// The path is canonicalized before persistence. A later picker rejects a@@ -235,12 +341,15 @@ fn update_registry(let path = registry_path(config);let mut registry = load_registry(&path)?;if mutate(&mut registry)? {- if registry.links.len() > MAX_LINKS {+ if registry.links.len() > MAX_LINKS || registry.bindings.len() > MAX_LINKS {bail!("client project registry exceeds {MAX_LINKS} links");}let mut rendered =serde_json::to_vec_pretty(®istry).context("serializing client project registry")?;rendered.push(b'\n');+ if rendered.len() as u64 > MAX_REGISTRY_BYTES {+ bail!("client project registry exceeds the byte limit; keeping the previous registry");+ }refuse_symlink(&path)?;ai_memory_wiki::write_atomic(&path, &rendered).with_context(|| format!("writing client project registry {}", path.display()))?;@@ -280,10 +389,16 @@ fn load_registry(path: &Path) -> Result<ProjectRegistry> {REGISTRY_VERSION);}- if registry.links.len() > MAX_LINKS {+ if registry.links.len() > MAX_LINKS || registry.bindings.len() > MAX_LINKS {bail!("client project registry exceeds {MAX_LINKS} links");}let mut keys = HashSet::with_capacity(registry.links.len());+ let mut binding_keys = HashSet::with_capacity(registry.bindings.len());+ for binding in ®istry.bindings {+ if !binding_keys.insert((&binding.server, &binding.workspace, &binding.path)) {+ bail!("duplicate checkout project binding; refusing ambiguous client state");+ }+ }for link in ®istry.links {if !keys.insert((&link.server, &link.workspace, &link.project)) {bail!(@@ -353,6 +468,155 @@ mod tests {ServerEndpoint::from_pair(Some(url.to_owned()), None)}+ #[test]+ fn project_id_bindings_survive_reload_and_reject_changed_checkout_or_scope() {+ let tmp = tempfile::tempdir().unwrap();+ let checkout = tmp.path().join("checkout");+ let other = tmp.path().join("other");+ fs::create_dir(&checkout).unwrap();+ fs::create_dir(&other).unwrap();+ let git = |args: &[&str]| {+ assert!(+ std::process::Command::new("git")+ .args(args)+ .current_dir(&checkout)+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_NOSYSTEM", "1")+ .output()+ .unwrap()+ .status+ .success()+ );+ };+ git(&["init"]);+ git(&[+ "remote",+ "add",+ "origin",+ "https://example.test/acme/api.git",+ ]);+ let config = config_at(&tmp.path().join("data"));+ let server = endpoint("http://memory:49374/mount");+ let scope = ManagedProjectScope {+ workspace_id: ai_memory_core::WorkspaceId::new(),+ project_id: ai_memory_core::ProjectId::new(),+ workspace: "default".into(),+ project: "acme-api".into(),+ };+ let fingerprints = inspect_repository_fingerprints(&checkout).unwrap();+ record_project_binding(&config, &server, "api", &checkout, &scope, &fingerprints).unwrap();+ let reloaded = config_at(&tmp.path().join("data"));+ assert_eq!(+ project_binding(&reloaded, &server, "default", "api", &checkout).unwrap(),+ Some(scope.clone())+ );+ assert!(+ project_binding(+ &reloaded,+ &endpoint("http://other:49374/mount"),+ "default",+ "api",+ &checkout+ )+ .unwrap()+ .is_none()+ );+ assert!(+ project_binding(+ &reloaded,+ &endpoint("http://memory:49374/another"),+ "default",+ "api",+ &checkout+ )+ .unwrap()+ .is_none()+ );+ assert!(+ project_binding(&reloaded, &server, "foreign", "api", &checkout)+ .unwrap()+ .is_none()+ );+ assert!(+ project_binding(&reloaded, &server, "default", "different", &checkout)+ .unwrap()+ .is_none()+ );+ assert!(+ project_binding(&reloaded, &server, "default", "api", &other)+ .unwrap()+ .is_none()+ );+ git(&[+ "remote",+ "set-url",+ "origin",+ "https://example.test/other/api.git",+ ]);+ assert!(+ project_binding(&reloaded, &server, "default", "api", &checkout)+ .unwrap()+ .is_none()+ );+ let before = fs::read(registry_path(&config)).unwrap();+ assert!(+ record_project_binding(&config, &server, "api", &checkout, &scope, &fingerprints)+ .is_err()+ );+ assert_eq!(fs::read(registry_path(&config)).unwrap(), before);+ git(&[+ "remote",+ "set-url",+ "origin",+ "https://example.test/acme/api.git",+ ]);+ let replacement = ManagedProjectScope {+ project_id: ai_memory_core::ProjectId::new(),+ ..scope+ };+ record_project_binding(+ &reloaded,+ &server,+ "api",+ &checkout,+ &replacement,+ &fingerprints,+ )+ .unwrap();+ assert_eq!(+ project_binding(&reloaded, &server, "default", "api", &checkout).unwrap(),+ Some(replacement)+ );+ assert_eq!(+ load_registry(®istry_path(&reloaded))+ .unwrap()+ .bindings+ .len(),+ 1+ );+ }++ #[test]+ fn project_id_registry_upgrade_and_failed_write_preserve_existing_state() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_at(&tmp.path().join("data"));+ fs::create_dir_all(&config.data_dir).unwrap();+ let old = b"{\"version\":1,\"links\":[]}";+ fs::write(registry_path(&config), old).unwrap();+ assert!(+ load_registry(®istry_path(&config))+ .unwrap()+ .bindings+ .is_empty()+ );+ let error = update_registry(&config, |registry| {+ registry.version = 123;+ bail!("injected failure before atomic replacement")+ });+ assert!(error.is_err());+ assert_eq!(fs::read(registry_path(&config)).unwrap(), old);+ }+#[test]fn links_are_isolated_by_server_and_scope() {let tmp = tempfile::TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rsindex 40f22b99..f9f52c8d 100644--- a/crates/ai-memory-cli/src/commands/resume.rs+++ b/crates/ai-memory-cli/src/commands/resume.rs@@ -69,6 +69,14 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {};let selected = &candidates[index];let target = continue_session::resolve_target(config, &selected.link)?;+ let project_id = project_registry::project_binding(+ config,+ &endpoint,+ &selected.link.workspace,+ &selected.link.project,+ &target,+ )?+ .map(|scope| scope.project_id);let harness = selected_harness(harness_indices[index], &harnesses);eprintln!("resuming workstream '{}' with harness '{}' in {} at {}",@@ -83,7 +91,8 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {config,RunArgs {workspace: Some(selected.link.workspace.clone()),- project: Some(selected.link.project.clone()),+ project: project_id.is_none().then(|| selected.link.project.clone()),+ project_id,workstream: Some(selected.summary.name.clone()),new_workstream: None,executable: None,@@ -126,9 +135,14 @@ async fn candidates_for_checkout(terminal_text(args.workspace.as_deref().unwrap_or_default()));}- let summaries =- workstreams::list_all_for_checkout(endpoint, &link.workspace, &link.project, &link.path)- .await?;+ let summaries = workstreams::list_all_for_checkout(+ config,+ endpoint,+ &link.workspace,+ &link.project,+ &link.path,+ )+ .await?;if summaries.is_empty() {bail!("no managed workstreams for the current checkout ({}); launch one here with `ai-memory run <harness>` first",@@ -194,6 +208,7 @@ async fn candidates_across_checkouts(}};let summaries = match workstreams::list_all_for_checkout(+ config,endpoint,&link.workspace,&link.project,diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 1829771d..90ca9ce8 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -680,11 +680,25 @@ async fn run_once_with_wiring(}let may_adopt_native_session = args.new_workstream.is_none() && !force_fresh;let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let project_id = if let Some(id) = args.project_id {+ Some(id)+ } else if args.project.is_none() {+ super::project_registry::project_binding(+ config,+ &endpoint,+ &workspace,+ &project,+ &repository.cwd,+ )?+ .map(|scope| scope.project_id)+ } else {+ None+ };// Probe before any server work: a homelab down for maintenance must// downgrade (or, with --require-server, fail) in ~2s, not after a// TCP-level timeout on the prepare POST. Any HTTP answer counts as// reachable — including 404/405 from a server older than /healthz.- let require_server = args.require_server || config.run.require_server;+ let require_server = args.require_server || config.run.require_server || project_id.is_some();if let ServerProbe::Unreachable(probe_error) = probe_server(&endpoint).await {if require_server {// Fail closed exactly like the prepare below would: same@@ -723,9 +737,14 @@ async fn run_once_with_wiring().await;}- let prepare = PrepareManagedRunRequest {+ let mut prepare = PrepareManagedRunRequest {+ project_id,workspace: workspace.clone(),- project: project.clone(),+ project: if project_id.is_some() {+ String::new()+ } else {+ project.clone()+ },cwd: repository.cwd.to_string_lossy().into_owned(),repo_fingerprint: repository.repo_fingerprint.clone(),worktree_fingerprint: repository.worktree_fingerprint.clone(),@@ -736,13 +755,42 @@ 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, marker_project),+ repository_identity: project_id+ .is_none()+ .then(|| remote_identity_naming(&repository.cwd, &project, marker_project))+ .flatten(),};let interrupted_before_spawn = CancellationToken::new();let interrupt_task = tokio::spawn(capture_interrupts(interrupted_before_spawn.clone()));- let prepared = prepare_managed_run(&endpoint, &prepare, interactive, &interrupted_before_spawn)- .await- .context("opening managed workstream; the agent was not started");+ let prepared = async {+ match prepare_managed_run(&endpoint, &prepare, interactive, &interrupted_before_spawn).await+ {+ Err(error)+ if (super::managed_project::is_ambiguous(&error)+ && prepare.project_id.is_none())+ || (args.project_id.is_none()+ && prepare.project_id.is_some()+ && super::managed_project::is_missing(&error)) =>+ {+ let scope = super::managed_project::choose(+ &endpoint,+ &workspace,+ &project,+ interactive,+ &interrupted_before_spawn,+ )+ .await?;+ prepare.project_id = Some(scope.project_id);+ prepare.project.clear();+ prepare.repository_identity = None;+ prepare_managed_run(&endpoint, &prepare, interactive, &interrupted_before_spawn)+ .await+ }+ result => result,+ }+ }+ .await+ .context("opening managed workstream; the agent was not started");let prepared = match prepared {Ok(prepared) => prepared,Err(error) => {@@ -753,17 +801,6 @@ async fn run_once_with_wiring(if let Some(warning) = prepared.manifest_warning.as_deref() {eprintln!("ai-memory: warning: {warning}");}- if let Err(error) = super::project_registry::record_prepared_checkout(- config,- &endpoint,- &workspace,- &project,- &repository.cwd,- ) {- eprintln!(- "ai-memory: could not refresh the client-local project link ({error:#}); continuing the managed run"- );- }let run_path = format!("/workstream/runs/{}", prepared.run_id);macro_rules! acquired_try {($result:expr) => {@@ -782,6 +819,42 @@ async fn run_once_with_wiring("managed run interrupted before the agent started")));}+ acquired_try!(super::managed_project::validate_prepared_scope(+ &prepare, &prepared+ ));+ if let Some(scope) = &prepared.resolved_project+ && let Err(error) = super::project_registry::record_project_binding(+ config,+ &endpoint,+ &project,+ &repository.cwd,+ scope,+ &ai_memory_workstream::RepositoryFingerprints {+ repo_fingerprint: prepare.repo_fingerprint.clone(),+ worktree_fingerprint: prepare.worktree_fingerprint.clone(),+ },+ )+ {+ eprintln!(+ "ai-memory: could not remember the project ID ({error:#}); use --project-id {} next time",+ scope.project_id+ );+ }+ let resolved_name = prepared+ .resolved_project+ .as_ref()+ .map_or(project.as_str(), |scope| scope.project.as_str());+ if let Err(error) = super::project_registry::record_prepared_checkout(+ config,+ &endpoint,+ &workspace,+ resolved_name,+ &repository.cwd,+ ) {+ eprintln!(+ "ai-memory: could not refresh the client-local project link ({error:#}); continuing the managed run"+ );+ }let privacy = acquired_try!(Sanitizer::new(&config.sanitize).map_err(anyhow::Error::from));if let Some(id) = prepared.native_session_id.as_deref() {acquired_try!(NativeSessionIdentity::parse(id, &privacy).map_err(anyhow::Error::from));@@ -934,6 +1007,7 @@ async fn run_once_with_wiring(&& prepared.native_session_id.is_none()&& prepared.may_adopt_existing_session&& may_adopt_native_session+ && prepare.project_id.is_none(){let candidate = acquired_try!(auto_candidates@@ -960,6 +1034,7 @@ async fn run_once_with_wiring(} else if prepared.native_session_id.is_none()&& prepared.may_adopt_existing_session&& may_adopt_native_session+ && prepare.project_id.is_none()&& allows_native_session_adoption(harness, &native_args)&& io::stdin().is_terminal()&& io::stderr().is_terminal()@@ -5456,6 +5531,7 @@ mod tests {fn run_args_for_after_run_test() -> RunArgs {RunArgs {+ project_id: None,workspace: Some("work".into()),project: Some("repo".into()),workstream: None,@@ -6336,6 +6412,7 @@ mod tests {.into_response();}axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -6357,6 +6434,7 @@ mod tests {let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });let endpoint = ServerEndpoint::from_pair(Some(format!("http://{address}")), None);let request = PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "project".into(),cwd: "/tmp/project".into(),@@ -6491,6 +6569,7 @@ mod tests {.into_response();}axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -6610,6 +6689,7 @@ mod tests {.into_response();}axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -6631,6 +6711,7 @@ mod tests {fn held_lease_request() -> PrepareManagedRunRequest {PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "project".into(),cwd: "/tmp/project".into(),@@ -7592,6 +7673,7 @@ mod tests {let mut config = Config::load(None, Some(tmp.path().join("data"))).unwrap();config.server_url = "http://127.0.0.1:1".into();let args = RunArgs {+ project_id: None,workspace: None,project: None,workstream: None,@@ -7872,6 +7954,7 @@ mod tests {"/workstream/runs",post(|| async {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -7940,6 +8023,7 @@ mod tests {);let args = RunArgs {+ project_id: None,workspace: Some("ws".into()),project: Some("proj".into()),workstream: None,@@ -8048,6 +8132,7 @@ mod tests {config.run_autowire = false;let args = RunArgs {+ project_id: None,workspace: Some("ws".into()),project: Some("proj".into()),workstream: None,@@ -8396,6 +8481,7 @@ mod tests {"/workstream/runs",post(|| async {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -8477,6 +8563,7 @@ mod tests {"/workstream/runs",post(|| async {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -8542,6 +8629,7 @@ mod tests {let default_home = home.path().join(".claude");let args = RunArgs {+ project_id: None,workspace: Some("ws".into()),project: Some("proj".into()),workstream: None,@@ -9289,6 +9377,7 @@ mod tests {"/workstream/runs",post(|| async {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -9348,6 +9437,7 @@ mod tests {..WireOverrides::default()};let args = RunArgs {+ project_id: None,workspace: Some("ws".into()),project: Some("proj".into()),workstream: None,@@ -9422,6 +9512,7 @@ mod tests {"/workstream/runs",post(|| async {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -9479,6 +9570,7 @@ mod tests {..WireOverrides::default()};let args = || RunArgs {+ project_id: None,workspace: Some("ws".into()),project: Some("proj".into()),workstream: None,@@ -9572,6 +9664,7 @@ mod tests {"/workstream/runs",post(move || async move {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -9624,6 +9717,7 @@ mod tests {"/workstream/runs",post(|| async {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),@@ -9748,6 +9842,133 @@ mod tests {(script, captured)}+ #[cfg(unix)]+ #[tokio::test]+ async fn managed_project_id_launch_reuses_binding_honors_override_and_refuses_old_server() {+ use ai_memory_core::ManagedProjectScope;+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+ let scope = ManagedProjectScope {+ workspace_id: ai_memory_core::WorkspaceId::new(),+ project_id: ai_memory_core::ProjectId::new(),+ workspace: "ws".into(),+ project: "selected".into(),+ };+ let requests = Arc::new(std::sync::Mutex::new(Vec::<PrepareManagedRunRequest>::new()));+ let confirms = Arc::new(AtomicBool::new(true));+ let cancelled = Arc::new(AtomicUsize::new(0));+ let app = Router::new()+ .route(+ "/workstream/runs",+ post({+ let scope = scope.clone();+ let requests = requests.clone();+ let confirms = confirms.clone();+ move |axum::Json(request): axum::Json<PrepareManagedRunRequest>| {+ let mut scope = scope.clone();+ let requests = requests.clone();+ let confirms = confirms.clone();+ async move {+ if request.project_id.is_none() {+ scope.project = request.project.clone();+ }+ requests.lock().unwrap().push(request);+ axum::Json(PrepareManagedRunResponse {+ resolved_project: confirms.load(Ordering::SeqCst).then_some(scope),+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: None,+ native_session_id: None,+ source_cursor: None,+ previous_native_session: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,+ manifest_warning: None,+ })+ }+ }+ }),+ )+ .route(+ "/workstream/runs/{run_id}/finish",+ post(|| async {+ axum::Json(FinishManagedRunResponse {+ imported_events: 0,+ latest_sequence: 0,+ })+ }),+ )+ .route(+ "/workstream/runs/{run_id}/cancel",+ post({+ let cancelled = cancelled.clone();+ move || {+ let cancelled = cancelled.clone();+ async move {+ cancelled.fetch_add(1, Ordering::SeqCst);+ 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 data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "AI_MEMORY_RUN_ID");+ let mut config = launch_config(home.path(), data.path(), address);+ config.run_autowire = false;+ let mut args = run_args(RunHarnessChoice::Claude, script, Vec::new(), &["--version"]);+ args.project = None;+ args.project_id = Some(scope.project_id);+ args.no_autowire = true;+ assert_eq!(+ run_from(&config, args.clone(), repo.path()).await.unwrap(),+ 0+ );+ args.project_id = None;+ assert_eq!(+ run_from(&config, args.clone(), repo.path()).await.unwrap(),+ 0+ );+ args.project = Some("override".into());+ assert_eq!(+ run_from(&config, args.clone(), repo.path()).await.unwrap(),+ 0+ );+ let before = std::fs::read_to_string(&captured).unwrap();+ confirms.store(false, Ordering::SeqCst);+ args.project = None;+ args.project_id = Some(scope.project_id);+ let error = run_from(&config, args, repo.path()).await.unwrap_err();+ assert!(+ error.to_string().contains("did not confirm project-ID"),+ "{error:#}"+ );+ assert_eq!(+ std::fs::read_to_string(&captured).unwrap(),+ before,+ "old-server response must not start the child"+ );+ assert_eq!(cancelled.load(Ordering::SeqCst), 1);+ let requests = requests.lock().unwrap();+ assert_eq!(requests.len(), 4);+ for index in [0, 1, 3] {+ assert_eq!(requests[index].project_id, Some(scope.project_id));+ assert!(+ requests[index].project.is_empty(),+ "old servers must reject the selector before creation"+ );+ assert!(requests[index].repository_identity.is_none());+ }+ assert_eq!(requests[2].project, "override");+ assert!(requests[2].project_id.is_none());+ server.abort();+ }+fn launch_config(home: &Path, data: &Path, address: std::net::SocketAddr) -> Config {let mut config = Config::load(None, Some(home.to_path_buf())).unwrap();config.data_dir = data.to_path_buf();@@ -9765,6 +9986,7 @@ mod tests {native_args: &[&str],) -> RunArgs {RunArgs {+ project_id: None,workspace: Some("ws".into()),project: Some("proj".into()),workstream: None,@@ -11081,6 +11303,7 @@ mod tests {"/workstream/runs",post(|| async {axum::Json(PrepareManagedRunResponse {+ resolved_project: None,workstream_id: WorkstreamId::new(),workstream_name: "default".into(),run_id: ManagedRunId::new(),diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rsindex 6dae743c..e5407652 100644--- a/crates/ai-memory-cli/src/commands/show.rs+++ b/crates/ai-memory-cli/src/commands/show.rs@@ -229,6 +229,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {crate::commands::run::run_from(config,RunArgs {+ project_id: None,workspace: Some(workspace),project: Some(project),workstream: None,diff --git a/crates/ai-memory-cli/src/commands/workstreams.rs b/crates/ai-memory-cli/src/commands/workstreams.rsindex 58fb6f77..d38f20e9 100644--- a/crates/ai-memory-cli/src/commands/workstreams.rs+++ b/crates/ai-memory-cli/src/commands/workstreams.rs@@ -2,6 +2,7 @@use std::collections::HashSet;use std::fmt::Write as _;+use std::io::IsTerminal as _;use std::path::Path;use ai_memory_core::{ListManagedWorkstreamsRequest, ManagedWorkstreamSummary};@@ -18,14 +19,53 @@ pub async fn run(config: &Config, args: WorkstreamsArgs) -> Result<()> {let (workspace, project) =super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;- let summaries = list_for_checkout(+ let fingerprints = inspect_repository_fingerprints(&cwd)?;+ let project_id = if args.project_id.is_some() || args.project.is_some() {+ args.project_id+ } else {+ super::project_registry::project_binding(config, &endpoint, &workspace, &project, &cwd)?+ .map(|scope| scope.project_id)+ };+ let summaries = match list_for_checkout(&endpoint,&workspace,&project,&cwd,usize::from(args.limit),+ project_id,)- .await?;+ .await+ {+ Err(error) if super::managed_project::is_ambiguous(&error) && project_id.is_none() => {+ let scope = super::managed_project::choose(+ &endpoint,+ &workspace,+ &project,+ !args.json && std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),+ &tokio_util::sync::CancellationToken::new(),+ )+ .await?;+ let summaries = list_for_checkout(+ &endpoint,+ &workspace,+ &project,+ &cwd,+ usize::from(args.limit),+ Some(scope.project_id),+ )+ .await?;+ super::project_registry::record_project_binding(+ config,+ &endpoint,+ &project,+ &cwd,+ &scope,+ &fingerprints,+ )?;+ summaries+ }+ result => result?,+ };if args.json {println!("{}", serde_json::to_string_pretty(&summaries)?);return Ok(());@@ -45,6 +85,7 @@ pub(super) async fn list_for_checkout(project: &str,checkout: &Path,limit: usize,+ project_id: Option<ai_memory_core::ProjectId>,) -> Result<Vec<ManagedWorkstreamSummary>> {let repository = inspect_repository_fingerprints(checkout).context("inspecting managed workstream checkout")?;@@ -52,8 +93,13 @@ pub(super) async fn list_for_checkout(endpoint,"/workstream/recent",&ListManagedWorkstreamsRequest {+ project_id,workspace: workspace.to_owned(),- project: project.to_owned(),+ project: if project_id.is_some() {+ String::new()+ } else {+ project.to_owned()+ },repo_fingerprint: repository.repo_fingerprint,worktree_fingerprint: repository.worktree_fingerprint,limit,@@ -65,6 +111,7 @@ pub(super) async fn list_for_checkout(/// Fetch every checkout-local page without changing the server's per-page cap.pub(super) async fn list_all_for_checkout(+ config: &Config,endpoint: &ServerEndpoint,workspace: &str,project: &str,@@ -72,11 +119,19 @@ pub(super) async fn list_all_for_checkout() -> Result<Vec<ManagedWorkstreamSummary>> {let repository = inspect_repository_fingerprints(checkout).context("inspecting managed workstream checkout")?;+ let project_id =+ super::project_registry::project_binding(config, endpoint, workspace, project, checkout)?+ .map(|scope| scope.project_id);let mut request = ListManagedWorkstreamsRequest {+ project_id,workspace: workspace.to_owned(),- project: project.to_owned(),- repo_fingerprint: repository.repo_fingerprint,- worktree_fingerprint: repository.worktree_fingerprint,+ project: if project_id.is_some() {+ String::new()+ } else {+ project.to_owned()+ },+ repo_fingerprint: repository.repo_fingerprint.clone(),+ worktree_fingerprint: repository.worktree_fingerprint.clone(),limit: 100,offset: 0,};@@ -84,7 +139,34 @@ pub(super) async fn list_all_for_checkout(let mut seen = HashSet::new();loop {let page: Vec<ManagedWorkstreamSummary> =- post_json(endpoint, "/workstream/recent", &request).await?;+ match post_json(endpoint, "/workstream/recent", &request).await {+ Err(error)+ if request.project_id.is_none()+ && super::managed_project::is_ambiguous(&error) =>+ {+ let scope = super::managed_project::choose(+ endpoint,+ workspace,+ project,+ std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),+ &tokio_util::sync::CancellationToken::new(),+ )+ .await?;+ request.project_id = Some(scope.project_id);+ request.project.clear();+ let page = post_json(endpoint, "/workstream/recent", &request).await?;+ super::project_registry::record_project_binding(+ config,+ endpoint,+ project,+ checkout,+ &scope,+ &repository,+ )?;+ page+ }+ result => result?,+ };let count = page.len();let before = summaries.len();summaries.extend(diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 89daf192..0cf5466e 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -109,6 +109,7 @@ pub use user::{pub use workstream::{FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,ListManagedWorkstreamsRequest, MANAGED_WORKSTREAM_PACKET_MARKER, ManagedNativeSessionReference,+ ManagedProjectCandidatesRequest, ManagedProjectCandidatesResponse, ManagedProjectScope,ManagedRunContextResponse, ManagedRunStatus, ManagedWorkstreamSummary, NativeSessionIdentity,NewWorkstreamEvent, PrepareManagedRunRequest, PrepareManagedRunResponse,RenameManagedWorkstreamRequest, RenamedManagedWorkstream, UNTRUSTED_MEMORY_NOTICE,diff --git a/crates/ai-memory-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rsindex c2523d20..3fc5cff6 100644--- a/crates/ai-memory-core/src/workstream.rs+++ b/crates/ai-memory-core/src/workstream.rs@@ -6,7 +6,7 @@use serde::{Deserialize, Serialize};-use crate::{AgentKind, ManagedRunId, WorkstreamId};+use crate::{AgentKind, ManagedRunId, ProjectId, WorkspaceId, WorkstreamId};/// Versioned origin marker placed at the start of every managed workstream/// context packet. Native transcript adapters use it to prevent a harness from@@ -229,6 +229,10 @@ pub struct PrepareManagedRunRequest {pub workspace: String,/// Project name resolved by the host CLI.pub project: String,+ /// Select an existing project within `workspace` by ID. When present,+ /// `project` must be empty: older servers then refuse before any write.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub project_id: Option<ProjectId>,/// Canonical host working directory.pub cwd: String,/// Stable repository identity hash.@@ -271,6 +275,9 @@ pub struct PrepareManagedRunRequest {/// Result of preparing a managed invocation.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct PrepareManagedRunResponse {+ /// Authorized scope selected by the server. Older servers omit it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub resolved_project: Option<ManagedProjectScope>,/// Selected logical workstream.pub workstream_id: WorkstreamId,/// Human-readable workstream name.@@ -401,6 +408,9 @@ pub struct ListManagedWorkstreamsRequest {pub workspace: String,/// Project name resolved by the host CLI.pub project: String,+ /// Existing project ID, mutually exclusive with a non-empty `project`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub project_id: Option<ProjectId>,/// Stable repository identity hash.pub repo_fingerprint: String,/// Stable worktree identity hash (distinct across linked worktrees).@@ -413,6 +423,37 @@ pub struct ListManagedWorkstreamsRequest {pub offset: usize,}+/// Authorized project coordinates, without server filesystem paths.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ManagedProjectScope {+ /// Stable workspace identity.+ pub workspace_id: WorkspaceId,+ /// Stable project identity.+ pub project_id: ProjectId,+ /// Current workspace name.+ pub workspace: String,+ /// Current project name.+ pub project: String,+}++/// Read-only recovery query for an ambiguous managed project name.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ManagedProjectCandidatesRequest {+ /// Workspace containing the projects.+ pub workspace: String,+ /// Exact, canonical or legacy name to match.+ pub project: String,+}++/// Bounded candidates the caller may select for a managed launch.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ManagedProjectCandidatesResponse {+ /// Matching projects on which the caller currently has Write access.+ pub candidates: Vec<ManagedProjectScope>,+ /// More matches exist; use an explicit ID if the intended row is absent.+ pub truncated: bool,+}+/// One checkout-local managed workstream returned by discovery reads.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ManagedWorkstreamSummary {diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 6a06b978..31b74868 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1776,7 +1776,8 @@ async fn fetch_and_accept_handoff_at(};// Authorized before the active-project pointer is published, so a refused// repository does not become the caller's default for later calls.- let (ws, proj) = resolve_authorized_startup_scope(state, &query, viewer).await?;+ let (ws, proj) =+ resolve_authorized_startup_scope(state, &query, actor.as_ref(), viewer).await?;// A managed run's ledger is additive, not a replacement. Resolve and// authorize the request's repository before interpreting the run id: a// shared Codex daemon may carry a terminal id from another checkout, and@@ -2054,17 +2055,104 @@ async fn fetch_and_accept_handoff_at())}-/// The repository a startup-context request names — by cwd, marker or-/// explicit scope — once the caller is authorized to read it. What `/handoff`-/// and `/brief` return is this repository's content (its handoff, its pinned,-/// rules and slot pages), keyed only on a project the caller named or a-/// directory they are in (#708), so both resolve it here: a subagent's brief-/// always comes from the repository its session start reads.+struct ManagedHookHint<'a> {+ run: Option<&'a str>,+ agent: AgentKind,+ cwd: Option<&'a str>,+ native_session: Option<&'a str>,+ session_start: bool,+}++/// Only a run prepared through the ID selector may supply its stored scope.+/// Ownership, native identity and current Write access precede the atomic+/// binding; a refused pinned run never falls back to name-based capture.+async fn pinned_managed_hook_scope(+ state: &HookState,+ hint: ManagedHookHint<'_>,+ actor: Option<&IdentityKey>,+ viewer: Option<ai_memory_core::UserId>,+) -> anyhow::Result<Option<(WorkspaceId, ProjectId)>> {+ let Some(run_id) = hint.run.and_then(|raw| ManagedRunId::from_str(raw).ok()) else {+ return Ok(None);+ };+ let owner_user = crate::workstream::managed_run_owner_stamp(+ &state.reader,+ actor,+ state.trusted_proxy_identity,+ )+ .await?;+ let scope = state+ .reader+ .managed_run_pinned_scope(ai_memory_store::ManagedRunHookIdentity {+ run_id,+ agent: hint.agent,+ cwd: hint.cwd.map(str::to_owned),+ native_session_id: hint.native_session.unwrap_or_default().to_owned(),+ owner_user: owner_user.clone(),+ session_start: hint.session_start,+ })+ .await?;+ let Some((workspace_id, project_id)) = scope else {+ return Ok(None);+ };+ let native = ai_memory_core::NativeSessionIdentity::parse(+ hint.native_session.unwrap_or_default(),+ &state.sanitizer,+ )?;+ ai_memory_store::authorize_scope_for(+ &state.reader,+ None,+ ai_memory_store::ResolvedScope {+ workspace_id,+ project_id,+ },+ viewer,+ ai_memory_store::ProjectAccess::Write,+ )+ .await?;+ let linked = state+ .writer+ .link_managed_run_session_in_scope(ai_memory_store::LinkManagedRunSessionInScope {+ run_id,+ workspace_id,+ project_id,+ agent: hint.agent,+ native_session_id: native.into_string(),+ owner_user,+ })+ .await?;+ if linked != ai_memory_store::ManagedRunSessionLink::Exact(run_id) {+ return Err(anyhow::anyhow!(+ "ID-selected managed run no longer admits this native session"+ ));+ }+ Ok(Some((workspace_id, project_id)))+}++/// Resolve startup scope from a validated pinned run or the normal marker/name+/// route, then apply the corresponding current project authorization.async fn resolve_authorized_startup_scope(state: &HookState,query: &HandoffQuery,+ actor: Option<&IdentityKey>,viewer: Option<ai_memory_core::UserId>,) -> anyhow::Result<(WorkspaceId, ProjectId)> {+ if let Some(scope) = pinned_managed_hook_scope(+ state,+ ManagedHookHint {+ run: query.managed_run.as_deref(),+ agent: query.agent.as_deref().map_or(AgentKind::Other, parse_agent),+ cwd: query.cwd.as_deref(),+ native_session: query.session_id.as_deref(),+ session_start: true,+ },+ actor,+ viewer,+ )+ .await?+ {+ return Ok(scope);+ }let repository = query.repository_identity();let aliases = crate::payload::marker_aliases_from_wire(query.project.as_deref(),@@ -2130,7 +2218,7 @@ async fn fetch_brief(actor: Option<&IdentityKey>,viewer: Option<ai_memory_core::UserId>,) -> anyhow::Result<Option<String>> {- let (ws, proj) = resolve_authorized_startup_scope(state, query, viewer).await?;+ let (ws, proj) = resolve_authorized_startup_scope(state, query, actor, viewer).await?;let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);// An `additionalContext` over that agent's limit is swapped for a file// path and a short preview, which would cut the brief's closing fence;@@ -4258,6 +4346,19 @@ async fn process_authorized(user: actor.as_ref().map(IdentityKey::storage_key),session_id: env.session_id.clone(),};+ let pinned_scope = pinned_managed_hook_scope(+ state,+ ManagedHookHint {+ run: env.managed_run.as_deref(),+ agent: env.agent,+ cwd: env.cwd.as_deref(),+ native_session: env.session_id.as_deref(),+ session_start: env.event == HookEvent::SessionStart,+ },+ actor.as_ref(),+ viewer,+ )+ .await?;// Session-sticky attribution: for an event whose session already// exists, the session's own scope is the source of truth (the same// rationale as the V19 repair). Per-event cwd derivation only decides@@ -4316,25 +4417,30 @@ async fn process_authorized(}_ => None,};- let publishable_scope = sticky_scope.is_some()+ let publishable_scope = pinned_scope.is_some()+ || sticky_scope.is_some()|| has_publishable_scope_hint(env.cwd.as_deref(), env.project_override.as_deref());- let (mut ws, mut proj) = match sticky_scope {- Some((session_ws, session_proj, _)) => (session_ws, session_proj),- None => {- resolve_project_ids_inner(- state,- env.cwd.as_deref(),- env.workspace_override.as_deref(),- env.project_override.as_deref(),- env.project_strategy,- env.identity.as_ref(),- env.identity_style,- &env.aliases,- env.project_source,- true,- viewer,- )- .await?+ let (mut ws, mut proj) = if let Some(scope) = pinned_scope {+ scope+ } else {+ match sticky_scope {+ Some((session_ws, session_proj, _)) => (session_ws, session_proj),+ None => {+ resolve_project_ids_inner(+ state,+ env.cwd.as_deref(),+ env.workspace_override.as_deref(),+ env.project_override.as_deref(),+ env.project_strategy,+ env.identity.as_ref(),+ env.identity_style,+ &env.aliases,+ env.project_source,+ true,+ viewer,+ )+ .await?+ }}};@@ -4475,7 +4581,11 @@ async fn process_authorized(.await;match result {Ok(admission) => break (admission, log_title, ingest_guard),- Err(error) if attempts == 0 && error.is_stale_session_scope_reference() => {+ Err(error)+ if pinned_scope.is_none()+ && attempts == 0+ && error.is_stale_session_scope_reference() =>+ {// Do not hold an old-project gate while resolving and acquiring// the refreshed scope's gate; that would permit nested gates.drop(ingest_guard);@@ -4590,7 +4700,8 @@ async fn process_authorized(}ws = admitted.workspace_id();proj = admitted.project_id();- if let Some(run_id) = managed_run+ if pinned_scope.is_none()+ && let Some(run_id) = managed_run&& let Some(native_session_id) = env.session_id.as_deref().and_then(|value| {ai_memory_core::NativeSessionIdentity::parse(value, &state.sanitizer).ok()})@@ -13562,6 +13673,7 @@ pub(crate) mod tests {.writer.prepare_workstream_run_owned(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: state.workspace_id,project_id: state.project_id,repo_fingerprint: "link-repo".into(),@@ -13637,6 +13749,284 @@ pub(crate) mod tests {);}+ #[tokio::test]+ async fn managed_project_id_pins_startup_and_capture_without_accepting_foreign_hooks() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let alice = IdentityKey::User("alice".into());+ let (selected, _) = state+ .writer+ .resolve_project_by_identity(+ state.workspace_id,+ ai_memory_core::repository_identity::RepositoryIdentity {+ identity: "github.com/acme/scratch".into(),+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,+ },+ ai_memory_core::repository_identity::IdentityStyle::Path,+ "remote",+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert_ne!(selected, state.project_id);+ let run = state+ .writer+ .prepare_workstream_run_owned(+ PrepareWorkstreamRun {+ scope_by_id: true,+ workspace_id: state.workspace_id,+ project_id: selected,+ repo_fingerprint: "pinned-repo".into(),+ worktree_fingerprint: "pinned-tree".into(),+ cwd: "/tmp/scratch".into(),+ agent: AgentKind::ClaudeCode,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::Current,+ lease_owner: "pinned-test".into(),+ },+ Some(alice.storage_key()),+ )+ .await+ .unwrap();+ let event = |native: &str| {+ let mut event = session_envelope("user-prompt-submit", native, "/tmp/scratch");+ event.managed_run = Some(run.run_id.to_string());+ event+ };+ let mut previous =+ session_envelope("user-prompt-submit", "foreign-scope-native", "/tmp/foreign");+ previous.project_override = Some("foreign-project".into());+ let previous_id = resolve_session_id(&previous).unwrap();+ process(&state, previous, Some(alice.clone()), Vec::new())+ .await+ .unwrap();+ let previous_scope = state.reader.find_session_scope(previous_id).await.unwrap();+ let previous_count = state+ .reader+ .observations_for_session(previous_id)+ .await+ .unwrap()+ .len();+ assert!(+ process_authorized(+ &state,+ event("foreign-scope-native"),+ Some(alice.clone()),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ None+ )+ .await+ .is_err()+ );+ assert_eq!(+ state.reader.find_session_scope(previous_id).await.unwrap(),+ previous_scope+ );+ assert_eq!(+ state+ .reader+ .observations_for_session(previous_id)+ .await+ .unwrap()+ .len(),+ previous_count+ );+ assert_eq!(+ run_native_session(&state, run.run_id).await,+ None,+ "a foreign native session must not be linked before capture admission"+ );+ for (case, owner) in [+ ("owner", IdentityKey::User("bob".into())),+ ("cwd", alice.clone()),+ ("agent", alice.clone()),+ ] {+ let mut rejected = event(case);+ if case == "cwd" {+ rejected.cwd = Some("/tmp/foreign".into());+ }+ if case == "agent" {+ rejected.agent = AgentKind::Codex;+ }+ let session = resolve_session_id(&rejected).unwrap();+ assert!(+ process_authorized(+ &state,+ rejected,+ Some(owner),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ None+ )+ .await+ .is_err(),+ "{case}"+ );+ assert!(+ state+ .reader+ .find_session_scope(session)+ .await+ .unwrap()+ .is_none(),+ "{case} captured data before refusal"+ );+ }+ let query = HandoffQuery {+ managed_run: Some(run.run_id.to_string()),+ session_id: Some("pinned-native".into()),+ agent: Some("claude-code".into()),+ cwd: Some("/tmp/scratch".into()),+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ ..Default::default()+ };+ let user = state+ .writer+ .create_human_user(+ ai_memory_core::NewUser {+ username: "alice".into(),+ name: None,+ email: None,+ },+ ai_memory_core::UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ state+ .writer+ .set_access_mode(selected, ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ state+ .writer+ .grant_memory(user, selected, ai_memory_store::GrantLevel::Read, None)+ .await+ .unwrap();+ assert!(+ resolve_authorized_startup_scope(&state, &query, Some(&alice), Some(user))+ .await+ .is_err()+ );+ assert_eq!(+ run_native_session(&state, run.run_id).await,+ None,+ "a read-only caller must not bind the run"+ );+ state+ .writer+ .grant_memory(user, selected, ai_memory_store::GrantLevel::Write, None)+ .await+ .unwrap();+ assert_eq!(+ resolve_authorized_startup_scope(&state, &query, Some(&alice), Some(user))+ .await+ .unwrap(),+ (state.workspace_id, selected)+ );+ let legitimate = event("pinned-native");+ let session = resolve_session_id(&legitimate).unwrap();+ process_authorized(+ &state,+ legitimate,+ Some(alice.clone()),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ Some(user),+ )+ .await+ .unwrap();+ let (_, captured, _) = state+ .reader+ .find_session_scope(session)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(+ captured, selected,+ "capture must use the same project ID as startup"+ );+ assert!(+ !state+ .reader+ .observations_for_session(session)+ .await+ .unwrap()+ .is_empty()+ );+ assert!(+ process_authorized(+ &state,+ event("wrong-native"),+ Some(alice.clone()),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ None+ )+ .await+ .is_err()+ );+ state+ .writer+ .grant_memory(user, selected, ai_memory_store::GrantLevel::Read, None)+ .await+ .unwrap();+ let count = state+ .reader+ .observations_for_session(session)+ .await+ .unwrap()+ .len();+ assert!(+ process_authorized(+ &state,+ event("pinned-native"),+ Some(alice.clone()),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ Some(user)+ )+ .await+ .is_err()+ );+ assert_eq!(+ state+ .reader+ .observations_for_session(session)+ .await+ .unwrap()+ .len(),+ count,+ "revoked write access must be rechecked on every capture"+ );+ state.writer.cancel_managed_run(run.run_id).await.unwrap();+ assert!(+ resolve_authorized_startup_scope(&state, &query, Some(&alice), None)+ .await+ .is_err()+ );+ assert!(+ process_authorized(+ &state,+ event("pinned-native"),+ Some(alice),+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ None+ )+ .await+ .is_err(),+ "expired pinned runs must not fall back to name routing"+ );+ }+/// #1082: an event admitted to a different project than the run's never/// links, even from the run's own operator.#[tokio::test]@@ -13697,6 +14087,7 @@ pub(crate) mod tests {let run = state.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: state.workspace_id,project_id: state.project_id,repo_fingerprint: "collision-repo".into(),@@ -19043,6 +19434,7 @@ pub(crate) mod tests {let cwd = tmp.path().to_string_lossy().into_owned();let prepare = PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: state.workspace_id,project_id: state.project_id,repo_fingerprint: "repo".into(),@@ -19855,6 +20247,7 @@ pub(crate) mod tests {let first = state.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: state.workspace_id,project_id: state.project_id,repo_fingerprint: "repo".into(),@@ -19905,6 +20298,7 @@ pub(crate) mod tests {let kimi = state.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: state.workspace_id,project_id: state.project_id,repo_fingerprint: "repo".into(),@@ -23922,6 +24316,7 @@ pub(crate) mod tests {let run = state.writer.prepare_workstream_run(ai_memory_store::PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: state.workspace_id,project_id: state.project_id,repo_fingerprint: "repo".into(),diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 9108895f..c561b091 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -8,7 +8,8 @@ use std::str::FromStr as _;use ai_memory_core::{AgentKind, AuthLevel, Capability, FinishManagedRunRequest, FinishManagedRunResponse,- LinkManagedRunRequest, ListManagedWorkstreamsRequest, ManagedRunContextResponse, ManagedRunId,+ LinkManagedRunRequest, ListManagedWorkstreamsRequest, ManagedProjectCandidatesRequest,+ ManagedProjectCandidatesResponse, ManagedProjectScope, ManagedRunContextResponse, ManagedRunId,ManagedRunStatus, ManagedWorkstreamSummary, NativeSessionIdentity, NewWorkstreamEvent,PrepareManagedRunRequest, PrepareManagedRunResponse, RenameManagedWorkstreamRequest,RenamedManagedWorkstream, Sanitizer, WorkstreamEventKind, WorkstreamId,@@ -16,7 +17,7 @@ use ai_memory_core::{use ai_memory_store::{FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, RenameWorkstream, ScopeResolutionError,StoreError, WorkstreamSelection, WorkstreamSelector, WriterHandle, authorize_scope_for,- create_explicit_scope_guarded, lookup_existing_scope_guarded,+ create_explicit_scope_guarded, lookup_existing_scope_guarded, lookup_project_id_guarded,};use ai_memory_wiki::Wiki;use axum::extract::{Path as AxumPath, Query, State};@@ -91,6 +92,7 @@ pub fn workstream_router(state: WorkstreamState) -> Router {post(recover_finish_run),).route("/workstream/recent", post(list_recent_workstreams))+ .route("/workstream/project-candidates", post(project_candidates)).route("/workstream/rename", post(rename_workstream)).route("/workstream/{workstream_id}/events", get(search_events)).with_state(state)@@ -99,6 +101,8 @@ pub fn workstream_router(state: WorkstreamState) -> Router {#[derive(Debug, Serialize)]struct ApiError {error: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ code: Option<&'static str>,#[serde(flatten)]warning: ai_memory_core::repository_identity::ManifestWarningContext,}@@ -118,6 +122,7 @@ fn api_failure_with_manifest_warning(status,Json(ApiError {error: message.into(),+ code: None,warning: ai_memory_core::repository_identity::ManifestWarningContext {manifest_warning,},@@ -253,6 +258,17 @@ async fn resolve_run_scope(};let workspace = request.workspace.trim();let project = request.project.trim();+ if let Some(project_id) = request.project_id {+ return lookup_project_id_guarded(+ &state.reader,+ workspace,+ project_id,+ viewer,+ ai_memory_store::ProjectAccess::Write,+ )+ .await+ .map(|scope| (scope, false));+ }let identity = request.repository_identity.as_deref()@@ -315,8 +331,19 @@ async fn prepare_run(if let Err(response) = authorize(level, Capability::NormalWrite) {return response.into_response();}+ if request.project.trim().is_empty() == request.project_id.is_none() {+ return error(+ StatusCode::BAD_REQUEST,+ "select exactly one project name or project_id",+ );+ }+ if request.project_id.is_some() && request.repository_identity.is_some() {+ return error(+ StatusCode::BAD_REQUEST,+ "project_id and repository_identity are mutually exclusive",+ );+ }if request.workspace.trim().is_empty()- || request.project.trim().is_empty()|| request.cwd.trim().is_empty()|| request.repo_fingerprint.trim().is_empty()|| request.worktree_fingerprint.trim().is_empty()@@ -409,9 +436,15 @@ async fn prepare_run(}let (scope, promoted) = match resolve_run_scope(&state, &request, actor_user(viewer)).await {Ok(resolved) => resolved,+ Err(failure @ ScopeResolutionError::ProjectNameAmbiguous { .. }) => {+ let (status, mut body) = api_failure(StatusCode::BAD_REQUEST, failure.to_string());+ body.0.code = Some("ambiguous_project");+ return (status, body).into_response();+ }Err(failure) if failure.is_forbidden() => {return error(StatusCode::FORBIDDEN, failure.to_string());}+ Err(failure) if request.project_id.is_some() => return scope_refusal(failure),Err(failure) => return error(StatusCode::BAD_REQUEST, failure.to_string()),};let manifest_warning = if promoted {@@ -457,12 +490,27 @@ async fn prepare_run(}};let force_unlock = request.force_unlock;+ let resolved_project = match state+ .reader+ .project_name_by_id(scope.workspace_id, scope.project_id)+ .await+ {+ Ok(Some(project)) => ManagedProjectScope {+ workspace_id: scope.workspace_id,+ project_id: scope.project_id,+ workspace: request.workspace.trim().to_owned(),+ project,+ },+ Ok(None) => return error(StatusCode::NOT_FOUND, "managed project no longer exists"),+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };let prepared = state.writer.prepare_workstream_run_owned_with_unlock(PrepareWorkstreamRun {workspace_id: scope.workspace_id,project_id: scope.project_id,+ scope_by_id: request.project_id.is_some(),repo_fingerprint: request.repo_fingerprint,worktree_fingerprint: request.worktree_fingerprint,cwd: request.cwd,@@ -478,6 +526,7 @@ async fn prepare_run(.await;match prepared {Ok(prepared) => Json(PrepareManagedRunResponse {+ resolved_project: Some(resolved_project),workstream_id: prepared.workstream_id,workstream_name: prepared.workstream_name,run_id: prepared.run_id,@@ -681,6 +730,68 @@ const fn default_event_limit() -> usize {20}+async fn project_candidates(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,+ Json(request): Json<ManagedProjectCandidatesRequest>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalWrite) {+ return response.into_response();+ }+ if [&request.workspace, &request.project]+ .iter()+ .any(|value| value.trim().is_empty() || value.len() > MAX_NAME_BYTES)+ {+ return error(+ StatusCode::BAD_REQUEST,+ "workspace and project must be non-empty bounded names",+ );+ }+ let workspace_id =+ match ai_memory_store::lookup_existing_workspace(&state.reader, request.workspace.trim())+ .await+ {+ Ok(id) => id,+ Err(failure) => return scope_refusal(failure),+ };+ let rows = match state+ .reader+ .project_coordinate_candidates(workspace_id, request.project.trim().to_owned())+ .await+ {+ Ok(rows) => rows,+ Err(failure) => return store_error_response(failure),+ };+ let truncated = rows.len() > 100;+ let mut candidates = Vec::new();+ for (project_id, project) in rows.into_iter().take(100) {+ match lookup_project_id_guarded(+ &state.reader,+ request.workspace.trim(),+ project_id,+ actor_user(actor),+ ai_memory_store::ProjectAccess::Write,+ )+ .await+ {+ Ok(_) => candidates.push(ManagedProjectScope {+ workspace_id,+ project_id,+ workspace: request.workspace.trim().to_owned(),+ project,+ }),+ Err(failure) if failure.is_forbidden() => {}+ Err(failure) => return scope_refusal(failure),+ }+ }+ Json(ManagedProjectCandidatesResponse {+ candidates,+ truncated,+ })+ .into_response()+}+async fn list_recent_workstreams(State(state): State<WorkstreamState>,level: Option<Extension<AuthLevel>>,@@ -690,6 +801,12 @@ async fn list_recent_workstreams(if let Err(response) = authorize(level, Capability::NormalRead) {return response.into_response();}+ if request.project.trim().is_empty() == request.project_id.is_none() {+ return error(+ StatusCode::BAD_REQUEST,+ "select exactly one project name or project_id",+ );+ }for (label, value) in [("workspace", request.workspace.as_str()),("project", request.project.as_str()),@@ -699,23 +816,39 @@ async fn list_recent_workstreams(request.worktree_fingerprint.as_str(),),] {- if value.trim().is_empty() {+ if value.trim().is_empty() && !(label == "project" && request.project_id.is_some()) {return error(StatusCode::BAD_REQUEST, format!("{label} cannot be empty"));}if value.len() > MAX_NAME_BYTES {return error(StatusCode::BAD_REQUEST, format!("{label} is too long"));}}- let scope = match lookup_existing_scope_guarded(- &state.reader,- request.workspace.trim(),- request.project.trim(),- actor_user(actor),- ai_memory_store::ProjectAccess::Read,- )- .await- {+ let resolved = if let Some(project_id) = request.project_id {+ lookup_project_id_guarded(+ &state.reader,+ request.workspace.trim(),+ project_id,+ actor_user(actor),+ ai_memory_store::ProjectAccess::Read,+ )+ .await+ } else {+ lookup_existing_scope_guarded(+ &state.reader,+ request.workspace.trim(),+ request.project.trim(),+ actor_user(actor),+ ai_memory_store::ProjectAccess::Read,+ )+ .await+ };+ let scope = match resolved {Ok(scope) => scope,+ Err(failure @ ScopeResolutionError::ProjectNameAmbiguous { .. }) => {+ let (status, mut body) = api_failure(StatusCode::BAD_REQUEST, failure.to_string());+ body.0.code = Some("ambiguous_project");+ return (status, body).into_response();+ }Err(failure) if failure.is_forbidden() => {return error(StatusCode::FORBIDDEN, failure.to_string());}@@ -1370,6 +1503,76 @@ fn truncate_owned(value: &mut String, max: usize) {#[cfg(test)]mod tests {+ #[tokio::test]+ async fn managed_project_id_recovers_an_ambiguous_scope_without_moving_history() {+ use tower::ServiceExt as _;++ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ 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,+ "unknown-system",+ None,+ None,+ None,+ )+ .await+ .unwrap();+ let twin = ai_memory_core::ProjectId::new();+ rusqlite::Connection::open(store.db_path()).unwrap().execute(+ "INSERT INTO projects (id, workspace_id, name, created_at) VALUES (?1, ?2, 'unknown-system', 0)",+ rusqlite::params![twin.as_bytes(), workspace_id.as_bytes()],+ ).unwrap();+ let before = project_names(&store).await;+ let by_name = prepare_run(+ State(test_state(&store, temp.path())),+ None,+ None,+ None,+ Json(identity_run_request("unknown-system", None)),+ )+ .await;+ assert_eq!(by_name.status(), StatusCode::BAD_REQUEST);++ let mut body = serde_json::to_value(identity_run_request("", None)).unwrap();+ body["project_id"] = serde_json::json!(holder);+ let response = workstream_router(test_state(&store, temp.path()))+ .oneshot(+ axum::http::Request::builder()+ .method("POST")+ .uri("/workstream/runs")+ .header("content-type", "application/json")+ .body(axum::body::Body::from(body.to_string()))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "an explicitly selected authorized ID must recover the legacy collision"+ );+ assert_eq!(run_project(&store, response).await, (workspace_id, holder));+ assert_eq!(project_names(&store).await, before);+ assert_eq!(+ store+ .reader+ .find_project(workspace_id, "unknown-system".into())+ .await+ .unwrap(),+ Some(twin)+ );+ }+use ai_memory_store::Store;use axum::body::to_bytes;use tempfile::TempDir;@@ -1398,6 +1601,7 @@ mod tests {owner: &str,) -> PrepareWorkstreamRun {PrepareWorkstreamRun {+ scope_by_id: false,workspace_id,project_id,repo_fingerprint: "repo".into(),@@ -1478,6 +1682,7 @@ mod tests {.await.unwrap();let request = || PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "acme-api".into(),cwd: "/repo".into(),@@ -1586,6 +1791,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "acme-api".into(),cwd: "/repo".into(),@@ -1656,6 +1862,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "acme-api".into(),cwd: "/repo".into(),@@ -1752,6 +1959,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "acme-api".into(),cwd: "/repo".into(),@@ -1836,6 +2044,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "acme-api".into(),cwd: "/repo".into(),@@ -2415,6 +2624,7 @@ mod tests {let prepared = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New("typo-nmae".into()),..prepare_input(workspace_id, project_id, AgentKind::OpenCode, "launcher")})@@ -2488,6 +2698,7 @@ mod tests {store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New("taken".into()),..prepare_input(workspace_id, project_id, AgentKind::OpenCode, "other")})@@ -2512,6 +2723,7 @@ mod tests {let prepared = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New("decide-after-death".into()),..prepare_input(workspace_id, project_id, AgentKind::OpenCode, "launcher")})@@ -2546,6 +2758,7 @@ mod tests {None,None,Json(ListManagedWorkstreamsRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),repo_fingerprint: "repo".into(),@@ -2573,6 +2786,7 @@ mod tests {None,None,Json(ListManagedWorkstreamsRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),repo_fingerprint: "repo".into(),@@ -2595,6 +2809,7 @@ mod tests {None,None,Json(ListManagedWorkstreamsRequest {+ project_id: None,workspace: "missing".into(),project: "managed".into(),repo_fingerprint: "repo".into(),@@ -2617,6 +2832,7 @@ mod tests {store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New(format!("local-{index:03}")),..prepare_input(workspace_id, project_id, AgentKind::Codex, "launcher")})@@ -2667,6 +2883,7 @@ mod tests {store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New(name.into()),repo_fingerprint: repo.into(),worktree_fingerprint: worktree.into(),@@ -2682,6 +2899,7 @@ mod tests {None,None,Json(ListManagedWorkstreamsRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),repo_fingerprint: "repo".into(),@@ -2755,6 +2973,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -2794,6 +3013,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -2845,6 +3065,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -2893,6 +3114,7 @@ mod tests {})),None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed-owner".into(),cwd: "/repo".into(),@@ -2996,6 +3218,7 @@ mod tests {actor("alice"),None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed-owner-routes".into(),cwd: "/repo".into(),@@ -3134,6 +3357,7 @@ mod tests {}))};let request = |force_unlock: bool, lease_owner: &str| PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed-force-unlock".into(),cwd: "/repo".into(),@@ -3219,6 +3443,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3269,6 +3494,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3300,6 +3526,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3350,6 +3577,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3381,6 +3609,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3431,6 +3660,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3482,6 +3712,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3532,6 +3763,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "managed".into(),cwd: "/repo".into(),@@ -3817,6 +4049,7 @@ mod tests {None,None,Json(PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: "alice-client-work".into(),cwd: "/repo".into(),@@ -4087,6 +4320,7 @@ mod tests {.writer.prepare_workstream_run_owned(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New(format!("revoke-{finished}")),..prepare_input(ws, project, AgentKind::Codex, "label")},@@ -4436,6 +4670,7 @@ mod tests {state.trusted_proxy_identity = true;let (ws, project) = seed_scope(&store).await;let prepare = |name: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: name.into(),@@ -4601,6 +4836,7 @@ mod tests {.writer.prepare_workstream_run_owned(PrepareWorkstreamRun {+ scope_by_id: false,repo_fingerprint: "superseded".into(),worktree_fingerprint: "superseded".into(),selection: WorkstreamSelection::Named("superseded".into()),@@ -4692,6 +4928,7 @@ mod tests {/// whose folder name differs from its remote's derived name.fn identity_run_request(project: &str, identity: Option<&str>) -> PrepareManagedRunRequest {PrepareManagedRunRequest {+ project_id: None,workspace: "default".into(),project: project.into(),cwd: "/repo/new-space-game".into(),diff --git a/crates/ai-memory-hooks/tests/suite/idle_end.rs b/crates/ai-memory-hooks/tests/suite/idle_end.rsindex 3b62c4e1..cf0281ef 100644--- a/crates/ai-memory-hooks/tests/suite/idle_end.rs+++ b/crates/ai-memory-hooks/tests/suite/idle_end.rs@@ -534,6 +534,7 @@ async fn idle_tick_excludes_active_managed_run_sessions() {let run = store.writer.prepare_workstream_run(ai_memory_store::PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: proj,repo_fingerprint: "repo".into(),@@ -622,6 +623,7 @@ async fn idle_tick_excluded_backlog_cannot_starve_the_batch() {let run = store.writer.prepare_workstream_run(ai_memory_store::PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: proj,repo_fingerprint: format!("repo-{i}"),diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rsindex 4b8cce10..2769bdd0 100644--- a/crates/ai-memory-mcp/src/auth.rs+++ b/crates/ai-memory-mcp/src/auth.rs@@ -1750,6 +1750,301 @@ mod tests {(id, token)}+ #[tokio::test]+ async fn managed_project_id_http_enforces_workspace_grants_and_candidate_privacy() {+ async fn send(+ http: &Router,+ token: Option<&str>,+ path: &str,+ body: serde_json::Value,+ ) -> Response {+ let mut request = Request::builder()+ .method("POST")+ .uri(path)+ .header("content-type", "application/json");+ if let Some(token) = token {+ request = request.header("authorization", format!("Bearer {token}"));+ }+ http.clone()+ .oneshot(request.body(Body::from(body.to_string())).unwrap())+ .await+ .unwrap()+ }+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ store+ .writer+ .get_or_create_workspace("foreign")+ .await+ .unwrap();+ let selected = store+ .writer+ .get_or_create_project(ws, "widget", None)+ .await+ .unwrap();+ let (hidden, _) = store+ .writer+ .resolve_project_by_identity(+ ws,+ ai_memory_core::repository_identity::RepositoryIdentity {+ identity: "github.com/private/widget".into(),+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,+ },+ ai_memory_core::repository_identity::IdentityStyle::Path,+ "remote",+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert_ne!(selected, hidden);+ for id in [selected, hidden] {+ store+ .writer+ .set_access_mode(id, ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ }+ let (user, token) = owner_finish_user(&store, "selector").await;+ let auth = AuthState::new(Some("root-selector-test".into())).with_multiuser(+ TokenPepper::new("finish-pepper"),+ store.reader.clone(),+ store.writer.clone(),+ );+ let http = owner_finish_http(&store, tmp.path(), auth);+ let prepare = serde_json::json!({"workspace":"default", "project":"", "project_id":selected,+ "cwd":"/client/widget", "repo_fingerprint":"repo", "worktree_fingerprint":"tree",+ "agent":"codex", "lease_owner":"test", "new_workstream":"selected"});+ let candidates = serde_json::json!({"workspace":"default", "project":"widget"});+ for (path, body) in [+ ("/workstream/runs", prepare.clone()),+ ("/workstream/project-candidates", candidates.clone()),+ ] {+ assert_eq!(+ send(&http, None, path, body).await.status(),+ StatusCode::UNAUTHORIZED+ );+ }+ assert_eq!(+ send(&http, Some(&token), "/workstream/runs", prepare.clone())+ .await+ .status(),+ StatusCode::FORBIDDEN+ );+ for (field, value, expected) in [+ (+ "workspace",+ serde_json::json!("foreign"),+ StatusCode::NOT_FOUND,+ ),+ (+ "workspace",+ serde_json::json!("missing"),+ StatusCode::NOT_FOUND,+ ),+ (+ "project_id",+ serde_json::json!(ai_memory_core::ProjectId::new()),+ StatusCode::NOT_FOUND,+ ),+ (+ "project",+ serde_json::json!("widget"),+ StatusCode::BAD_REQUEST,+ ),+ ] {+ let mut body = prepare.clone();+ body[field] = value;+ assert_eq!(+ send(&http, Some("root-selector-test"), "/workstream/runs", body)+ .await+ .status(),+ expected+ );+ }+ assert!(+ store+ .reader+ .find_workspace("missing".into())+ .await+ .unwrap()+ .is_none()+ );+ store+ .writer+ .grant_memory(user, selected, ai_memory_store::GrantLevel::Read, None)+ .await+ .unwrap();+ assert_eq!(+ send(&http, Some(&token), "/workstream/runs", prepare.clone())+ .await+ .status(),+ StatusCode::FORBIDDEN+ );+ let response = send(+ &http,+ Some(&token),+ "/workstream/project-candidates",+ candidates.clone(),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let rows: ai_memory_core::ManagedProjectCandidatesResponse =+ serde_json::from_slice(&bytes).unwrap();+ assert!(+ rows.candidates.is_empty(),+ "read access must not be offered as a writable choice"+ );+ store+ .writer+ .grant_memory(user, selected, ai_memory_store::GrantLevel::Write, None)+ .await+ .unwrap();+ let response = send(+ &http,+ Some(&token),+ "/workstream/project-candidates",+ candidates.clone(),+ )+ .await;+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let rows: ai_memory_core::ManagedProjectCandidatesResponse =+ serde_json::from_slice(&bytes).unwrap();+ assert_eq!(+ rows.candidates+ .iter()+ .map(|row| row.project_id)+ .collect::<Vec<_>>(),+ [selected]+ );+ let body = String::from_utf8(bytes.to_vec()).unwrap();+ assert!(!body.contains("private-widget") && !body.contains(&hidden.to_string()));+ assert!(!body.contains("repo_path") && !body.contains("/client/"));+ let response = send(&http, Some(&token), "/workstream/runs", prepare.clone()).await;+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let run: ai_memory_core::PrepareManagedRunResponse =+ serde_json::from_slice(&bytes).unwrap();+ assert_eq!(run.resolved_project.unwrap().project_id, selected);+ let recent = serde_json::json!({"workspace":"default", "project":"", "project_id":selected,+ "repo_fingerprint":"repo", "worktree_fingerprint":"tree", "limit":20});+ let response = send(&http, Some(&token), "/workstream/recent", recent.clone()).await;+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let rows: Vec<ai_memory_core::ManagedWorkstreamSummary> =+ serde_json::from_slice(&bytes).unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].workstream_id, run.workstream_id);+ let mut other = recent;+ other["workspace"] = serde_json::json!("foreign");+ assert_eq!(+ send(&http, Some(&token), "/workstream/recent", other)+ .await+ .status(),+ StatusCode::NOT_FOUND+ );+ let mut root_prepare = prepare;+ root_prepare["new_workstream"] = serde_json::json!("root-selection");+ assert_eq!(+ send(+ &http,+ Some("root-selector-test"),+ "/workstream/runs",+ root_prepare+ )+ .await+ .status(),+ StatusCode::OK+ );+ let response = send(+ &http,+ Some("root-selector-test"),+ "/workstream/project-candidates",+ candidates,+ )+ .await;+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let rows: ai_memory_core::ManagedProjectCandidatesResponse =+ serde_json::from_slice(&bytes).unwrap();+ assert_eq!(rows.candidates.len(), 2);++ // IDs must preserve the named-write restriction on reserved profiles,+ // even when an operator has an explicit write grant on that project.+ let own_profile = ai_memory_core::profile::user_profile_project(user);+ let foreign_profile =+ ai_memory_core::profile::user_profile_project(ai_memory_core::UserId::new());+ for (profile, allowed) in [+ ("_profile", false),+ (foreign_profile.as_str(), false),+ (own_profile.as_str(), true),+ ] {+ let project_id = store+ .writer+ .get_or_create_project(ws, profile, None)+ .await+ .unwrap();+ store+ .writer+ .grant_memory(user, project_id, ai_memory_store::GrantLevel::Write, None)+ .await+ .unwrap();+ let body = serde_json::json!({"workspace":"default", "project":"", "project_id":project_id,+ "cwd":"/client/widget", "repo_fingerprint":"repo", "worktree_fingerprint":"tree",+ "agent":"codex", "lease_owner":"test", "new_workstream":"profile-selection"});+ assert_eq!(+ send(&http, Some(&token), "/workstream/runs", body.clone())+ .await+ .status(),+ if allowed {+ StatusCode::OK+ } else {+ StatusCode::FORBIDDEN+ },+ "reserved profile selection: {profile}"+ );+ let response = send(+ &http,+ Some(&token),+ "/workstream/project-candidates",+ serde_json::json!({"workspace":"default", "project":profile}),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let rows: ai_memory_core::ManagedProjectCandidatesResponse =+ serde_json::from_slice(&bytes).unwrap();+ assert_eq!(rows.candidates.len(), usize::from(allowed));+ if !allowed {+ assert_eq!(+ send(&http, Some("root-selector-test"), "/workstream/runs", body)+ .await+ .status(),+ StatusCode::OK,+ "root retains profile repair access"+ );+ }+ }+ }+async fn owner_finish_run(store: &Store,ws: ai_memory_core::WorkspaceId,@@ -1761,6 +2056,7 @@ mod tests {.writer.prepare_workstream_run_owned(ai_memory_store::PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "repo".into(),diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rsindex 09f5fd45..6be94812 100644--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs@@ -217,6 +217,7 @@ async fn move_project_true_move_into_fresh_dest() {let managed = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: src_ws,project_id: src_proj,repo_fingerprint: "repo".into(),@@ -1193,6 +1194,7 @@ async fn copy_purge_force_never_deletes_a_live_managed_workstream() {let prepared = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: src_ws,project_id: src_proj,repo_fingerprint: "repo".into(),@@ -2128,6 +2130,7 @@ async fn delete_workspace_force_removes_everything() {let prepared = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id,project_id,repo_fingerprint: "repo".into(),@@ -2322,6 +2325,7 @@ async fn delete_workspace_dry_run_reports_the_same_counts_the_confirmed_delete_wlet prepared = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: proj,repo_fingerprint: "repo".into(),diff --git a/crates/ai-memory-mcp/tests/suite/admin_purge.rs b/crates/ai-memory-mcp/tests/suite/admin_purge.rsindex 6fadb01f..822330ef 100644--- a/crates/ai-memory-mcp/tests/suite/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_purge.rs@@ -1136,6 +1136,7 @@ async fn purge_project_removes_raw_workstream_segments() {let prepared = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id,project_id,repo_fingerprint: "repo".into(),@@ -1822,6 +1823,7 @@ async fn purge_project_dry_run_conflicts_on_a_live_managed_run_without_force() {store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id,project_id,repo_fingerprint: "repo".into(),diff --git a/crates/ai-memory-store/migrations/V91__managed_run_scope_by_id.sql b/crates/ai-memory-store/migrations/V91__managed_run_scope_by_id.sqlnew file mode 100644index 00000000..9f164ac8--- /dev/null+++ b/crates/ai-memory-store/migrations/V91__managed_run_scope_by_id.sql@@ -0,0 +1,4 @@+-- An explicit project-ID selection pins hook routing to this run's scope.+-- Existing runs keep the original name/marker-based routing contract.+ALTER TABLE managed_runs ADD COLUMN scope_by_id INTEGER NOT NULL DEFAULT 0+ CHECK (scope_by_id IN (0, 1));diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rsindex e23c7ca4..59802667 100644--- a/crates/ai-memory-store/src/api_credentials.rs+++ b/crates/ai-memory-store/src/api_credentials.rs@@ -470,7 +470,7 @@ mod tests {|row| row.get(0),).unwrap();- assert_eq!(version, 90, "update the pin when adding a migration");+ assert_eq!(version, 91, "update the pin when adding a migration");let cols: i64 = conn.query_row("SELECT COUNT(*) FROM pragma_table_info('users') \diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex d75b509c..09f28ff5 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -113,7 +113,7 @@ pub use scope::{create_explicit_scope, create_explicit_scope_guarded, create_global_scope,create_profile_scope, lookup_existing_scope, lookup_existing_scope_guarded,lookup_existing_workspace, lookup_global_scope, lookup_profile_scope,- resolve_many_existing_scopes, resolve_many_existing_scopes_guarded,+ lookup_project_id_guarded, resolve_many_existing_scopes, resolve_many_existing_scopes_guarded,};pub use session_consolidation::{SESSION_CONSOLIDATION_MAX_ATTEMPTS, SessionConsolidationJob, enqueue_in_tx,@@ -122,10 +122,10 @@ pub use users::{LoginUser, TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, hash_tokepub use web_sessions::{LiveWebSession, WebSession, hash_session_secret};pub use workstream::{FinishWorkstreamRun, FinishedWorkstreamRun, LinkManagedRunSessionInScope,- LinkOrAdoptManagedRunSession, ManagedRunAuthority, ManagedRunContext, ManagedRunSessionLink,- OperationalWorkstreamSummary, PrepareWorkstreamRun, PreparedWorkstreamRun, RenameWorkstream,- RenamedWorkstream, StoredManagedRunStatus, StoredWorkstreamSummary,- WorkstreamOperationalStatus, WorkstreamSelection, WorkstreamSelector,+ LinkOrAdoptManagedRunSession, ManagedRunAuthority, ManagedRunContext, ManagedRunHookIdentity,+ ManagedRunSessionLink, OperationalWorkstreamSummary, PrepareWorkstreamRun,+ PreparedWorkstreamRun, RenameWorkstream, RenamedWorkstream, StoredManagedRunStatus,+ StoredWorkstreamSummary, WorkstreamOperationalStatus, WorkstreamSelection, WorkstreamSelector,};pub use writer::{StartupContextAcceptance, WriterHandle};@@ -5681,6 +5681,7 @@ mod tests {.await.unwrap();let prepare = PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "repo".into(),@@ -5858,6 +5859,7 @@ mod tests {.await.unwrap();let prepare = PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "repo".into(),@@ -6121,6 +6123,7 @@ mod tests {.await.unwrap();let prepare = PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: workspace,project_id: project,repo_fingerprint: "repo".into(),@@ -6177,6 +6180,7 @@ mod tests {.await.unwrap();let prepare = |agent, owner: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: workspace,project_id: project,repo_fingerprint: "repo".into(),@@ -6344,6 +6348,7 @@ mod tests {.await.unwrap();let base = |agent, owner: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: workspace,project_id: project,repo_fingerprint: "repo".into(),@@ -6421,6 +6426,7 @@ mod tests {let run = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: workspace,project_id: project,repo_fingerprint: "same-repository".into(),@@ -6503,6 +6509,7 @@ mod tests {owner: &str,) -> PrepareWorkstreamRun {PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: proj,repo_fingerprint: "repo".into(),@@ -7592,6 +7599,7 @@ mod tests {let store = Store::open(tmp.path()).unwrap();let (ws, proj) = open_managed_scope(&store, "managed-selection").await;let prepare = |selection| PrepareWorkstreamRun {+ scope_by_id: false,selection,..managed_prepare_input(ws, proj, "test:1")};@@ -7651,6 +7659,7 @@ mod tests {let store = Store::open(tmp.path()).unwrap();let (ws, proj) = open_managed_scope(&store, "managed-list").await;let prepare = |name: &str, agent| PrepareWorkstreamRun {+ scope_by_id: false,agent,selection: WorkstreamSelection::New(name.into()),..managed_prepare_input(ws, proj, name)@@ -7692,6 +7701,7 @@ mod tests {let claude = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,agent: AgentKind::ClaudeCode,selection: WorkstreamSelection::Named("current".into()),..managed_prepare_input(ws, proj, "claude")@@ -7750,6 +7760,7 @@ mod tests {let hidden = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,repo_fingerprint: "other-repo".into(),worktree_fingerprint: "other-worktree".into(),selection: WorkstreamSelection::New("hidden".into()),@@ -7834,6 +7845,7 @@ mod tests {store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New(name.into()),..managed_prepare_input(ws, proj, name)})@@ -7872,6 +7884,7 @@ mod tests {let prepared = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New((*name).into()),..managed_prepare_input(ws, proj, name)})@@ -7947,6 +7960,7 @@ mod tests {store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::Named(name.into()),..managed_prepare_input(ws, proj, name)})diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rsindex 37d9933e..a470a1fb 100644--- a/crates/ai-memory-store/src/migrations.rs+++ b/crates/ai-memory-store/src/migrations.rs@@ -164,6 +164,67 @@ mod tests {};use rusqlite::{Connection, params};+ #[test]+ fn project_id_pinning_upgrade_preserves_runs_and_failed_prepare_rolls_back() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 90).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ let ws = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();+ let project = crate::ops::get_or_create_project(&mut conn, &ws, "project", None).unwrap();+ let workstream = ai_memory_core::WorkstreamId::new();+ let run_id = ai_memory_core::ManagedRunId::new();+ conn.execute("INSERT INTO workstreams \+ (id, workspace_id, project_id, repo_fingerprint, worktree_fingerprint, name, cwd, created_at, selected_at, updated_at) \+ VALUES (?1, ?2, ?3, 'repo', 'tree', 'default', '/repo', 1, 1, 1)",+ params![workstream.as_bytes(), ws.as_bytes(), project.as_bytes()]).unwrap();+ conn.execute("INSERT INTO managed_runs \+ (id, workstream_id, agent_kind, lease_owner, state, sync_after, sync_through, context_delivered, lease_expires_at, started_at) \+ VALUES (?1, ?2, 'codex', 'host:1', 'active', 3, 7, 1, ?3, 1)",+ params![run_id.as_bytes(), workstream.as_bytes(), jiff::Timestamp::now().as_microsecond() + 60_000_000]).unwrap();+ run(&mut conn).unwrap();+ let snapshot = |conn: &Connection| {+ conn.query_row(+ "SELECT state, sync_after, sync_through, context_delivered, scope_by_id FROM managed_runs WHERE id = ?1",+ params![run_id.as_bytes()], |row| Ok((row.get::<_,String>(0)?, row.get::<_,i64>(1)?, row.get::<_,i64>(2)?, row.get::<_,bool>(3)?, row.get::<_,bool>(4)?))).unwrap()+ };+ assert_eq!(snapshot(&conn), ("active".into(), 3, 7, true, false));+ conn.execute_batch("CREATE TRIGGER reject_new_run BEFORE INSERT ON managed_runs BEGIN SELECT RAISE(ABORT, 'injected failure'); END;").unwrap();+ let input = crate::PrepareWorkstreamRun {+ workspace_id: ws,+ project_id: project,+ scope_by_id: true,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "tree".into(),+ cwd: "/repo".into(),+ agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: crate::WorkstreamSelection::Named("default".into()),+ lease_owner: "host:2".into(),+ };+ assert!(crate::workstream::prepare_run(&mut conn, &input, None, true).is_err());+ assert_eq!(+ snapshot(&conn),+ ("active".into(), 3, 7, true, false),+ "failed prepare must roll back forced expiry and preserve the legacy flag"+ );+ let count: i64 = conn+ .query_row("SELECT COUNT(*) FROM managed_runs", [], |row| row.get(0))+ .unwrap();+ assert_eq!(count, 1);+ conn.execute_batch("DROP TRIGGER reject_new_run;").unwrap();+ let prepared = crate::workstream::prepare_run(&mut conn, &input, None, true).unwrap();+ let pinned: bool = conn+ .query_row(+ "SELECT scope_by_id FROM managed_runs WHERE id = ?1",+ params![prepared.run_id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert!(pinned);+ assert_eq!(snapshot(&conn).0, "expired");+ }+/// A store migrated by a newer build (an applied version above anything/// this binary embeds) must fail to open with the actionable/// `DataSchemaAhead` error, not refinery's raw "missing from thediff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 91634ef6..fec67a7e 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -15157,6 +15157,7 @@ pub(crate) mod tests {let managed = crate::workstream::prepare_run(&mut conn,&crate::PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: src_ws,project_id: proj,repo_fingerprint: "repo".into(),@@ -17853,6 +17854,7 @@ pub(crate) mod tests {crate::workstream::prepare_run(conn,&crate::workstream::PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: *ws,project_id: *proj,repo_fingerprint: "repo-fp".to_string(),diff --git a/crates/ai-memory-store/src/project_coordinates.rs b/crates/ai-memory-store/src/project_coordinates.rsindex 9a2d97d4..657febbb 100644--- a/crates/ai-memory-store/src/project_coordinates.rs+++ b/crates/ai-memory-store/src/project_coordinates.rs@@ -105,10 +105,27 @@ pub(crate) fn matches(workspace_id: WorkspaceId,requested: &str,repository: Option<&RepositoryIdentity>,+) -> StoreResult<Vec<ProjectCoordinateMatch>> {+ matches_bounded(+ conn,+ workspace_id,+ requested,+ repository,+ MAX_COORDINATE_ROWS,+ )+}++/// The same indexed coordinate match with a caller-owned result bound.+pub(crate) fn matches_bounded(+ conn: &Connection,+ workspace_id: WorkspaceId,+ requested: &str,+ repository: Option<&RepositoryIdentity>,+ max_rows: usize,) -> StoreResult<Vec<ProjectCoordinateMatch>> {let identity = repository.map_or("", |repository| repository.identity.as_str());let canonical = repository.and_then(path_style_name).unwrap_or_default();- let limit = i64::try_from(MAX_COORDINATE_ROWS).unwrap_or(i64::MAX);+ let limit = i64::try_from(max_rows).unwrap_or(i64::MAX);let mut statement = conn.prepare(MATCH_SQL)?;let rows = statement.query_map(diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 9b417193..32c78d82 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -2979,6 +2979,16 @@ impl ReaderPool {.await}+ /// Validated scope of an explicitly ID-selected run, if it opted in.+ /// Legacy runs return `None`; invalid pinned boundaries fail closed.+ pub async fn managed_run_pinned_scope(+ &self,+ identity: crate::ManagedRunHookIdentity,+ ) -> StoreResult<Option<(WorkspaceId, ProjectId)>> {+ self.with_conn(move |conn| crate::workstream::pinned_hook_scope(conn, &identity))+ .await+ }+/// The repository a workstream belongs to, or `None` when it does not/// exist. See [`Self::managed_run_scope`] for why the routes need it.///@@ -12356,6 +12366,25 @@ impl ReaderPool {.await}+ /// Bounded coordinate candidates for an explicitly authorized picker.+ /// These are internal rows: callers must authorize each before disclosure.+ pub async fn project_coordinate_candidates(+ &self,+ workspace_id: WorkspaceId,+ name: String,+ ) -> StoreResult<Vec<(ProjectId, String)>> {+ self.with_conn(move |conn| {+ crate::project_coordinates::matches_bounded(conn, workspace_id, &name, None, 101).map(+ |rows| {+ rows.into_iter()+ .map(|row| (row.id, row.current_name))+ .collect()+ },+ )+ })+ .await+ }+/// Resolve a local marker's former names inside one workspace, requiring/// the selected row to carry the checkout's full git-remote identity.pub async fn resolve_existing_project_aliases(diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex ee885d8a..569e2bde 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -532,6 +532,41 @@ pub async fn lookup_existing_scope_guarded(authorize_scope_for(reader, None, scope, viewer, need).await}+/// Resolve an existing ID inside the named workspace, then authorize it.+/// Never creates a workspace/project or falls back to a name on refusal.+///+/// # Errors+/// Missing coordinates, insufficient access, or a store failure.+pub async fn lookup_project_id_guarded(+ reader: &ReaderPool,+ workspace: &str,+ project_id: ProjectId,+ viewer: Option<UserId>,+ need: ProjectAccess,+) -> Result<ResolvedScope, ScopeResolutionError> {+ let workspace_id = lookup_existing_workspace(reader, workspace).await?;+ let Some(project) = reader.project_name_by_id(workspace_id, project_id).await? else {+ return Err(ScopeResolutionError::ProjectNotFoundInWorkspace {+ workspace: workspace.to_owned(),+ project: project_id.to_string(),+ });+ };+ if need == ProjectAccess::Write {+ refuse_foreign_profile_name(Some(workspace), &project, viewer)?;+ }+ authorize_scope_for(+ reader,+ None,+ ResolvedScope {+ workspace_id,+ project_id,+ },+ viewer,+ need,+ )+ .await+}+/// [`create_explicit_scope`] on behalf of `viewer`, authorized for a write./// Returns promotion metadata that the runtime caller must use to refresh the/// scope manifest after the SQL transaction commits.diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex f7713ef6..0568986a 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -156,6 +156,8 @@ pub struct PrepareWorkstreamRun {pub workspace_id: WorkspaceId,/// Resolved project.pub project_id: ProjectId,+ /// Pin managed hook routing after an explicit, authorized ID selection.+ pub scope_by_id: bool,/// Repository identity hash.pub repo_fingerprint: String,/// Worktree identity hash.@@ -256,6 +258,58 @@ pub struct LinkManagedRunSessionInScope {pub owner_user: Option<String>,}+/// Native hook identity checked before an ID-selected run may supply scope.+pub struct ManagedRunHookIdentity {+ /// Invocation named by the hook.+ pub run_id: ManagedRunId,+ /// Harness sending the hook.+ pub agent: AgentKind,+ /// Client checkout; required for startup and the first session binding.+ pub cwd: Option<String>,+ /// Original, privacy-validated native session identifier.+ pub native_session_id: String,+ /// Operator derived from authenticated middleware.+ pub owner_user: Option<String>,+ /// Startup always checks the checkout, even for an already linked session.+ pub session_start: bool,+}++/// Read the opt-in scope without turning an arbitrary run ID into authority.+/// The caller must still authorize this scope and atomically link the native+/// session before using it; that link closes races between initial hooks.+pub(crate) fn pinned_hook_scope(+ conn: &Connection,+ input: &ManagedRunHookIdentity,+) -> StoreResult<Option<(WorkspaceId, ProjectId)>> {+ let tx = conn.unchecked_transaction()?;+ let pin: Option<(bool, bool, bool, i64)> = tx.query_row(+ "SELECT scope_by_id, native_session_linked_at IS NOT NULL, context_delivered, lease_expires_at \+ FROM managed_runs WHERE id = ?1",+ params![input.run_id.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),+ ).optional()?;+ let Some((true, linked, delivered, expires)) = pin else {+ return Ok(None);+ };+ let refused = || StoreError::InvalidState("ID-selected managed run boundary mismatch".into());+ let run = ManagedRunBoundaryRow::read(&tx, input.run_id)?.ok_or_else(refused)?;+ let native = NativeSessionIdentity::parse(&input.native_session_id, &Sanitizer::builtin())+ .map_err(|_| refused())?;+ if run.state != "active"+ || expires <= Timestamp::now().as_microsecond()+ || run.agent != input.agent.as_str()+ || run.owner_user != input.owner_user+ || ((linked || delivered) && run.native_session.as_deref() != Some(native.as_str()))+ || ((input.session_start || !linked) && input.cwd.as_deref() != Some(run.cwd.as_str()))+ {+ return Err(refused());+ }+ Ok(Some((+ WorkspaceId::from_slice(&run.workspace)?,+ ProjectId::from_slice(&run.project)?,+ )))+}+/// Store-level finish input after the raw segment has been made durable.#[derive(Debug, Clone)]pub struct FinishWorkstreamRun {@@ -495,6 +549,7 @@ struct LinkRunRow {native_session_linked: bool,sync_through: i64,context_delivered: bool,+ scope_by_id: bool,}struct ManagedRunBoundaryRow {@@ -651,8 +706,8 @@ pub(crate) fn prepare_run("INSERT INTO managed_runs( \id, workstream_id, agent_kind, lease_owner, native_session_id, owner_user, state, \sync_after, sync_through, context_delivered, lease_expires_at, started_at, \- previous_agent_kind, previous_native_session_id \- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'active', ?7, ?8, 0, ?9, ?10, ?11, ?12)",+ previous_agent_kind, previous_native_session_id, scope_by_id \+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'active', ?7, ?8, 0, ?9, ?10, ?11, ?12, ?13)",params![run_id.as_bytes(),workstream_id.as_bytes(),@@ -670,6 +725,7 @@ pub(crate) fn prepare_run(previous_native_session.as_ref().map(|source| source.native_session_id.as_str()),+ input.scope_by_id,],)?;tx.execute(@@ -894,7 +950,7 @@ fn link_native_session_in_transaction(let run: Option<LinkRunRow> = tx.query_row("SELECT workstream_id, agent_kind, native_session_id, \- native_session_linked_at IS NOT NULL, sync_through, context_delivered \+ native_session_linked_at IS NOT NULL, sync_through, context_delivered, scope_by_id \FROM managed_runs WHERE id = ?1 AND state = 'active'",params![run_id.as_bytes()],|row| {@@ -905,6 +961,7 @@ fn link_native_session_in_transaction(native_session_linked: row.get(3)?,sync_through: row.get(4)?,context_delivered: row.get(5)?,+ scope_by_id: row.get(6)?,})},)@@ -915,6 +972,24 @@ fn link_native_session_in_transaction(if run.agent != agent.as_str() {return Ok(false);}+ if run.scope_by_id {+ // A native session already captured in another scope or by another+ // operator cannot be adopted just because it lives in the same cwd.+ let foreign: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM sessions s \+ JOIN managed_runs mr ON mr.id = ?1 JOIN workstreams w ON w.id = mr.workstream_id \+ WHERE s.id = ?2 AND (s.workspace_id <> w.workspace_id OR s.project_id <> w.project_id \+ OR s.agent_kind <> mr.agent_kind OR s.actor_user IS NOT mr.owner_user))",+ params![+ run_id.as_bytes(),+ ai_memory_core::SessionId::from_native(native_session_id).as_bytes()+ ],+ |row| row.get(0),+ )?;+ if foreign {+ return Ok(false);+ }+ }if (run.context_delivered || run.native_session_linked)&& run.native_sessiondiff --git a/crates/ai-memory-store/tests/suite/idle_session_end.rs b/crates/ai-memory-store/tests/suite/idle_session_end.rsindex b27685ea..9bb3378c 100644--- a/crates/ai-memory-store/tests/suite/idle_session_end.rs+++ b/crates/ai-memory-store/tests/suite/idle_session_end.rs@@ -1269,6 +1269,7 @@ async fn idle_end_writer_recheck_refuses_runs_linked_after_selection() {.await;let prepare = |name: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: proj,repo_fingerprint: "repo".into(),diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 9de5d090..8d78d63c 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -1906,6 +1906,7 @@ async fn a_session_linked_by_one_managed_run_is_not_another_runs() {let store = Store::open(tmp.path()).unwrap();let (ws, proj) = scope(&store).await;let prepare = |name: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: proj,repo_fingerprint: "repo".into(),@@ -1980,6 +1981,7 @@ async fn stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundarilet alice = operator("alice");let bob = operator("bob");let prepare = |project_id, name: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id,repo_fingerprint: format!("repo-{project_id}"),@@ -2086,6 +2088,7 @@ async fn force_unlock_replaces_only_the_same_operators_active_run() {let alice = operator("alice");let bob = operator("bob");let prepare = |lease_owner: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: proj,repo_fingerprint: "repo".into(),@@ -2145,6 +2148,7 @@ async fn force_unlock_replaces_only_the_same_operators_active_run() {.writer.prepare_workstream_run_owned(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::New("solo".into()),..prepare("solo:1")},@@ -2156,6 +2160,7 @@ async fn force_unlock_replaces_only_the_same_operators_active_run() {.writer.prepare_workstream_run_owned_with_unlock(PrepareWorkstreamRun {+ scope_by_id: false,selection: WorkstreamSelection::Named("solo".into()),..prepare("solo:2")},@@ -2182,6 +2187,7 @@ async fn stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch(.unwrap();let owner = operator("alice");let prepare = |project_id, name: &str| PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id,repo_fingerprint: format!("repo-{project_id}"),@@ -2415,6 +2421,7 @@ impl FinishFixture {.writer.prepare_workstream_run_owned(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: self.ws,project_id: self.project,repo_fingerprint: "repo-finish".into(),@@ -2848,6 +2855,7 @@ async fn owner_finish_store_raw_ids_use_the_actual_project_and_workspace() {.writer.prepare_workstream_run_owned(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "foreign".into(),@@ -2905,6 +2913,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {let run = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "reload".into(),@@ -3030,6 +3039,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {.writer.prepare_workstream_run_owned(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "recoverable".into(),@@ -3106,6 +3116,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {let old = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "reload".into(),@@ -3128,6 +3139,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {let replacement = store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id: ws,project_id: project,repo_fingerprint: "reload".into(),diff --git a/crates/ai-memory-store/tests/suite/workstream_provenance.rs b/crates/ai-memory-store/tests/suite/workstream_provenance.rsindex 02b90ecf..e8b083a9 100644--- a/crates/ai-memory-store/tests/suite/workstream_provenance.rs+++ b/crates/ai-memory-store/tests/suite/workstream_provenance.rs@@ -33,6 +33,7 @@ async fn prepare(store: &Store) -> ai_memory_store::PreparedWorkstreamRun {store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id,project_id,repo_fingerprint: "repo".into(),diff --git a/crates/ai-memory-web/tests/suite/workstreams.rs b/crates/ai-memory-web/tests/suite/workstreams.rsindex ab31817b..2967f2ee 100644--- a/crates/ai-memory-web/tests/suite/workstreams.rs+++ b/crates/ai-memory-web/tests/suite/workstreams.rs@@ -70,6 +70,7 @@ async fn prepare_with_selection(.store.writer.prepare_workstream_run(PrepareWorkstreamRun {+ scope_by_id: false,workspace_id,project_id,repo_fingerprint: format!("repo-secret-{project}"),diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 590a4ed2..172a1ee7 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -295,6 +295,66 @@ Probably not at first. Hooks alone already carry most continuity.If you never switch harnesses mid-workstream, the default path issimpler and you lose nothing by staying on it.+## Recovering an ambiguous project++Older installations can contain two populated projects that answer to the+same name, for example `widget` and `acme-widget` with legacy key `widget`.+Name resolution deliberately refuses that collision. A unique checkout path+does not make the server's name selector unambiguous.++`run` can select an existing project by its stable ID inside a workspace:++```sh+ai-memory run --workspace default --project-id <project-uuid> claude+ai-memory run --workspace default --project-id <project-uuid> codex+ai-memory workstreams --workspace default --project-id <project-uuid> --json+```++With a terminal, an ambiguous `run` offers a numbered choice of matching+projects the caller may write. Enter cancels without opening a run. Scripts+receive an actionable error containing authorized IDs and must pass+`--project-id`; they never select the first match automatically. The candidate+query examines a bounded set of matches and reports when more exist. An+explicit ID remains available when the intended project is not shown.++After a successful prepare, the client remembers the resolved ID in+`<data-dir>/client-projects.json`. An explicit authorized choice during+workstream discovery is also remembered after the read succeeds. Bindings+include the normalized server origin and mount, workspace, requested project,+canonical checkout path, and repository/worktree fingerprints. Changed+remotes, other checkouts, servers and scopes do not reuse the binding. The+server checks workspace membership and current permissions on every request;+the local record grants no access. An unreadable local registry is left unchanged+and falls back to name resolution, which still refuses ambiguous names. `resume` uses the same binding when listing+and launching a workstream. An explicit `--project` overrides a cached ID;+`--project-id` replaces the checkout's choice after successful preparation.+Neither operation moves, merges or deletes project history.++An empty workstream selected by ID starts a fresh native session instead of+automatically adopting an unlinked session found at the same path. A native+session already captured under another project or operator is refused; native+sessions already linked to the selected workstream remain resumable.++ID-selected runs require a reachable server. Their SessionStart context and+capture hooks use the run's pinned project after validating the launching+operator, active lease, harness and native session. Startup and initial binding+also require the original checkout. A stale, expired or foreign pinned run is+refused rather than routed by the ambiguous name. Existing runs retain their+original marker/name routing; the additive schema flag defaults to off.++The wire requests for `/workstream/runs` and `/workstream/recent` accept an+optional `project_id`, mutually exclusive with a non-empty `project`. Clients+send an empty `project` for ID selection so older servers reject it before+creating anything. Prepare responses include optional `resolved_project`+coordinates; a client requesting an ID refuses to start the harness unless+the server confirms that exact ID and workspace. Upgrade the server before+using ID selection. Name-only clients continue to work.++`POST /workstream/project-candidates` accepts `workspace` and `project` names+and returns `candidates` plus `truncated`. It works without the web UI, uses the+normal authentication middleware, includes only writable matches, and returns+IDs and names without server filesystem paths.+## Project-first launcher`ai-memory show` reverses the usual `cd` then `run` flow: choose a localdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 7322b282..fcf3662e 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -44,6 +44,7 @@ the legitimate restricted-project control and the failed-query cases.| 1k | Budgeted answer chronology uses only retrieved IDs and same-scope session timestamps | `memory_query` passes only authorized hit IDs to bounded `answer_evidence_metadata`; its session join checks workspace and project and never expands links; evidence priority is scoped | Store `answer_evidence_metadata_returns_only_requested_ids_without_expanding_links`, `answer_evidence_metadata_uses_session_time_only_in_the_same_scope`; MCP `answer_budget_uses_store_recency_without_reordering_retrieval_hits`; unit `answer_budget_unrelated_scopes_titles_and_equal_times_preserve_rank` | Adversarial requested-only and foreign-session controls; mutation results recorded in the PR || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate; `ai-memory-web` `history_replay.rs` (another workspace's page path, version id and session id answer 404, same tests and bites as row 1) | STRONG || 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-workstream/src/repository.rs` `inspect_repository_fingerprints` shares the launch identity derivation without checkpoint scans; `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; the explicit `--all` walk (`candidates_across_checkouts`) lists each linked checkout through its own fingerprint-scoped request and applies `--workspace` before any request; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`, `resume_all_walks_every_linked_checkout_and_honours_the_workspace_filter` (a foreign workspace filter sends no request; the default picker still ignores the registry); `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links); `repository.rs` `reports_origin_push_url_and_linked_worktree` verifies lightweight/full fingerprint parity and distinct worktree keys; CLI `resume_yolo_displays_picker_without_scanning_git_status` verifies listing skips status scans | STRONG |+| 2c | ID-selected managed scope remains authorized and invocation-bound | `scope.rs` `lookup_project_id_guarded` checks the existing workspace/project pair, reserved-profile write policy and current access; `workstream.rs` `project_candidates` applies the same selector guard; `router.rs` `pinned_managed_hook_scope` checks the opt-in run flag, owner, active lease, harness, checkout and native session, then authorizes and atomically links before startup or capture; store `link_native_session_in_transaction` refuses a native session already captured under a different scope, agent or operator; `project_registry.rs` keys local bindings by server, scope, canonical checkout and repository/worktree fingerprints | `auth.rs` `managed_project_id_http_enforces_workspace_grants_and_candidate_privacy` covers anonymous refusal, DB read/write grants, root control, missing/foreign workspace IDs, reserved profiles and hidden candidates; `router.rs` `managed_project_id_pins_startup_and_capture_without_accepting_foreign_hooks` covers legitimate startup/capture and wrong owner, cwd, agent, native session, foreign captured session, revoked grant and expired-run refusals; CLI `managed_project_id_launch_reuses_binding_honors_override_and_refuses_old_server` and registry isolation tests cover cache reuse, explicit override and old-server refusal; migration `project_id_pinning_upgrade_preserves_runs_and_failed_prepare_rolls_back` preserves legacy routing and rolls back a failed prepare. Removing the project-access, checkout or existing-native-scope guard fails its adversarial test; the reserved-profile test also failed before its guard was applied | STRONG || 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP; `serve.rs` mounts API-only and web+API protected routers behind `require_dual_auth` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control); `serve.rs` `api_only_mode_keeps_data_authenticated_and_web_absent` (anonymous API read refused, authenticated control admitted, browser route absent; #986) | STRONG || 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed); `ai-memory-mcp` `admin.rs` `pending_write_approve_foreign_scope_returns_404` and `pending_write_reject_foreign_scope_returns_404` — an id staged in workspace `alpha` requested through an existing `default` scope is 404 (never approved or rejected across the boundary), with the in-scope reject as the legitimate control (each proven to fail with 500 with the `pending_detail` guard removed, #1205) | STRONG || 3c | Public human-auth routes refuse bodies a foreign page can send without a preflight (login CSRF, password guessing, root recovery) | `ai-memory-mcp/src/human_auth.rs` `handle_login` / `handle_recovery` read their bodies by hand (to rate-limit first), so each checks `declares_json_body` before reading: a `Content-Type` other than `application/json` or `application/*+json` (parameters and case ignored), or none, → 415 before any password or recovery-token check and without charging the per-IP failure budget. `text/plain`, form-urlencoded and multipart are the only bodies a cross-site page can `POST` without a preflight, and `/auth/*` carries no CORS layer. The built-in login page, the `docs/frontend-api.md` examples and the recovery `curl` in `docs/install.md` send `application/json` | `human_auth.rs` `public_auth_routes_refuse_preflight_free_browser_bodies`: valid root credentials and a valid recovery token, sent from a foreign origin as `text/plain`, form-urlencoded, multipart and with no content type, more times than the per-IP failure budget → 415, no session cookie; controls: a same-origin JSON login then succeeds (password unchanged, budget untouched) and a JSON recovery returns 204. `json_body_declaration` (header table) | STRONG. Bite check: with the check removed, the `text/plain` login returns 200 with the session cookie (the pre-fix behaviour) and the test fails. `/auth/password` and `/auth/logout` were already closed: they run behind `require_session`, whose unsafe methods need the `x-csrf-token` header (a custom header, so preflighted), and `/auth/password` also uses axum `Json` |