Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hook): route capture to the marker-selected server profile (#992)
Talysson de Oliveira Cassianoad7a0aec7f61
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0c8cba45..28df5778 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1722,6 +1722,16 @@ pub struct BackfillArgs {/// been attempted for this checkout. Not for interactive use.#[arg(long, hide = true)]pub auto: bool,+ /// Internal: deliver to the server the spawning hook is installed+ /// against, instead of the configured one. Set by the SessionStart+ /// trigger so the backfill cannot depend on the agent's environment.+ #[arg(long, hide = true, conflicts_with = "server_profile")]+ pub server_url: Option<String>,+ /// Internal: deliver to this registered server profile (#992), with the+ /// profile's own stored token. Set by the SessionStart trigger when the+ /// repository's marker selects a profile.+ #[arg(long, hide = true)]+ pub server_profile: Option<String>,}/// Arguments for `repair-backfill-timestamps`.diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rsindex b048ef3e..bab712a6 100644--- a/crates/ai-memory-cli/src/commands/backfill.rs+++ b/crates/ai-memory-cli/src/commands/backfill.rs@@ -145,6 +145,41 @@ fn write_sentinel(data_dir: &Path, cwd: &Path) {let _ = std::fs::write(&path, b"");}+/// The server this backfill delivers to.+///+/// A SessionStart-spawned run names the hook's own target: a server profile+/// (#992), whose stored token is the only credential it will present, or the+/// install-time hook URL, authenticated exactly like the hook's own events to+/// it: the persisted hook token, then OIDC. The config/env bearer is never+/// used there, because it may belong to a different server than the one the+/// hook is installed against. A manual run keeps resolving from config.+async fn backfill_endpoint(+ config: &Config,+ args: &crate::cli::BackfillArgs,+) -> Result<ServerEndpoint> {+ if let Some(raw) = args.server_profile.as_deref() {+ let name = crate::server_profiles::ProfileName::parse(raw)+ .with_context(|| format!("`{raw}` is not a valid server profile name"))?;+ let profile = crate::server_profiles::lookup(&config.data_dir, &name)+ .map_err(|r| anyhow::anyhow!("server profile `{name}` was refused ({})", r.as_str()))?;+ return Ok(ServerEndpoint::for_hook_target(+ profile.url,+ Some(profile.token),+ ));+ }+ if let Some(url) = args.server_url.as_deref() {+ let static_token = crate::config::read_hook_auth_token(&config.data_dir);+ let token = super::hook_spool::resolve_bearer(+ &reqwest::Client::new(),+ &config.data_dir,+ static_token.as_deref(),+ )+ .await;+ return Ok(ServerEndpoint::for_hook_target(url.to_owned(), token));+ }+ Ok(ServerEndpoint::from_config_resolving_auth(config).await)+}+/// Run the backfill.////// # Errors@@ -168,7 +203,7 @@ pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()>let (workspace, project) =super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;let home = run::native_home(config).context("locating the local harness session stores")?;- let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let endpoint = backfill_endpoint(config, &args).await?;let mut report = BackfillReport {workspace: workspace.clone(),@@ -998,6 +1033,70 @@ mod tests {assert!(only.is_empty(), "no session matches the filter: {only:?}");}+ fn spawned_args(+ server_url: Option<&str>,+ server_profile: Option<&str>,+ ) -> crate::cli::BackfillArgs {+ crate::cli::BackfillArgs {+ workspace: None,+ project: None,+ session: None,+ force: false,+ dry_run: false,+ max_sessions: 25,+ json: false,+ quiet: true,+ auto: true,+ server_url: server_url.map(str::to_owned),+ server_profile: server_profile.map(str::to_owned),+ }+ }++ /// #992: a SessionStart-spawned backfill presents only the credential the+ /// hook itself uses for that server — never the config/env bearer, which+ /// may belong to another server entirely.+ #[tokio::test]+ async fn a_spawned_backfill_authenticates_like_the_hook_that_spawned_it() {+ let home = tempfile::tempdir().unwrap();+ let data_dir = tempfile::tempdir().unwrap();+ let mut config =+ crate::config::Config::load(None, Some(home.path().to_path_buf())).unwrap();+ config.data_dir = data_dir.path().to_path_buf();+ config.auth.bearer_token = Some("CONFIG-SERVER-TOKEN".into());++ let url = "https://hook.example/wiki";+ let endpoint = backfill_endpoint(&config, &spawned_args(Some(url), None))+ .await+ .unwrap();+ assert_eq!(+ endpoint.auth_token, None,+ "no hook token: nothing, not config's"+ );+ assert_eq!(endpoint.url, "https://hook.example");+ assert_eq!(endpoint.base_path, "/wiki");++ crate::config::store_hook_auth_token(data_dir.path(), "HOOK-TOKEN").unwrap();+ let endpoint = backfill_endpoint(&config, &spawned_args(Some(url), None))+ .await+ .unwrap();+ assert_eq!(endpoint.auth_token.as_deref(), Some("HOOK-TOKEN"));++ let name = crate::server_profiles::ProfileName::parse("team-b").unwrap();+ crate::server_profiles::add(data_dir.path(), &name, "https://b.example", &[], Some("B"))+ .unwrap();+ let endpoint = backfill_endpoint(&config, &spawned_args(None, Some("team-b")))+ .await+ .unwrap();+ assert_eq!(endpoint.url, "https://b.example");+ assert_eq!(endpoint.auth_token.as_deref(), Some("B"));+ assert!(+ backfill_endpoint(&config, &spawned_args(None, Some("nobody")))+ .await+ .is_err(),+ "an unregistered profile is refused, not replaced by config"+ );+ }+/// The automatic path must honor the `backfill_on_start` opt-out: it records/// the attempt (so it never re-spawns) and returns without contacting the/// server at all.@@ -1013,18 +1112,7 @@ mod tests {// must return before we ever build the endpoint.config.server_url = "http://127.0.0.1:9".to_string();- let args = crate::cli::BackfillArgs {- workspace: None,- project: None,- session: None,- force: false,- dry_run: false,- max_sessions: 25,- json: false,- quiet: true,- auto: true,- };- run(&config, args)+ run(&config, spawned_args(None, None)).await.expect("opted-out auto run must succeed without contacting the server");diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 5b6d7e6b..db657a09 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -24,6 +24,7 @@ use ai_memory_hooks::{use ai_memory_llm::OidcToken;use crate::cli::HookArgs;+use crate::server_profiles::{self, ProfileName, Rejection, ResolvedServer};use sha2::{Digest as _, Sha256};@@ -648,12 +649,14 @@ whereinspection_cwd.as_deref().unwrap_or(""),)});+ let dd = resolve_data_dir(data_dir.as_deref());// Precedence: an explicit flag (tests, one-off runs) wins; otherwise the// persisted per-install mode; otherwise the historical default.let capture_mode = args.capture_mode.map_or_else(- || persisted_capture_mode(&resolve_data_dir(data_dir.as_deref())),+ || persisted_capture_mode(&dd),crate::cli::CaptureModeArg::mode,);+ let route = resolve_hook_route(&dd, policy_cwd.as_deref(), || std::env::current_dir().ok());// Marker presence is the opt-in signal under allowlist mode. Resolved from// the same upward walk the policy uses, so opting in needs no new file.let marker_present = policy_cwd@@ -672,6 +675,8 @@ where"path_count": protocol.map_or(0, |protocol| protocol.path_count()),"disposition": protocol.map_or(CaptureDisposition::Keep, |protocol| protocol.disposition()),"extraction_state": protocol.map_or(ai_memory_hooks::ExtractionState::NotApplicable, |protocol| protocol.extraction_state()),+ "server_profile": route.profile_name().map(ProfileName::as_str),+ "server_resolution": route.resolution(),});if external_capture {output["external_capture"] = true.into();@@ -679,6 +684,25 @@ wherewriteln!(stdout, "{output}")?;return Ok(());}+ // #992: a marker that selects a server profile which does not resolve+ // emits nothing — not the event, not a handoff fetch, not a backfill.+ // Delivering to the install default instead would hand one team's+ // capture to another team's server.+ let profile = match route {+ HookRoute::InstallDefault => None,+ HookRoute::Profile(resolved) => Some(resolved),+ HookRoute::Rejected { name, reason } => {+ eprintln!(+ "ai-memory hook warning: this repository's marker selects server profile {}, \+ which was refused ({}); the event was dropped",+ name.as_ref()+ .map_or_else(|| "<invalid>".to_owned(), |n| format!("`{n}`")),+ reason.as_str()+ );+ write_success_response(stdout, agent_kind, hook_event)?;+ return Ok(());+ }+ };// #446: under allowlist mode a repository that never opted in emits// nothing. This sits outside the `tool_event` path on purpose — `decision`// is `None` for UserPromptSubmit, SessionStart/End and Stop, so gating via@@ -722,8 +746,6 @@ where&json,args.project_strategy.and_then(|s| s.baked()),);- let base = args.server_url.trim_end_matches('/');- let dd = resolve_data_dir(data_dir.as_deref());let spool = hook_spool::spool_dir(&dd);let session_qs = session_id_query_suffix(&dd, &args.agent, &args.event, &json);let managed_qs = managed_run_query_suffix();@@ -738,7 +760,19 @@ where// dir. An explicit `--auth-token` still wins, which keeps every config// written before this change working exactly as it did.let persisted_token = crate::config::read_hook_auth_token(&dd);- let effective_token = args.auth_token.as_deref().or(persisted_token.as_deref());+ let install_token = args.auth_token.as_deref().or(persisted_token.as_deref());+ // A profile carries its own URL and token and never falls back to the+ // install's credentials or to OIDC: `auth.json` belongs to the install+ // default, and presenting it to a profile's server would leak it across+ // servers.+ let (base, effective_token, profile_name) = match &profile {+ Some(profile) => (+ profile.url.as_str(),+ Some(profile.token.as_str()),+ Some(profile.name.as_str()),+ ),+ None => (args.server_url.trim_end_matches('/'), install_token, None),+ };let oidc_present = effective_token.is_none()&& OidcToken::load(&dd.join("auth.json"))@@ -765,7 +799,8 @@ whereargs.event, args.agent, hook_qs, capture_qs);let entry =- hook_spool::entry_for(event_url, payload.clone(), effective_token, oidc_present);+ hook_spool::entry_for(event_url, payload.clone(), effective_token, oidc_present)+ .routed_to(profile_name);if hook_spool::enqueue(&spool, &entry).is_err() {eprintln!("ai-memory hook warning: failed to spool lifecycle event; capture for this event was skipped"@@ -808,7 +843,11 @@ where&& let Ok(trigger_cwd) = std::env::current_dir()&& !super::backfill::sentinel_path(&dd, &trigger_cwd).exists(){- let _ = hook_drain_process::spawn_backfill(&dd);+ let target = match profile_name {+ Some(name) => hook_drain_process::BackfillTarget::Profile(name),+ None => hook_drain_process::BackfillTarget::ServerUrl(base),+ };+ let _ = hook_drain_process::spawn_backfill(&dd, target);}}@@ -979,13 +1018,14 @@ where&& should_spawn_background_drainer(&args.event)&& let Err(err) = after_background_drain_event_enqueue(&dd,- // The hook's own token, resolved the same way it authenticates- // its own request: `--auth-token`, else the environment, else the- // copy `install-hooks --apply` persisted under the data dir- // (#552). Current by construction either way. The drain uses it- // only to retry an entry the server has already rejected with 401- // (#542).- effective_token,+ // The install's own token, resolved the same way an install-default+ // event authenticates: `--auth-token`, else the copy+ // `install-hooks --apply` persisted under the data dir (#552).+ // Current by construction either way. The drain uses it only to+ // retry an install-default entry the server has already rejected+ // with 401 (#542); a profile entry retries with its own profile's+ // token, so a profile's token is never handed over here.+ install_token,spawn_background_drainer,){@@ -1024,6 +1064,77 @@ fn hook_context(agent: &str, raw: &serde_json::Value) -> (Option<String>, Option}}+/// Where one event is delivered (#992).+#[derive(Debug)]+enum HookRoute {+ /// No marker selects a server: the install-time `--server-url`, exactly+ /// as before profiles existed.+ InstallDefault,+ /// The marker's profile resolved; its URL and token replace the install's.+ Profile(ResolvedServer),+ /// The marker selects a profile that did not resolve. Nothing is emitted.+ Rejected {+ /// The selected name, when it is a valid one (safe to print).+ name: Option<ProfileName>,+ reason: Rejection,+ },+}++impl HookRoute {+ fn profile_name(&self) -> Option<&ProfileName> {+ match self {+ Self::InstallDefault => None,+ Self::Profile(resolved) => Some(&resolved.name),+ Self::Rejected { name, .. } => name.as_ref(),+ }+ }++ /// Label for `--check-capture`. Never a URL, path, or token.+ fn resolution(&self) -> &'static str {+ match self {+ Self::InstallDefault => "install-default",+ Self::Profile(_) => "marker",+ Self::Rejected { reason, .. } => reason.as_str(),+ }+ }+}++/// Resolve the route for one event.+///+/// The payload's cwd decides; when the payload carries none, the hook+/// process's own cwd does (the agent launches hooks in its workspace). An+/// event without a payload cwd must not escape a profile-routed tree to the+/// install default merely because the harness omitted the field.+fn resolve_hook_route(+ data_dir: &Path,+ policy_cwd: Option<&str>,+ process_cwd: impl FnOnce() -> Option<PathBuf>,+) -> HookRoute {+ let home = super::path_util::home_dir();+ let cwd = policy_cwd+ .map(str::to_owned)+ .or_else(|| process_cwd().map(|dir| dir.to_string_lossy().into_owned()));+ let Some(selection) = cwd+ .as_deref()+ .and_then(|cwd| crate::marker::find_server_selection(cwd, home.as_deref()))+ else {+ return HookRoute::InstallDefault;+ };+ let Some(raw_name) = selection.name else {+ return HookRoute::Rejected {+ name: None,+ reason: Rejection::UnreadableMarker,+ };+ };+ match server_profiles::resolve(data_dir, &raw_name, &selection.marker_dir, home.as_deref()) {+ Ok(resolved) => HookRoute::Profile(resolved),+ Err(reason) => HookRoute::Rejected {+ name: ProfileName::parse(&raw_name),+ reason,+ },+ }+}+/// Normalize the raw hook `cwd` into the base `policy.inspect` joins a tool/// event's relative candidate path onto — lexically, via/// `marker::absolute_normalized`, NOT `fs::canonicalize` (#671).@@ -2478,6 +2589,8 @@ mod tests {"marker_present","path_count","policy_state",+ "server_profile",+ "server_resolution","tool_family","version",]@@ -2857,6 +2970,254 @@ mod tests {);}+ // ── #992: per-repository server profiles ─────────────────────────────++ /// Register `name` in `data_dir` with a token and the given roots.+ fn register_profile(+ data_dir: &Path,+ name: &str,+ url: &str,+ roots: &[&Path],+ token: Option<&str>,+ ) {+ let roots: Vec<String> = roots+ .iter()+ .map(|r| r.to_string_lossy().into_owned())+ .collect();+ crate::server_profiles::add(+ data_dir,+ &ProfileName::parse(name).unwrap(),+ url,+ &roots,+ token,+ )+ .unwrap();+ }++ fn repo_with_marker(parent: &Path, name: &str, marker: &str) -> PathBuf {+ let repo = parent.join(name);+ std::fs::create_dir_all(&repo).unwrap();+ std::fs::write(repo.join(".ai-memory.toml"), marker).unwrap();+ repo+ }++ fn claude_args(event: &str, server_url: &str) -> HookArgs {+ let mut args = devin_hook_args(event);+ args.agent = "claude-code".into();+ args.server_url = server_url.into();+ args+ }++ async fn run_prompt(data_dir: &Path, args: HookArgs, cwd: &Path) -> Vec<u8> {+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.to_path_buf()),+ args,+ serde_json::json!({"session_id": "s", "cwd": cwd, "prompt": "hello"}).to_string(),+ &mut stdout,+ |_, _| panic!("a prompt must only spool"),+ )+ .await+ .unwrap();+ stdout+ }++ /// Two repositories on one install deliver to two servers, each with its+ /// own token, and neither with the install's persisted one.+ #[tokio::test]+ async fn each_repository_spools_to_its_own_profile_with_its_own_token() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let work = tmp.path().join("work");+ let repo_a = repo_with_marker(&work, "a", "server = \"team-a\"\n");+ let repo_b = repo_with_marker(&work, "b", "workspace = \"b\"\nserver = \"team-b\"\n");+ register_profile(+ &data_dir,+ "team-a",+ "https://a.example",+ &[&repo_a],+ Some("tok-a"),+ );+ register_profile(+ &data_dir,+ "team-b",+ "https://b.example/",+ &[&repo_b],+ Some("tok-b"),+ );+ crate::config::store_hook_auth_token(&data_dir, "INSTALL-TOKEN").unwrap();++ run_prompt(+ &data_dir,+ claude_args("user-prompt-submit", "https://default.example"),+ &repo_a,+ )+ .await;+ run_prompt(+ &data_dir,+ claude_args("user-prompt-submit", "https://default.example"),+ &repo_b,+ )+ .await;++ let entries = read_spooled_entries(&hook_spool::spool_dir(&data_dir));+ assert_eq!(entries.len(), 2);+ assert!(+ entries[0].url.starts_with("https://a.example/hook?"),+ "{}",+ entries[0].url+ );+ assert_eq!(entries[0].token.as_deref(), Some("tok-a"));+ assert_eq!(entries[0].profile.as_deref(), Some("team-a"));+ assert!(+ entries[1].url.starts_with("https://b.example/hook?"),+ "{}",+ entries[1].url+ );+ assert_eq!(entries[1].token.as_deref(), Some("tok-b"));+ assert_eq!(entries[1].profile.as_deref(), Some("team-b"));+ }++ /// Backward compatibility: without a `server` key the install default is+ /// used exactly as before, and the spooled entry carries no profile.+ #[tokio::test]+ async fn a_repository_without_a_server_key_keeps_the_install_default() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let repo = repo_with_marker(tmp.path(), "repo", "workspace = \"w\"\n");+ register_profile(&data_dir, "team-a", "https://a.example", &[], Some("tok-a"));+ crate::config::store_hook_auth_token(&data_dir, "INSTALL-TOKEN").unwrap();++ run_prompt(+ &data_dir,+ claude_args("user-prompt-submit", "https://default.example"),+ &repo,+ )+ .await;++ let spool = hook_spool::spool_dir(&data_dir);+ let entries = read_spooled_entries(&spool);+ assert_eq!(entries.len(), 1);+ assert!(entries[0].url.starts_with("https://default.example/hook?"));+ assert_eq!(entries[0].token.as_deref(), Some("INSTALL-TOKEN"));+ let raw = std::fs::read_dir(&spool)+ .unwrap()+ .map(|e| std::fs::read_to_string(e.unwrap().path()).unwrap())+ .next()+ .unwrap();+ assert!(!raw.contains("\"profile\""), "{raw}");+ }++ /// Every refusal emits nothing — no spool entry, no drainer — and+ /// `--check-capture` names the reason without a URL, path, or token.+ #[tokio::test]+ async fn a_selection_that_does_not_resolve_emits_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let inside = repo_with_marker(tmp.path(), "inside", "server = \"rooted\"\n");+ let outside = repo_with_marker(tmp.path(), "outside", "server = \"rooted\"\n");+ let unknown = repo_with_marker(tmp.path(), "unknown", "server = \"nobody\"\n");+ let tokenless = repo_with_marker(tmp.path(), "tokenless", "server = \"tokenless\"\n");+ let unrooted = repo_with_marker(tmp.path(), "unrooted", "server = \"unrooted\"\n");+ let bare = repo_with_marker(tmp.path(), "bare", "server = Bad/Name\n");+ register_profile(+ &data_dir,+ "rooted",+ "https://r.example",+ &[&inside],+ Some("tok-r"),+ );+ register_profile(+ &data_dir,+ "tokenless",+ "https://t.example",+ &[&tokenless],+ None,+ );+ register_profile(+ &data_dir,+ "unrooted",+ "https://u.example",+ &[],+ Some("tok-u"),+ );+ crate::config::store_hook_auth_token(&data_dir, "INSTALL-TOKEN").unwrap();++ for (cwd, resolution) in [+ (&outside, "rejected-outside-roots"),+ (&unknown, "rejected-unknown-profile"),+ (&tokenless, "rejected-no-token"),+ (&unrooted, "rejected-roots-required"),+ (&bare, "rejected-invalid-profile-name"),+ (&inside, "marker"),+ ] {+ let mut args = claude_args("user-prompt-submit", "https://default.example");+ args.check_capture = true;+ let stdout = run_prompt(&data_dir, args, cwd).await;+ let output: serde_json::Value = serde_json::from_slice(&stdout).unwrap();+ assert_eq!(output["server_resolution"], resolution, "{}", cwd.display());+ let printed = String::from_utf8(stdout).unwrap();+ for secret in ["tok-", "https://", &*tmp.path().to_string_lossy()] {+ assert!(!printed.contains(secret), "{printed}");+ }++ let spool = hook_spool::spool_dir(&data_dir);+ let before = hook_spool::spool_len(&spool);+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ claude_args("session-end", "https://default.example"),+ serde_json::json!({"session_id": "s", "cwd": cwd}).to_string(),+ &mut stdout,+ |_, token| {+ assert!(+ resolution == "marker",+ "a refused route must not spawn a drainer"+ );+ assert_eq!(+ token,+ Some("INSTALL-TOKEN"),+ "the drain gets the install token for install-default retries, \+ never the profile's"+ );+ Ok(())+ },+ )+ .await+ .unwrap();+ let spooled = hook_spool::spool_len(&spool) - before;+ assert_eq!(spooled, usize::from(resolution == "marker"), "{resolution}");+ }+ }++ /// An event whose payload has no cwd is routed by the hook process's own+ /// cwd, so a harness omitting the field cannot escape a routed tree.+ #[test]+ fn an_event_without_a_payload_cwd_routes_by_the_process_cwd() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let repo = repo_with_marker(tmp.path(), "repo", "server = \"team-b\"\n");+ register_profile(+ &data_dir,+ "team-b",+ "https://b.example",+ &[&repo],+ Some("tok-b"),+ );++ let routed = resolve_hook_route(&data_dir, None, || Some(repo.clone()));+ assert!(matches!(routed, HookRoute::Profile(ref p) if p.url == "https://b.example"));+ let refused = resolve_hook_route(&data_dir, None, || Some(repo.join("..")));+ assert!(matches!(refused, HookRoute::InstallDefault), "{refused:?}");+ let unknown = resolve_hook_route(&data_dir, None, || None);+ assert!(matches!(unknown, HookRoute::InstallDefault));+ let payload_wins =+ resolve_hook_route(&data_dir, Some(&tmp.path().to_string_lossy()), || {+ Some(repo.clone())+ });+ assert!(matches!(payload_wins, HookRoute::InstallDefault));+ }+/// Kimi injects any UserPromptSubmit stdout into the turn verbatim, so a/// prompt dropped by allowlist mode must print nothing — not even `{}`.#[tokio::test]@@ -2879,6 +3240,218 @@ mod tests {assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);}+ /// The same for a prompt dropped because its profile was refused.+ #[tokio::test]+ async fn a_refused_route_prints_nothing_for_kimi_user_prompts() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let repo = repo_with_marker(tmp.path(), "repo", "server = \"nobody\"\n");+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ kimi_hook_args("user-prompt", &dead_server_url()),+ serde_json::json!({"session_id": "k", "cwd": repo, "prompt": "hi"}).to_string(),+ &mut stdout,+ |_, _| panic!("a refused route spawns nothing"),+ )+ .await+ .unwrap();+ assert!(stdout.is_empty(), "{:?}", String::from_utf8_lossy(&stdout));+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);+ }++ /// Session start fetches the handoff from the profile's server with the+ /// profile's token; the install-default server sees nothing at all.+ #[tokio::test]+ async fn session_start_handoff_comes_from_the_profile_server_only() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let (profile_base, mut profile_requests) = serve_requests("200 OK", "B-HANDOFF").await;+ let (default_base, mut default_requests) = serve_requests("200 OK", "A-HANDOFF").await;+ let repo = repo_with_marker(tmp.path(), "repo", "server = \"team-b\"\n");+ register_profile(&data_dir, "team-b", &profile_base, &[&repo], Some("tok-b"));+ crate::config::store_hook_auth_token(&data_dir, "INSTALL-TOKEN").unwrap();++ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ kiro_hook_args("session-start", &default_base),+ serde_json::json!({"session_id": "kiro-session", "cwd": repo}).to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"B-HANDOFF\n");+ let mut recorded = Vec::new();+ while let Some(request) = first_request(&mut profile_requests).await {+ recorded.push(request);+ }+ assert!(+ recorded.iter().any(|r| r.starts_with("GET /handoff?")+ && r.lines()+ .any(|l| l.eq_ignore_ascii_case("authorization: Bearer tok-b"))),+ "{recorded:?}"+ );+ assert!(+ recorded.iter().all(|r| !r.contains("INSTALL-TOKEN")),+ "{recorded:?}"+ );+ assert_eq!(first_request(&mut default_requests).await, None);+ }++ /// Recording stub that accepts exactly one bearer. An authorised+ /// `/hook/batch` answers `{"accepted": n}`, an authorised per-event POST+ /// `202`, anything else `401`. Every request is recorded whole (head and+ /// body), so a test can see both who authenticated and what was delivered.+ async fn serve_token_gated(+ accepted_token: &'static str,+ ) -> (String, tokio::sync::mpsc::UnboundedReceiver<String>) {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();+ tokio::spawn(async move {+ loop {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ // Read until the head is complete and the body has arrived:+ // a batch body can land in a second segment.+ let mut raw = Vec::new();+ let mut chunk = [0_u8; 8192];+ loop {+ let read = stream.read(&mut chunk).await.unwrap_or(0);+ if read == 0 {+ break;+ }+ raw.extend_from_slice(&chunk[..read]);+ let text = String::from_utf8_lossy(&raw);+ let Some((head, body)) = text.split_once("\r\n\r\n") else {+ continue;+ };+ let expected = head+ .lines()+ .find_map(|l| {+ l.to_ascii_lowercase()+ .strip_prefix("content-length:")+ .map(|v| v.trim().parse::<usize>().unwrap_or(0))+ })+ .unwrap_or(0);+ if body.len() >= expected {+ break;+ }+ }+ let request = String::from_utf8_lossy(&raw).into_owned();+ let _ = tx.send(request.clone());+ let authorized = request.lines().any(|l| {+ l.trim()+ .eq_ignore_ascii_case(&format!("authorization: Bearer {accepted_token}"))+ });+ let is_batch = request+ .lines()+ .next()+ .is_some_and(|l| l.contains("/hook/batch"));+ let (status, body) = if !authorized {+ ("401 Unauthorized", "{\"error\":\"bad token\"}".to_string())+ } else if is_batch {+ let payload = request.split("\r\n\r\n").nth(1).unwrap_or("");+ let accepted = serde_json::from_str::<serde_json::Value>(payload)+ .ok()+ .and_then(|v| v.as_array().map(Vec::len))+ .unwrap_or(0);+ ("200 OK", format!("{{\"accepted\":{accepted}}}"))+ } else {+ ("202 Accepted", "queued".to_string())+ };+ let response = format!(+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ (format!("http://{addr}"), rx)+ }++ /// Everything a stub recorded, once no more requests arrive.+ async fn recorded(requests: &mut tokio::sync::mpsc::UnboundedReceiver<String>) -> Vec<String> {+ let mut all = Vec::new();+ while let Ok(Some(request)) =+ tokio::time::timeout(Duration::from_millis(250), requests.recv()).await+ {+ all.push(request);+ }+ all+ }++ /// The issue's first acceptance criterion at the wire: two repositories+ /// on one install, one routed to a profile and one not, spool into the+ /// same queue and are drained by one pass, and each server receives+ /// exactly its own event with exactly its own bearer. Server A accepts+ /// only the install token and server B only the profile's, so a+ /// misdelivered event or a swapped credential would be refused and+ /// counted as undelivered.+ #[tokio::test]+ async fn a_mixed_spool_drains_each_event_only_to_its_own_server() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let work = tmp.path().join("work");+ let (base_a, mut requests_a) = serve_token_gated("INSTALL-TOKEN").await;+ let (base_b, mut requests_b) = serve_token_gated("tok-b").await;+ let repo_a = repo_with_marker(&work, "a", "workspace = \"a\"\n");+ let repo_b = repo_with_marker(&work, "b", "workspace = \"b\"\nserver = \"team-b\"\n");+ register_profile(&data_dir, "team-b", &base_b, &[&repo_b], Some("tok-b"));+ crate::config::store_hook_auth_token(&data_dir, "INSTALL-TOKEN").unwrap();++ for (repo, sentinel) in [(&repo_a, "SENTINEL-A"), (&repo_b, "SENTINEL-B")] {+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ claude_args("user-prompt-submit", &base_a),+ serde_json::json!({"session_id": "s", "cwd": repo, "prompt": sentinel}).to_string(),+ &mut stdout,+ |_, _| panic!("a prompt only spools"),+ )+ .await+ .unwrap();+ }+ let spool = hook_spool::spool_dir(&data_dir);+ assert_eq!(hook_spool::spool_len(&spool), 2);++ let result = hook_spool::drain_with_live_token(+ &spool,+ &data_dir,+ Duration::from_secs(5),+ Duration::from_millis(500),+ Some("INSTALL-TOKEN"),+ )+ .await;+ assert_eq!(result.sent, 2, "{result:?}");+ assert_eq!(hook_spool::spool_len(&spool), 0, "nothing left queued");++ let got_a = recorded(&mut requests_a).await;+ let got_b = recorded(&mut requests_b).await;+ assert_eq!(got_a.len(), 1, "server A saw {got_a:?}");+ assert_eq!(got_b.len(), 1, "server B saw {got_b:?}");+ let (a, b) = (&got_a[0], &got_b[0]);+ assert!(a.contains("SENTINEL-A") && !a.contains("SENTINEL-B"), "{a}");+ assert!(b.contains("SENTINEL-B") && !b.contains("SENTINEL-A"), "{b}");+ assert!(+ a.lines()+ .any(|l| l.eq_ignore_ascii_case("authorization: Bearer INSTALL-TOKEN"))+ && !a.contains("tok-b"),+ "{a}"+ );+ assert!(+ b.lines()+ .any(|l| l.eq_ignore_ascii_case("authorization: Bearer tok-b"))+ && !b.contains("INSTALL-TOKEN"),+ "{b}"+ );+ }+#[tokio::test]async fn kimi_user_prompt_prints_the_handoff_body_verbatim() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/src/commands/hook_drain_process.rs b/crates/ai-memory-cli/src/commands/hook_drain_process.rsindex d3b046fb..aeab13ba 100644--- a/crates/ai-memory-cli/src/commands/hook_drain_process.rs+++ b/crates/ai-memory-cli/src/commands/hook_drain_process.rs@@ -92,15 +92,37 @@ pub fn command_spec(data_dir: &Path, live_token: Option<&str>) -> io::Result<Dra})}-/// Build `ai-memory --data-dir <dir> backfill --auto --quiet`.+/// Which server the spawned backfill delivers to: the one the spawning hook+/// resolved for this event, never whatever the environment points at.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BackfillTarget<'a> {+ /// The hook's install-time `--server-url`.+ ServerUrl(&'a str),+ /// A server profile the repository's marker selected (#992).+ Profile(&'a str),+}++/// Build `ai-memory --data-dir <dir> backfill --auto --quiet` plus the hook's+/// resolved target.////// The one-time boot backfill of pre-hook local history is potentially long/// (it reads native transcripts and imports them), so it runs detached exactly/// like the drainer rather than inline in the SessionStart hook's tight budget.-/// It carries no bearer on its argv or in its environment: `backfill` resolves-/// auth from config / the persisted hook token itself, and the automatic path-/// only runs in the loopback single-operator posture where no token is needed.-pub fn backfill_command_spec(data_dir: &Path) -> io::Result<DrainCommandSpec> {+///+/// The target is passed explicitly because, left to itself, `backfill`+/// resolves the server from config and the environment: a hook pointed at a+/// remote server then backfilled into `127.0.0.1` whenever the agent was+/// launched without `AI_MEMORY_SERVER_URL`. It carries no bearer on its argv+/// or in its environment: `backfill` reads the persisted hook token, or the+/// profile's own token, from the data dir.+pub fn backfill_command_spec(+ data_dir: &Path,+ target: BackfillTarget<'_>,+) -> io::Result<DrainCommandSpec> {+ let (flag, value) = match target {+ BackfillTarget::ServerUrl(url) => ("--server-url", url),+ BackfillTarget::Profile(name) => ("--server-profile", name),+ };Ok(DrainCommandSpec {exe: std::env::current_exe()?,args: vec![@@ -109,6 +131,8 @@ pub fn backfill_command_spec(data_dir: &Path) -> io::Result<DrainCommandSpec> {OsString::from("backfill"),OsString::from("--auto"),OsString::from("--quiet"),+ OsString::from(flag),+ OsString::from(value),],stderr_log: data_dir.join("logs").join("backfill.log"),live_token: None,@@ -117,8 +141,8 @@ pub fn backfill_command_spec(data_dir: &Path) -> io::Result<DrainCommandSpec> {/// Spawn the detached one-time boot backfill without inheriting hook stdio./// Best-effort: a spawn failure must never break session start.-pub fn spawn_backfill(data_dir: &Path) -> io::Result<()> {- let spec = backfill_command_spec(data_dir)?;+pub fn spawn_backfill(data_dir: &Path, target: BackfillTarget<'_>) -> io::Result<()> {+ let spec = backfill_command_spec(data_dir, target)?;spawn_spec(&spec)}@@ -358,6 +382,34 @@ mod tests {);}+ /// The backfill goes where the hook resolved, and a profile travels as a+ /// name only — the worker reads its token from the data dir.+ #[test]+ fn backfill_carries_the_hooks_target_and_no_token() {+ let tmp = tempfile::tempdir().unwrap();+ let default =+ backfill_command_spec(tmp.path(), BackfillTarget::ServerUrl("https://a.example"))+ .unwrap();+ assert_eq!(+ &default.args[2..],+ [+ "backfill",+ "--auto",+ "--quiet",+ "--server-url",+ "https://a.example"+ ]+ .map(OsString::from)+ );+ let profile = backfill_command_spec(tmp.path(), BackfillTarget::Profile("team-b")).unwrap();+ assert_eq!(+ &profile.args[5..],+ ["--server-profile", "team-b"].map(OsString::from)+ );+ assert!(profile.live_token.is_none());+ assert!(default.live_token.is_none());+ }+/// An absent or empty token carries nothing, so a no-auth deployment does/// not export an empty bearer into the child.#[test]diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rsindex f5107308..539c6e53 100644--- a/crates/ai-memory-cli/src/http_client.rs+++ b/crates/ai-memory-cli/src/http_client.rs@@ -138,6 +138,14 @@ impl ServerEndpoint {)}+ /// Build for a target the spawning hook already resolved: its URL+ /// (including any mount path, as `install-hooks` rendered it) and the+ /// bearer it authenticates with. No config or environment is consulted.+ #[must_use]+ pub(crate) fn for_hook_target(url: String, token: Option<String>) -> Self {+ Self::build(Some(url), token, true, None)+ }+/// Build from an explicit URL + token pair (useful for tests that/// cannot safely mutate the process environment).///diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 75506c0e..88974be6 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -25,6 +25,7 @@ mod repo_layout;mod routing_instructions;mod routing_skills;mod serve_shutdown;+mod server_profiles;mod shutdown_signals;mod upgrade_e2e;mod yolo_ai_jail;diff --git a/crates/ai-memory-cli/tests/suite/server_profiles.rs b/crates/ai-memory-cli/tests/suite/server_profiles.rsnew file mode 100644index 00000000..6761dc9d--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/server_profiles.rs@@ -0,0 +1,509 @@+//! Server profiles (#992) driven through the shipped binary: `ai-memory+//! server` writes the registry that `ai-memory hook` then routes by. The unit+//! tests cover each piece in-process; this checks the CLI wiring between them+//! — argument parsing, `--data-dir` resolution, stdin token entry, and the+//! JSON contract of `--check-capture` — without any network: no server is+//! contacted, and the profile URLs here never resolve.++use std::io::Write as _;+use std::path::{Path, PathBuf};+use std::process::{Command, Output, Stdio};+use std::time::{Duration, Instant};++use super::e2e_support::{ServerGuard, free_port, hermetic};++const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");+const DEFAULT_SERVER: &str = "https://default.example";+const PROFILE_SERVER: &str = "https://b.example";+const SECRET: &str = "SECRET-TOKEN-B";++/// A temp `$HOME` with the repository and data dir inside it, so every marker+/// walk stops at the sandbox and the agent config paths stay out of the real+/// profile.+struct Sandbox {+ _home: tempfile::TempDir,+ home: PathBuf,+ data_dir: PathBuf,+ repo: PathBuf,+}++impl Sandbox {+ fn new() -> Self {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().to_path_buf();+ let repo = home.join("work").join("team-b").join("repo");+ std::fs::create_dir_all(&repo).unwrap();+ for dir in [+ ".config",+ ".local/share",+ "AppData/Roaming",+ "AppData/Local",+ ] {+ std::fs::create_dir_all(home.join(dir)).unwrap();+ }+ Self {+ data_dir: home.join(".ai-memory-data"),+ _home: tmp,+ home,+ repo,+ }+ }++ fn root(&self) -> String {+ self.home+ .join("work")+ .join("team-b")+ .to_string_lossy()+ .into_owned()+ }++ fn write_marker(&self, body: &str) {+ std::fs::write(self.repo.join(".ai-memory.toml"), body).unwrap();+ }++ fn cmd(&self) -> Command {+ let mut cmd = hermetic(BIN);+ cmd.env("HOME", &self.home)+ .env("USERPROFILE", &self.home)+ .env("XDG_CONFIG_HOME", self.home.join(".config"))+ .env("XDG_DATA_HOME", self.home.join(".local/share"))+ .env("APPDATA", self.home.join("AppData/Roaming"))+ .env("LOCALAPPDATA", self.home.join("AppData/Local"))+ .env("AI_MEMORY_HOME", &self.home)+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env("RUST_LOG", "off")+ .arg("--data-dir")+ .arg(&self.data_dir);+ cmd+ }++ fn run(&self, args: &[&str], stdin: Option<&str>) -> Output {+ let mut child = self+ .cmd()+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap_or_else(|e| panic!("spawn `{}`: {e}", args.join(" ")));+ let mut pipe = child.stdin.take().expect("stdin");+ if let Some(input) = stdin {+ pipe.write_all(input.as_bytes()).expect("write stdin");+ }+ drop(pipe);+ child.wait_with_output().expect("wait")+ }++ fn run_ok(&self, args: &[&str], stdin: Option<&str>) -> String {+ let out = self.run(args, stdin);+ assert!(+ out.status.success(),+ "`{}` failed: {}\nstdout: {}\nstderr: {}",+ args.join(" "),+ out.status,+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr),+ );+ String::from_utf8(out.stdout).expect("stdout utf8")+ }++ fn hook(&self, event: &str, check_capture: bool) -> Output {+ self.hook_at(&self.repo, DEFAULT_SERVER, None, event, check_capture)+ }++ fn hook_at(+ &self,+ cwd: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ event: &str,+ check_capture: bool,+ ) -> Output {+ let payload = serde_json::json!({+ "session_id": format!("s-{}", cwd.file_name().unwrap().to_string_lossy()),+ "cwd": cwd,+ "prompt": "hello",+ })+ .to_string();+ let mut args = vec![+ "hook",+ "--event",+ event,+ "--agent",+ "claude-code",+ "--server-url",+ server_url,+ ];+ if let Some(token) = auth_token {+ args.extend(["--auth-token", token]);+ }+ if check_capture {+ args.push("--check-capture");+ }+ self.run(&args, Some(&payload))+ }++ fn check_capture(&self) -> serde_json::Value {+ let out = self.hook("user-prompt-submit", true);+ assert!(+ out.status.success(),+ "{}",+ String::from_utf8_lossy(&out.stderr)+ );+ serde_json::from_slice(&out.stdout).expect("check-capture json")+ }++ fn spooled_entries(&self) -> Vec<serde_json::Value> {+ let Ok(dir) = std::fs::read_dir(self.data_dir.join("hook-spool")) else {+ return Vec::new();+ };+ dir.flatten()+ .filter(|e| e.path().extension().is_some_and(|x| x == "json"))+ .map(|e| serde_json::from_slice(&std::fs::read(e.path()).unwrap()).unwrap())+ .collect()+ }++ fn register(&self) {+ let root = self.root();+ self.run_ok(+ &[+ "server",+ "add",+ "team-b",+ "--url",+ PROFILE_SERVER,+ "--root",+ &root,+ "--auth-token-stdin",+ ],+ Some(&format!("{SECRET}\n")),+ );+ }+}++fn token_dir(data_dir: &Path) -> PathBuf {+ data_dir.join("auth-tokens")+}++/// The whole path through the binary: register with a token on stdin, the+/// listing shows the profile without the secret, and a hook in the routed+/// repository spools to the profile's server with the profile's token.+#[test]+fn a_routed_repository_spools_to_its_profile_through_the_binary() {+ let sb = Sandbox::new();+ sb.register();++ let listing = sb.run_ok(&["server", "list", "--json"], None);+ let rows: serde_json::Value = serde_json::from_str(&listing).expect("list json");+ assert_eq!(rows[0]["name"], "team-b");+ assert_eq!(rows[0]["url"], PROFILE_SERVER);+ assert_eq!(rows[0]["token"], "stored");+ assert!(!listing.contains(SECRET), "{listing}");+ let human = sb.run_ok(&["server", "list"], None);+ assert!(!human.contains(SECRET), "{human}");++ sb.write_marker("workspace = \"team-b\"\nserver = \"team-b\"\n");+ let check = sb.check_capture();+ assert_eq!(check["server_resolution"], "marker");+ assert_eq!(check["server_profile"], "team-b");+ assert!(!check.to_string().contains(SECRET));+ assert!(!check.to_string().contains("example"), "no URL: {check}");++ let out = sb.hook("user-prompt-submit", false);+ assert!(out.status.success());+ assert_eq!(out.stdout, b"{}\n");+ let entries = sb.spooled_entries();+ assert_eq!(entries.len(), 1, "{entries:?}");+ let url = entries[0]["url"].as_str().unwrap();+ assert!(url.starts_with(&format!("{PROFILE_SERVER}/hook?")), "{url}");+ assert!(url.contains("workspace=team-b"), "{url}");+ assert_eq!(entries[0]["token"], SECRET);+ assert_eq!(entries[0]["profile"], "team-b");+}++/// Without a `server` key the install default is used and the spooled entry+/// has no profile field at all.+#[test]+fn an_unrouted_repository_keeps_the_install_default_through_the_binary() {+ let sb = Sandbox::new();+ sb.register();+ sb.write_marker("workspace = \"team-b\"\n");++ assert_eq!(sb.check_capture()["server_resolution"], "install-default");+ let out = sb.hook("user-prompt-submit", false);+ assert!(out.status.success());+ let entries = sb.spooled_entries();+ assert_eq!(entries.len(), 1);+ assert!(+ entries[0]["url"]+ .as_str()+ .unwrap()+ .starts_with(&format!("{DEFAULT_SERVER}/hook?"))+ );+ assert!(entries[0].get("profile").is_none(), "{:?}", entries[0]);+ assert!(entries[0].get("token").is_none(), "{:?}", entries[0]);+}++/// A selection that does not resolve emits nothing: no spool entry, a+/// warning on stderr that names the profile but not a URL or token, and a+/// `--check-capture` that reports the reason.+#[test]+fn an_unknown_profile_drops_the_event_through_the_binary() {+ let sb = Sandbox::new();+ sb.register();+ sb.write_marker("server = \"nobody\"\n");++ assert_eq!(+ sb.check_capture()["server_resolution"],+ "rejected-unknown-profile"+ );+ let out = sb.hook("user-prompt-submit", false);+ assert!(out.status.success());+ assert_eq!(out.stdout, b"{}\n");+ let stderr = String::from_utf8_lossy(&out.stderr);+ assert!(stderr.contains("`nobody`"), "{stderr}");+ assert!(stderr.contains("rejected-unknown-profile"), "{stderr}");+ assert!(+ !stderr.contains("example") && !stderr.contains(SECRET),+ "{stderr}"+ );+ assert!(sb.spooled_entries().is_empty());+}++/// A real `ai-memory serve` child on a free loopback port with its own data+/// dir and root token, hermetic like the other e2e suites (no embedder, no+/// wiki watcher).+struct RealServer {+ _guard: ServerGuard,+ _data: tempfile::TempDir,+ base: String,+ token: &'static str,+}++impl RealServer {+ async fn start(token: &'static str) -> Self {+ let data = tempfile::tempdir().unwrap();+ let port = free_port();+ let base = format!("http://127.0.0.1:{port}");+ let guard = ServerGuard(+ hermetic(BIN)+ .args([+ "serve",+ "--transport",+ "http",+ "--bind",+ &format!("127.0.0.1:{port}"),+ "--no-watcher",+ ])+ .env("AI_MEMORY_DATA_DIR", data.path())+ .env("AI_MEMORY_HOME", data.path())+ .env("AI_MEMORY_AUTH_TOKEN", token)+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env("RUST_LOG", "off")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn serve"),+ );+ let client = reqwest::Client::new();+ let deadline = Instant::now() + Duration::from_secs(30);+ loop {+ if client+ .get(format!("{base}/mcp"))+ .timeout(Duration::from_secs(2))+ .send()+ .await+ .is_ok()+ {+ break;+ }+ assert!(+ Instant::now() < deadline,+ "server on {base} never became reachable"+ );+ tokio::time::sleep(Duration::from_millis(150)).await;+ }+ Self {+ _guard: guard,+ _data: data,+ base,+ token,+ }+ }++ /// The server's session count for one scope as seen with `token`, or the+ /// HTTP status when the server refuses the request. A scope the server+ /// has never written (404) counts as zero.+ async fn sessions(+ &self,+ client: &reqwest::Client,+ token: &str,+ workspace: &str,+ project: &str,+ ) -> Result<u64, reqwest::StatusCode> {+ let resp = client+ .get(format!("{}/admin/sessions/by-agent", self.base))+ .bearer_auth(token)+ .query(&[("workspace", workspace), ("project", project)])+ .send()+ .await+ .expect("by-agent request");+ match resp.status() {+ s if s.is_success() => {+ let body: serde_json::Value = resp.json().await.expect("by-agent json");+ Ok(body["by_agent"]+ .as_array()+ .map(|agents| agents.iter().filter_map(|a| a["sessions"].as_u64()).sum())+ .unwrap_or(0))+ }+ reqwest::StatusCode::NOT_FOUND => Ok(0),+ other => Err(other),+ }+ }++ /// Poll until the scope shows `want` sessions: `/hook/batch` answers as+ /// soon as the events are queued, and the writer admits them shortly+ /// after.+ async fn settled_sessions(+ &self,+ client: &reqwest::Client,+ workspace: &str,+ project: &str,+ want: u64,+ ) -> u64 {+ let deadline = Instant::now() + Duration::from_secs(10);+ loop {+ let count = self+ .sessions(client, self.token, workspace, project)+ .await+ .unwrap_or_else(|status| panic!("{} refused its own token: {status}", self.base));+ if count == want || Instant::now() >= deadline {+ return count;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }+}++/// The manual two-server check as a test: two real servers, each with its own+/// root token, and one client install whose install default is server A. A+/// repository routed to profile `b` ends up as a session on server B only,+/// an unrouted one on server A only, after the spool is drained by the same+/// `hook-drain` an installed hook would spawn. Each server refuses the other's+/// token, so a swapped credential would have been rejected at delivery.+#[tokio::test]+async fn two_real_servers_each_receive_only_their_own_repository() {+ let sb = Sandbox::new();+ let server_a = RealServer::start("TOKEN-A").await;+ let server_b = RealServer::start("TOKEN-B").await;+ let repo_a = sb.home.join("work").join("alpha");+ let repo_b = sb.home.join("work").join("beta");+ std::fs::create_dir_all(&repo_a).unwrap();+ std::fs::create_dir_all(&repo_b).unwrap();+ std::fs::write(+ repo_a.join(".ai-memory.toml"),+ "workspace = \"alpha-ws\"\nproject = \"alpha\"\n",+ )+ .unwrap();+ std::fs::write(+ repo_b.join(".ai-memory.toml"),+ "workspace = \"beta-ws\"\nproject = \"beta\"\nserver = \"b\"\n",+ )+ .unwrap();+ let root_b = repo_b.to_string_lossy().into_owned();+ sb.run_ok(+ &[+ "server",+ "add",+ "b",+ "--url",+ &server_b.base,+ "--root",+ &root_b,+ "--auth-token-stdin",+ ],+ Some("TOKEN-B\n"),+ );++ for repo in [&repo_a, &repo_b] {+ let out = sb.hook_at(+ repo,+ &server_a.base,+ Some("TOKEN-A"),+ "user-prompt-submit",+ false,+ );+ assert!(+ out.status.success(),+ "{}",+ String::from_utf8_lossy(&out.stderr)+ );+ }+ assert_eq!(sb.spooled_entries().len(), 2);+ sb.run_ok(&["hook-drain"], None);+ assert!(+ sb.spooled_entries().is_empty(),+ "the drain delivered both entries"+ );++ let client = reqwest::Client::new();+ assert_eq!(+ server_a+ .settled_sessions(&client, "alpha-ws", "alpha", 1)+ .await,+ 1+ );+ assert_eq!(+ server_b+ .settled_sessions(&client, "beta-ws", "beta", 1)+ .await,+ 1+ );+ assert_eq!(+ server_a+ .sessions(&client, "TOKEN-A", "beta-ws", "beta")+ .await,+ Ok(0),+ "the routed repository must not reach the install default"+ );+ assert_eq!(+ server_b+ .sessions(&client, "TOKEN-B", "alpha-ws", "alpha")+ .await,+ Ok(0),+ "the unrouted repository must not reach the profile's server"+ );+ assert_eq!(+ server_b+ .sessions(&client, "TOKEN-A", "beta-ws", "beta")+ .await,+ Err(reqwest::StatusCode::UNAUTHORIZED),+ "control: server B refuses server A's token, so a swapped bearer could not have delivered"+ );+}++/// `uninstall` removes the hooks that read the profile tokens, so it removes+/// the tokens too — but keeps the registry, exactly as it keeps `config.toml`.+#[test]+fn uninstall_removes_profile_tokens_and_keeps_the_registry() {+ let sb = Sandbox::new();+ std::fs::create_dir_all(sb.home.join(".claude")).unwrap();+ sb.run_ok(+ &["install-hooks", "--agent", "claude-code", "--apply"],+ None,+ );+ sb.register();+ assert!(token_dir(&sb.data_dir).join("team-b").is_file());++ sb.run_ok(&["uninstall", "--apply", "--only", "hooks", "--yes"], None);++ assert!(+ !token_dir(&sb.data_dir).exists(),+ "tokens must not outlive the hooks"+ );+ assert!(sb.data_dir.join("servers.toml").is_file());+ let listing = sb.run_ok(&["server", "list", "--json"], None);+ let rows: serde_json::Value = serde_json::from_str(&listing).unwrap();+ assert_eq!(rows[0]["token"], "missing", "{listing}");+}