Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(mcp): wire every MCP client to a token-file server via the bridge
AkitaOnRailsb9463480fb04
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1edd6397..ebd12125 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -219,10 +219,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0created without it. It reuses or creates an owner-only token at`<data_dir>/auth-tokens/default`, records it in `config.toml`, gives theinstalled hooks the token when they hold no other credential, and- re-registers Claude Code's MCP entry for this server as the- `ai-memory mcp-bridge` stdio bridge. Running it again changes nothing, and- the token is never printed or written into a harness config. Restart the- server afterwards.+ re-registers every MCP client whose `ai-memory` entry points at this server+ the way `install-mcp` now wires a token-file install. It lists each client+ it changed, each entry for another server it left alone, and anything that+ needs a manual change. Running it again changes nothing, and the token is+ never printed or written into a harness config. Restart the server+ afterwards.+- Added `ai-memory mcp-bridge --no-session-id`, a plain stdio-to-HTTP MCP+ bridge for any client that runs local commands. It authenticates with the+ token from config (`AI_MEMORY_AUTH_TOKEN`, `[auth] bearer_token`, or the+ file `[auth] bearer_token_file` names), forwards no session identity (the+ client passes `workspace` and `project` like any static MCP client, and an+ inherited `CLAUDE_CODE_SESSION_ID` is ignored), and exits at once with+ `401 Unauthorized` when the server refuses it. Without the flag the bridge+ keeps Claude Code's session forwarding and still refuses to start without+ `CLAUDE_CODE_SESSION_ID`.- Added the `[auth] bearer_token_file` config key (env`AI_MEMORY_AUTH__BEARER_TOKEN_FILE`): a file holding the root bearer token,read once at startup. A relative path resolves against the data dir.@@ -230,9 +241,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`[auth] bearer_token` is a startup error, and a server whose configured fileis missing or empty refuses to start. A token read from the file is neverwritten into a harness config: `install-mcp` registers Claude Code through- `ai-memory mcp-bridge`, gives Codex and Prime Agent a reference to- `$AI_MEMORY_AUTH_TOKEN`, and refuses clients that can only hold a literal- header; `install-hooks --apply` stores it in the hook credential files only.+ the session-aware `ai-memory mcp-bridge`, gives Codex and Prime Agent a+ reference to `$AI_MEMORY_AUTH_TOKEN`, and writes every other client a stdio+ entry for `ai-memory mcp-bridge --no-session-id` in that client's own config+ format (OpenCode, OpenCode 2, Cursor, Claude Desktop, Gemini CLI, OpenClaw,+ OMP, Antigravity CLI, Zero, Devin, Grok, Kimi Code, Kiro CLI, Command Code,+ Copilot CLI, Swival, VS Code, Zed, Muse Code; DeepSeek Harness's printed+ patch too). Only ZCode, whose config keeps HTTP entries only, is refused with+ the manual option. `uninstall` recognises these entries.+ `install-hooks --apply` stores the token in the hook credential files only.- `ai-memory status` and `ai-memory doctor` now show the server's authposture, and for an unauthenticated loopback server print`auth: none (loopback)` with the fix, `ai-memory auth enable`.diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex f50bcd6c..9f07e16e 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -237,7 +237,8 @@ pub enum Command {/// Current values are listed under `--client`; see docs/mcp-install.md/// for the full guide.InstallMcp(InstallMcpArgs),- /// Internal stdio-to-HTTP MCP bridge for session-aware Claude Code installs.+ /// Internal stdio-to-HTTP MCP bridge: session-aware for Claude Code, or+ /// session-less (`--no-session-id`) for every other stdio MCP client.#[command(hide = true)]McpBridge(McpBridgeArgs),/// Stage + commit the wiki tree under git.@@ -3219,14 +3220,25 @@ pub struct InstallMcpArgs {/// out of the harness config.#[arg(skip)]pub token_env_var: bool,+ /// Write a stdio entry that runs the session-less `ai-memory mcp-bridge`+ /// instead of an HTTP entry. Set by the installer, never a flag: it is how+ /// a client without env-var indirection reaches a server whose token lives+ /// in `[auth].bearer_token_file`.+ #[arg(skip)]+ pub stdio_bridge: bool,}-/// Arguments for the internal Claude Code session-aware MCP bridge.+/// Arguments for the internal stdio-to-HTTP MCP bridge.#[derive(Debug, Clone, Args)]pub struct McpBridgeArgs {/// Remote ai-memory base URL or full `/mcp` endpoint.#[arg(long)]pub server_url: Option<String>,+ /// Run as a plain stdio-to-HTTP bridge that forwards no session identity,+ /// for MCP clients other than Claude Code. Without it the bridge forwards+ /// `CLAUDE_CODE_SESSION_ID` and refuses to start when it is missing.+ #[arg(long)]+ pub no_session_id: bool,}/// Transport for the MCP server.diff --git a/crates/ai-memory-cli/src/commands/auth_enable.rs b/crates/ai-memory-cli/src/commands/auth_enable.rsindex 0d78136b..3497a8b8 100644--- a/crates/ai-memory-cli/src/commands/auth_enable.rs+++ b/crates/ai-memory-cli/src/commands/auth_enable.rs@@ -9,9 +9,12 @@//! 2. record `bearer_token_file` in `config.toml`, keeping its comments;//! 3. give the hooks the token through `auth-token` / `auth-header`, the files//! every hook front door reads, unless another credential is stored there;-//! 4. re-register Claude Code's `ai-memory` MCP entry, when it points at this-//! server, through `install-mcp`: it becomes the `mcp-bridge` stdio entry,-//! which reads the token file itself.+//! 4. re-register every MCP client whose `ai-memory` entry points at this+//! server, through `install-mcp`: Claude Code gets the session-aware+//! `mcp-bridge` entry, Codex and Prime Agent a reference to+//! `$AI_MEMORY_AUTH_TOKEN`, every other client a stdio entry for the+//! session-less bridge, which reads the token file itself. A client that can+//! only hold a literal header (ZCode) is listed for a manual change.//!//! The token is never printed and never written into a harness config.@@ -19,25 +22,40 @@ use std::path::{Path, PathBuf};use anyhow::{Context as _, Result, bail};-use crate::cli::{AuthEnableArgs, InstallMcpArgs, McpClient};+use crate::cli::{AuthEnableArgs, InstallMcpArgs, McpClient, SchemaFlavor};use crate::commands::install_mcp::{self, mcp_server_url_from_base};use crate::config::Config;use crate::local_auth::{self, HookCredential};use crate::server_profiles::{self, ProfileName};-/// What happened to Claude Code's MCP registration.+/// The MCP entry name `install-mcp` writes by default.+const ENTRY_NAME: &str = "ai-memory";++/// What happened to one client's `ai-memory` MCP entry. Clients without one+/// are not listed.#[derive(Debug, Clone, PartialEq, Eq)]-pub(crate) enum ClaudeWiring {- /// `--no-mcp`, or no Claude Code config to look at.- Skipped,- /// No `ai-memory` entry is registered.- NotRegistered,+pub(crate) enum Wiring {+ /// Re-registered through `install-mcp` so it reaches the token file.+ Rewired,/// The entry targets another server; it is left alone.OtherServer(String),- /// The entry was re-registered as the stdio bridge.- Rewired,+ /// It targets this server but could not be re-registered; the reason+ /// says what to do by hand.+ Manual(String),+}++/// One client's line in the outcome.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ClientWiring {+ pub(crate) client: McpClient,+ pub(crate) path: PathBuf,+ pub(crate) wiring: Wiring,}+/// Where each client keeps its MCP config; injectable so tests never touch a+/// real harness config.+pub(crate) type ConfigLocator<'a> = &'a dyn Fn(McpClient) -> Option<PathBuf>;+/// The result of one `auth enable`.#[derive(Debug)]pub(crate) struct EnableOutcome {@@ -49,7 +67,7 @@ pub(crate) struct EnableOutcome {pub(crate) config_path: PathBuf,pub(crate) config_changed: bool,pub(crate) hooks: Option<HookCredential>,- pub(crate) claude: ClaudeWiring,+ pub(crate) mcp: Vec<ClientWiring>,}/// Run `auth enable`.@@ -58,12 +76,9 @@ pub(crate) struct EnableOutcome {/// Fails when a server profile named `default` would share the token file,/// when `servers.toml` or `config.toml` cannot be parsed, or on a failed write.pub fn run(config: &Config, args: &AuthEnableArgs, config_path: Option<&Path>) -> Result<()> {- let claude_config = if args.no_mcp {- None- } else {- install_mcp::mcp_config_path(McpClient::ClaudeCode).ok()- };- let outcome = enable(config, config_path, claude_config.as_deref())?;+ let locate = |client: McpClient| install_mcp::mcp_config_path(client).ok();+ let locator: Option<ConfigLocator<'_>> = (!args.no_mcp).then_some(&locate as _);+ let outcome = enable(config, config_path, locator)?;print_outcome(&outcome);Ok(())}@@ -71,7 +86,7 @@ pub fn run(config: &Config, args: &AuthEnableArgs, config_path: Option<&Path>) -pub(crate) fn enable(config: &Config,config_path: Option<&Path>,- claude_config: Option<&Path>,+ locate: Option<ConfigLocator<'_>>,) -> Result<EnableOutcome> {let data_dir = &config.data_dir;let config_path = config_path.map_or_else(|| data_dir.join("config.toml"), PathBuf::from);@@ -88,7 +103,7 @@ pub(crate) fn enable(config_path,config_changed: false,hooks: None,- claude: ClaudeWiring::Skipped,+ mcp: Vec::new(),});}@@ -105,10 +120,7 @@ pub(crate) fn enable(enabled.auth.adopt_token_file(minted.path.clone(), minted.token.clone());- let claude = match claude_config {- Some(path) => rewire_claude_code(&enabled, path)?,- None => ClaudeWiring::Skipped,- };+ let mcp = locate.map_or_else(Vec::new, |locate| rewire_clients(&enabled, locate));Ok(EnableOutcome {already_inline: false,@@ -117,7 +129,7 @@ pub(crate) fn enable(config_path,config_changed,hooks: Some(hooks),- claude,+ mcp,})}@@ -197,60 +209,89 @@ fn record_token_file(config_path: &Path) -> Result<bool> {Ok(true)}-/// The URL an existing Claude Code `ai-memory` entry targets: an HTTP entry's-/// `url`, or the bridge's `--server-url`.-fn claude_entry_url(path: &Path) -> Result<Option<String>> {- let text = match std::fs::read_to_string(path) {- Ok(text) => text,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),- Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),- };- let root: serde_json::Value =- serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;- let Some(entry) = root.get("mcpServers").and_then(|s| s.get("ai-memory")) else {- return Ok(None);- };- if let Some(url) = entry.get("url").and_then(serde_json::Value::as_str) {- return Ok(Some(url.to_owned()));- }- let args: Vec<&str> = entry- .get("args")- .and_then(serde_json::Value::as_array)- .map(|args| args.iter().filter_map(serde_json::Value::as_str).collect())- .unwrap_or_default();- Ok(args+/// Clients `install-mcp --apply` writes a config file for. Pi has no MCP+/// config (its extension reads the hook credential file) and DeepSeek+/// Harness is print-only, so neither has an entry to re-point.+fn rewirable_clients() -> impl Iterator<Item = McpClient> {+ <McpClient as clap::ValueEnum>::value_variants().iter()- .position(|arg| *arg == "--server-url")- .and_then(|i| args.get(i + 1))- .map(|url| (*url).to_owned()))+ .copied()+ .filter(|client| !matches!(client, McpClient::Pi | McpClient::Dsh))}-fn rewire_claude_code(config: &Config, path: &Path) -> Result<ClaudeWiring> {- let Some(url) = claude_entry_url(path)? else {- return Ok(ClaudeWiring::NotRegistered);- };- // Only an entry for this install's server is re-pointed; one for a remote- // server has its own credential and must keep its destination.- let ours = mcp_server_url_from_base(&config.server_url);- let without_flavor = url.split('?').next().unwrap_or(&url);- if mcp_server_url_from_base(without_flavor) != ours {- return Ok(ClaudeWiring::OtherServer(url));+/// The endpoint without a `?flavor=` (or any) query, normalised to `/mcp`.+fn bare_endpoint(url: &str) -> String {+ mcp_server_url_from_base(url.split('?').next().unwrap_or(url))+}++/// The schema flavor an existing entry's URL pinned, so re-registering keeps+/// the dialect the operator chose with `--flavor`.+fn pinned_flavor(url: &str) -> Option<SchemaFlavor> {+ let query = url.split_once('?')?.1;+ <SchemaFlavor as clap::ValueEnum>::value_variants()+ .iter()+ .copied()+ .find(|flavor| {+ query+ .split('&')+ .any(|pair| pair == format!("flavor={}", flavor.marker()))+ })+}++/// Re-register every client whose `ai-memory` entry targets this server. One+/// client failing never stops the others: it is reported as manual.+fn rewire_clients(config: &Config, locate: ConfigLocator<'_>) -> Vec<ClientWiring> {+ let ours = bare_endpoint(&config.server_url);+ let mut outcome = Vec::new();+ for client in rewirable_clients() {+ let Some(path) = locate(client) else {+ continue;+ };+ let wiring = match install_mcp::existing_entry_endpoint(client, &path, ENTRY_NAME) {+ Ok(None) => continue,+ Err(e) => Wiring::Manual(format!("{e:#}")),+ Ok(Some(url)) if bare_endpoint(&url) != ours => Wiring::OtherServer(url),+ Ok(Some(url)) => match rewire(config, client, &path, &ours, pinned_flavor(&url)) {+ Ok(()) => Wiring::Rewired,+ Err(e) => Wiring::Manual(format!("{e:#}")),+ },+ };+ outcome.push(ClientWiring {+ client,+ path,+ wiring,+ });}- install_mcp::run(- config,- InstallMcpArgs {- client: McpClient::ClaudeCode,- server_url: Some(ours),- name: "ai-memory".to_owned(),- auth_token: None,- apply: true,- config_file: Some(path.to_path_buf()),- session_aware: true,- flavor: None,- token_env_var: false,- },- )?;- Ok(ClaudeWiring::Rewired)+ outcome+}++fn rewire(+ config: &Config,+ client: McpClient,+ path: &Path,+ url: &str,+ flavor: Option<SchemaFlavor>,+) -> Result<()> {+ let args = InstallMcpArgs {+ client,+ server_url: Some(url.to_owned()),+ name: ENTRY_NAME.to_owned(),+ auth_token: None,+ apply: true,+ config_file: Some(path.to_path_buf()),+ session_aware: false,+ flavor,+ token_env_var: false,+ stdio_bridge: false,+ };+ // Name the OpenCode major version outright: both share one file, and+ // probing `opencode --version` here would pick one for both locations.+ let dialect = match client {+ McpClient::OpenCode => Some(ai_memory_workstream::OpenCodeDialect::V1),+ McpClient::OpenCode2 => Some(ai_memory_workstream::OpenCodeDialect::V2),+ _ => None,+ };+ install_mcp::run_with_opencode_dialect(config, args, dialect)}fn print_outcome(outcome: &EnableOutcome) {@@ -289,22 +330,21 @@ fn print_outcome(outcome: &EnableOutcome) {),None => {}}- match &outcome.claude {- ClaudeWiring::Rewired => {- println!(- "claude-code: MCP entry now runs `ai-memory mcp-bridge`, which reads the token file"- );- }- ClaudeWiring::OtherServer(url) => {- println!("claude-code: MCP entry targets {url}, another server; left unchanged");+ for line in &outcome.mcp {+ let client = format!("{:?}", line.client);+ match &line.wiring {+ Wiring::Rewired => println!(+ "mcp {client}: re-registered in {} so it reads the token without holding it",+ line.path.display()+ ),+ Wiring::OtherServer(url) => {+ println!("mcp {client}: targets {url}, another server; left unchanged");+ }+ Wiring::Manual(reason) => {+ println!("mcp {client}: needs a manual change: {reason}");+ }}- ClaudeWiring::NotRegistered | ClaudeWiring::Skipped => {}}- println!(- "Other MCP clients: re-run `ai-memory install-mcp --client <client> --apply`. Codex and \- Prime Agent then read the token from $AI_MEMORY_AUTH_TOKEN; clients that only take a \- literal header are refused rather than given the token."- );println!("Restart the ai-memory server for it to require the token.");}@@ -332,22 +372,6 @@ mod tests {.unwrap();}- fn claude_json(home: &Path, url: &str) -> PathBuf {- let path = home.join(".claude.json");- std::fs::write(- &path,- serde_json::json!({- "mcpServers": {- "ai-memory": {"type": "http", "url": url},- "other": {"type": "http", "url": "https://other.example/mcp"}- }- })- .to_string(),- )- .unwrap();- path- }-/// Every file under `root`, read as text where it is text.fn files_under(root: &Path) -> Vec<(PathBuf, String)> {let mut out = Vec::new();@@ -365,10 +389,39 @@ mod tests {out}- /// `auth enable` on a pre-default install: token minted, the key recorded with- /// the operator's comments intact, the hooks given the token, Claude Code- /// re-registered as the bridge. Run twice, the second run changes nothing,- /// and the token appears in no harness config.+ /// Every client `rewire_clients` considers, each wired the pre-default way+ /// (`install-mcp --apply`, no token) into its own file under `home`.+ fn wire_every_client_over_http(home: &Path, url: &str) -> Vec<(McpClient, PathBuf)> {+ let open = Config::default();+ rewirable_clients()+ .map(|client| {+ let ext = if matches!(client, McpClient::Codex | McpClient::Grok) {+ "toml"+ } else {+ "json"+ };+ let path = home.join(format!("{client:?}.{ext}"));+ rewire(&open, client, &path, url, None)+ .unwrap_or_else(|e| panic!("pre-default {client:?} install: {e:#}"));+ (client, path)+ })+ .collect()+ }++ fn locator(files: &[(McpClient, PathBuf)]) -> impl Fn(McpClient) -> Option<PathBuf> + '_ {+ move |client| {+ files+ .iter()+ .find(|(c, _)| *c == client)+ .map(|(_, path)| path.clone())+ }+ }++ /// `auth enable` on a pre-default install: token minted, the key recorded+ /// with the operator's comments intact, the hooks given the token, and+ /// every client whose entry points at this server re-registered (ZCode,+ /// which only takes a literal header, listed as manual). Run twice, the+ /// second run changes nothing, and the token appears in no harness config.#[test]fn enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config() {let tmp = tempfile::tempdir().unwrap();@@ -376,13 +429,23 @@ mod tests {let home = tmp.path().join("home");std::fs::create_dir_all(&home).unwrap();pre_a1_install(&data_dir);- let claude = claude_json(&home, "http://127.0.0.1:49374/mcp");+ let files = wire_every_client_over_http(&home, "http://127.0.0.1:49374/mcp");+ let locate = locator(&files);- let first = enable(&config_in(&data_dir), None, Some(&claude)).unwrap();+ let first = enable(&config_in(&data_dir), None, Some(&locate)).unwrap();assert!(first.token_created);assert!(first.config_changed);assert_eq!(first.hooks, Some(HookCredential::Seeded));- assert_eq!(first.claude, ClaudeWiring::Rewired);+ assert_eq!(first.mcp.len(), files.len(), "{:?}", first.mcp);+ for line in &first.mcp {+ match line.client {+ McpClient::Zcode => assert!(+ matches!(&line.wiring, Wiring::Manual(reason) if reason.contains("ZCode")),+ "{line:?}"+ ),+ _ => assert_eq!(line.wiring, Wiring::Rewired, "{line:?}"),+ }+ }let token = crate::config::read_trimmed_secret(&first.token_path).unwrap();let config_text = std::fs::read_to_string(data_dir.join("config.toml")).unwrap();@@ -396,22 +459,42 @@ mod tests {config_text.contains("bearer_token_file = \"auth-tokens/default\""),"{config_text}");- let claude_after_first = std::fs::read_to_string(&claude).unwrap();- let entry: serde_json::Value = serde_json::from_str(&claude_after_first).unwrap();+ let claude = &files+ .iter()+ .find(|(c, _)| *c == McpClient::ClaudeCode)+ .unwrap()+ .1;+ let entry: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(claude).unwrap()).unwrap();let entry = &entry["mcpServers"]["ai-memory"];assert_eq!(entry["type"], "stdio");- assert_eq!(entry["command"], "ai-memory");+ assert_eq!(entry["args"][0], "mcp-bridge");assert!(entry.get("env").is_none(), "no token env: {entry}");+ let cursor = &files+ .iter()+ .find(|(c, _)| *c == McpClient::Cursor)+ .unwrap()+ .1;+ let entry: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(cursor).unwrap()).unwrap();+ assert_eq!(+ entry["mcpServers"]["ai-memory"]["args"][1],+ "--no-session-id"+ );assert_eq!(config_in(&data_dir).auth.bearer_token.as_deref(),Some(token.as_str()));+ let after_first: Vec<String> = files+ .iter()+ .map(|(_, path)| std::fs::read_to_string(path).unwrap())+ .collect();- let second = enable(&config_in(&data_dir), None, Some(&claude)).unwrap();+ let second = enable(&config_in(&data_dir), None, Some(&locate)).unwrap();assert!(!second.token_created);assert!(!second.config_changed);assert_eq!(second.hooks, Some(HookCredential::Current));- assert_eq!(second.claude, ClaudeWiring::Rewired);+ assert_eq!(second.mcp, first.mcp);assert_eq!(crate::config::read_trimmed_secret(&second.token_path),Some(token.clone())@@ -420,10 +503,13 @@ mod tests {std::fs::read_to_string(data_dir.join("config.toml")).unwrap(),config_text);- assert_eq!(- std::fs::read_to_string(&claude).unwrap(),- claude_after_first- );+ for ((client, path), before) in files.iter().zip(&after_first) {+ assert_eq!(+ &std::fs::read_to_string(path).unwrap(),+ before,+ "{client:?} changed on the second run"+ );+ }for (path, text) in files_under(&home) {assert!(@@ -446,19 +532,32 @@ mod tests {/// Control: an entry for a remote server keeps its destination.#[test]- fn enable_leaves_a_claude_entry_for_another_server_alone() {+ fn enable_leaves_an_entry_for_another_server_alone() {let tmp = tempfile::tempdir().unwrap();let data_dir = tmp.path().join("data");pre_a1_install(&data_dir);- let claude = claude_json(tmp.path(), "https://team.example/mcp");- let before = std::fs::read_to_string(&claude).unwrap();-- let outcome = enable(&config_in(&data_dir), None, Some(&claude)).unwrap();- assert_eq!(- outcome.claude,- ClaudeWiring::OtherServer("https://team.example/mcp".into())- );- assert_eq!(std::fs::read_to_string(&claude).unwrap(), before);+ let files = wire_every_client_over_http(tmp.path(), "https://team.example/mcp");+ let before: Vec<String> = files+ .iter()+ .map(|(_, path)| std::fs::read_to_string(path).unwrap())+ .collect();+ let locate = locator(&files);++ let outcome = enable(&config_in(&data_dir), None, Some(&locate)).unwrap();+ assert_eq!(outcome.mcp.len(), files.len());+ for line in &outcome.mcp {+ assert!(+ matches!(&line.wiring, Wiring::OtherServer(url) if url.starts_with("https://team.example/mcp")),+ "{line:?}"+ );+ }+ for ((client, path), before) in files.iter().zip(&before) {+ assert_eq!(+ &std::fs::read_to_string(path).unwrap(),+ before,+ "{client:?}"+ );+ }}/// A registered profile named `default` would read the same file as thediff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 73a12f61..38fccab7 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -164,33 +164,219 @@ pub(crate) fn run_with_opencode_dialect(/// Wire a client to a server whose bearer lives in `[auth].bearer_token_file`/// without writing the token into the client's config.///-/// - Claude Code gets the `ai-memory mcp-bridge` stdio entry: the bridge is-/// our own process, loads config like every other subcommand, and so reads-/// the token from the file at launch.-/// - Codex and Prime Agent reference `AI_MEMORY_AUTH_TOKEN` by name, a form-/// both document; the operator exports it where they launch the client.-/// - Every other client is refused. Its config can only carry a literal-/// header, and copying the token there is exactly what the file prevents.+/// - Claude Code gets the session-aware `ai-memory mcp-bridge` entry.+/// - Codex and Prime Agent reference `AI_MEMORY_AUTH_TOKEN` by name, the+/// form their writers already use and both clients document.+/// - Pi is unchanged: its generated extension reads the hook credential file.+/// - Every other client that runs local commands gets a stdio entry for the+/// session-less bridge (`mcp-bridge --no-session-id`), in that client's own+/// documented stdio shape. The bridge is our own process, loads config like+/// any subcommand, and so reads the token from the file at launch.+/// - ZCode is refused: its entry schema keeps only `type`/`url`/`headers`/+/// `enabled`/`timeoutMs` and silently drops `command`/`args` (#511), so it+/// can only take a literal header.fn route_file_token(args: &mut InstallMcpArgs, token_file: &Path) -> Result<()> {match args.client {McpClient::ClaudeCode => args.session_aware = true,McpClient::Codex | McpClient::PrimeAgent => args.token_env_var = true,- _ => bail!(+ McpClient::Pi => {}+ McpClient::Zcode => bail!("this server's bearer token lives in {path} and ai-memory does not copy it into \- another program's config. {client:?} can only take it as a literal header, so \- it is not registered automatically. Options: register Claude Code (it runs the \- `ai-memory mcp-bridge` stdio bridge, which reads the file), Codex or Prime Agent \- (they reference ${env} by name); or add the entry by hand with the header read \- from that file; or pass the token explicitly with \- `{env}=... ai-memory install-mcp ...` if you accept it being stored in that config.",+ another program's config. ZCode keeps only HTTP entries (`type`/`url`/`headers`), \+ so it can only take the token as a literal header and is not registered \+ automatically. Add the entry by hand with the header read from that file, or pass \+ the token explicitly with `{env}=... ai-memory install-mcp --client zcode ...` if \+ you accept it being stored in ZCode's config.",path = token_file.display(),- client = args.client,env = PRIME_AGENT_TOKEN_ENV,),+ _ => args.stdio_bridge = true,}Ok(())}+/// The command a stdio bridge entry runs. Resolved through `PATH` like the+/// Claude Code entry, so the Docker wrapper (which intercepts `mcp-bridge`)+/// and a native install both answer to it.+const BRIDGE_COMMAND: &str = "ai-memory";++/// Arguments of the session-less bridge for `args`: the URL carries the+/// client's schema-flavor marker, because the bridge forwards `tools/list`+/// to it verbatim and the client is the one that needs the dialect.+fn session_less_bridge_args(args: &InstallMcpArgs) -> Vec<String> {+ let base_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);+ vec![+ "mcp-bridge".to_owned(),+ "--no-session-id".to_owned(),+ "--server-url".to_owned(),+ flavored_url_for(args, base_url),+ ]+}++/// The upstream URL of an ai-memory bridge entry: `command: "ai-memory"` with+/// `args`, or OpenCode's single `command` array, running `mcp-bridge` with a+/// `--server-url`. `None` for any other entry.+pub(crate) fn bridge_entry_url(entry: &serde_json::Value) -> Option<&str> {+ let argv: Vec<&str> = match entry.get("command")? {+ serde_json::Value::String(command) if command == BRIDGE_COMMAND => entry+ .get("args")?+ .as_array()?+ .iter()+ .filter_map(serde_json::Value::as_str)+ .collect(),+ serde_json::Value::Array(command) => {+ let mut words = command.iter().filter_map(serde_json::Value::as_str);+ if words.next() != Some(BRIDGE_COMMAND) {+ return None;+ }+ words.collect()+ }+ _ => return None,+ };+ if argv.first() != Some(&"mcp-bridge") {+ return None;+ }+ argv.iter()+ .position(|arg| *arg == "--server-url")+ .and_then(|i| argv.get(i + 1))+ .copied()+}++/// What the entry `name` in `client`'s config file at `path` targets: an+/// HTTP entry's URL (`url`, `httpUrl`, `serverUrl`), a bridge entry's+/// upstream, or the URL a Claude Desktop `mcp-remote` shim forwards to.+/// `Ok(None)` when the file or the entry is absent, or the entry targets no+/// URL this installer could have written.+///+/// # Errors+/// The file exists but cannot be read or parsed.+pub(crate) fn existing_entry_endpoint(+ client: McpClient,+ path: &Path,+ name: &str,+) -> Result<Option<String>> {+ let text = match fs::read_to_string(path) {+ Ok(text) => text,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),+ };+ if matches!(client, McpClient::Codex | McpClient::Grok) {+ let doc: toml_edit::DocumentMut = text+ .parse()+ .with_context(|| format!("parsing {}", path.display()))?;+ let Some(table) = doc+ .get("mcp_servers")+ .and_then(|servers| servers.get(name))+ .and_then(toml_edit::Item::as_table_like)+ else {+ return Ok(None);+ };+ let as_json = json!({+ "url": table.get("url").and_then(toml_edit::Item::as_str),+ "command": table.get("command").and_then(toml_edit::Item::as_str),+ "args": table.get("args").and_then(toml_edit::Item::as_array).map(|args| {+ args.iter().filter_map(toml_edit::Value::as_str).collect::<Vec<_>>()+ }),+ });+ return Ok(entry_endpoint(&as_json).map(str::to_owned));+ }+ let Some(location) = json_mcp_location(client) else {+ return Ok(None);+ };+ let root: serde_json::Value = jsonc_parser::parse_to_ast(+ &text,+ &jsonc_parser::CollectOptions::default(),+ &ParseOptions::default(),+ )+ .map_err(|e| anyhow::anyhow!("parsing {}: {e}", path.display()))?+ .value+ .map_or(serde_json::Value::Null, Into::into);+ let pointer = match location {+ JsonMcpLocation::RootMcpServers => "/mcpServers",+ JsonMcpLocation::RootMcp => "/mcp",+ JsonMcpLocation::NestedMcpServers => "/mcp/servers",+ JsonMcpLocation::RootServers => "/servers",+ JsonMcpLocation::RootContextServers => "/context_servers",+ JsonMcpLocation::RootMcpServersSnake => "/mcp_servers",+ };+ let Some(entry) = root.pointer(pointer).and_then(|servers| servers.get(name)) else {+ return Ok(None);+ };+ if let Some(url) = ["url", "httpUrl", "serverUrl"]+ .iter()+ .find_map(|key| entry.get(*key).and_then(serde_json::Value::as_str))+ .or_else(|| bridge_entry_url(entry))+ {+ return Ok(Some(url.to_owned()));+ }+ let args: Vec<&str> = entry+ .get("args")+ .and_then(serde_json::Value::as_array)+ .map(|args| args.iter().filter_map(serde_json::Value::as_str).collect())+ .unwrap_or_default();+ Ok(args+ .iter()+ .position(|arg| *arg == "mcp-remote")+ .and_then(|i| args.get(i + 1))+ .map(|url| (*url).to_owned()))+}++/// The stdio entry, in the client's documented shape, that runs the+/// session-less bridge. `None` for clients whose entry is not JSON or that+/// take no stdio entry here.+fn stdio_bridge_entry(args: &InstallMcpArgs) -> Option<serde_json::Value> {+ let bridge = session_less_bridge_args(args);+ let plain = || json!({"command": BRIDGE_COMMAND, "args": bridge.clone()});+ let typed =+ |kind: &str| json!({"type": kind, "command": BRIDGE_COMMAND, "args": bridge.clone()});+ let mut opencode_argv = vec![BRIDGE_COMMAND.to_owned()];+ opencode_argv.extend(bridge.iter().cloned());+ Some(match args.client {+ McpClient::ClaudeDesktop+ | McpClient::Zed+ | McpClient::Devin+ | McpClient::KimiCode+ | McpClient::KiroCli+ | McpClient::Openclaw => plain(),+ McpClient::GeminiCli | McpClient::AntigravityCli => json!({+ "command": BRIDGE_COMMAND,+ "args": bridge,+ "timeout": GEMINI_MCP_TIMEOUT_MS,+ }),+ McpClient::Cursor | McpClient::VsCodeCopilot | McpClient::Swival | McpClient::Zero => {+ typed("stdio")+ }+ McpClient::Omp => json!({+ "type": "stdio",+ "command": BRIDGE_COMMAND,+ "args": bridge,+ "enabled": true,+ }),+ McpClient::CopilotCli => json!({+ "type": "local",+ "command": BRIDGE_COMMAND,+ "args": bridge,+ "tools": ["*"],+ }),+ McpClient::CommandCode => json!({+ "transport": "stdio",+ "enabled": true,+ "command": BRIDGE_COMMAND,+ "args": bridge,+ }),+ McpClient::Muse => json!({+ "transport": "stdio",+ "command": BRIDGE_COMMAND,+ "args": bridge,+ "enabled": true,+ "mode": "optional",+ }),+ McpClient::OpenCode => json!({"type": "local", "command": opencode_argv, "enabled": true}),+ McpClient::OpenCode2 => json!({"type": "local", "command": opencode_argv}),+ _ => return None,+ })+}+fn effective_mcp_server_url(config: &Config, args: &InstallMcpArgs) -> String {if let Some(url) = &args.server_url {// Normalize an explicit --server-url exactly like the config/env@@ -208,11 +394,21 @@ fn effective_mcp_server_url(config: &Config, args: &InstallMcpArgs) -> String {}pub(crate) fn mcp_server_url_from_base(server_url: &str) -> String {- let trimmed = server_url.trim().trim_end_matches('/');- if trimmed.ends_with("/mcp") {- trimmed.to_string()+ let trimmed = server_url.trim();+ // A query (a schema `?flavor=` marker on a bridge's upstream URL) stays+ // after the path, which is what gains the `/mcp` suffix.+ let (path, query) = trimmed+ .split_once('?')+ .map_or((trimmed, None), |(path, query)| (path, Some(query)));+ let path = path.trim_end_matches('/');+ let path = if path.ends_with("/mcp") {+ path.to_string()} else {- format!("{trimmed}/mcp")+ format!("{path}/mcp")+ };+ match query {+ Some(query) => format!("{path}?{query}"),+ None => path,}}@@ -828,6 +1024,11 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {validate_args(args)?;+ if args.stdio_bridge+ && let Some(entry) = stdio_bridge_entry(args)+ {+ return Ok(entry);+ }match args.client {McpClient::OpenCode => build_mcp_entry_opencode(args),McpClient::OpenCode2 => build_mcp_entry_opencode2(args),@@ -986,10 +1187,7 @@ fn inferred_owned_opencode_entry(}let object = entry.as_object()?;Some(InferredOpenCodeMcpConfig {- mcp_url: object- .get("url")- .and_then(serde_json::Value::as_str)?- .to_string(),+ mcp_url: entry_endpoint(entry)?.to_string(),auth_token: object.get("headers").and_then(|headers| headers.get("Authorization"))@@ -1029,6 +1227,9 @@ fn opencode_generated_headers(headers: Option<&serde_json::Value>) -> bool {}fn opencode_mcp_entry_has_generated_shape(entry: &serde_json::Value, location: McpClient) -> bool {+ if bridge_entry_url(entry).is_some() {+ return opencode_bridge_entry_has_generated_shape(entry, location);+ }let Some(entry) = entry.as_object() else {return false;};@@ -1059,9 +1260,45 @@ fn opencode_mcp_entry_has_generated_shape(entry: &serde_json::Value, location: M}}+/// The stdio bridge entry `install-mcp` writes for OpenCode on a token-file+/// install: `type: "local"` and the `command` array, plus `enabled: true` in+/// the V1 location only.+fn opencode_bridge_entry_has_generated_shape(+ entry: &serde_json::Value,+ location: McpClient,+) -> bool {+ let Some(object) = entry.as_object() else {+ return false;+ };+ let allowed = ["type", "command", "enabled"];+ if object.get("type").and_then(serde_json::Value::as_str) != Some("local")+ || !object+ .get("command")+ .is_some_and(serde_json::Value::is_array)+ || object.keys().any(|key| !allowed.contains(&key.as_str()))+ {+ return false;+ }+ match location {+ McpClient::OpenCode => {+ object.get("enabled").and_then(serde_json::Value::as_bool) == Some(true)+ }+ McpClient::OpenCode2 => !object.contains_key("enabled"),+ _ => false,+ }+}++/// The endpoint an entry targets: its `url`, or a bridge entry's upstream.+fn entry_endpoint(entry: &serde_json::Value) -> Option<&str> {+ entry+ .get("url")+ .and_then(serde_json::Value::as_str)+ .or_else(|| bridge_entry_url(entry))+}+fn opencode_mcp_entry_is_owned(entry: &serde_json::Value, args: &InstallMcpArgs) -> bool {let expected_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);- entry.get("url").and_then(serde_json::Value::as_str) == Some(expected_url)+ entry_endpoint(entry) == Some(expected_url)&& opencode_mcp_entry_has_generated_shape(entry,match args.client {@@ -1578,6 +1815,19 @@ fn grok_upsert_mcp_server(use toml_edit::{Item, Table, value};let mut server = Table::new();+ if args.stdio_bridge {+ // Grok picks stdio from `command` (and HTTP from `url`).+ server["command"] = value(BRIDGE_COMMAND);+ server["args"] = value(+ session_less_bridge_args(args)+ .iter()+ .map(String::as_str)+ .collect::<toml_edit::Array>(),+ );+ server["enabled"] = value(true);+ upsert_toml_mcp_server(doc, &args.name, server);+ return Ok(());+ }server["url"] = value(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL));server["enabled"] = value(true);if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {@@ -1922,6 +2172,19 @@ fn render_dsh_snippet(args: &InstallMcpArgs) -> String {out.push_str(" name: '@deepseek-ai/dsh-mcp-client'\n");out.push_str(" config:\n");out.push_str(&format!(" serverName: {name}\n"));+ if args.stdio_bridge {+ out.push_str(" transport: stdio\n");+ out.push_str(&format!(+ " command: {}\n",+ yaml_single_quote(BRIDGE_COMMAND)+ ));+ out.push_str(" args:\n");+ for arg in session_less_bridge_args(args) {+ out.push_str(&format!(" - {}\n", yaml_single_quote(&arg)));+ }+ out.push_str(" toolCallTimeoutMs: 120000");+ return out;+ }out.push_str(" transport: streamable-http\n");out.push_str(&format!(" url: {url}\n"));if let Some(value) = bearer_header_value(args.auth_token.as_deref()) {@@ -2151,6 +2414,7 @@ mod tests {session_aware: false,flavor: None,token_env_var: false,+ stdio_bridge: false,}}@@ -2165,6 +2429,7 @@ mod tests {session_aware: false,flavor: None,token_env_var: false,+ stdio_bridge: false,}}@@ -3332,72 +3597,130 @@ mod tests {let mut args = args_for(client);args.apply = true;args.config_file = Some(file.to_path_buf());- run_with_opencode_dialect(config, args, None)+ let dialect = match client {+ McpClient::OpenCode => Some(ai_memory_workstream::OpenCodeDialect::V1),+ McpClient::OpenCode2 => Some(ai_memory_workstream::OpenCodeDialect::V2),+ _ => None,+ };+ run_with_opencode_dialect(config, args, dialect)}- /// New-install default: a token read from the token file is never written into a harness- /// config. Claude Code gets the stdio bridge (which reads the file- /// itself); Codex and Prime Agent reference the variable by name.+ /// New-install default: a token read from the token file is never written+ /// into a harness config, and every client `install-mcp --apply` writes+ /// still gets an entry that reaches the server: Claude Code the+ /// session-aware bridge, Codex and Prime Agent a reference to+ /// `$AI_MEMORY_AUTH_TOKEN`, every other client the session-less bridge in+ /// its own stdio shape. ZCode, which keeps only HTTP entries, is the one+ /// refusal, and writes nothing.#[test]- fn a_file_sourced_token_is_wired_without_entering_any_harness_config() {+ fn a_file_sourced_token_wires_every_client_without_entering_its_config() {let tmp = tempfile::tempdir().unwrap();let config = file_token_config(tmp.path());-- let claude = tmp.path().join("claude.json");- apply_with(&config, McpClient::ClaudeCode, &claude).unwrap();- let text = std::fs::read_to_string(&claude).unwrap();- let entry: serde_json::Value = serde_json::from_str(&text).unwrap();- let entry = &entry["mcpServers"]["ai-memory"];- assert_eq!(entry["type"], "stdio", "{text}");- assert_eq!(entry["args"][0], "mcp-bridge", "{text}");- assert!(entry.get("env").is_none(), "{text}");- assert!(entry.get("headers").is_none(), "{text}");-- let codex = tmp.path().join("codex.toml");- apply_with(&config, McpClient::Codex, &codex).unwrap();- let text = std::fs::read_to_string(&codex).unwrap();- assert!(- text.contains("bearer_token_env_var = \"AI_MEMORY_AUTH_TOKEN\""),- "{text}"- );- assert!(!text.contains("http_headers"), "{text}");-- let prime = tmp.path().join("prime.json");- apply_with(&config, McpClient::PrimeAgent, &prime).unwrap();- let text = std::fs::read_to_string(&prime).unwrap();- assert!(text.contains("\"bearerTokenEnvVar\""), "{text}");-- for file in [&claude, &codex, &prime] {- let text = std::fs::read_to_string(file).unwrap();+ let url = DEFAULT_MCP_URL;+ for &client in <McpClient as clap::ValueEnum>::value_variants() {+ if matches!(client, McpClient::Pi | McpClient::Dsh) {+ continue; // no config file: an extension, and print-only+ }+ let ext = if matches!(client, McpClient::Codex | McpClient::Grok) {+ "toml"+ } else {+ "json"+ };+ let file = tmp.path().join(format!("{client:?}.{ext}"));+ let result = apply_with(&config, client, &file);+ if client == McpClient::Zcode {+ let err = result.unwrap_err();+ assert!(format!("{err:#}").contains("ZCode"), "{err:#}");+ assert!(!file.exists(), "ZCode must not be written");+ continue;+ }+ result.unwrap_or_else(|e| panic!("{client:?}: {e:#}"));+ let text = std::fs::read_to_string(&file).unwrap();assert!(!text.contains(FILE_TOKEN),- "token leaked into {}",- file.display()+ "token leaked into {client:?}: {text}");+ assert!(+ !text.contains("Authorization"),+ "{client:?} got a header: {text}"+ );+ match client {+ McpClient::Codex => assert!(+ text.contains("bearer_token_env_var = \"AI_MEMORY_AUTH_TOKEN\""),+ "{text}"+ ),+ McpClient::PrimeAgent => {+ assert!(text.contains("\"bearerTokenEnvVar\""), "{text}");+ }+ _ => {+ let endpoint = existing_entry_endpoint(client, &file, "ai-memory")+ .unwrap()+ .unwrap_or_else(|| panic!("{client:?} entry has no endpoint: {text}"));+ assert_eq!(endpoint.split('?').next(), Some(url), "{client:?}: {text}");+ assert!(text.contains("mcp-bridge"), "{client:?}: {text}");+ assert_eq!(+ text.contains("--no-session-id"),+ client != McpClient::ClaudeCode,+ "only Claude Code forwards a session id: {text}"+ );+ }+ }}}- /// Clients that can only hold a literal header are refused, and nothing- /// is written, rather than being given the token.+ /// The documented stdio shape of a few clients whose keys differ.#[test]- fn a_file_sourced_token_refuses_literal_header_clients() {- let tmp = tempfile::tempdir().unwrap();- let config = file_token_config(tmp.path());- for client in [- McpClient::Cursor,- McpClient::GeminiCli,- McpClient::OpenCode2,- McpClient::Grok,- McpClient::VsCodeCopilot,- ] {- let file = tmp.path().join(format!("{client:?}.cfg"));- let err = apply_with(&config, client, &file).unwrap_err();- assert!(- format!("{err:#}").contains("does not copy it"),- "{client:?}: {err:#}"- );- assert!(!file.exists(), "{client:?} wrote {}", file.display());- }+ fn stdio_bridge_entries_follow_each_clients_documented_shape() {+ let entry = |client| {+ let mut args = args_for(client);+ args.stdio_bridge = true;+ build_json_mcp_entry(&args).unwrap()+ };+ let opencode = entry(McpClient::OpenCode);+ assert_eq!(opencode["type"], "local");+ assert_eq!(opencode["command"][0], "ai-memory");+ assert_eq!(opencode["command"][1], "mcp-bridge");+ assert_eq!(opencode["enabled"], true);+ assert!(entry(McpClient::OpenCode2).get("enabled").is_none());+ assert_eq!(entry(McpClient::CopilotCli)["type"], "local");+ assert_eq!(entry(McpClient::CopilotCli)["tools"][0], "*");+ assert_eq!(entry(McpClient::CommandCode)["transport"], "stdio");+ assert_eq!(entry(McpClient::Muse)["mode"], "optional");+ assert_eq!(entry(McpClient::VsCodeCopilot)["type"], "stdio");+ assert!(entry(McpClient::Zed).get("type").is_none());+ // Kimi Code's schema dialect rides the bridge's upstream URL.+ assert_eq!(+ entry(McpClient::KimiCode)["args"][3],+ "http://127.0.0.1:49374/mcp?flavor=moonshot"+ );++ let mut grok = args_for(McpClient::Grok);+ grok.stdio_bridge = true;+ let mut doc = toml_edit::DocumentMut::new();+ grok_upsert_mcp_server(&mut doc, &grok).unwrap();+ let text = doc.to_string();+ assert!(text.contains("command = \"ai-memory\""), "{text}");+ assert!(!text.contains("url ="), "{text}");++ let mut dsh = args_for(McpClient::Dsh);+ dsh.stdio_bridge = true;+ let yaml = render_dsh_snippet(&dsh);+ assert!(yaml.contains("transport: stdio"), "{yaml}");+ assert!(yaml.contains("- '--no-session-id'"), "{yaml}");+ }++ /// A flavored upstream URL keeps its query when the bridge normalises it.+ #[test]+ fn mcp_server_url_from_base_keeps_a_query_after_the_path() {+ assert_eq!(+ mcp_server_url_from_base("http://h:1/mcp?flavor=moonshot"),+ "http://h:1/mcp?flavor=moonshot"+ );+ assert_eq!(+ mcp_server_url_from_base("http://h:1/?flavor=gemini"),+ "http://h:1/mcp?flavor=gemini"+ );+ assert_eq!(mcp_server_url_from_base("http://h:1/"), "http://h:1/mcp");}/// Controls: an inline token (pre-default install, `AI_MEMORY_AUTH_TOKEN`) anddiff --git a/crates/ai-memory-cli/src/commands/mcp_bridge.rs b/crates/ai-memory-cli/src/commands/mcp_bridge.rsindex 1958c7c7..ffa46e27 100644--- a/crates/ai-memory-cli/src/commands/mcp_bridge.rs+++ b/crates/ai-memory-cli/src/commands/mcp_bridge.rs@@ -1,4 +1,25 @@-//! Session-aware Claude Code stdio bridge for a remote ai-memory MCP server.+//! Stdio MCP bridge to an ai-memory HTTP MCP server.+//!+//! Two modes, chosen by the entry that launches it, never by the environment:+//!+//! - **Session-aware** (the default, `install-mcp --client claude-code`):+//! forwards Claude Code's `CLAUDE_CODE_SESSION_ID` as+//! `X-Memory-Actor-Session-Id` on every upstream request, and refuses to+//! start without it. That refusal is deliberate (`docs/auto-scope.md`): a+//! registration installed to give Claude Code per-session routing must not+//! silently degrade to the shared single slot when the id is missing.+//! - **Session-less** (`--no-session-id`, every other client): a plain+//! stdio-to-HTTP relay that forwards no session identity, so the client+//! is a static MCP client and passes `workspace` + `project` explicitly,+//! exactly as with a direct HTTP entry. It ignores `CLAUDE_CODE_SESSION_ID`+//! even when present: a client started from a Claude Code terminal inherits+//! that session's id, and forwarding it would steer this client's unscoped+//! calls through another session's active-project pointer.+//!+//! Either way the bridge authenticates with the bearer `Config::load`+//! resolved (`AI_MEMORY_AUTH_TOKEN`, `[auth].bearer_token`, or the file+//! `[auth].bearer_token_file` names), so a harness config that launches it+//! carries no token and no token reaches its command line.use std::collections::HashMap;@@ -61,7 +82,7 @@ fn upstream_error(error: ServiceError) -> McpError {fn upstream_config(server_url: &str,- session_id: &str,+ session_id: Option<&str>,auth_token: Option<&str>,) -> Result<StreamableHttpClientTransportConfig> {// Every transport in this module is built from a config this function@@ -72,12 +93,14 @@ fn upstream_config(install_crypto_provider()?;let mut headers = HashMap::new();- headers.insert(- ACTOR_SESSION_HEADER,- HeaderValue::from_str(session_id).context(- "CLAUDE_CODE_SESSION_ID contains characters that are invalid in an HTTP header",- )?,- );+ if let Some(session_id) = session_id {+ headers.insert(+ ACTOR_SESSION_HEADER,+ HeaderValue::from_str(session_id).context(+ "CLAUDE_CODE_SESSION_ID contains characters that are invalid in an HTTP header",+ )?,+ );+ }let mut config =StreamableHttpClientTransportConfig::with_uri(server_url).custom_headers(headers);@@ -87,11 +110,21 @@ fn upstream_config(Ok(config)}-/// Run the Claude Code session-aware stdio bridge.-///-/// # Errors-/// Returns an error when Claude did not provide a lifecycle session id, the-/// upstream HTTP MCP server cannot initialize, or either transport fails.+/// The session id to forward: the inherited `CLAUDE_CODE_SESSION_ID` in the+/// session-aware mode, which refuses to run without one, and nothing at all+/// in the session-less mode, whatever the environment holds (see the module+/// docs for why an inherited id must not be forwarded there).+fn bridge_session_id(inherited: Option<&str>, no_session_id: bool) -> Result<Option<&str>> {+ if no_session_id {+ return Ok(None);+ }+ inherited.map(Some).context(+ "CLAUDE_CODE_SESSION_ID is missing; this session-aware bridge must be launched by \+ Claude Code as an stdio MCP server (other clients register it with \+ `--no-session-id`)",+ )+}+/// Install a process-wide rustls crypto provider before the bridge opens an HTTPS/// transport.///@@ -115,9 +148,17 @@ fn install_crypto_provider() -> Result<()> {Ok(())}+/// Run the stdio bridge, session-aware or session-less (see the module docs).+///+/// # Errors+/// Returns an error when the session-aware mode has no Claude session id, the+/// upstream HTTP MCP server refuses or cannot initialize (an unauthenticated+/// connection to a server that requires a token included), or either+/// transport fails.pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {- let session_id = config.runtime_env.claude_code_session_id().context(- "CLAUDE_CODE_SESSION_ID is missing; this bridge must be launched by Claude Code as an stdio MCP server",+ let session_id = bridge_session_id(+ config.runtime_env.claude_code_session_id(),+ args.no_session_id,)?;let server_url = args.server_url@@ -130,10 +171,33 @@ pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {config.auth.bearer_token.as_deref(),)?);- let mut upstream = ()- .serve(transport)- .await- .with_context(|| format!("connecting session-aware bridge to {server_url}"))?;+ // Connecting before serving stdio means a refused credential (401) or an+ // unreachable server ends the process with this error at once; the client+ // sees the MCP server exit instead of a session that never answers.+ let mut upstream = match ().serve(transport).await {+ Ok(upstream) => upstream,+ Err(error) => {+ let error = anyhow::Error::new(error);+ // rmcp reports the server's 401 only as "Auth required"; name it.+ let refused = format!("{error:#}").contains("Auth required");+ return Err(error).with_context(|| {+ format!(+ "connecting the MCP bridge to {server_url}{}{}",+ if refused {+ ": the server answered 401 Unauthorized"+ } else {+ ""+ },+ if config.auth.bearer_token.is_some() {+ ""+ } else {+ " (sent without a bearer token; the bridge reads it from \+ AI_MEMORY_AUTH_TOKEN, [auth].bearer_token or [auth].bearer_token_file)"+ }+ )+ });+ }+ };let server_info = upstream.peer_info().map(|info| (*info).clone())@@ -176,7 +240,7 @@ mod tests {/// the contract so the call is not quietly deleted.#[test]fn upstream_config_leaves_a_crypto_provider_installed() {- let config = upstream_config("http://127.0.0.1:1/mcp", "session-for-provider", None);+ let config = upstream_config("http://127.0.0.1:1/mcp", Some("session-for-provider"), None);assert!(config.is_ok(), "config build must succeed");assert!(rustls::crypto::CryptoProvider::get_default().is_some(),@@ -252,7 +316,7 @@ mod tests {fn upstream_config_injects_session_id_and_raw_bearer_token() {let config = upstream_config("https://memory.example/mcp",- "550e8400-e29b-41d4-a716-446655440000",+ Some("550e8400-e29b-41d4-a716-446655440000"),Some("secret-token"),).unwrap();@@ -271,8 +335,12 @@ mod tests {#[test]fn upstream_config_rejects_an_invalid_header_value() {- let error =- upstream_config("https://memory.example/mcp", "session\ninjected", None).unwrap_err();+ let error = upstream_config(+ "https://memory.example/mcp",+ Some("session\ninjected"),+ None,+ )+ .unwrap_err();assert!(error.to_string().contains("invalid in an HTTP header"),"{error:#}"@@ -285,6 +353,7 @@ mod tests {&Config::default(),McpBridgeArgs {server_url: Some("https://memory.example/mcp".into()),+ no_session_id: false,},).await@@ -298,6 +367,25 @@ mod tests {);}+ /// The session-aware mode still fails closed without an id; the+ /// session-less mode never forwards one, not even an inherited id.+ #[test]+ fn only_the_session_aware_mode_forwards_and_requires_a_session_id() {+ assert_eq!(bridge_session_id(Some("s"), false).unwrap(), Some("s"));+ assert!(bridge_session_id(None, false).is_err());+ assert_eq!(bridge_session_id(Some("inherited"), true).unwrap(), None);+ assert_eq!(bridge_session_id(None, true).unwrap(), None);+ }++ /// Session-less mode sends no session header at all, even when a+ /// `CLAUDE_CODE_SESSION_ID` is inherited (it is not even consulted).+ #[test]+ fn a_session_less_upstream_config_carries_no_session_header() {+ let config = upstream_config("https://memory.example/mcp", None, Some("t")).unwrap();+ assert!(!config.custom_headers.contains_key(&ACTOR_SESSION_HEADER));+ assert_eq!(config.auth_header.as_deref(), Some("t"));+ }+async fn assert_bridge_round_trip(stateful: bool) {let seen_session = Arc::new(Mutex::new(None));let echo = EchoServer {@@ -320,7 +408,12 @@ mod tests {});let upstream_transport = StreamableHttpClientTransport::from_config(- upstream_config(&format!("http://{address}/mcp"), "claude-session-244", None).unwrap(),+ upstream_config(+ &format!("http://{address}/mcp"),+ Some("claude-session-244"),+ None,+ )+ .unwrap(),);let upstream = ().serve(upstream_transport).await.unwrap();let bridge = SessionAwareBridge {diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 4b023c0d..cb5b4a35 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -410,6 +410,7 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverridesession_aware: false,flavor: None,token_env_var: false,+ stdio_bridge: false,});WireInstalls {opencode_dialect,diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 3b79dd7a..ec0ed955 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -393,6 +393,7 @@ fn emit_extension_setup_hint(config: &Config, args: &SetupAgentArgs) -> Result<(session_aware: false,flavor: None,token_env_var: false,+ stdio_bridge: false,},Some(dialect),)?;diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex e2ff52ba..b92d940a 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -1290,18 +1290,37 @@ fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: Option<&str>, ureturn true;}}+ // Our stdio bridge, in any client's shape (`command` + `args`, or+ // OpenCode's single `command` array), aimed at this server.+ if install_mcp::bridge_entry_url(entry) == Some(url) {+ return true;+ }if let Some(args) = entry.get("args").and_then(|a| a.as_array()) {let has_remote = args.iter().any(|a| a.as_str() == Some("mcp-remote"));- let has_session_bridge = entry.get("command").and_then(|v| v.as_str()) == Some("ai-memory")- && args.iter().any(|a| a.as_str() == Some("mcp-bridge"));let has_url = args.iter().any(|a| a.as_str() == Some(url));- if (has_remote || has_session_bridge) && has_url {+ if has_remote && has_url {return true;}}false}+/// A TOML `[mcp_servers.<name>]` table (Codex, Grok) aimed at `url`: an HTTP+/// entry by its `url`, or our stdio bridge by `command` + `args`.+fn toml_mcp_entry_targets(table: &dyn toml_edit::TableLike, url: &str) -> bool {+ if table.get("url").and_then(|u| u.as_str()) == Some(url) {+ return true;+ }+ let as_json = serde_json::json!({+ "command": table.get("command").and_then(|c| c.as_str()),+ "args": table+ .get("args")+ .and_then(|a| a.as_array())+ .map(|a| a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>()),+ });+ install_mcp::bridge_entry_url(&as_json) == Some(url)+}+/// URL forms uninstall matches for `client`: the endpoint as given, plus/// for clients whose installer appends a schema flavor, the form/// `install-mcp` actually writes (`--mcp-url` keeps the unflavored default).@@ -1445,10 +1464,8 @@ fn strip_mcp_toml(content: &str, name: Option<&str>, url: &str) -> Result<(Strinfor k in keys {let matches_url = servers.get(&k)- .and_then(|item| item.as_table())- .and_then(|t| t.get("url"))- .and_then(|u| u.as_str())- == Some(url);+ .and_then(|item| item.as_table_like())+ .is_some_and(|t| toml_mcp_entry_targets(t, url));if name.is_none_or(|name| k == name) && matches_url {servers.remove(&k);removed.push(k);@@ -1461,9 +1478,7 @@ fn strip_mcp_toml(content: &str, name: Option<&str>, url: &str) -> Result<(Strinlet matches_url = servers.get(&k).and_then(|value| value.as_inline_table())- .and_then(|table| table.get("url"))- .and_then(|value| value.as_str())- == Some(url);+ .is_some_and(|table| toml_mcp_entry_targets(table, url));if name.is_none_or(|name| k == name) && matches_url {servers.remove(&k);removed.push(k);@@ -2318,6 +2333,62 @@ mod tests {assert!(removed.is_empty());}+ /// The stdio bridge entries `install-mcp` writes on a token-file install+ /// are ours when they target this server, in every client shape, and a+ /// bridge aimed at another server is not.+ #[test]+ fn bridge_entries_are_recognised_by_their_upstream_url() {+ let url = "http://127.0.0.1:49374/mcp";+ let bridge = |target: &str| {+ serde_json::json!({+ "type": "stdio",+ "command": "ai-memory",+ "args": ["mcp-bridge", "--no-session-id", "--server-url", target],+ })+ };+ let opencode = serde_json::json!({+ "type": "local",+ "command": ["ai-memory", "mcp-bridge", "--no-session-id", "--server-url", url],+ "enabled": true,+ });+ assert!(mcp_entry_is_ours(+ "ai-memory",+ &bridge(url),+ Some("ai-memory"),+ url+ ));+ assert!(mcp_entry_is_ours(+ "ai-memory",+ &opencode,+ Some("ai-memory"),+ url+ ));+ assert!(!mcp_entry_is_ours(+ "ai-memory",+ &bridge("https://team.example/mcp"),+ Some("ai-memory"),+ url+ ));+ let foreign =+ serde_json::json!({"command": "other", "args": ["mcp-bridge", "--server-url", url]});+ assert!(!mcp_entry_is_ours(+ "ai-memory",+ &foreign,+ Some("ai-memory"),+ url+ ));++ let toml = format!(+ "[mcp_servers.ai-memory]\ncommand = \"ai-memory\"\nargs = [\"mcp-bridge\", \"--no-session-id\", \"--server-url\", \"{url}\"]\n\n[mcp_servers.other]\ncommand = \"other\"\n"+ );+ let (out, removed) = strip_mcp_toml(&toml, Some("ai-memory"), url).unwrap();+ assert_eq!(removed, vec!["ai-memory".to_string()]);+ assert!(out.contains("[mcp_servers.other]"), "{out}");+ let (_, kept) =+ strip_mcp_toml(&toml, Some("ai-memory"), "https://team.example/mcp").unwrap();+ assert!(kept.is_empty());+ }+#[test]fn strip_mcp_toml_by_name_keeps_comments_and_tables() {let content = "# my codex config\n[other]\nkeep = true\n\n[mcp_servers.ai-memory]\nurl = \"http://127.0.0.1:49374/mcp\"\n";diff --git a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rsindex 889149ef..f2e4c83d 100644--- a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs@@ -79,6 +79,9 @@ mod slow {.env("AI_MEMORY_BACKFILL_ON_START", "false").env("AI_MEMORY_AUTO_IMPROVE__SCHEDULER__ENABLED", "false").env("RUST_LOG", "off")+ // A developer (or agent) running these tests from Claude Code+ // has its session id exported; a child must not inherit it.+ .env_remove("CLAUDE_CODE_SESSION_ID").current_dir(&self.home);cmd}@@ -338,10 +341,42 @@ mod slow {/// `initialize`, `notifications/initialized`, `tools/list`. Returns the/// `tools/list` reply. `check` runs while the bridge is alive.fn bridge_tools_list(install: &Install, base: &str, check: impl FnOnce(u32)) -> Value {- let mut child = install- .cmd()- .args(["mcp-bridge", "--server-url", base])- .env("CLAUDE_CODE_SESSION_ID", "authdef-bridge-session")+ bridge_exchange(install, BridgeMode::SessionAware, base, None, check).0+ }++ /// How the bridge is launched, as the entry `install-mcp` writes runs it.+ #[derive(Clone, Copy)]+ enum BridgeMode {+ /// Claude Code's entry: forwards `CLAUDE_CODE_SESSION_ID`.+ SessionAware,+ /// Every other client's entry: `--no-session-id`, no id in the env.+ SessionLess,+ }++ /// `initialize`, `notifications/initialized`, `tools/list` and, when+ /// given, one `tools/call`, through the bridge over stdio. Returns the+ /// `tools/list` and `tools/call` replies; `check` runs while it is alive.+ fn bridge_exchange(+ install: &Install,+ mode: BridgeMode,+ base: &str,+ call: Option<Value>,+ check: impl FnOnce(u32),+ ) -> (Value, Option<Value>) {+ let mut cmd = install.cmd();+ match mode {+ BridgeMode::SessionAware => {+ cmd.args(["mcp-bridge", "--server-url", base])+ .env("CLAUDE_CODE_SESSION_ID", "authdef-bridge-session");+ }+ BridgeMode::SessionLess => {+ // A client started from a Claude Code terminal inherits that+ // session's id; the session-less bridge must work regardless.+ cmd.args(["mcp-bridge", "--no-session-id", "--server-url", base])+ .env("CLAUDE_CODE_SESSION_ID", "inherited-from-a-claude-terminal");+ }+ }+ let mut child = cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())@@ -395,13 +430,54 @@ mod slow {json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}),);let tools = wait_for(2);+ let called = call.map(|params| {+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": params}),+ );+ wait_for(3)+ });check(child.id());drop(stdin);let _ = child.kill();let _ = child.wait();- tools+ (tools, called)}+ #[cfg(target_os = "linux")]+ fn environ(pid: u32) -> String {+ std::fs::read(format!("/proc/{pid}/environ"))+ .map(|bytes| String::from_utf8_lossy(&bytes).replace('\0', "\n"))+ .unwrap_or_default()+ }++ /// The clients `install-mcp --apply` writes a config file for on a+ /// token-file install, by their CLI names. Pi (an extension), DeepSeek+ /// Harness (print-only) and ZCode (HTTP-only, refused) are not among them.+ const WRITTEN_CLIENTS: &[&str] = &[+ "claude-code",+ "codex",+ "opencode2",+ "cursor",+ "claude-desktop",+ "gemini-cli",+ "openclaw",+ "omp",+ "antigravity-cli",+ "zero",+ "devin",+ "grok",+ "kimi-code",+ "kiro-cli",+ "command-code",+ "copilot-cli",+ "swival",+ "vscode-copilot",+ "zed",+ "muse",+ "prime-agent",+ ];+/// A fresh `init`: every guarded route refuses an unauthenticated/// request, `/healthz` answers, and the hook, a CLI command and the MCP/// bridge all succeed without a token in their environment. Wiring the@@ -477,22 +553,17 @@ mod slow {],Some(&base),);- install.run_ok(- &["install-mcp", "--client", "claude-code", "--apply"],- Some(&base),- );- install.run_ok(- &["install-mcp", "--client", "codex", "--apply"],- Some(&base),- );+ for client in WRITTEN_CLIENTS {+ install.run_ok(&["install-mcp", "--client", client, "--apply"], Some(&base));+ }let refused = install.run(- &["install-mcp", "--client", "cursor", "--apply"],+ &["install-mcp", "--client", "zcode", "--apply"],Some(&base),None,);assert!(!refused.status.success(),- "a literal-header client is refused"+ "ZCode, which only takes a literal header, is refused");let first = install.run_ok(&["auth", "enable"], Some(&base));let config_after_first =@@ -521,6 +592,98 @@ mod slow {drop(server);}+ /// The session-less bridge any non-Claude client runs: against a fresh+ /// auth-on install it lists the tools and answers a `memory_query` with+ /// explicit scope, with the token on neither its command line nor in its+ /// environment. Controls: the session-aware bridge still refuses to start+ /// without `CLAUDE_CODE_SESSION_ID`, and the static `memory_query` reaches+ /// the project the hook wrote.+ #[tokio::test]+ async fn a_session_less_bridge_serves_any_client_without_holding_the_token() {+ let install = Install::new();+ install.run_ok(&["init"], None);+ let token = install.root_token().unwrap();+ let client = reqwest::Client::new();+ let (_server, base) = install.serve(&client, "serve-bridge.log").await;+ install.hook_prompt(&base, "authdef-bridge-hook");+ assert_eq!(settled_sessions(&client, &base, &token, 1).await, 1);++ let query = json!({+ "name": "memory_query",+ "arguments": {"q": "authdef hook prompt", "workspace": WORKSPACE, "project": PROJECT},+ });+ let (tools, called) = bridge_exchange(+ &install,+ BridgeMode::SessionLess,+ &base,+ Some(query),+ |_pid| {+ #[cfg(target_os = "linux")]+ {+ assert!(!cmdline(_pid).contains(&token), "token in the bridge argv");+ assert!(!environ(_pid).contains(&token), "token in the bridge env");+ }+ },+ );+ assert!(+ tools["result"]["tools"]+ .as_array()+ .is_some_and(|t| !t.is_empty()),+ "{tools}"+ );+ let called = called.expect("memory_query reply");+ assert!(called.get("error").is_none(), "{called}");+ assert_ne!(called["result"]["isError"], json!(true), "{called}");++ let out = install.run(&["mcp-bridge", "--server-url", &base], None, Some(""));+ assert!(!out.status.success());+ assert!(+ String::from_utf8_lossy(&out.stderr).contains("CLAUDE_CODE_SESSION_ID is missing"),+ "the session-aware mode keeps failing closed: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ }++ /// A bridge with no token against an auth-on server exits at once with+ /// the refusal, before it serves stdio, so the client sees the server+ /// exit rather than a session that never answers.+ #[tokio::test]+ async fn a_bridge_without_the_token_is_refused_cleanly_not_hung() {+ let install = Install::new();+ install.run_ok(&["init"], None);+ let client = reqwest::Client::new();+ let (_server, base) = install.serve(&client, "serve-refused.log").await;++ let stranger = Install::new(); // no data dir token, no config+ let mut child = stranger+ .cmd()+ .args(["mcp-bridge", "--no-session-id", "--server-url", &base])+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let deadline = Instant::now() + Duration::from_secs(20);+ let status = loop {+ if let Some(status) = child.try_wait().unwrap() {+ break status;+ }+ if Instant::now() >= deadline {+ let _ = child.kill();+ panic!("the bridge hung on a refused connection");+ }+ std::thread::sleep(Duration::from_millis(50));+ };+ let mut stderr = String::new();+ std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut stderr).unwrap();+ assert!(!status.success());+ assert!(stderr.contains("sent without a bearer token"), "{stderr}");+ assert!(+ stderr.contains("401") || stderr.to_ascii_lowercase().contains("unauthorized"),+ "the refusal is surfaced: {stderr}"+ );+ }+/// The control, and the opt-in. An install that predates the default/// (a database, no token file) keeps the loopback no-auth behaviour and/// is told how to change it; `auth enable` run twice then turns the tokendiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 4b624e25..b7f58940 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -660,14 +660,27 @@ MCP parameter aliases are intentionally sparse: `memory_query.query` accepts`q|search`, and limit fields accept `n` / `top_k` where shipped. Project andcwd parameters use their canonical names.-Claude Code's optional session-aware MCP registration is a transport adapter,-not a second tool implementation. `ai-memory mcp-bridge` serves the upstream-tool catalogue over local stdio, delegates tool calls to the configured HTTP-server through rmcp's client transport, and injects the inherited-`CLAUDE_CODE_SESSION_ID` as `X-Memory-Actor-Session-Id`. The server therefore-keeps the same auth, scope resolver, and tool handlers as direct HTTP clients.-The adapter fails closed without a Claude session id and is installed only by-the explicit `install-mcp --client claude-code --session-aware` option.+`ai-memory mcp-bridge` is a transport adapter, not a second tool+implementation. It serves the upstream tool catalogue over local stdio and+delegates tool calls to the configured HTTP server through rmcp's client+transport, authenticating with the bearer `Config::load` resolved, so the+server keeps the same auth, scope resolver, and tool handlers as direct HTTP+clients. It has two modes, chosen by the entry that launches it:++- session-aware (Claude Code, `install-mcp --client claude-code+ --session-aware`, and every Claude Code entry on a token-file install): it+ injects the inherited `CLAUDE_CODE_SESSION_ID` as+ `X-Memory-Actor-Session-Id` and fails closed without one, so a+ registration meant for per-session routing never silently degrades to the+ shared slot;+- session-less (`--no-session-id`, every other client on a token-file+ install): it forwards no session identity and ignores an inherited+ `CLAUDE_CODE_SESSION_ID`, which a client started from a Claude Code+ terminal would otherwise lend to that session's active-project pointer.+ The client is a static MCP client and passes `workspace` + `project`.++The bridge connects upstream before it serves stdio, so a refused credential+(401) or an unreachable server ends it at once with the reason.## HTTP authentication classes@@ -1303,13 +1316,17 @@ and no bearer supplied another way. An existing install keeps the loopbackno-auth behaviour until `ai-memory auth enable`, which is idempotent: it reusesor mints the file, records the key, copies the token into the hook credentialfiles (`auth-token`, `auth-header`) when none are stored, and re-registers-Claude Code's MCP entry for this server as the `mcp-bridge` stdio bridge.+every MCP client whose `ai-memory` entry targets this server the way+`install-mcp` wires a token-file install, listing what it changed and what+needs a manual change.A token read from the file is never written into a harness config or onto a-command line. `install-mcp` gives Claude Code the `ai-memory mcp-bridge` stdio-entry, which reads the file itself; Codex and Prime Agent reference-`AI_MEMORY_AUTH_TOKEN` by name; clients that only accept a literal header are-refused. `install-hooks --apply` persists it to the hook credential files and+command line. `install-mcp` gives Claude Code the session-aware+`ai-memory mcp-bridge` stdio entry, which reads the file itself; Codex and+Prime Agent reference `AI_MEMORY_AUTH_TOKEN` by name; every other client gets+a stdio entry, in its own config format, for `ai-memory mcp-bridge+--no-session-id`. ZCode keeps HTTP entries only and is refused.+`install-hooks --apply` persists it to the hook credential files andnever inlines it. Client commands of a packaged install, whose config livesoutside the data dir and so is not read without `--config`, use`<data_dir>/auth-tokens/default` when no config file exists where they look,diff --git a/docs/auto-scope.md b/docs/auto-scope.mdindex f0383610..2f708366 100644--- a/docs/auto-scope.md+++ b/docs/auto-scope.md@@ -186,6 +186,13 @@ subprocess the startup id rather than the resumed id. Restart Claude Code afterwhen no `CLAUDE_CODE_SESSION_ID` is available instead of silently degrading tothe shared single slot.+The same binary also runs session-less, as `ai-memory mcp-bridge+--no-session-id`: the stdio entry `install-mcp` writes for every other client+when the server's token lives in `[auth].bearer_token_file`. It forwards no+session id, not even an inherited `CLAUDE_CODE_SESSION_ID`, so those clients+stay static MCP clients and pass `workspace` + `project`; they never touch a+per-session pointer.+Use `per_session` only when your client or bridge can send the sameopaque session id from the hook payload on each MCP request as`X-Memory-Actor-Session-Id`, native MCP metadata as above, or `Mcp-Session-Id`. Otherwisediff --git a/docs/install.md b/docs/install.mdindex 6f5c4f2b..056dd90b 100644--- a/docs/install.md+++ b/docs/install.md@@ -325,9 +325,11 @@ start them:export AI_MEMORY_AUTH_TOKEN="$(cat ~/.local/share/ai-memory/auth-tokens/default)"```-`install-mcp` refuses clients that can only hold a literal header rather-than write the token into their config. Add those entries by hand if you-accept that.+Every other client `install-mcp` supports gets a local stdio entry that+runs `ai-memory mcp-bridge --no-session-id`, which also reads the token file+at launch, so `ai-memory` must be on the `PATH` the client sees. ZCode only+takes HTTP entries and is refused; add its entry by hand with the header if+you accept the token in its config.An install created before this default keeps running without auth.`ai-memory status` then shows `auth: none (loopback)`; rundiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex f4c22c47..e9325eaa 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -15,11 +15,16 @@ Factory Droid, Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no> **Token kept in the data dir.** When this install's bearer comes from> `[auth].bearer_token_file` (every fresh `ai-memory init`, and> `ai-memory auth enable`), `install-mcp` never writes it into a client's-> config. Claude Code gets the `ai-memory mcp-bridge` stdio entry, which reads-> the file at launch; Codex (`bearer_token_env_var`) and Prime Agent-> (`bearerTokenEnvVar`) name `AI_MEMORY_AUTH_TOKEN`, which you export where you-> start them; every other client is refused. Passing `--auth-token` explicitly-> (or `AI_MEMORY_AUTH_TOKEN`) keeps the snippets below, header included.+> config. Claude Code gets the session-aware `ai-memory mcp-bridge` stdio+> entry; Codex (`bearer_token_env_var`) and Prime Agent (`bearerTokenEnvVar`)+> name `AI_MEMORY_AUTH_TOKEN`, which you export where you start them. Every+> other client gets a local stdio entry, in its own format, that runs+> `ai-memory mcp-bridge --no-session-id --server-url <url>`: the bridge reads+> the token file at launch and forwards no session id, so the client passes+> `workspace` and `project` like any static client. The client must find+> `ai-memory` on its `PATH` (GUI apps may need the full path). ZCode keeps+> HTTP entries only and is refused. Passing `--auth-token` explicitly (or+> `AI_MEMORY_AUTH_TOKEN`) keeps the HTTP snippets below, header included.> **Transport is stateless by default.** Since v0.1.2 the HTTP transport> answers each request independently (plain JSON, no `Mcp-Session-Id`diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex f2e94716..476b636c 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -49,7 +49,7 @@ means the boundary is not built yet.| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks || 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI || 5e | Conditional page mutation (#986, invariant #16) | `ai-memory-store/src/ops.rs` `upsert_page_if` reads the latest version and writes in one transaction, the authority; `ai-memory-wiki/src/wiki.rs` `write_page_if` pre-checks under the per-page lock before touching disk and restores the file when the store check fails; conditional deletes reuse `delete_page_if_latest` (exclusive mutation lock plus an in-transaction check). `ai-memory-mcp/src/server.rs` checks the precondition only after scope resolution and the write grant, against the resolved scope's own latest row, and returns `precondition_failed` with no write, checkpoint or webhook dispatch | `multi_session.rs` `conditional_writers_on_one_base_exactly_one_wins_and_nothing_is_destroyed` (two writers from one version: one wins, the base stays reachable, no loser row; fails with the store check removed); `server.rs` `conditional_page_writes::*` (stale id, `create_only` on an existing page, a version id from another project, and conditional deletes are refused and change nothing, with and without the wiki pre-check; the store check proven to bite with the reader pre-check off); `a_reader_may_read_everything_and_change_nothing` (a read-only user's conditional write or delete, with the right id or a wrong one, gets the authorization error and no version data; the page is unchanged) | STRONG |-| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`) | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed` | STRONG |+| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`); `ai-memory-cli/src/commands/mcp_bridge.rs` `bridge_session_id`: the session-less bridge (`--no-session-id`, every non-Claude stdio client on a token-file install) never forwards an inherited `CLAUDE_CODE_SESSION_ID`, so a client launched from a Claude Code terminal cannot steer that session's per-session pointer | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed`; `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id` (an inherited id is dropped in session-less mode; the session-aware control forwards it and still fails closed without one) and `a_session_less_upstream_config_carries_no_session_header` | STRONG || 6b | Native `_meta` routing coordinate is routing-only (never grants identity) | `ai-memory-mcp/src/server.rs` `attach_native_session` reads only `_meta["ai.opencode/sessionID"]` into `ActorKey.session_id` (trimmed, non-empty-string-validated); `user` still comes from the authenticated `ActorContext`, so a forged `_meta` cannot cross a user/scope boundary — it only selects a session slot behind the existing `active_project` guard | `server.rs` `native_session_metadata_is_routing_only_and_preserves_precedence`, `native_session_metadata_validates_strings_without_granting_identity`; `autoscope_multiuser.rs` `native_metadata_routes_concurrent_reads_and_writes_to_hook_workspaces` (#864) | STRONG || 6c | Per-user slot namespaces stay per operator (`[slots] per_user`) | `ai-memory-mcp/src/server.rs` `place_slot_mutation`, shared by `place_slot_write` (`memory_write_page`) and `place_slot_delete` (`memory_delete_page`): a non-admin's generic `_slots/<name>.md` is redirected to their own `_slots/u-<operator>/` namespace, a path inside another operator's namespace is refused, admins bypass, and nothing changes with the flag off (#1083) | `slot_identity.rs` `oidc_operator_cannot_delete_another_operators_personal_slot`, `oidc_operator_deleting_shared_slot_path_deletes_their_personal_slot` (shared slot survives), legitimate controls `oidc_operator_can_delete_their_own_personal_slot_explicitly`, `admin_can_delete_shared_and_personal_slots` | STRONG || 7 | Sanitizer trust boundary (invariant #6) | `ai-memory-core/src/sanitize.rs` `Sanitized<T>` (private field, only `sanitize()` ctor); `Sanitized::new` scrubs the title *before* the 80-char display cap; `ai-memory-mcp/src/server.rs` `sanitize_feedback_reason` scrubs the reason *before* the 500-char cap; `ai-memory-hooks/src/router.rs` `durable_body` scrubs the full excerpt *before* the per-event body caps (`payload::durable_body_cap`), which no longer run at excerpt extraction; `ai-memory-hooks/src/payload.rs` `cap_object_fields` scrubs with the built-in sanitizer *before* the client spool cap; `WriterHandle::insert_observation` requires `Sanitized`; `ops` crate-private | Structural (compile-time) + `store/src/lib.rs` `insert_observation_boundary_scrubs_before_disk` + sanitizer scrub unit tests + `ai-memory-core::sanitize` `title_is_scrubbed_before_the_80_char_cap_runs` + `ai-memory-hooks::router` `issue_980_user_prompt_title_is_sanitized_before_truncated` (a secret straddling the 80-char boundary is redacted, not stored truncated; #980) + `ai-memory-mcp::server` `feedback_reason_is_scrubbed_before_the_500_char_cap` (#1109) + `ai-memory-hooks::router` `issue_1114_user_prompt_body_is_sanitized_before_the_16kib_cap`, `issue_1114_post_compaction_body_is_sanitized_before_the_16kib_cap`, `issue_1114_tool_body_is_sanitized_before_the_2kb_cap`, `tool_body_cap_keeps_the_utf8_boundary` + `ai-memory-hooks::payload` `client_body_cap_scrubs_before_truncating` (each places a secret straddling the cap and asserts a `[REDACTED:…]` marker survives with no raw fragment; #1114) | STRONG (structural) |@@ -78,7 +78,7 @@ means the boundary is not built yet.| 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper. For a server initialized on the named volume, `bin/ai-memory` `refresh_volume_token` (run only by `install-hooks`) copies `/data/auth-tokens/default` (only when `/data/config.toml` names it) to an owner-only `native-runner/server-token` through the helper's stdout, and `use_volume_token` points the native client at that copy (the managed host commands and `mcp-bridge` only read it and never enter the container engine) with `AI_MEMORY_AUTH__BEARER_TOKEN_FILE`, so it is a file-sourced token (never rendered into a harness config) and never an argv; a bind-mounted `AI_MEMORY_DATA_DIR` is read directly and an explicit `AI_MEMORY_AUTH_TOKEN` wins | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused; `Checking the wrapper hands host commands the volume's root bearer`: for `mcp-bridge`, `install-hooks` and `run` the fake native client receives the token file (mode 600, right content) and the token is absent from its argv; controls: a bind-mounted data dir and an explicit `AI_MEMORY_AUTH_TOKEN` make no copy and ask no container (bite: dropping the export fails the check); `auth_default_e2e.rs` `a_host_client_given_the_token_file_by_env_authenticates` (the native side of the handoff, with a no-variable control) | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 || 11j | Offline recovery journal and transcript replay | `ai-memory-cli/src/commands/recovery.rs` keeps bounded locators, ordered semantic transcript digests, pre-launch cursors and persistent correlated-delivery/loss evidence in an atomic journal, refuses a symlinked data dir and any symlinked component inside it (ancestors above the data dir are trusted, so macOS `/var` → `/private/var` works), sanitizes/caps failure reasons, and bounds each replay plus the whole pass; `hook_spool` coordinates enqueue and quarantine with short filesystem locks, canonically resolves partial scope from the recorded cwd, bounds per-file reads and current global occupancy across the main spool and recovery directories, sweeps completed tombstones, and holds correlated events outside drain until replay succeeds or restores them on failure; degraded resumes use `ai-memory-workstream`'s adapter-validated delta export, whose blocking parse and baseline scans are capped by record, event-count, source-byte and serialized-byte totals; `backfill::import_exact_session` chunks by item and byte limits and requires per-item durable acknowledgements; `run.rs` journals every session launch, including explicit spool-only evidence for unsupported exporters, and journals a resumed export only after capturing its exact pre-launch cursor; `workstream.rs` `/recover/finish` retains owner/project authorization, rejects superseded runs, and validates a finished retry by durable transcript/native/cursor/exit identity without regenerating its checkpoint; validated recovery ingest keys bind session, agent, event kind and sanitized event identity until session purge | `transcript.rs` `persisted_baseline_exports_only_offline_append_and_rejects_rewrite`, parser/baseline cap and ordered-semantic digest tests; CLI `run_offline.rs` real degraded spool-only and overlap/idempotency tests; `recovery.rs` `spool_only_without_correlated_evidence_never_auto_clears`, `a_dropped_spool_event_stays_lost_on_the_next_empty_pass`, loss/time-budget tests, `symlinked_journal_and_ancestor_are_refused`, `a_symlinked_ancestor_of_the_data_dir_is_trusted`, `a_symlink_inside_a_data_dir_under_a_symlinked_ancestor_is_refused`; `hook_spool.rs` partial-scope late enqueue, completion-race, occupancy churn/active-cap, bounded-read and tombstone-sweep tests, plus interval isolation (`completed_tombstone_keeps_a_later_resume_of_the_same_session` proves a post-interval resume hook is delivered, `completing_one_recovery_interval_leaves_the_other_intervals_entries_intact` proves one interval's completion never consumes another's evidence and ambiguous entries fail closed into the main spool); `backfill.rs` `two_sequential_recovery_intervals_on_one_resumed_session_replay_exactly_once` proves the second interval's content and session-end are stored with end-of-session effects while reruns stay pure replays; `transcript.rs` `an_oversized_first_record_is_skipped_by_session_listing_caps` proves the first-record byte caps bite before allocation; store `insert_observation_ingest_dedups_on_key` rejects cross-session and changed-event preclaims; hooks `expired_run_recovery_is_owner_only_and_refuses_superseded_runs` proves changed transcript refusal and changed-checkpoint no-op | STRONG on Unix integration coverage; Unix lock opens use no-follow and atomic replacement rechecks the destination. Windows owner-only ACL/reparse and lock semantics require the PR `windows` lane || 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |-| 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile; `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the `ai-memory mcp-bridge` stdio entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every literal-header client is refused), `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`; `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp` for Claude Code and Codex, a refused Cursor install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, `default` profile, env token); `install_mcp.rs` `a_file_sourced_token_is_wired_without_entering_any_harness_config`, `a_file_sourced_token_refuses_literal_header_clients`, `inline_and_explicit_tokens_still_embed_as_before` (control); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config`, `enable_leaves_a_claude_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential` | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); a client that only takes a literal header is refused rather than wired, so it needs a manual entry |+| 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile; `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the session-aware `ai-memory mcp-bridge` entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every other client a `stdio_bridge_entry` that runs `mcp-bridge --no-session-id` in its documented stdio shape, Pi keeps its extension, ZCode (HTTP-only) is refused) and `mcp_bridge.rs`, which authenticates with the config-resolved bearer and connects upstream before serving stdio, so a refused token ends it with `401 Unauthorized` instead of hanging; `uninstall.rs` `mcp_entry_is_ours` / `toml_mcp_entry_targets` recognise bridge entries by `install_mcp::bridge_entry_url`; `auth_enable.rs` `rewire_clients` re-registers every client whose entry targets this server, `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`; `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp --apply` for every client it writes (21, by default config path under the test home), a refused ZCode install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, `default` profile, env token); `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (`tools/list` and a scoped `memory_query` through `mcp-bridge --no-session-id` against a fresh auth-on server, the token in neither the bridge's `/proc/<pid>/cmdline` nor its `/proc/<pid>/environ`; control: the session-aware mode still refuses to start without `CLAUDE_CODE_SESSION_ID`) and `a_bridge_without_the_token_is_refused_cleanly_not_hung` (exits promptly naming `401 Unauthorized`); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id`, `a_session_less_upstream_config_carries_no_session_header`, `stdio_bridge_forwards_tools_and_session_header_in_both_http_modes` (control); `install_mcp.rs` `a_file_sourced_token_wires_every_client_without_entering_its_config` (every written client: no token, no header, an entry that reaches the server; ZCode refused and unwritten), `stdio_bridge_entries_follow_each_clients_documented_shape`, `inline_and_explicit_tokens_still_embed_as_before` (control); `uninstall.rs` `bridge_entries_are_recognised_by_their_upstream_url` (JSON, OpenCode array and TOML shapes; a bridge to another server and a foreign command are kept); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config` (every client pre-wired over HTTP is re-registered, ZCode reported as manual, the second run byte-identical), `enable_leaves_an_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential` | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with `route_file_token` no longer choosing the stdio bridge the every-client and `auth enable` tests fail; with `auth enable` skipping the re-registration its test fails; with the session-less mode forwarding an inherited id the bridge unit test fails; without the 401 naming the refusal e2e fails; without bridge-entry recognition the uninstall test fails; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); ZCode takes only HTTP entries and is refused, so it needs a manual entry; the stdio entries for Zero, Muse Code and DeepSeek Harness follow their documented or source-level format but were not run against those clients || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten || 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op || 12d | The web UI and `/api/v1` cannot write, and render stored text inert | `crates/ai-memory-web/clippy.toml` `disallowed-methods`: every `Wiki` write and destructive method (`write_page`, `write_page_if`, `apply_batch`, the delete/evict/purge/restore/move/reindex/remove-dir helpers, `commit_all`, `approve_auto_improve_proposal`) and the `writer()` / `git()` accessors are lint errors in the crate, so the `Wiki` held by `WebState` stays read-only under `cargo clippy -D warnings`; only the integration-test module carries the `allow`, for fixtures. Templates are askama with HTML auto-escaping; the history diff (`templates/history.html`) and the session timeline (`templates/session.html`) print page lines, observation titles and bodies escaped, with no `|safe`, and no captured value is interpolated into a script | `ai-memory-web` `history_replay.rs` `session_timeline_renders_captured_markup_inert` (a `<script>` title and body plus `"><img onerror>` and `' onmouseover='` payloads, checked to survive ingest first, render escaped) and `history_diff_renders_page_markup_inert` (the same payloads in a page version's diff lines); `mount.rs` `web_surfaces_refuse_to_be_framed` covers the history, timeline and history-API routes (200 with both anti-framing headers) | STRONG. Bite checks: a `Wiki::write_page` and a `Wiki::delete_page` call added to `routes/history.rs` fail `cargo clippy -p ai-memory-web --all-targets -- -D warnings` with `use of a disallowed method`; `|safe` on the observation body or a diff line fails the matching inert-render test. The lint is per crate: a write reached through another crate's helper is outside it, which review and the `/api/v1` "zero writer calls" rule still cover |diff --git a/docs/security.md b/docs/security.mdindex 10548b12..93d7e7c5 100644--- a/docs/security.md+++ b/docs/security.md@@ -7,16 +7,19 @@ dir writes a random root bearer to `<data_dir>/auth-tokens/default` (owneronly) and records `[auth].bearer_token_file`; the server then refuses everyroute except `/healthz` without it. The hooks, the CLI and the`ai-memory mcp-bridge` stdio bridge read it from the data dir, so the token is-never pasted into a harness config or passed on a command line. Codex and-Prime Agent reference it as `$AI_MEMORY_AUTH_TOKEN`; MCP clients that only-take a literal header are not registered automatically.+never pasted into a harness config or passed on a command line. Claude Code+runs the session-aware bridge, Codex and Prime Agent reference the token as+`$AI_MEMORY_AUTH_TOKEN`, and every other MCP client `install-mcp` supports+runs `ai-memory mcp-bridge --no-session-id` as a local stdio server. ZCode,+which takes only HTTP entries, is the exception and needs a manual entry.An install created before this default keeps its loopback-only(`127.0.0.1:49374`), no-auth behaviour. That stays safe from the network, butevery local process and browser page can reach the server. `ai-memory status`and `ai-memory doctor` show `auth: none (loopback)` with the fix,`ai-memory auth enable`, which mints the token, records it in config, gives-the hooks the token and re-registers Claude Code through the bridge. Restart+the hooks the token and re-registers every MCP client that points at this+server. Restartthe server afterwards.Unauthenticated non-loopback HTTP now fails closed. Set