Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(llm): run the Cursor Agent child with an allowlisted environment
AkitaOnRails16ee21a7a504
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 4bfae0f0..0580c252 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -12,9 +12,10 @@ use std::path::{Path, PathBuf};use std::sync::Arc;use ai_memory_llm::{- AuthRequirement, CURSOR_DEFAULT_MODEL, Candidate, EmbedderChoice, EmbedderConfig, ExtraHeaders,- FallbackLlmProvider, LlmError, LlmProvider, LlmResult, OPENCODE_DEFAULT_MODEL, ProviderAuth,- ProviderChoice, ProviderConfig, ReasoningEffort, build_provider, cursor_executable,+ AuthRequirement, CURSOR_DEFAULT_MODEL, Candidate, CursorAuth, EmbedderChoice, EmbedderConfig,+ ExtraHeaders, FallbackLlmProvider, LlmError, LlmProvider, LlmResult, OPENCODE_DEFAULT_MODEL,+ ProviderAuth, ProviderChoice, ProviderConfig, ReasoningEffort, build_provider,+ cursor_executable,};use anyhow::{Context, Result};use figment::{@@ -673,6 +674,7 @@ pub struct RuntimeEnv {codex_home: Option<PathBuf>,codex_executable: Option<PathBuf>,cursor_executable: Option<PathBuf>,+ temp_dir: Option<PathBuf>,server_url: Option<String>,auth_token: Option<String>,host_cwd: Option<String>,@@ -715,6 +717,7 @@ impl RuntimeEnv {codex_home: env_path("CODEX_HOME"),codex_executable: env_path("AI_MEMORY_CODEX_EXECUTABLE"),cursor_executable: env_path("AI_MEMORY_CURSOR_AGENT"),+ temp_dir: Some(std::env::temp_dir()),server_url: env_string("AI_MEMORY_SERVER_URL"),auth_token: env_string("AI_MEMORY_AUTH_TOKEN"),host_cwd: env_string("AI_MEMORY_HOST_CWD"),@@ -2556,9 +2559,7 @@ impl Config {AuthRequirement::AnthropicOAuthToken => {ProviderAuth::anthropic_oauth_token(self.runtime_env.anthropic_oauth_token.clone())}- AuthRequirement::CursorCli => ProviderAuth::cursor(cursor_executable(- self.runtime_env.cursor_executable.as_deref(),- )),+ AuthRequirement::CursorCli => ProviderAuth::cursor(self.cursor_auth()),}}@@ -2834,6 +2835,20 @@ impl Config {resolve_codex_auth_file(self.runtime_env.codex_home.as_deref(), platform_home)}+ /// Cursor Agent CLI inputs, from values captured once by [`Config::load`].+ ///+ /// The child gets only the allowlisted part of the captured process+ /// environment. Without a captured temp dir (a test-built config) the+ /// root is empty and the provider refuses to run instead of writing the+ /// prompt under its cwd.+ fn cursor_auth(&self) -> CursorAuth {+ CursorAuth::new(+ cursor_executable(self.runtime_env.cursor_executable.as_deref()),+ self.runtime_env.temp_dir.clone().unwrap_or_default(),+ self.runtime_env.process_env(),+ )+ }+/// Shared Copilot auth token file path.#[must_use]pub fn copilot_token_path(&self) -> PathBuf {@@ -2899,9 +2914,7 @@ impl Config {AuthRequirement::AnthropicOAuthToken => {ProviderAuth::anthropic_oauth_token(self.runtime_env.anthropic_oauth_token.clone())}- AuthRequirement::CursorCli => ProviderAuth::cursor(cursor_executable(- self.runtime_env.cursor_executable.as_deref(),- )),+ AuthRequirement::CursorCli => ProviderAuth::cursor(self.cursor_auth()),}}@@ -5746,6 +5759,48 @@ input_token_safety_margin = {margin}assert_eq!(provider.auth.requirement(), AuthRequirement::CursorCli);}+ /// The Cursor child reads untrusted session text: the provider config+ /// hands it the captured environment's allowlisted part only, so the+ /// server's own bearer and other providers' keys never reach it.+ #[test]+ fn cursor_provider_hands_the_child_only_allowlisted_env() {+ let entries = [+ ("HOME", "/home/op"),+ ("PATH", "/usr/bin"),+ ("CURSOR_API_KEY", "cursor-key"),+ ("AI_MEMORY_AUTH_TOKEN", "root-bearer-canary"),+ ("ANTHROPIC_API_KEY", "sk-ant-canary"),+ ];+ let cfg = Config {+ llm_provider: Some("cursor".into()),+ runtime_env: RuntimeEnv {+ temp_dir: Some(PathBuf::from("/tmp")),+ process_env: CapturedProcessEnv(+ entries+ .iter()+ .map(|(name, value)| (OsString::from(name), OsString::from(value)))+ .collect(),+ ),+ ..RuntimeEnv::default()+ },+ ..Config::default()+ };++ let auth = cfg+ .llm_provider_config()+ .unwrap()+ .unwrap()+ .auth+ .require_cursor_auth()+ .unwrap();+ let mut names: Vec<_> = auth+ .child_env_names()+ .map(|name| name.to_string_lossy().into_owned())+ .collect();+ names.sort();+ assert_eq!(names, ["CURSOR_API_KEY", "HOME", "PATH"]);+ }+fn load_with_toml(toml: &str) -> anyhow::Result<Config> {let tmp = TempDir::new().unwrap();let config_path = tmp.path().join("config.toml");diff --git a/crates/ai-memory-llm/src/auth.rs b/crates/ai-memory-llm/src/auth.rsindex 78288628..5c1212ae 100644--- a/crates/ai-memory-llm/src/auth.rs+++ b/crates/ai-memory-llm/src/auth.rs@@ -5,6 +5,7 @@//! providers extend this layer instead of teaching each provider to read env//! vars directly.+use std::ffi::OsString;use std::path::{Path, PathBuf};use secrecy::SecretString;@@ -76,10 +77,56 @@ pub struct CodexAuth {}/// Resolved inputs for the Cursor Agent CLI provider.-#[derive(Debug, Clone, PartialEq, Eq)]+///+/// The child process reads untrusted captured session text, so it never+/// inherits the server's environment: [`CursorAuth::new`] keeps only the+/// variables the CLI needs to find its login, locale and network+/// (see [`crate::cursor_agent::cursor_child_env`]).+#[derive(Clone, PartialEq, Eq)]pub struct CursorAuth {/// `agent` binary, or the path in `AI_MEMORY_CURSOR_AGENT`.pub executable: PathBuf,+ /// Directory each request's private workspace is created under.+ pub(crate) temp_root: PathBuf,+ /// The allowlisted environment the child runs with, and nothing else.+ pub(crate) child_env: Vec<(OsString, OsString)>,+}++impl CursorAuth {+ /// Resolve Cursor inputs from values captured once at config load.+ ///+ /// `process_env` is the server's environment; only allowlisted entries+ /// are kept. `temp_root` must be absolute; the provider refuses to run+ /// otherwise rather than create a workspace relative to its cwd.+ #[must_use]+ pub fn new(+ executable: impl Into<PathBuf>,+ temp_root: impl Into<PathBuf>,+ process_env: &[(OsString, OsString)],+ ) -> Self {+ Self {+ executable: executable.into(),+ temp_root: temp_root.into(),+ child_env: crate::cursor_agent::cursor_child_env(process_env),+ }+ }++ /// Names of the environment variables the child receives.+ pub fn child_env_names(&self) -> impl Iterator<Item = &OsString> {+ self.child_env.iter().map(|(name, _)| name)+ }+}++impl std::fmt::Debug for CursorAuth {+ // Values stay out of logs: `CURSOR_API_KEY` is allowlisted.+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("CursorAuth")+ .field("executable", &self.executable)+ .field("temp_root", &self.temp_root)+ .field("child_env", &self.child_env_names().collect::<Vec<_>>())+ .finish()+ }}/// Materialized provider credential.@@ -171,14 +218,12 @@ impl ProviderAuth {}}- /// Resolve Cursor auth from the agent executable path.+ /// Resolve Cursor auth from the agent executable and its child inputs.#[must_use]- pub fn cursor(executable: impl Into<PathBuf>) -> Self {+ pub fn cursor(auth: CursorAuth) -> Self {Self {requirement: AuthRequirement::CursorCli,- credential: Some(Credential::Cursor(CursorAuth {- executable: executable.into(),- })),+ credential: Some(Credential::Cursor(auth)),source: CredentialSource::Environment {name: "AI_MEMORY_CURSOR_AGENT",},diff --git a/crates/ai-memory-llm/src/cursor_agent.rs b/crates/ai-memory-llm/src/cursor_agent.rsindex d3f2108b..a754708a 100644--- a/crates/ai-memory-llm/src/cursor_agent.rs+++ b/crates/ai-memory-llm/src/cursor_agent.rs@@ -3,8 +3,18 @@//! Consolidation calls the logged-in Cursor Agent CLI (`agent --print`)//! instead of a platform API key. The CLI already holds the Cursor//! subscription. Invocations stay in `--mode ask`: captured session text is-//! untrusted, and `--yolo` / `--force` would let that text run tools.+//! untrusted, and `--yolo` / `--force` would let that text run tools. For the+//! same reason the child gets an allowlisted environment+//! ([`cursor_child_env`]), never the server's: `AI_MEMORY_AUTH_TOKEN` and+//! other providers' keys stay out of its reach.+//!+//! The CLI has no JSON-schema mode. The schema travels in the prompt, the+//! answer is parsed leniently (code fences and surrounding prose stripped),+//! and the caller's serde deserialisation is the only validation: a value+//! that deserialises is accepted even if it breaks a schema constraint serde+//! does not check.+use std::ffi::{OsStr, OsString};use std::path::{Path, PathBuf};use std::process::Stdio;use std::time::Duration;@@ -29,6 +39,78 @@ pub const CURSOR_DEFAULT_MODEL: &str = "cursor-grok-4.6-high";const MAX_STDOUT_BYTES: usize = 1024 * 1024;const MAX_STDERR_BYTES: usize = 64 * 1024;+/// Variables the child keeps, compared ASCII-case-insensitively (Windows+/// names are case-insensitive and proxies come in both cases): identity and+/// home for the CLI's stored login and keychain, locale, temp, the session+/// bus for a Linux keyring, proxy and CA settings, and the Windows process+/// basics.+const CURSOR_CHILD_ENV: &[&str] = &[+ "PATH",+ "HOME",+ "USER",+ "LOGNAME",+ "SHELL",+ "LANG",+ "LANGUAGE",+ "TZ",+ "TERM",+ "TMPDIR",+ "TMP",+ "TEMP",+ "XDG_CONFIG_HOME",+ "XDG_DATA_HOME",+ "XDG_CACHE_HOME",+ "XDG_STATE_HOME",+ "XDG_RUNTIME_DIR",+ "DBUS_SESSION_BUS_ADDRESS",+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "ALL_PROXY",+ "NO_PROXY",+ "SSL_CERT_FILE",+ "SSL_CERT_DIR",+ "NODE_EXTRA_CA_CERTS",+ "USERPROFILE",+ "APPDATA",+ "LOCALAPPDATA",+ "PROGRAMDATA",+ "SYSTEMROOT",+ "WINDIR",+ "COMSPEC",+ "PATHEXT",+];++/// Prefixes the child keeps: locale categories and the CLI's own settings+/// (`CURSOR_API_KEY` among them).+const CURSOR_CHILD_ENV_PREFIXES: &[&str] = &["LC_", "CURSOR_"];++/// The subset of `process_env` the Cursor Agent CLI child runs with.+///+/// The child reads untrusted captured session text, so everything outside+/// the allowlist — ai-memory's own token, other providers' keys, arbitrary+/// operator secrets — is dropped.+#[must_use]+pub fn cursor_child_env(process_env: &[(OsString, OsString)]) -> Vec<(OsString, OsString)> {+ process_env+ .iter()+ .filter(|(name, _)| is_allowed_child_var(name))+ .cloned()+ .collect()+}++fn is_allowed_child_var(name: &OsStr) -> bool {+ let Some(name) = name.to_str() else {+ return false;+ };+ CURSOR_CHILD_ENV+ .iter()+ .any(|allowed| name.eq_ignore_ascii_case(allowed))+ || CURSOR_CHILD_ENV_PREFIXES.iter().any(|prefix| {+ name.len() > prefix.len()+ && name.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes())+ })+}+/// Chat provider that shells out to the Cursor `agent` CLI.pub struct CursorAgentProvider {model: String,@@ -62,13 +144,20 @@ impl CursorAgentProvider {request: &ChatRequest,schema: Option<&serde_json::Value>,) -> LlmResult<String> {- let workspace = TempWorkspace::create()?;+ let workspace = TempWorkspace::create(&self.auth.temp_root)?;let body = render_request(request, schema);std::fs::write(workspace.path.join("request.md"), body).map_err(|err| LlmError::UnexpectedShape(format!("writing cursor prompt: {err}")))?;let mut command = Command::new(&self.auth.executable);command+ .env_clear()+ .envs(+ self.auth+ .child_env+ .iter()+ .map(|(name, value)| (name, value)),+ ).arg("--print").arg("--mode").arg("ask")@@ -181,8 +270,14 @@ struct TempWorkspace {}impl TempWorkspace {- fn create() -> LlmResult<Self> {- let path = std::env::temp_dir().join(format!("ai-memory-cursor-{}", Uuid::now_v7()));+ fn create(root: &Path) -> LlmResult<Self> {+ if !root.is_absolute() {+ return Err(LlmError::NotConfigured(format!(+ "cursor workspace root must be an absolute path, got {}",+ root.display()+ )));+ }+ let path = root.join(format!("ai-memory-cursor-{}", Uuid::now_v7()));// The prompt is captured session text: keep the workspace private// to the server's user on a shared temp directory.#[cfg(unix)]diff --git a/crates/ai-memory-llm/src/lib.rs b/crates/ai-memory-llm/src/lib.rsindex 7d1c3b54..51d5a204 100644--- a/crates/ai-memory-llm/src/lib.rs+++ b/crates/ai-memory-llm/src/lib.rs@@ -24,8 +24,10 @@//! plus `responseSchema` (OpenAPI 3 subset; `$ref`s inlined,//! Draft-2020-12 keywords stripped before send).//! * **Cursor**: the logged-in `agent` CLI in `--mode ask`. No HTTP client-//! and no copied token; `--yolo` is never passed because the prompt is-//! captured session text.+//! and no copied token; `--yolo` is never passed and the child gets an+//! allowlisted environment because the prompt is captured session text.+//! The CLI has no schema mode: the schema rides in the prompt, the answer+//! is parsed leniently, and serde deserialisation is the only validation.//! * **OpenAI-compat** (Ollama, vLLM, LM Studio): we ask for//! `response_format: { type: "json_object" }` when supported,//! otherwise parse the first balanced `{…}` from the text body.@@ -110,7 +112,9 @@ pub use copilot::{GITHUB_ACCESS_TOKEN_URL, GITHUB_COPILOT_CLIENT_ID, GITHUB_COPILOT_TOKEN_URL,GITHUB_DEVICE_CODE_URL,};-pub use cursor_agent::{CURSOR_DEFAULT_MODEL, CursorAgentProvider, cursor_executable};+pub use cursor_agent::{+ CURSOR_DEFAULT_MODEL, CursorAgentProvider, cursor_child_env, cursor_executable,+};pub use embedding::{Embedder, OpenAiCompatEmbedder, OpenAiEmbedder, QueryVector, SyntheticEmbedder, VoyageEmbedder,cosine, embed_search_query,diff --git a/crates/ai-memory-llm/tests/suite/cursor_provider.rs b/crates/ai-memory-llm/tests/suite/cursor_provider.rsindex f0aae8f1..513e1bd7 100644--- a/crates/ai-memory-llm/tests/suite/cursor_provider.rs+++ b/crates/ai-memory-llm/tests/suite/cursor_provider.rs@@ -5,11 +5,12 @@#![cfg(unix)]+use std::ffi::OsString;use std::os::unix::fs::PermissionsExt as _;use std::path::{Path, PathBuf};use ai_memory_llm::{- CURSOR_DEFAULT_MODEL, ChatRequest, CursorAgentProvider, LlmProvider, ProviderAuth,+ CURSOR_DEFAULT_MODEL, ChatRequest, CursorAgentProvider, CursorAuth, LlmProvider, ProviderAuth,};fn sh_single(value: &str) -> String {@@ -48,9 +49,21 @@ impl Drop for TempDir {}}+/// The fake agents are shell scripts that need `PATH`; the workspace root is+/// the fake agent's own temp dir.fn provider(executable: PathBuf, model: &str) -> CursorAgentProvider {+ let path = std::env::var_os("PATH").unwrap_or_default();+ provider_with_env(executable, model, &[(OsString::from("PATH"), path)])+}++fn provider_with_env(+ executable: PathBuf,+ model: &str,+ process_env: &[(OsString, OsString)],+) -> CursorAgentProvider {+ let root = executable.parent().unwrap().to_path_buf();CursorAgentProvider::new(- ProviderAuth::cursor(executable)+ ProviderAuth::cursor(CursorAuth::new(executable, root, process_env)).require_cursor_auth().expect("cursor executable resolves"),model,@@ -173,3 +186,69 @@ async fn the_prompt_workspace_is_private() {let listing = std::fs::read_to_string(&sink).unwrap();assert!(listing.starts_with("drwx------"), "{listing}");}++/// The child reads untrusted captured session text, so it runs with the+/// allowlisted environment only: the server's bearer and another provider's+/// key never reach it, and nothing leaks from the parent process itself+/// (cargo sets `CARGO_*` in every test process). Control: the allowlisted+/// `PATH`, `HOME` and `CURSOR_API_KEY` arrive, and the workspace sits under+/// the injected root rather than the process temp dir.+#[tokio::test]+async fn the_child_gets_only_the_allowlisted_environment() {+ let dir = TempDir::new();+ let sink = dir.0.join("env");+ let agent = script_agent(+ &dir.0,+ &format!(+ "env > {sink}\npwd >> {sink}\nprintf 'OK\\n'",+ sink = sh_single(&sink.display().to_string())+ ),+ );+ let process_env: Vec<(OsString, OsString)> = [+ ("PATH", std::env::var("PATH").unwrap_or_default()),+ ("HOME", "/home/operator".to_string()),+ ("CURSOR_API_KEY", "cursor-key-ok".to_string()),+ ("AI_MEMORY_AUTH_TOKEN", "root-bearer-canary".to_string()),+ ("OPENAI_API_KEY", "sk-openai-canary".to_string()),+ ]+ .into_iter()+ .map(|(name, value)| (OsString::from(name), OsString::from(value)))+ .collect();++ let response = provider_with_env(agent, "default", &process_env)+ .complete(ChatRequest::user_prompt("hi"))+ .await+ .unwrap();+ assert_eq!(response.text, "OK");++ let seen = std::fs::read_to_string(&sink).unwrap();+ assert!(!seen.contains("root-bearer-canary"), "{seen}");+ assert!(!seen.contains("sk-openai-canary"), "{seen}");+ assert!(+ !seen.lines().any(|line| line.starts_with("CARGO_")),+ "the parent's own environment must not be inherited: {seen}"+ );+ assert!(seen.contains("HOME=/home/operator\n"), "{seen}");+ assert!(seen.contains("CURSOR_API_KEY=cursor-key-ok\n"), "{seen}");+ let workspace = seen.lines().last().unwrap();+ let root = std::fs::canonicalize(&dir.0).unwrap();+ assert!(+ Path::new(workspace).starts_with(&dir.0) || Path::new(workspace).starts_with(&root),+ "workspace {workspace} must sit under the injected root"+ );+}++/// A relative workspace root would put the prompt under the server's cwd;+/// the provider refuses instead.+#[tokio::test]+async fn a_relative_workspace_root_is_refused() {+ let auth = CursorAuth::new("agent", "relative-root", &[]);+ let err = CursorAgentProvider::new(+ ProviderAuth::cursor(auth).require_cursor_auth().unwrap(),+ "default",+ )+ .complete(ChatRequest::user_prompt("hi"))+ .await+ .unwrap_err();+ assert!(err.to_string().contains("absolute"), "{err}");+}diff --git a/docs/llm-providers.md b/docs/llm-providers.mdindex c8d19513..fb014d78 100644--- a/docs/llm-providers.md+++ b/docs/llm-providers.md@@ -90,9 +90,16 @@ ai-memory llm-test --provider codex --model gpt-5.6-luna --structured --prompt "into a temporary workspace and calls `agent --print --mode ask --trust`. Itdoes not pass `--yolo` or `--force`: consolidation text is untrusted capturedcontent, and those flags would allow tool execution. The Cursor CLI has no-JSON-schema mode, so the schema travels in the prompt and the answer is parsed-and validated against it. The `agent` process inherits the server's-environment, so run the server with only the credentials it needs.+JSON-schema mode, so the schema travels in the prompt. The answer is parsed+leniently (code fences and surrounding prose are stripped) and then+deserialised into the expected type; nothing checks it against the schema+itself, so a value that deserialises is accepted even if it breaks a constraint+serde does not enforce. The `agent` process does not inherit the server's+environment. It gets `PATH`, `HOME`, user and locale variables (`LANG`,+`LC_*`), temp and XDG directories, `DBUS_SESSION_BUS_ADDRESS`, proxy and CA+settings, the Windows process basics, and every `CURSOR_*` variable, so+`AI_MEMORY_AUTH_TOKEN` and other providers' keys never reach it. The per-call+workspace is created under the system temp directory captured at startup.```bashexport AI_MEMORY_LLM_PROVIDER=cursordiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex b24f8ca9..7867e2e8 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -58,6 +58,7 @@ means the boundary is not built yet.| 7a | Eval observations: server provenance and reason privacy | `ai-memory-consolidate/src/auto_improve.rs` constructs private results from the existing execution, ignores extra model/scorer result fields and all eval results on report deserialization, hashes the evaluated request/bodies, and scrubs reasons before the 2,048-character cap and pending persistence; changed bodies cannot receive the earlier result | `auto_improve::tests::structured_eval_records_server_observation`; `tests/suite/eval_results.rs` `eval_reason_is_sanitized_before_pending_storage_with_legitimate_control` attempts forged deserialized reports and IDs/digests and malicious reasons with secrets/control characters, checks report and stored evidence before sidecar rendering, and preserves a legitimate reason and external evidence without independent results; fails with reason scrubbing or the report deserialization guard removed | STRONG || 7b | New public page metadata is bounded and cannot supply scope, author or admission controls; admin kind retains its legacy adapter | `ai-memory-core/src/page.rs` `PageWriteMetadata::into_frontmatter`; MCP validates all four fields; admin consumes legacy kind explicitly and shares entities/abstract/relations validation before scope creation; both use `Wiki::write_page` for sanitization/admission/authenticated attribution | `admin_write_page.rs` `write_page_metadata_rejects_invalid_payload_before_scope_creation` (invalid shapes, unknown relation kinds, raw-input over-limit values, untrimmed relation scopes and escaping paths refused; legitimate control admitted), `write_page_metadata_preserves_admin_auth_and_sanitization` (anonymous/DB-user refused, root control admitted with scrubbed metadata and authenticated attribution); `server.rs` `memory_write_page_metadata_rejects_invalid_before_scope_creation`, `memory_write_page_metadata_preserves_scope_author_and_sanitization` (foreign user denied; writer control admitted, forged frontmatter/author ignored, secrets scrubbed, invalid rewrite leaves disk and SQL latest unchanged); core `page_write_metadata_scope_components_refuse_surrounding_whitespace` and `page_write_metadata_limits_apply_before_trimming_and_normalization`; admin `write_page_metadata_admin_legacy_kind_matches_base` compares long/control-character kind behavior with the base adapter; entity-bound refusal bite-checked with its validation removed | STRONG || 7c | A compaction checkpoint cannot bypass `consolidate` admission by deferring its provider rewrite (#1229) | `ai-memory-hooks/src/router.rs` `write_checkpoint_page` gives the PreCompact / PostCompaction rule-based write the `consolidate` admission operation whenever a consolidator is configured, and `process_authorized` queues the durable rewrite only after that write succeeds; the worker's rewrite runs admission again through `Consolidator::consolidate_session` | `router.rs` `checkpoint_admission_refusal_writes_no_page_and_queues_no_rewrite` (a policy refusing `consolidate` leaves no page and no queued job; control: a policy gating only `handoff_begin` writes the page and queues the job), `checkpoint_preserves_the_consolidate_admission_operation` (the hook path sends exactly one `consolidate` admission call and never calls the provider); both bite-checked with the admission context removed | STRONG |+| 7d | The Cursor Agent CLI child, which reads captured session text, never sees the server's own credentials | `ai-memory-llm/src/cursor_agent.rs` `complete_text` spawns `agent` with `env_clear()` plus `CursorAuth::child_env`, which `CursorAuth::new` filters through `cursor_child_env` (an allowlist of `PATH`/`HOME`/user, locale, temp/XDG, session bus, proxy/CA and Windows basics, plus `LC_*`/`CURSOR_*`); the environment and the workspace root are captured once by `ai-memory-cli/src/config.rs` `Config::cursor_auth`, so the provider reads no environment itself; a relative workspace root is refused | `cursor_provider.rs` `the_child_gets_only_the_allowlisted_environment` (`AI_MEMORY_AUTH_TOKEN` and `OPENAI_API_KEY` canaries and the test process's own `CARGO_*` variables never reach the child; control: `PATH`, `HOME` and `CURSOR_API_KEY` do, and the workspace sits under the injected root; bite-checked by dropping `env_clear()`), `a_relative_workspace_root_is_refused`; `config.rs` `cursor_provider_hands_the_child_only_allowlisted_env` | STRONG || 8a | Messaging: recipient-only visibility | `ai-memory-store/src/ops.rs` pop target-select + `reader.rs` `list_messages` (`to_*` predicate) | `agent_messages.rs` `a_message_is_only_visible_to_its_recipient`; `agent_messages_tools.rs` non-recipient cannot pop | STRONG || 8b | Messaging: cancel-own-only | `ai-memory-store/src/ops.rs` `cancel_messages` (AND-gated on `from_*` sender coordinate) | `agent_messages.rs` — whole-outbox **and** a foreign **specific-id** cancel refused | STRONG || 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG |diff --git a/evals/src/ab.rs b/evals/src/ab.rsindex bf3ae04b..5f9daef2 100644--- a/evals/src/ab.rs+++ b/evals/src/ab.rs@@ -471,7 +471,11 @@ fn resolve_provider(side: &str, args: &AbArgs) -> Result<ResolvedConfig> {base_url.clone(),),AuthRequirement::AnthropicOAuthToken => ProviderAuth::anthropic_oauth_token(api_key),- AuthRequirement::CursorCli => ProviderAuth::cursor("agent"),+ AuthRequirement::CursorCli => ProviderAuth::cursor(ai_memory_llm::CursorAuth::new(+ "agent",+ std::env::temp_dir(),+ &std::env::vars_os().collect::<Vec<_>>(),+ )),};Ok(ResolvedConfig {diff --git a/evals/src/retrieval/qa.rs b/evals/src/retrieval/qa.rsindex 1e42a2c3..e70eeb53 100644--- a/evals/src/retrieval/qa.rs+++ b/evals/src/retrieval/qa.rs@@ -367,7 +367,11 @@ fn build_llm_provider(ProviderAuth::copilot(tf.to_path_buf(), None, None, base_url.map(str::to_string))}AuthRequirement::AnthropicOAuthToken => ProviderAuth::anthropic_oauth_token(api_key),- AuthRequirement::CursorCli => ProviderAuth::cursor("agent"),+ AuthRequirement::CursorCli => ProviderAuth::cursor(ai_memory_llm::CursorAuth::new(+ "agent",+ std::env::temp_dir(),+ &std::env::vars_os().collect::<Vec<_>>(),+ )),};let config = ProviderConfig {