Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
M16: bearer-token auth + body limits + symlink filter
AkitaOnRailsa861ec3d5988
diff --git a/Cargo.lock b/Cargo.lockindex 275bcc80..e174aed7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -46,15 +46,18 @@ dependencies = ["dirs","figment","flate2",+ "getrandom 0.3.4","rmcp","secrecy","serde","serde_json",+ "subtle","sysinfo","tar","tempfile","tokio","tokio-util",+ "tower","tracing","tracing-appender","tracing-subscriber",diff --git a/Cargo.toml b/Cargo.tomlindex 27fd85c9..e175909e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -58,8 +58,10 @@ figment = { version = "0.10", features = ["toml", "env"] }clap = { version = "4", features = ["derive", "env"] }dirs = "5"-# Secrets.+# Secrets + constant-time / RNG primitives for bearer-token auth.secrecy = { version = "0.10", features = ["serde"] }+subtle = "2"+getrandom = "0.3"# Storage.rusqlite = { version = "0.32", features = ["bundled", "backup"] }@@ -76,6 +78,8 @@ sysinfo = "0.32"rmcp = { version = "1.7", features = ["server", "macros", "transport-io", "transport-streamable-http-server", "schemars"] }schemars = "1"axum = "0.8"+# Direct dep so tests can use `Router::oneshot` via `ServiceExt`.+tower = { version = "0.5", features = ["util"] }# Backup / restore archive format.tar = "0.4"diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.tomlindex 1808979b..e5b59c2d 100644--- a/crates/ai-memory-cli/Cargo.toml+++ b/crates/ai-memory-cli/Cargo.toml@@ -21,6 +21,8 @@ ai-memory-mcp.workspace = trueai-memory-store.workspace = trueai-memory-wiki.workspace = truesecrecy.workspace = true+subtle.workspace = true+getrandom.workspace = trueanyhow.workspace = trueaxum.workspace = trueclap.workspace = true@@ -42,6 +44,7 @@ tempfile.workspace = true[dev-dependencies]tempfile.workspace = true+tower.workspace = true[lints]workspace = truediff --git a/crates/ai-memory-cli/src/auth.rs b/crates/ai-memory-cli/src/auth.rsnew file mode 100644index 00000000..f47287ba--- /dev/null+++ b/crates/ai-memory-cli/src/auth.rs@@ -0,0 +1,261 @@+//! Bearer-token authorization middleware for the HTTP server.+//!+//! When `[auth].bearer_token` (or the `AI_MEMORY_AUTH_TOKEN` env var)+//! is set, every request to `/mcp`, `/hook`, and `/handoff` must+//! carry an `Authorization: Bearer <token>` header that matches.+//!+//! When the token is *unset*, the middleware is a no-op — preserving+//! the zero-config local-development experience and keeping the+//! existing e2e + unit tests working.+//!+//! Comparison uses [`subtle::ConstantTimeEq`] so an attacker on the+//! same LAN cannot use response-time leaks to recover the token byte+//! by byte. The constant-time guarantee depends on both sides being+//! the same length; `subtle` returns a constant-cost `Choice::from(0)`+//! when lengths differ, which is the right thing here.+//!+//! Wire shape matches the MCP authorization spec+//! (modelcontextprotocol.io/specification/.../basic/authorization):+//! 401 responses include a `WWW-Authenticate: Bearer …` header so+//! conformant clients can detect missing/expired credentials.+//!+//! ## Why not OAuth+//!+//! The MCP spec mandates full OAuth 2.1 for HTTP-authenticated+//! servers. That's overkill for a single-user homelab and would+//! force every MCP client config to deal with authorization-server+//! discovery + PKCE + token refresh. A static bearer token is+//! wire-compatible with the spec's `Authorization: Bearer …` shape+//! (clients send the header the same way; they just don't run the+//! OAuth dance to obtain the token). Every supported client+//! (Claude Code, Codex, OpenCode, Cursor, Claude Desktop via+//! `mcp-remote`, Gemini CLI, OpenClaw) accepts a static+//! `Authorization` header in its config.++use std::sync::Arc;++use axum::extract::State;+use axum::http::{Request, StatusCode, header};+use axum::middleware::Next;+use axum::response::{IntoResponse, Response};+use subtle::ConstantTimeEq;+use tracing::debug;++/// Shared auth state. Cheap to clone — just an `Arc` wrapping the+/// optional configured token.+#[derive(Clone, Debug)]+pub struct AuthState {+ expected: Option<String>,+}++impl AuthState {+ /// Build state from the (optional) configured token. `None` means+ /// "auth disabled, accept everything".+ #[must_use]+ pub fn new(expected: Option<String>) -> Self {+ Self { expected }+ }++ /// True when a token is configured (i.e. the middleware is doing+ /// anything). Useful for the startup log line so the operator+ /// sees whether their server is open or closed.+ #[must_use]+ pub fn enabled(&self) -> bool {+ self.expected.is_some()+ }+}++/// axum middleware closure. Wire with+/// `axum::middleware::from_fn_with_state(state, require_bearer)`.+pub async fn require_bearer(+ State(state): State<Arc<AuthState>>,+ req: Request<axum::body::Body>,+ next: Next,+) -> Response {+ let Some(expected) = state.expected.as_deref() else {+ return next.run(req).await;+ };++ let provided = req+ .headers()+ .get(header::AUTHORIZATION)+ .and_then(|h| h.to_str().ok())+ .and_then(|h| {+ // Accept both "Bearer xxx" and "bearer xxx" (case-insensitive+ // scheme per RFC 7235 §2.1).+ let (scheme, value) = h.split_once(' ')?;+ if scheme.eq_ignore_ascii_case("Bearer") {+ Some(value.trim_start())+ } else {+ None+ }+ })+ .unwrap_or("");++ if provided.as_bytes().ct_eq(expected.as_bytes()).into() {+ next.run(req).await+ } else {+ debug!("auth rejected: invalid or missing bearer token");+ unauthorized()+ }+}++fn unauthorized() -> Response {+ let mut resp = (StatusCode::UNAUTHORIZED, "auth required\n").into_response();+ resp.headers_mut().insert(+ header::WWW_AUTHENTICATE,+ // MCP spec wants this header; clients use it to disambiguate+ // "missing token" from "wrong token" and surface a helpful+ // diagnostic. The `realm` is informational.+ "Bearer realm=\"ai-memory\", error=\"invalid_token\""+ .parse()+ .expect("static header value is valid"),+ );+ resp+}++/// Generate a fresh random bearer token, hex-encoded.+///+/// `bytes` is the entropy budget; 32 bytes (256 bits) is plenty for+/// any conceivable threat model.+///+/// # Errors+/// Propagates failures from the OS RNG.+pub fn generate_token_hex(bytes: usize) -> Result<String, getrandom::Error> {+ let mut buf = vec![0u8; bytes];+ getrandom::fill(&mut buf)?;+ Ok(hex_encode(&buf))+}++fn hex_encode(bytes: &[u8]) -> String {+ const HEX: &[u8; 16] = b"0123456789abcdef";+ let mut s = String::with_capacity(bytes.len() * 2);+ for &b in bytes {+ s.push(HEX[(b >> 4) as usize] as char);+ s.push(HEX[(b & 0x0f) as usize] as char);+ }+ s+}++#[cfg(test)]+mod tests {+ use super::*;+ use axum::Router;+ use axum::body::Body;+ use axum::http::Request;+ use axum::routing::get;+ use tower::ServiceExt;++ fn router_with_auth(token: Option<&str>) -> Router {+ let state = Arc::new(AuthState::new(token.map(str::to_string)));+ Router::new()+ .route("/probe", get(|| async { "ok" }))+ .layer(axum::middleware::from_fn_with_state(state, require_bearer))+ }++ #[tokio::test]+ async fn no_token_configured_passes_anything_through() {+ let r = router_with_auth(None);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn missing_header_returns_401_with_www_authenticate() {+ let r = router_with_auth(Some("secret"));+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ let www = resp.headers().get(header::WWW_AUTHENTICATE).unwrap();+ assert!(www.to_str().unwrap().contains("Bearer"));+ }++ #[tokio::test]+ async fn wrong_token_returns_401() {+ let r = router_with_auth(Some("the-right-one"));+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-wrong-one")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ }++ #[tokio::test]+ async fn right_token_returns_200() {+ let r = router_with_auth(Some("right-token"));+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer right-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn lowercase_scheme_is_accepted() {+ let r = router_with_auth(Some("right-token"));+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "bearer right-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn non_bearer_scheme_is_rejected() {+ let r = router_with_auth(Some("right-token"));+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Basic dXNlcjpwYXNz")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ }++ #[test]+ fn generated_token_is_hex_and_correct_length() {+ let t = generate_token_hex(32).unwrap();+ assert_eq!(t.len(), 64);+ assert!(t.chars().all(|c| c.is_ascii_hexdigit()));+ // Distinct calls produce distinct tokens (modulo OS RNG bugs).+ let t2 = generate_token_hex(32).unwrap();+ assert_ne!(t, t2);+ }+}diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex fac0bc09..a398ff46 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -61,6 +61,18 @@ pub enum Command {Lint(LintArgs),/// Compute + store embeddings for every latest page (M9).Embed(EmbedArgs),+ /// Generate a random hex bearer token for AI_MEMORY_AUTH_TOKEN.+ GenerateAuthToken(GenerateAuthTokenArgs),+}++/// Arguments for `generate-auth-token`.+#[derive(Debug, Args)]+pub struct GenerateAuthTokenArgs {+ /// Number of random bytes of entropy. The token printed is hex-+ /// encoded, so the output length is 2× this value. 32 bytes+ /// (256 bits) is plenty for any homelab threat model.+ #[arg(long, default_value_t = 32)]+ pub bytes: usize,}/// Arguments for `init`.@@ -262,6 +274,12 @@ pub struct InstallHooksArgs {/// Server URL the hooks will POST to.#[arg(long, default_value = "http://127.0.0.1:49374")]pub server_url: String,+ /// Bearer token to embed in the hook config's `env` block. When+ /// set, every hook call carries `Authorization: Bearer <token>`,+ /// matching what the server requires when AI_MEMORY_AUTH_TOKEN+ /// is set there. Generate one with `ai-memory generate-auth-token`.+ #[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]+ pub auth_token: Option<String>,}/// Arguments for `install-mcp`.@@ -276,6 +294,12 @@ pub struct InstallMcpArgs {/// Friendly name the client should show for this server entry.#[arg(long, default_value = "ai-memory")]pub name: String,+ /// Bearer token to embed in the client config. When set, the+ /// rendered snippet includes an `Authorization: Bearer <token>`+ /// header so the client can authenticate against a server that+ /// requires it. Picked up from `AI_MEMORY_AUTH_TOKEN` if unset.+ #[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]+ pub auth_token: Option<String>,}/// Transport for the MCP server.diff --git a/crates/ai-memory-cli/src/commands/generate_auth_token.rs b/crates/ai-memory-cli/src/commands/generate_auth_token.rsnew file mode 100644index 00000000..373b9d88--- /dev/null+++ b/crates/ai-memory-cli/src/commands/generate_auth_token.rs@@ -0,0 +1,28 @@+//! `ai-memory generate-auth-token` — print a random bearer token.+//!+//! Operator workflow:+//! $ ai-memory generate-auth-token >> docker/.env.production+//! $ $EDITOR docker/.env.production # prefix with AI_MEMORY_AUTH_TOKEN=+//!+//! The token is read from `AI_MEMORY_AUTH_TOKEN` (or+//! `[auth].bearer_token` in config.toml) at server startup and+//! validated on every HTTP request via the middleware in `auth.rs`.++use anyhow::Result;++use crate::auth::generate_token_hex;+use crate::cli::GenerateAuthTokenArgs;+use crate::config::Config;++/// Run the `generate-auth-token` subcommand.+///+/// # Errors+/// Propagates failures from the OS RNG.+pub fn run(_config: &Config, args: GenerateAuthTokenArgs) -> Result<()> {+ // getrandom::Error in 0.3 doesn't implement std::error::Error, so+ // anyhow's Context trait doesn't apply. Map manually.+ let token = generate_token_hex(args.bytes)+ .map_err(|e| anyhow::anyhow!("generating random token: {e}"))?;+ println!("{token}");+ Ok(())+}diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 2c768b6a..ad58ca64 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -21,17 +21,31 @@ use crate::config::Config;/// Returns an error if the hook script directory cannot be located.pub fn run(_config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ let auth = args.auth_token.as_deref();match args.agent {- AgentChoice::ClaudeCode => render_claude_code(&hooks_dir, &args.server_url),- AgentChoice::Codex => render_agent("codex", &hooks_dir, &args.server_url),- AgentChoice::OpenCode => render_agent("opencode", &hooks_dir, &args.server_url),+ AgentChoice::ClaudeCode => render_claude_code(&hooks_dir, &args.server_url, auth),+ AgentChoice::Codex => render_agent("codex", &hooks_dir, &args.server_url, auth),+ AgentChoice::OpenCode => render_agent("opencode", &hooks_dir, &args.server_url, auth),}}-fn render_agent(label: &str, hooks_dir: &Path, server_url: &str) -> Result<()> {+fn render_agent(+ label: &str,+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+) -> Result<()> {println!("# {label} hook scripts (manual install — wire each to the matching event)");println!("# Hook scripts: {}", hooks_dir.display());println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: set AI_MEMORY_AUTH_TOKEN in each hook's environment to the");+ println!("# value passed via --auth-token (omitted from this printout).");+ } else {+ println!("# Auth: server requires no bearer token. To require one, generate a");+ println!("# token with `ai-memory generate-auth-token` and pass it via");+ println!("# --auth-token here AND set AI_MEMORY_AUTH_TOKEN on the server.");+ }println!();for entry in std::fs::read_dir(hooks_dir)? {let entry = entry?;@@ -88,7 +102,7 @@ fn repo_root_guess() -> Option<PathBuf> {.and_then(|p| p.parent()?.parent()?.parent().map(Path::to_path_buf))}-fn render_claude_code(hooks_dir: &Path, server_url: &str) -> Result<()> {+fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&str>) -> Result<()> {let scripts: [(&str, &str); 7] = [("SessionStart", "session-start.sh"),("UserPromptSubmit", "user-prompt-submit.sh"),@@ -105,11 +119,26 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str) -> Result<()> {if !abs.exists() {anyhow::bail!("missing hook script: {}", abs.display());}+ // The env block is passed to the hook command by Claude Code.+ // We always include AI_MEMORY_HOOK_URL; when an auth token is+ // configured, we also include AI_MEMORY_AUTH_TOKEN so the+ // hook scripts can forward it as `Authorization: Bearer …`.+ let mut env = serde_json::Map::new();+ env.insert(+ "AI_MEMORY_HOOK_URL".into(),+ serde_json::Value::String(server_url.to_string()),+ );+ if let Some(t) = auth_token {+ env.insert(+ "AI_MEMORY_AUTH_TOKEN".into(),+ serde_json::Value::String(t.to_string()),+ );+ }hooks_block.insert(event.into(),json!([{"command": abs.to_string_lossy().into_owned(),- "env": { "AI_MEMORY_HOOK_URL": server_url },+ "env": env,}]),);}@@ -120,6 +149,10 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str) -> Result<()> {println!("# Claude Code hook config — merge into ~/.claude/settings.json");println!("# Hook scripts: {}", hooks_dir.display());println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook's env block below.");+ println!("# Treat ~/.claude/settings.json as sensitive (chmod 600).");+ }println!();println!("{serialized}");Ok(())diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex f2a08b56..37c6f555 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -41,59 +41,96 @@ pub fn run(_config: &Config, args: InstallMcpArgs) -> Result<()> {Ok(())}+/// Render an `Authorization: Bearer <token>` header value if a token+/// is set; returns `None` otherwise. Centralised so every renderer+/// makes the same choice.+fn bearer_header_value(args: &InstallMcpArgs) -> Option<String> {+ args.auth_token.as_deref().map(|t| format!("Bearer {t}"))+}+fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {+ let bearer = bearer_header_value(args);+ let cli_line = if let Some(b) = &bearer {+ format!(+ "claude mcp add --transport http {name} {url} \\\n --header \"Authorization: {b}\"",+ name = args.name,+ url = args.server_url,+ b = b,+ )+ } else {+ format!(+ "claude mcp add --transport http {name} {url}",+ name = args.name,+ url = args.server_url,+ )+ };+ let mut entry = serde_json::Map::new();+ entry.insert("type".into(), json!("http"));+ entry.insert("url".into(), json!(args.server_url));+ if let Some(b) = &bearer {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }+ let snippet = serde_json::to_string_pretty(&json!({+ "mcpServers": { args.name.as_str(): entry }+ }))?;Ok(format!("# Claude Code — register the MCP server\n\#\n\# Recommended (one-shot CLI):\n\- claude mcp add --transport http {name} {url}\n\+ {cli_line}\n\#\n\# Equivalent JSON if you'd rather edit settings directly\n\# (~/.claude/settings.json):\n\- {snippet}\n",- name = args.name,- url = args.server_url,- snippet = serde_json::to_string_pretty(&json!({- "mcpServers": {- args.name.as_str(): {- "type": "http",- "url": args.server_url,- }- }- }))?,+ {snippet}\n"))}fn render_codex(args: &InstallMcpArgs) -> String {// Codex uses TOML, not JSON. Hand-render the snippet so the// table headers stay deterministic.- format!(+ let mut out = format!("# Codex CLI — append to ~/.codex/config.toml\n\#\n\[mcp_servers.{name}]\n\url = \"{url}\"\n",name = args.name,url = args.server_url,- )+ );+ if let Some(b) = bearer_header_value(args) {+ out.push_str(&format!(+ "\n# Codex passes [mcp_servers.<name>.headers] verbatim:\n\+ [mcp_servers.{name}.headers]\n\+ Authorization = \"{b}\"\n",+ name = args.name,+ b = b,+ ));+ }+ out}fn render_opencode(args: &InstallMcpArgs) -> Result<String> {+ let mut entry = serde_json::Map::new();+ entry.insert("type".into(), json!("remote"));+ entry.insert("url".into(), json!(args.server_url));+ entry.insert("enabled".into(), json!(true));+ if let Some(b) = bearer_header_value(args) {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }Ok(format!("# OpenCode — add to ~/.config/opencode/opencode.json under \"mcp\":\n\{snippet}\n",snippet = serde_json::to_string_pretty(&json!({- "mcp": {- args.name.as_str(): {- "type": "remote",- "url": args.server_url,- "enabled": true,- }- }+ "mcp": { args.name.as_str(): entry }}))?,))}fn render_cursor(args: &InstallMcpArgs) -> Result<String> {+ let mut entry = serde_json::Map::new();+ entry.insert("url".into(), json!(args.server_url));+ if let Some(b) = bearer_header_value(args) {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }Ok(format!("# Cursor — write to one of:\n\# - ~/.cursor/mcp.json (global, all projects)\n\@@ -105,16 +142,19 @@ fn render_cursor(args: &InstallMcpArgs) -> Result<String> {# is still flaky.\n\{snippet}\n",snippet = serde_json::to_string_pretty(&json!({- "mcpServers": {- args.name.as_str(): {- "url": args.server_url,- }- }+ "mcpServers": { args.name.as_str(): entry }}))?,))}fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {+ // mcp-remote's --header flag is how we plumb the Authorization+ // through Claude Desktop's stdio-only config.+ let mut cmd_args = vec![json!("-y"), json!("mcp-remote"), json!(args.server_url)];+ if let Some(b) = bearer_header_value(args) {+ cmd_args.push(json!("--header"));+ cmd_args.push(json!(format!("Authorization: {b}")));+ }Ok(format!("# Claude Desktop — write to claude_desktop_config.json:\n\# - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json\n\@@ -132,7 +172,7 @@ fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {"mcpServers": {args.name.as_str(): {"command": "npx",- "args": ["-y", "mcp-remote", args.server_url.as_str()],+ "args": cmd_args,}}}))?,@@ -140,6 +180,12 @@ fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {}fn render_gemini_cli(args: &InstallMcpArgs) -> Result<String> {+ let mut entry = serde_json::Map::new();+ entry.insert("httpUrl".into(), json!(args.server_url));+ entry.insert("timeout".into(), json!(5000));+ if let Some(b) = bearer_header_value(args) {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }Ok(format!("# Gemini CLI — merge into ~/.gemini/settings.json:\n\#\n\@@ -147,17 +193,18 @@ fn render_gemini_cli(args: &InstallMcpArgs) -> Result<String> {# endpoints. The `timeout` is in milliseconds.\n\{snippet}\n",snippet = serde_json::to_string_pretty(&json!({- "mcpServers": {- args.name.as_str(): {- "httpUrl": args.server_url,- "timeout": 5000,- }- }+ "mcpServers": { args.name.as_str(): entry }}))?,))}fn render_openclaw(args: &InstallMcpArgs) -> Result<String> {+ let mut entry = serde_json::Map::new();+ entry.insert("url".into(), json!(args.server_url));+ entry.insert("transport".into(), json!("streamable-http"));+ if let Some(b) = bearer_header_value(args) {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }Ok(format!("# OpenClaw — merge into ~/.openclaw/config.json:\n\#\n\@@ -165,14 +212,7 @@ fn render_openclaw(args: &InstallMcpArgs) -> Result<String> {# \"transport\": \"streamable-http\" for ai-memory's HTTP endpoint.\n\{snippet}\n",snippet = serde_json::to_string_pretty(&json!({- "mcp": {- "servers": {- args.name.as_str(): {- "url": args.server_url,- "transport": "streamable-http",- }- }- }+ "mcp": { "servers": { args.name.as_str(): entry } }}))?,))}@@ -208,6 +248,52 @@ mod tests {client,server_url: "http://127.0.0.1:49374/mcp".into(),name: "ai-memory".into(),+ auth_token: None,+ }+ }++ fn args_with_token(client: McpClient) -> InstallMcpArgs {+ InstallMcpArgs {+ client,+ server_url: "http://127.0.0.1:49374/mcp".into(),+ name: "ai-memory".into(),+ auth_token: Some("test-token-deadbeef".into()),+ }+ }++ fn render_with_token(client: McpClient) -> String {+ let args = args_with_token(client);+ match args.client {+ McpClient::ClaudeCode => render_claude_code(&args).unwrap(),+ McpClient::Codex => render_codex(&args),+ McpClient::OpenCode => render_opencode(&args).unwrap(),+ McpClient::Cursor => render_cursor(&args).unwrap(),+ McpClient::ClaudeDesktop => render_claude_desktop(&args).unwrap(),+ McpClient::GeminiCli => render_gemini_cli(&args).unwrap(),+ McpClient::Openclaw => render_openclaw(&args).unwrap(),+ McpClient::Pi => render_pi_explanation(&args),+ }+ }++ /// With `--auth-token` set, every non-pi renderer must embed the+ /// Bearer header in its output. pi prints the same non-support+ /// message regardless.+ #[test]+ fn auth_token_threaded_into_every_client() {+ for client in [+ McpClient::ClaudeCode,+ McpClient::Codex,+ McpClient::OpenCode,+ McpClient::Cursor,+ McpClient::ClaudeDesktop,+ McpClient::GeminiCli,+ McpClient::Openclaw,+ ] {+ let out = render_with_token(client);+ assert!(+ out.contains("Bearer test-token-deadbeef"),+ "client {client:?} did not embed the bearer token:\n{out}"+ );}}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 70631813..81f0458f 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -4,6 +4,7 @@ pub mod backup;pub mod commit;pub mod embed;pub mod forget_sweep;+pub mod generate_auth_token;pub mod init;pub mod install_hooks;pub mod install_mcp;diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 7a7169a8..0e1c942b 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -10,6 +10,7 @@ use ai_memory_mcp::AiMemoryServer;use ai_memory_store::Store;use ai_memory_wiki::{WatcherHandle, Wiki};use anyhow::{Context, Result};+use axum::extract::DefaultBodyLimit;use rmcp::ServiceExt;use rmcp::transport::stdio;use rmcp::transport::streamable_http_server::{@@ -18,9 +19,18 @@ use rmcp::transport::streamable_http_server::{use tokio_util::sync::CancellationToken;use tracing::info;+use crate::auth::{AuthState, require_bearer};use crate::cli::{ServeArgs, TransportKind};use crate::config::Config;+/// 10 MB cap on inbound HTTP bodies. The /hook ingress accepts the+/// agent's raw payload which can include a tool output excerpt+/// (capped at 2 KB on our side via `truncate_excerpt`), but Claude+/// Code et al. send the full envelope, which can run to a few KB.+/// 10 MB is generous headroom; without a cap, axum streams unbounded+/// bodies into memory (audit critical #2).+const MAX_BODY_BYTES: usize = 10 * 1024 * 1024;+/// Run the `serve` subcommand.////// # Errors@@ -146,16 +156,48 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {consolidator: consolidator.clone(),sanitizer: sanitizer.clone(),});+ // Build the auth state. Precedence (highest first):+ // 1. AI_MEMORY_AUTH_TOKEN env var+ // 2. config.toml [auth].bearer_token+ // 3. neither → open mode (no auth)+ // Read env directly (not via figment) to match the pattern+ // used by AI_MEMORY_LLM_* in factory.rs — keeps the+ // operator's mental model simple.+ let token = std::env::var("AI_MEMORY_AUTH_TOKEN")+ .ok()+ .filter(|s| !s.is_empty())+ .or_else(|| config.auth.bearer_token.clone());+ let auth_state = Arc::new(AuthState::new(token));+ let auth_enabled = auth_state.enabled();let router = axum::Router::new().nest_service("/mcp", mcp_service)- .merge(hooks);+ .merge(hooks)+ .layer(axum::middleware::from_fn_with_state(+ auth_state,+ require_bearer,+ ))+ .layer(DefaultBodyLimit::max(MAX_BODY_BYTES));let listener = tokio::net::TcpListener::bind(&bind).await.with_context(|| format!("binding {bind}"))?;info!(%bind,+ auth = auth_enabled,+ body_limit_mb = MAX_BODY_BYTES / 1024 / 1024,"MCP HTTP server ready (POST /mcp, POST /hook, Ctrl-C to stop)",);+ if !auth_enabled && !bind.starts_with("127.") {+ // Loud warning: a non-loopback bind with no auth is+ // the audit's critical-#1 scenario. The operator gets+ // a one-line "you sure?" instead of silent exposure.+ tracing::warn!(+ %bind,+ "no AI_MEMORY_AUTH_TOKEN configured AND binding to a non-loopback \+ address — anyone on the network can call destructive MCP tools. \+ Generate a token with `ai-memory generate-auth-token` and set \+ AI_MEMORY_AUTH_TOKEN in the server's environment."+ );+ }axum::serve(listener, router).with_graceful_shutdown(async move {let _ = tokio::signal::ctrl_c().await;diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex b03017f0..b1b5fcc8 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -42,6 +42,23 @@ pub struct Config {/// Privacy-strip tuning. Built-in patterns always run; this section/// lets the operator extend or punch holes in them.pub sanitize: ai_memory_core::SanitizeConfig,+ /// Bearer token required on every HTTP request. When `None`/unset,+ /// the server runs open (zero-config local-dev behaviour). When set,+ /// requests to /mcp + /hook + /handoff must carry+ /// `Authorization: Bearer <token>`. Settable via the+ /// `AI_MEMORY_AUTH_TOKEN` env var or `[auth].bearer_token` in+ /// config.toml.+ pub auth: AuthSettings,+}++/// `[auth]` section of `config.toml`.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(default)]+pub struct AuthSettings {+ /// Shared bearer token. When set, all HTTP routes require+ /// `Authorization: Bearer <token>`. Generate one with+ /// `ai-memory generate-auth-token`.+ pub bearer_token: Option<String>,}impl Default for Config {@@ -52,6 +69,7 @@ impl Default for Config {log_level: "info".into(),decay: ai_memory_store::DecayParams::default(),sanitize: ai_memory_core::SanitizeConfig::default(),+ auth: AuthSettings::default(),}}}diff --git a/crates/ai-memory-cli/src/logging.rs b/crates/ai-memory-cli/src/logging.rsindex a5c511c3..cddb4029 100644--- a/crates/ai-memory-cli/src/logging.rs+++ b/crates/ai-memory-cli/src/logging.rs@@ -8,7 +8,7 @@use std::fs;-use anyhow::{Context, Result};+use anyhow::Result;use tracing_appender::non_blocking::WorkerGuard;use tracing_appender::rolling::{RollingFileAppender, Rotation};use tracing_subscriber::EnvFilter;@@ -26,10 +26,18 @@ use crate::config::Config;/// Returns an error if the log directory cannot be created.pub fn init(config: &Config) -> Result<WorkerGuard> {let log_dir = config.data_dir.join("logs");- fs::create_dir_all(&log_dir)- .with_context(|| format!("creating log directory {}", log_dir.display()))?;-- let appender = RollingFileAppender::new(Rotation::DAILY, &log_dir, "ai-memory.log");+ // If the data dir doesn't exist yet (e.g. user hasn't run+ // `ai-memory init` and is calling a pure-stdout subcommand like+ // `generate-auth-token`), fall back to a tempdir-backed appender+ // so the binary still works. The server's `serve` subcommand+ // explicitly creates the data dir before this point in practice,+ // so this fallback only kicks in for one-shot commands.+ let appender_dir = match fs::create_dir_all(&log_dir) {+ Ok(()) => log_dir,+ Err(_) => std::env::temp_dir(),+ };++ let appender = RollingFileAppender::new(Rotation::DAILY, &appender_dir, "ai-memory.log");let (file_writer, guard) = tracing_appender::non_blocking(appender);let default_filter = format!("{},tracing_appender=warn", config.log_level);diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex c193fa2b..87959152 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -13,6 +13,7 @@ use anyhow::Result;use clap::Parser;use tracing::info;+mod auth;mod cli;mod commands;mod config;@@ -53,5 +54,6 @@ async fn main() -> Result<()> {Command::ForgetSweep(args) => commands::forget_sweep::run(&config, args).await,Command::Lint(args) => commands::lint::run(&config, args).await,Command::Embed(args) => commands::embed::run(&config, args).await,+ Command::GenerateAuthToken(args) => commands::generate_auth_token::run(&config, args),}}diff --git a/crates/ai-memory-wiki/src/watcher.rs b/crates/ai-memory-wiki/src/watcher.rsindex 7d3fd578..5567bceb 100644--- a/crates/ai-memory-wiki/src/watcher.rs+++ b/crates/ai-memory-wiki/src/watcher.rs@@ -203,6 +203,15 @@ fn walk_markdown(root: &Path) -> WikiResult<Vec<PagePath>> {let entry = entry?;let path = entry.path();let ft = entry.file_type()?;+ // Skip symlinks entirely. An attacker with write access to+ // the wiki/ dir could otherwise plant a symlink to /etc/hosts,+ // /home/user/.ssh/id_ed25519 etc. and have the watcher+ // index the target's content. The sanitiser would still+ // scrub credentials, but we'd be reading files we+ // shouldn't be reading. (Audit critical #3.)+ if ft.is_symlink() {+ continue;+ }if ft.is_dir() {stack.push(path);} else if ft.is_file()@@ -314,4 +323,34 @@ mod tests {let q = Path::new("/some/dir/normal.md");assert!(!is_tempfile(q));}++ /// Defence: an attacker who can write to wiki/ shouldn't be able+ /// to make the watcher index arbitrary files via symlinks.+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn walk_markdown_skips_symlinks() {+ let tmp = TempDir::new().unwrap();+ let wiki_root = tmp.path().join("wiki");+ std::fs::create_dir_all(&wiki_root).unwrap();++ // A real file (should be picked up).+ std::fs::write(wiki_root.join("real.md"), "real content\n").unwrap();++ // A "secret" file outside the wiki root.+ let secret = tmp.path().join("secret.md");+ std::fs::write(&secret, "this is sensitive\n").unwrap();++ // Plant a symlink inside wiki/ pointing at the outside file.+ #[cfg(unix)]+ std::os::unix::fs::symlink(&secret, wiki_root.join("symlinked.md")).unwrap();+ #[cfg(windows)]+ std::os::windows::fs::symlink_file(&secret, wiki_root.join("symlinked.md")).unwrap();++ let found = walk_markdown(&wiki_root).unwrap();+ let names: Vec<_> = found.iter().map(|p| p.as_str().to_string()).collect();+ assert!(names.contains(&"real.md".to_string()), "real file present");+ assert!(+ !names.contains(&"symlinked.md".to_string()),+ "symlink to outside file must be skipped; got: {names:?}"+ );+ }}diff --git a/docker/.env.production.example b/docker/.env.production.exampleindex 0be67acc..deb9b405 100644--- a/docker/.env.production.example+++ b/docker/.env.production.example@@ -50,3 +50,18 @@ OPENAI_API_KEY=sk-REPLACE_ME# The compose file maps the host port to this. Don't change unless# you also change the compose port mapping.# AI_MEMORY_BIND=0.0.0.0:49374++# -- Bearer-token auth -------------------------------------------------+# Required when the server is reachable from anything beyond loopback+# (i.e. any LAN-binding deploy). When set, every /mcp + /hook + /handoff+# request must carry `Authorization: Bearer <token>`. The matching+# token goes into each client's MCP config (use `ai-memory install-mcp+# --client <name> --auth-token <token>` to render the snippet).+#+# Generate with:+# ai-memory generate-auth-token+#+# Without this set, the server logs a loud warning at startup AND+# accepts every request — fine for loopback-only `serve --bind 127...`+# but a critical hole on a LAN binding.+AI_MEMORY_AUTH_TOKEN=REPLACE_WITH_OUTPUT_OF_GENERATE_AUTH_TOKENdiff --git a/docs/deploy.md b/docs/deploy.mdindex d3b05eca..c13e85ef 100644--- a/docs/deploy.md+++ b/docs/deploy.md@@ -61,6 +61,52 @@ ssh "$SERVER" "docker inspect --format='{{.State.Health.Status}}' ai-memory"# Expect: healthy```+## Security — bearer-token auth + encrypted transport++The default `docker-compose.prod.yml.example` binds to `0.0.0.0:49374`+so the LAN can reach the MCP endpoint. **A LAN-bound server with no+auth lets anyone on the network call destructive MCP tools** (delete+all pages, inject fake observations, drain your LLM budget). ai-memory+ships a built-in bearer-token check; turn it on before the first deploy.++```bash+# 1. Generate a token (32 bytes / 64 hex chars).+ai-memory generate-auth-token >> docker/.env.production+$EDITOR docker/.env.production # prefix the new line with AI_MEMORY_AUTH_TOKEN=++# 2. Sync to the homelab + restart.+scp docker/.env.production "$SERVER:$DEPLOY_DIR/.env.production"+ssh "$SERVER" "cd $DEPLOY_DIR && docker compose up -d"+```++The startup log will now show `auth=true`. Verify from the laptop:++```bash+curl -sI http://homelab:49374/handoff # → HTTP/1.1 401 Unauthorized+curl -sI http://homelab:49374/handoff \+ -H "Authorization: Bearer $TOKEN" # → HTTP/1.1 200 OK+```++**Then update every MCP client** to send the same token. `ai-memory+install-mcp --client <name> --auth-token <token>` prints the exact+snippet per client (Claude Code, Codex, OpenCode, Cursor, Claude+Desktop, Gemini CLI, OpenClaw). The agent CLI sends an+`Authorization: Bearer <token>` header on every call; ai-memory's+middleware validates with a constant-time comparison.++**Encrypted transport.** Plain HTTP on the LAN means anyone with a+packet capture on the network can read the bearer token and the wiki+content in transit. Two pragmatic ways to add TLS:++| Option | When it fits |+|---|---|+| **Front with cloudflared** (your existing homelab tunnel) | You want to access ai-memory from outside the LAN too. cloudflared terminates TLS at Cloudflare's edge and tunnels to the container over HTTP. The bearer token still applies; Cloudflare provides the encryption + DDoS shield. Configure a new `--hostname ai-memory.your-domain.tld --url http://localhost:49374` route on the existing cloudflared instance. |+| **Caddy reverse proxy** in a sibling container | You want LAN-only TLS without public DNS. Caddy auto-issues a self-signed cert with a tofu prompt the first time each client connects. Mount your homelab's CA cert into the container running each MCP client. |++For most homelab use cases the bearer token alone over plain HTTP on+a trusted LAN is acceptable. The token is what stops the LAN+neighbour; TLS is what stops a packet-capture-with-a-laptop-on-the-WiFi.+## Routine deploysAfter the first-time setup, every subsequent deploy is just:diff --git a/hooks/claude-code/post-tool-use.sh b/hooks/claude-code/post-tool-use.shindex 526151dc..462037b6 100755--- a/hooks/claude-code/post-tool-use.sh+++ b/hooks/claude-code/post-tool-use.sh@@ -1,8 +1,20 @@#!/bin/sh-# Claude Code PostToolUse hook.+# Claude Code post-tool-use hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=post-tool-use&agent=claude-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=post-tool-use&agent=claude-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/pre-compact.sh b/hooks/claude-code/pre-compact.shindex 49d862b5..3c97d83e 100755--- a/hooks/claude-code/pre-compact.sh+++ b/hooks/claude-code/pre-compact.sh@@ -1,8 +1,20 @@#!/bin/sh-# Claude Code PreCompact hook.+# Claude Code pre-compact hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=pre-compact&agent=claude-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=pre-compact&agent=claude-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/pre-tool-use.sh b/hooks/claude-code/pre-tool-use.shindex 4e451e44..020cf3a1 100755--- a/hooks/claude-code/pre-tool-use.sh+++ b/hooks/claude-code/pre-tool-use.sh@@ -1,8 +1,20 @@#!/bin/sh-# Claude Code PreToolUse hook.+# Claude Code pre-tool-use hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=pre-tool-use&agent=claude-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=pre-tool-use&agent=claude-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/session-end.sh b/hooks/claude-code/session-end.shindex ced6eb99..6c55b6df 100755--- a/hooks/claude-code/session-end.sh+++ b/hooks/claude-code/session-end.sh@@ -1,10 +1,20 @@#!/bin/sh-# Claude Code SessionEnd hook (final).-# We give the session-end hook a longer timeout because the server-# synthesises a wiki page from the observation log here.+# Claude Code session-end hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 2.0 \- -X POST "$SERVER/hook?event=session-end&agent=claude-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=session-end&agent=claude-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/session-start.sh b/hooks/claude-code/session-start.shindex db193784..ce064db9 100755--- a/hooks/claude-code/session-start.sh+++ b/hooks/claude-code/session-start.sh@@ -3,18 +3,37 @@## 1. Forwards the event JSON to the ai-memory server (fire-and-forget).# 2. Synchronously fetches any pending cross-agent handoff and prints-# it to stdout — Claude Code prepends this to the session, so the-# next agent picks up where the previous one left off without the-# user having to ask.+# it to stdout — agent CLIs prepend session-start hook stdout to+# the next session, so the resuming agent sees prior context with+# no human in the loop.#-# Both calls are capped at sub-second timeouts so a server outage-# never blocks startup. The hook always exits 0.+# Both calls carry an Authorization: Bearer header when+# AI_MEMORY_AUTH_TOKEN is set in this hook's environment.SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"PAYLOAD=$(cat)-echo "$PAYLOAD" | curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=session-start&agent=claude-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true-curl -s --max-time 1.0 \- "$SERVER/handoff?agent=claude-code" 2>/dev/null || true++post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}++get_handoff() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 1.0 "$1" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"+ else+ curl -s --max-time 1.0 "$1"+ fi+}++echo "$PAYLOAD" | post_hook "$SERVER/hook?event=session-start&agent=claude-code" >/dev/null 2>&1 || true+get_handoff "$SERVER/handoff?agent=claude-code" 2>/dev/null || trueexit 0diff --git a/hooks/claude-code/stop.sh b/hooks/claude-code/stop.shindex a0b0fdd2..f748c088 100755--- a/hooks/claude-code/stop.sh+++ b/hooks/claude-code/stop.sh@@ -1,8 +1,20 @@#!/bin/sh-# Claude Code Stop hook (agent finished one turn).+# Claude Code stop hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=stop&agent=claude-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=stop&agent=claude-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/user-prompt-submit.sh b/hooks/claude-code/user-prompt-submit.shindex 6bf8a027..a77a41e8 100755--- a/hooks/claude-code/user-prompt-submit.sh+++ b/hooks/claude-code/user-prompt-submit.sh@@ -1,8 +1,20 @@#!/bin/sh-# Claude Code UserPromptSubmit hook.+# Claude Code user-prompt hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=user-prompt&agent=claude-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=user-prompt&agent=claude-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/codex/post-tool-use.sh b/hooks/codex/post-tool-use.shindex 91bc71d5..ba4003fa 100755--- a/hooks/codex/post-tool-use.sh+++ b/hooks/codex/post-tool-use.sh@@ -1,8 +1,20 @@#!/bin/sh# codex post-tool-use hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=post-tool-use&agent=codex" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=post-tool-use&agent=codex" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/codex/pre-compact.sh b/hooks/codex/pre-compact.shindex b4fe103d..4d237025 100755--- a/hooks/codex/pre-compact.sh+++ b/hooks/codex/pre-compact.sh@@ -1,8 +1,20 @@#!/bin/sh# codex pre-compact hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=pre-compact&agent=codex" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=pre-compact&agent=codex" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/codex/pre-tool-use.sh b/hooks/codex/pre-tool-use.shindex 32abe9dc..00f004bd 100755--- a/hooks/codex/pre-tool-use.sh+++ b/hooks/codex/pre-tool-use.sh@@ -1,8 +1,20 @@#!/bin/sh# codex pre-tool-use hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=pre-tool-use&agent=codex" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=pre-tool-use&agent=codex" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/codex/session-end.sh b/hooks/codex/session-end.shindex 66516797..b6bbe5b4 100755--- a/hooks/codex/session-end.sh+++ b/hooks/codex/session-end.sh@@ -1,8 +1,20 @@#!/bin/sh# codex session-end hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 2.0 \- -X POST "$SERVER/hook?event=session-end&agent=codex" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=session-end&agent=codex" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/codex/session-start.sh b/hooks/codex/session-start.shindex 8cdf1c7b..9fecc07b 100755--- a/hooks/codex/session-start.sh+++ b/hooks/codex/session-start.sh@@ -1,15 +1,39 @@#!/bin/sh# codex SessionStart hook.#-# Same shape as the claude-code variant: POST the event to /hook, then-# synchronously GET /handoff and echo the markdown so codex sees any-# pending cross-agent handoff at session start.+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).+# 2. Synchronously fetches any pending cross-agent handoff and prints+# it to stdout — agent CLIs prepend session-start hook stdout to+# the next session, so the resuming agent sees prior context with+# no human in the loop.+#+# Both calls carry an Authorization: Bearer header when+# AI_MEMORY_AUTH_TOKEN is set in this hook's environment.SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"PAYLOAD=$(cat)-echo "$PAYLOAD" | curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=session-start&agent=codex" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true-curl -s --max-time 1.0 \- "$SERVER/handoff?agent=codex" 2>/dev/null || true++post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}++get_handoff() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 1.0 "$1" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"+ else+ curl -s --max-time 1.0 "$1"+ fi+}++echo "$PAYLOAD" | post_hook "$SERVER/hook?event=session-start&agent=codex" >/dev/null 2>&1 || true+get_handoff "$SERVER/handoff?agent=codex" 2>/dev/null || trueexit 0diff --git a/hooks/codex/stop.sh b/hooks/codex/stop.shindex cde7ba0a..ccd1e5c6 100755--- a/hooks/codex/stop.sh+++ b/hooks/codex/stop.sh@@ -1,8 +1,20 @@#!/bin/sh# codex stop hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=stop&agent=codex" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=stop&agent=codex" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/codex/user-prompt-submit.sh b/hooks/codex/user-prompt-submit.shindex 8e7021a6..9d34ed8b 100755--- a/hooks/codex/user-prompt-submit.sh+++ b/hooks/codex/user-prompt-submit.sh@@ -1,8 +1,20 @@#!/bin/sh-# codex user-prompt-submit hook.+# codex user-prompt hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=user-prompt&agent=codex" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=user-prompt&agent=codex" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/opencode/post-tool-use.sh b/hooks/opencode/post-tool-use.shindex 49e1f6ea..fc38ff32 100755--- a/hooks/opencode/post-tool-use.sh+++ b/hooks/opencode/post-tool-use.sh@@ -1,8 +1,20 @@#!/bin/sh# opencode post-tool-use hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=post-tool-use&agent=open-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=post-tool-use&agent=open-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/opencode/pre-compact.sh b/hooks/opencode/pre-compact.shindex e5837ac5..a0f73cf4 100755--- a/hooks/opencode/pre-compact.sh+++ b/hooks/opencode/pre-compact.sh@@ -1,8 +1,20 @@#!/bin/sh# opencode pre-compact hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=pre-compact&agent=open-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=pre-compact&agent=open-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/opencode/pre-tool-use.sh b/hooks/opencode/pre-tool-use.shindex 2fe04074..f6f14f42 100755--- a/hooks/opencode/pre-tool-use.sh+++ b/hooks/opencode/pre-tool-use.sh@@ -1,8 +1,20 @@#!/bin/sh# opencode pre-tool-use hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=pre-tool-use&agent=open-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=pre-tool-use&agent=open-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/opencode/session-end.sh b/hooks/opencode/session-end.shindex 73551e65..c72ea310 100755--- a/hooks/opencode/session-end.sh+++ b/hooks/opencode/session-end.sh@@ -1,8 +1,20 @@#!/bin/sh# opencode session-end hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 2.0 \- -X POST "$SERVER/hook?event=session-end&agent=open-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=session-end&agent=open-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/opencode/session-start.sh b/hooks/opencode/session-start.shindex f4a46a57..345ad753 100755--- a/hooks/opencode/session-start.sh+++ b/hooks/opencode/session-start.sh@@ -1,15 +1,39 @@#!/bin/sh# opencode SessionStart hook.#-# Same shape as the claude-code variant: POST the event to /hook, then-# synchronously GET /handoff and echo the markdown so opencode sees-# any pending cross-agent handoff at session start.+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).+# 2. Synchronously fetches any pending cross-agent handoff and prints+# it to stdout — agent CLIs prepend session-start hook stdout to+# the next session, so the resuming agent sees prior context with+# no human in the loop.+#+# Both calls carry an Authorization: Bearer header when+# AI_MEMORY_AUTH_TOKEN is set in this hook's environment.SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"PAYLOAD=$(cat)-echo "$PAYLOAD" | curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=session-start&agent=open-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true-curl -s --max-time 1.0 \- "$SERVER/handoff?agent=open-code" 2>/dev/null || true++post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}++get_handoff() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 1.0 "$1" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"+ else+ curl -s --max-time 1.0 "$1"+ fi+}++echo "$PAYLOAD" | post_hook "$SERVER/hook?event=session-start&agent=open-code" >/dev/null 2>&1 || true+get_handoff "$SERVER/handoff?agent=open-code" 2>/dev/null || trueexit 0diff --git a/hooks/opencode/stop.sh b/hooks/opencode/stop.shindex e9102234..42e36226 100755--- a/hooks/opencode/stop.sh+++ b/hooks/opencode/stop.sh@@ -1,8 +1,20 @@#!/bin/sh# opencode stop hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=stop&agent=open-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=stop&agent=open-code" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/opencode/user-prompt-submit.sh b/hooks/opencode/user-prompt-submit.shindex a72df1e7..bd1ee137 100755--- a/hooks/opencode/user-prompt-submit.sh+++ b/hooks/opencode/user-prompt-submit.sh@@ -1,8 +1,20 @@#!/bin/sh-# opencode user-prompt-submit hook.+# opencode user-prompt hook.+# Forwards the event JSON to the ai-memory server. Adds an+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in+# this hook's environment (set it via install-hooks --auth-token).SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-curl -s --max-time 0.5 \- -X POST "$SERVER/hook?event=user-prompt&agent=open-code" \- -H "Content-Type: application/json" \- --data-binary @- >/dev/null 2>&1 || true+post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}+post_hook "$SERVER/hook?event=user-prompt&agent=open-code" >/dev/null 2>&1 || trueexit 0diff --git a/tests/e2e/handoff_smoke.sh b/tests/e2e/handoff_smoke.shindex 2667c504..2fb396c6 100755--- a/tests/e2e/handoff_smoke.sh+++ b/tests/e2e/handoff_smoke.sh@@ -107,6 +107,12 @@ EOF# Canary that MUST be redacted end-to-end.CANARY_KEY="sk-canary-LEAK_ME_PLEASE_e2e_smoketest_xxxxxxxxxxxx"+# Generated bearer token for this test run. The test starts ai-memory+# with AI_MEMORY_AUTH_TOKEN set, then exercises both the unauth (must+# 401) and auth (must 200) paths.+AUTH_TOKEN="testtoken-$(date +%s)-$(printf '%08x' $RANDOM$RANDOM)"+AUTH_HEADER="Authorization: Bearer $AUTH_TOKEN"+# --------------------------------------------------------------------# Gemini helper# --------------------------------------------------------------------@@ -144,7 +150,8 @@ AI_MEMORY="$REPO_ROOT/target/release/ai-memory"step "Initialising ai-memory data dir at $AI_MEMORY_DATA_DIR""$AI_MEMORY" init >>"$LOG_FILE" 2>&1-step "Starting ai-memory server on $SERVER_URL"+step "Starting ai-memory server on $SERVER_URL (auth-required)"+AI_MEMORY_AUTH_TOKEN="$AUTH_TOKEN" \"$AI_MEMORY" serve \--transport http --bind "127.0.0.1:$PORT" \--workspace e2e-test --project blog \@@ -156,12 +163,47 @@ if ! kill -0 "$SERVER_PID" 2>/dev/null; thentail -30 "$LOG_FILE" >&2exit 1fi-# Verify it's actually listening before continuing.+# Verify it's actually listening before continuing. /mcp without auth+# returns 401, which is fine — it proves the server is up AND that+# the auth layer is wired in. (Without auth we'd see 405 GET-not-allowed.)for _ in 1 2 3 4 5; do- curl -sf -o /dev/null --max-time 2 "$SERVER_URL/mcp" && break+ code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "$SERVER_URL/mcp" 2>/dev/null || echo 000)+ [[ "$code" == "401" || "$code" == "405" || "$code" == "200" ]] && breaksleep 1done+# Auth-path assertions — the server must reject unauthenticated calls+# and accept authenticated ones. We check this BEFORE the main flow+# so a misconfigured server fails fast with a clear signal.+step "Auth probe: GET /handoff without token must 401"+unauth_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 3 \+ "$SERVER_URL/handoff?agent=open-code" 2>/dev/null || echo 000)+if [[ "$unauth_code" != "401" ]]; then+ echo "FAIL: expected 401 without auth, got $unauth_code" >&2+ exit 1+fi+echo " PASS: unauth → 401"++step "Auth probe: GET /handoff with wrong token must 401"+wrong_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 3 \+ -H "Authorization: Bearer not-the-right-one" \+ "$SERVER_URL/handoff?agent=open-code" 2>/dev/null || echo 000)+if [[ "$wrong_code" != "401" ]]; then+ echo "FAIL: expected 401 with wrong token, got $wrong_code" >&2+ exit 1+fi+echo " PASS: wrong-token → 401"++step "Auth probe: GET /handoff with right token must NOT be 401"+right_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 3 \+ -H "$AUTH_HEADER" \+ "$SERVER_URL/handoff?agent=open-code" 2>/dev/null || echo 000)+if [[ "$right_code" == "401" ]]; then+ echo "FAIL: right token also rejected, got $right_code" >&2+ exit 1+fi+echo " PASS: right-token → $right_code (not 401)"+# --------------------------------------------------------------------# Session 1 — model A. Plant the plan + the canary.# --------------------------------------------------------------------@@ -173,6 +215,7 @@ echo "{\"session_id\":\"$SESSION_ID_1\",\"cwd\":\"$TEST_DIR/blog\",\"model\":\"$| curl -sS --max-time 3 \-X POST "$SERVER_URL/hook?event=session-start&agent=open-code" \-H "Content-Type: application/json" \+ -H "$AUTH_HEADER" \--data-binary @- >>"$LOG_FILE" 2>&1step "Session 1: invoke model A with the plan + canary"@@ -199,6 +242,7 @@ echo "{\"session_id\":\"$SESSION_ID_1\",\"prompt\":$(jq -Rs <<<"$S1_PROMPT")}" \| curl -sS --max-time 3 \-X POST "$SERVER_URL/hook?event=user-prompt&agent=open-code" \-H "Content-Type: application/json" \+ -H "$AUTH_HEADER" \--data-binary @- >>"$LOG_FILE" 2>&1# Synthetic "tool use" observation so the handoff's "next steps"@@ -208,6 +252,7 @@ for tool in "Read" "Edit" "Write"; do| curl -sS --max-time 2 \-X POST "$SERVER_URL/hook?event=post-tool-use&agent=open-code" \-H "Content-Type: application/json" \+ -H "$AUTH_HEADER" \--data-binary @- >>"$LOG_FILE" 2>&1done@@ -215,6 +260,7 @@ echo "{\"session_id\":\"$SESSION_ID_1\",\"cwd\":\"$TEST_DIR/blog\"}" \| curl -sS --max-time 10 \-X POST "$SERVER_URL/hook?event=session-end&agent=open-code" \-H "Content-Type: application/json" \+ -H "$AUTH_HEADER" \--data-binary @- >>"$LOG_FILE" 2>&1# Server work is async (writer actor + auto-commit). Give it a beat.@@ -224,8 +270,8 @@ sleep 2# Probe: handoff exists; canary already scrubbed at this point# ---------------------------------------------------------------------step "Probe: fetch handoff via GET /handoff"-HANDOFF_MD="$(curl -sS --max-time 5 "$SERVER_URL/handoff?agent=open-code")"+step "Probe: fetch handoff via GET /handoff (authed)"+HANDOFF_MD="$(curl -sS --max-time 5 -H "$AUTH_HEADER" "$SERVER_URL/handoff?agent=open-code")"echo "$HANDOFF_MD" >"$TEST_DIR/handoff.md"echo "--- handoff body ---"echo "$HANDOFF_MD"@@ -243,6 +289,7 @@ echo "{\"session_id\":\"$SESSION_ID_2\",\"cwd\":\"$TEST_DIR/blog\",\"model\":\"$| curl -sS --max-time 3 \-X POST "$SERVER_URL/hook?event=session-start&agent=open-code" \-H "Content-Type: application/json" \+ -H "$AUTH_HEADER" \--data-binary @- >>"$LOG_FILE" 2>&1step "Session 2: invoke model B, with the handoff prepended"