Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(auth): require a bearer token on new installs
AkitaOnRailsb3c747c874a5
diff --git a/AGENTS.md b/AGENTS.mdindex adbf4f0b..18ebd5c5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -519,8 +519,10 @@ Additional boundary rules:## Security considerations-- **Default posture:** loopback-only bind (`127.0.0.1:49374`), no auth —- safe for a single-user machine. Any non-loopback bind should set a+- **Default posture:** loopback-only bind (`127.0.0.1:49374`). A fresh+ `ai-memory init` mints a root bearer into `<data_dir>/auth-tokens/default`+ (`[auth].bearer_token_file`); an install created before that keeps no+ auth until `ai-memory auth enable`. Any non-loopback bind should set abearer token (`AI_MEMORY_AUTH_TOKEN`) and `AI_MEMORY_ALLOWED_HOSTS`(DNS-rebinding guard). TLS is deliberately delegated to a reverseproxy (see `docs/https-via-proxy.md`).diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 436b688d..1edd6397 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -215,6 +215,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`memory_consolidate`, which ai-memory also has with different arguments. Thecheck only reads; it never edits or deletes another tool's files. `doctor--json` carries the findings as `agentmemory_residue`.+- Added `ai-memory auth enable`, which turns on bearer auth for an install+ created without it. It reuses or creates an owner-only token at+ `<data_dir>/auth-tokens/default`, records it in `config.toml`, gives the+ installed 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.+- 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.+ `AI_MEMORY_AUTH_TOKEN` still takes precedence; setting the key together with+ `[auth] bearer_token` is a startup error, and a server whose configured file+ is missing or empty refuses to start. A token read from the file is never+ written 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.+- `ai-memory status` and `ai-memory doctor` now show the server's auth+ posture, and for an unauthenticated loopback server print+ `auth: none (loopback)` with the fix, `ai-memory auth enable`.### Changed- Documented hand-written MCP recipes for Factory Droid, Warp, Cline, Kilo@@ -230,6 +251,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`[retrieval] observation_stream = false` (or`AI_MEMORY_RETRIEVAL__OBSERVATION_STREAM=false`); ranking is then identicalto before.+- Changed `ai-memory init` on a fresh data dir (no config file and no+ database yet) to create a root bearer token at+ `<data_dir>/auth-tokens/default` and record `[auth] bearer_token_file`, so+ a new install's server requires the token on every route except `/healthz`.+ The hooks, the CLI and `ai-memory mcp-bridge` read it from the data dir;+ client commands of a packaged install, whose config lives outside the data+ dir, find it there too when they read no config file and target a loopback+ server. Existing installs are unchanged and keep running without auth until+ `ai-memory auth enable`; so is an `init` that finds a database or a bearer+ supplied another way. `uninstall` keeps this token, since it is the+ server's credential. The Docker wrapper hands a host command (`install-hooks`,+ `mcp-bridge`, `run`) the token of a server initialized on its volume as an+ owner-only file that `install-hooks` copies from the volume, never on a+ command line.- Changed `ai-memory-wikisync` files to carry a small frontmatter (`title`,plus `tags`, `pinned` and a non-default `tier` when set) above the body,so metadata survives a round trip. The first run after upgrading rewritesdiff --git a/README.md b/README.mdindex ef6bf717..e73c9b58 100644--- a/README.md+++ b/README.md@@ -272,10 +272,11 @@ The published Docker image includes `linux/amd64` and `linux/arm64` variants,so Apple Silicon Macs and ARM64 Linux hosts can pull `akitaonrails/ai-memory`without `--platform linux/amd64` emulation.-The default quick-start has **no authentication**. The server binds-to loopback only, so on a single-user laptop nothing else can reach-it. Adding a bearer token is a one-line change once you're ready to-expose the server on the LAN; see [Security](#security) below.+The Docker quick-start below has **no authentication**: the container never+runs `init`, so it starts without a token. The server binds to loopback only,+so nothing outside the machine can reach it, but local processes and browser+pages can. Native installs that run `ai-memory init` get a bearer token by+default; see [Security](#security) below for that and for adding a token here.```bash# 1. Install the ai-memory CLI wrapper (a small shell script that@@ -516,8 +517,12 @@ data directory, never two.## Security-The quick-start default is loopback-only with no auth, so nothing outside-your machine can reach it. From there, hardening is incremental: a bearer+The server binds to loopback only by default. A fresh `ai-memory init` also+mints a root bearer token into the data dir, which the hooks, the CLI and the+`ai-memory mcp-bridge` stdio bridge read from there; it is never written into+a harness config. An install created before that default (and the Docker+quick-start) runs without auth until `ai-memory auth enable`, and+`ai-memory status` says so. From there, hardening is incremental: a bearertoken for the LAN, per-user accounts, OIDC device auth for hooks, TLS viaa reverse proxy. Capture is sanitized at a typed privacy boundary beforeanything is stored, and per-repository `[capture]` rules can excludediff --git a/bin/ai-memory b/bin/ai-memoryindex 274ae17e..a6e68473 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -562,6 +562,56 @@ native_host_binary() {printf '%s\n' "${binary}"}+# A server initialized on the named volume keeps its root bearer there+# (/data/auth-tokens/default, named by `[auth].bearer_token_file`). The host+# commands below run the native client against the host data dir, which cannot+# see the volume, so the token is copied to an owner-only host file and the+# client is pointed at it with AI_MEMORY_AUTH__BEARER_TOKEN_FILE. The client+# then treats it as a token file: it authenticates with it, persists it for+# hooks, and never writes it into a harness config. The token crosses only the+# helper's stdout and a 0600 file, never an argv. A bind-mounted+# AI_MEMORY_DATA_DIR needs none of this (the client reads the same files), and+# an explicit token wins.+VOLUME_TOKEN_FILE="${NATIVE_RUNNER_DIR}/server-token"++volume_token_applies() {+ [ -z "${AI_MEMORY_AUTH_TOKEN:-}" ] || return 1+ [ -z "${AI_MEMORY_AUTH__BEARER_TOKEN_FILE:-}" ] || return 1+ if [ -n "${AI_MEMORY_DATA_DIR:-}" ] && [ -d "${AI_MEMORY_DATA_DIR}" ]; then+ return 1+ fi+ return 0+}++# Point the native client at the host copy, when there is one.+use_volume_token() {+ volume_token_applies || return 0+ [ -s "${VOLUME_TOKEN_FILE}" ] || return 0+ export AI_MEMORY_AUTH__BEARER_TOKEN_FILE="${VOLUME_TOKEN_FILE}"+}++# Refresh the host copy from the volume, then use it. Only `install-hooks`,+# the setup step, does this: the managed host commands (`run`, `show`, ...)+# and `mcp-bridge`, which starts with every agent session, never enter the+# container engine, so they read the copy it leaves behind.+refresh_volume_token() {+ volume_token_applies || return 0+ local token+ token="$("${DOCKER}" run --rm -v "${DATA_VOLUME}:/data:ro" --entrypoint /bin/sh "${IMAGE}" -c \+ 'grep -qs "^[[:space:]]*bearer_token_file[[:space:]]*=[[:space:]]*\"auth-tokens/default\"" /data/config.toml && cat /data/auth-tokens/default' \+ 2>/dev/null)" || token=""+ token="$(printf '%s' "${token}" | tr -d '\r\n')"+ if [ -n "${token}" ]; then+ (+ umask 077+ mkdir -p "${NATIVE_RUNNER_DIR}" \+ && printf '%s\n' "${token}" >"${VOLUME_TOKEN_FILE}.tmp.$$" \+ && mv -f "${VOLUME_TOKEN_FILE}.tmp.$$" "${VOLUME_TOKEN_FILE}"+ ) 2>/dev/null || true+ fi+ use_volume_token+}+# ---- intercept wrapper-only subcommands ----------------------------------case "${1:-}" in@@ -574,6 +624,7 @@ case "${1:-}" inNATIVE_HOST_COMMAND=$1shiftNATIVE_HOST_BIN=$(native_host_binary)+ use_volume_tokenexec "${NATIVE_HOST_BIN}" "${NATIVE_HOST_COMMAND}" "$@";;install-hooks)@@ -585,6 +636,7 @@ case "${1:-}" inposix | windows) ;;*)NATIVE_HOST_BIN=$(native_host_binary)+ refresh_volume_tokenexec "${NATIVE_HOST_BIN}" "$@";;esac@@ -596,6 +648,7 @@ case "${1:-}" in# has no host networking), so the bridge must run on the host through# the same checksum-verified native client install-hooks uses.NATIVE_HOST_BIN=$(native_host_binary)+ use_volume_tokenexec "${NATIVE_HOST_BIN}" "$@";;esacdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex c113406f..f50bcd6c 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1354,6 +1354,13 @@ pub enum AuthCommand {Logout(AuthLogoutArgs),/// Show stored provider auth state without printing secrets.Status(AuthStatusArgs),+ /// Require a bearer token on this install's server. Idempotent: mints+ /// `<data_dir>/auth-tokens/default` (owner-only) if missing, records+ /// `[auth].bearer_token_file`, gives the hooks the token through their+ /// credential files, and re-registers Claude Code's MCP entry as the+ /// `ai-memory mcp-bridge` stdio bridge. The token is never printed or+ /// written into a harness config. Restart the server afterwards.+ Enable(AuthEnableArgs),}/// Provider choices for `auth`.@@ -1404,6 +1411,15 @@ pub struct AuthLogoutArgs {#[derive(Debug, Args)]pub struct AuthStatusArgs {}+/// Arguments for `auth enable`.+#[derive(Debug, Args)]+pub struct AuthEnableArgs {+ /// Leave harness MCP registrations alone; only provision the token,+ /// the config key and the hook credential files.+ #[arg(long)]+ pub no_mcp: bool,+}+/// Which concern `uninstall` should touch. Omitted = all four.#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]pub enum UninstallOnly {@@ -3196,6 +3212,13 @@ pub struct InstallMcpArgs {/// wants `gemini`. Kimi Code and Kiro already get theirs; this overrides.#[arg(long, value_enum)]pub flavor: Option<SchemaFlavor>,+ /// Reference the token by the `AI_MEMORY_AUTH_TOKEN` variable name+ /// instead of embedding it (Codex `bearer_token_env_var`, Prime Agent+ /// `bearerTokenEnvVar`). Set by the installer, never a flag: it is how an+ /// install whose token lives in `[auth].bearer_token_file` keeps the token+ /// out of the harness config.+ #[arg(skip)]+ pub token_env_var: bool,}/// Arguments for the internal Claude Code session-aware MCP bridge.diff --git a/crates/ai-memory-cli/src/commands/auth.rs b/crates/ai-memory-cli/src/commands/auth.rsindex 337ed2f4..d8ce8613 100644--- a/crates/ai-memory-cli/src/commands/auth.rs+++ b/crates/ai-memory-cli/src/commands/auth.rs@@ -1,5 +1,7 @@-//! `ai-memory auth` — manage upstream LLM provider credentials.+//! `ai-memory auth` — manage upstream LLM provider credentials, and require a+//! bearer token on this install's own server (`auth enable`).+use std::path::Path;use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use ai_memory_llm::{@@ -26,7 +28,7 @@ const POLLING_SAFETY_MARGIN_SECS: u64 = 3;////// # Errors/// Returns an error if token storage or provider auth requests fail.-pub async fn run(config: &Config, args: AuthArgs) -> Result<()> {+pub async fn run(config: &Config, args: AuthArgs, config_path: Option<&Path>) -> Result<()> {match args.command {AuthCommand::Login(args) => match args.provider {AuthProviderChoice::OpenaiOauth => {@@ -63,6 +65,7 @@ pub async fn run(config: &Config, args: AuthArgs) -> Result<()> {AuthProviderChoice::OidcDevice => logout_oidc_device(config),},AuthCommand::Status(_) => status(config),+ AuthCommand::Enable(args) => super::auth_enable::run(config, &args, config_path),}}diff --git a/crates/ai-memory-cli/src/commands/auth_enable.rs b/crates/ai-memory-cli/src/commands/auth_enable.rsnew file mode 100644index 00000000..0d78136b--- /dev/null+++ b/crates/ai-memory-cli/src/commands/auth_enable.rs@@ -0,0 +1,537 @@+//! `ai-memory auth enable` — require a bearer token on this install's server.+//!+//! The opt-in for installs that predate the new-install default: it does what+//! `init` does on a fresh data dir, then re-points the wiring that already+//! exists at the token. Idempotent, so a second run changes nothing:+//!+//! 1. reuse `[auth].bearer_token_file`'s token, or mint+//! `<data_dir>/auth-tokens/default` (`0600`);+//! 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.+//!+//! The token is never printed and never written into a harness config.++use std::path::{Path, PathBuf};++use anyhow::{Context as _, Result, bail};++use crate::cli::{AuthEnableArgs, InstallMcpArgs, McpClient};+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.+#[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,+ /// The entry targets another server; it is left alone.+ OtherServer(String),+ /// The entry was re-registered as the stdio bridge.+ Rewired,+}++/// The result of one `auth enable`.+#[derive(Debug)]+pub(crate) struct EnableOutcome {+ /// A bearer was already supplied inline (`AI_MEMORY_AUTH_TOKEN` or+ /// `[auth].bearer_token`); nothing was changed.+ pub(crate) already_inline: bool,+ pub(crate) token_path: PathBuf,+ pub(crate) token_created: bool,+ pub(crate) config_path: PathBuf,+ pub(crate) config_changed: bool,+ pub(crate) hooks: Option<HookCredential>,+ pub(crate) claude: ClaudeWiring,+}++/// Run `auth enable`.+///+/// # Errors+/// 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())?;+ print_outcome(&outcome);+ Ok(())+}++pub(crate) fn enable(+ config: &Config,+ config_path: Option<&Path>,+ claude_config: Option<&Path>,+) -> Result<EnableOutcome> {+ let data_dir = &config.data_dir;+ let config_path = config_path.map_or_else(|| data_dir.join("config.toml"), PathBuf::from);+ let token_path = config.auth.token_file_path().map_or_else(+ || server_profiles::root_token_path(data_dir),+ Path::to_path_buf,+ );++ if config.auth.renderable_bearer_token().is_some() {+ return Ok(EnableOutcome {+ already_inline: true,+ token_path,+ token_created: false,+ config_path,+ config_changed: false,+ hooks: None,+ claude: ClaudeWiring::Skipped,+ });+ }++ refuse_a_profile_sharing_the_token(data_dir, &token_path)?;+ let minted = local_auth::provision_root_token(&token_path)?;+ let config_changed = if config.auth.bearer_token_file.is_none() {+ record_token_file(&config_path)?+ } else {+ false+ };+ let hooks = local_auth::seed_hook_credential(data_dir, &minted.token)?;++ let mut enabled = config.clone();+ 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,+ };++ Ok(EnableOutcome {+ already_inline: false,+ token_path: minted.path,+ token_created: minted.created,+ config_path,+ config_changed,+ hooks: Some(hooks),+ claude,+ })+}++/// A registered server profile named `default` reads `auth-tokens/default`+/// too: the hook would then present this server's root bearer to that+/// profile's server.+fn refuse_a_profile_sharing_the_token(data_dir: &Path, token_path: &Path) -> Result<()> {+ let Some(name) = ProfileName::parse(server_profiles::ROOT_TOKEN_NAME) else {+ return Ok(());+ };+ if !server_profiles::profile_shares_root_token(data_dir, &name, Some(token_path)) {+ return Ok(());+ }+ if server_profiles::root_token_name_is_registered(data_dir)+ .context("reading servers.toml to check the `default` profile name")?+ {+ bail!(+ "a server profile named `default` is registered, and its token file is the one \+ `auth enable` would use for this server's root bearer. Re-register that profile \+ under another name (`ai-memory server add <name> ...`, then \+ `ai-memory server remove default`) and run `ai-memory auth enable` again."+ );+ }+ Ok(())+}++/// Set `[auth].bearer_token_file` in the config file, keeping every comment+/// and other key. Creates the file (owner-only) when the install never had+/// one. Returns whether the file changed.+fn record_token_file(config_path: &Path) -> Result<bool> {+ let existing = match std::fs::read_to_string(config_path) {+ Ok(text) => Some(text),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,+ Err(e) => {+ return Err(e).with_context(|| format!("reading {}", config_path.display()));+ }+ };+ let mut doc: toml_edit::DocumentMut = existing+ .as_deref()+ .unwrap_or_default()+ .parse()+ .with_context(|| format!("parsing {}", config_path.display()))?;+ let auth = doc+ .entry("auth")+ .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()))+ .as_table_like_mut()+ .with_context(|| format!("`auth` in {} is not a table", config_path.display()))?;+ if auth.get("bearer_token_file").is_some() {+ return Ok(false);+ }+ auth.insert(+ "bearer_token_file",+ toml_edit::value(server_profiles::ROOT_TOKEN_RELATIVE),+ );++ #[cfg(unix)]+ let mode = {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::metadata(config_path)+ .ok()+ .map(|meta| meta.permissions().mode())+ };+ if let Some(parent) = config_path.parent() {+ crate::commands::path_util::create_private_dir(parent)+ .with_context(|| format!("creating {}", parent.display()))?;+ }+ // The atomic write's temp file is owner-only; an existing config keeps+ // the mode it had (a packaged one may be group-readable on purpose).+ ai_memory_wiki::write_atomic(config_path, doc.to_string().as_bytes())+ .with_context(|| format!("writing {}", config_path.display()))?;+ #[cfg(unix)]+ if let Some(mode) = mode {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(config_path, std::fs::Permissions::from_mode(mode))+ .with_context(|| format!("restoring the mode of {}", config_path.display()))?;+ }+ 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+ .iter()+ .position(|arg| *arg == "--server-url")+ .and_then(|i| args.get(i + 1))+ .map(|url| (*url).to_owned()))+}++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));+ }+ 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)+}++fn print_outcome(outcome: &EnableOutcome) {+ if outcome.already_inline {+ println!(+ "auth: already required by AI_MEMORY_AUTH_TOKEN or [auth].bearer_token; nothing changed."+ );+ return;+ }+ println!(+ "auth: bearer token {} at {} (owner-only)",+ if outcome.token_created {+ "generated"+ } else {+ "kept"+ },+ outcome.token_path.display()+ );+ println!(+ "config: {} {}",+ if outcome.config_changed {+ "recorded [auth].bearer_token_file in"+ } else {+ "already names the token file:"+ },+ outcome.config_path.display()+ );+ match outcome.hooks {+ Some(HookCredential::Seeded) => {+ println!("hooks: given the token through the hook credential files");+ }+ Some(HookCredential::Current) => println!("hooks: already use the token"),+ Some(HookCredential::KeptOther) => println!(+ "hooks: another credential is stored for them and was kept; re-run \+ `ai-memory install-hooks --agent <agent> --apply` to switch them to this token"+ ),+ 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");+ }+ 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.");+}++#[cfg(test)]+mod tests {+ use super::*;++ fn config_in(data_dir: &Path) -> Config {+ Config::load_with_runtime_env(+ None,+ Some(data_dir.to_path_buf()),+ crate::config::RuntimeEnv::default(),+ )+ .unwrap()+ }++ /// The pre-default config `init` wrote: a token pepper and comments, no+ /// bearer.+ fn pre_a1_install(data_dir: &Path) {+ std::fs::create_dir_all(data_dir).unwrap();+ std::fs::write(+ data_dir.join("config.toml"),+ "# operator comment\nlog_level = \"info\"\n\n[auth]\n# keep me\nsecure_cookie = false\ntoken_pepper = \"pp\"\n",+ )+ .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();+ let mut stack = vec![root.to_path_buf()];+ while let Some(dir) = stack.pop() {+ for entry in std::fs::read_dir(&dir).unwrap() {+ let path = entry.unwrap().path();+ if path.is_dir() {+ stack.push(path);+ } else if let Ok(text) = std::fs::read_to_string(&path) {+ out.push((path, text));+ }+ }+ }+ 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.+ #[test]+ fn enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ 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 first = enable(&config_in(&data_dir), None, Some(&claude)).unwrap();+ assert!(first.token_created);+ assert!(first.config_changed);+ assert_eq!(first.hooks, Some(HookCredential::Seeded));+ assert_eq!(first.claude, ClaudeWiring::Rewired);++ 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();+ assert!(config_text.contains("# operator comment"), "{config_text}");+ assert!(config_text.contains("# keep me"), "{config_text}");+ assert!(+ config_text.contains("token_pepper = \"pp\""),+ "{config_text}"+ );+ assert!(+ 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 entry = &entry["mcpServers"]["ai-memory"];+ assert_eq!(entry["type"], "stdio");+ assert_eq!(entry["command"], "ai-memory");+ assert!(entry.get("env").is_none(), "no token env: {entry}");+ assert_eq!(+ config_in(&data_dir).auth.bearer_token.as_deref(),+ Some(token.as_str())+ );++ let second = enable(&config_in(&data_dir), None, Some(&claude)).unwrap();+ assert!(!second.token_created);+ assert!(!second.config_changed);+ assert_eq!(second.hooks, Some(HookCredential::Current));+ assert_eq!(second.claude, ClaudeWiring::Rewired);+ assert_eq!(+ crate::config::read_trimmed_secret(&second.token_path),+ Some(token.clone())+ );+ assert_eq!(+ 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 (path, text) in files_under(&home) {+ assert!(+ !text.contains(&token),+ "token leaked into {}",+ path.display()+ );+ }+ for (path, text) in files_under(&data_dir) {+ let allowed = path == first.token_path+ || path == crate::config::hook_auth_token_path_in(&data_dir)+ || path == crate::config::hook_auth_header_path_in(&data_dir);+ assert!(+ allowed || !text.contains(&token),+ "token copied to an unexpected file {}",+ path.display()+ );+ }+ }++ /// Control: an entry for a remote server keeps its destination.+ #[test]+ fn enable_leaves_a_claude_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);+ }++ /// A registered profile named `default` would read the same file as the+ /// root bearer and present it to its own server: refused before anything+ /// is written.+ #[test]+ fn enable_refuses_while_a_default_profile_would_share_the_token() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ pre_a1_install(&data_dir);+ let default = ProfileName::parse("default").unwrap();+ server_profiles::add(+ &data_dir,+ &default,+ "https://team.example",+ &[],+ Some("team"),+ )+ .unwrap();++ let err = enable(&config_in(&data_dir), None, None).unwrap_err();+ assert!(format!("{err:#}").contains("named `default`"), "{err:#}");+ assert_eq!(+ server_profiles::read_token(&data_dir, &default).as_deref(),+ Some("team"),+ "the profile's own token is untouched"+ );+ assert!(+ !std::fs::read_to_string(data_dir.join("config.toml"))+ .unwrap()+ .contains("bearer_token_file")+ );++ // Control: another profile name does not conflict.+ server_profiles::remove(&data_dir, &default).unwrap();+ let team = ProfileName::parse("team").unwrap();+ server_profiles::add(&data_dir, &team, "https://team.example", &[], Some("team")).unwrap();+ assert!(enable(&config_in(&data_dir), None, None).is_ok());+ }++ /// An inline bearer is already enforcement; `auth enable` adds nothing.+ #[test]+ fn enable_with_an_inline_bearer_changes_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ pre_a1_install(&data_dir);+ let mut config = config_in(&data_dir);+ config.auth.bearer_token = Some("inline".into());++ let outcome = enable(&config, None, None).unwrap();+ assert!(outcome.already_inline);+ assert!(!server_profiles::root_token_path(&data_dir).exists());+ assert!(crate::config::read_hook_auth_token(&data_dir).is_none());+ }++ /// An install that never had a config file gets one, owner-only.+ #[test]+ fn enable_without_a_config_file_creates_one() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ std::fs::create_dir_all(&data_dir).unwrap();++ enable(&config_in(&data_dir), None, None).unwrap();+ let loaded = config_in(&data_dir);+ assert!(loaded.auth.bearer_token.is_some());+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ let mode = std::fs::metadata(data_dir.join("config.toml"))+ .unwrap()+ .permissions()+ .mode();+ assert_eq!(mode & 0o777, 0o600);+ }+ }+}diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex e35d557f..259e5c20 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -167,6 +167,9 @@ struct DoctorReport {marker_capture_problem: Option<MarkerCaptureProblem>,capture_owner_active: bool,identity: Option<OperatorIdentity>,+ /// From `identity.level`: `anonymous` only when the server has no bearer+ /// configured. `None` when the identity was unavailable.+ auth_posture: Option<crate::local_auth::AuthPosture>,project_coordinate: Option<ProjectCoordinateReport>,/// Native "memory" stores found for harnesses that keep one, and whether/// the nearest marker would exclude a read of them (harness-issue@@ -591,7 +594,11 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {}),);+ let auth_posture = identity.as_ref().map(|identity| {+ crate::local_auth::AuthPosture::classify(identity.level == "anonymous", &ep.url)+ });let report = DoctorReport {+ auth_posture,workspace,project,server: ep.url.clone(),@@ -759,6 +766,9 @@ fn render_human(report: &DoctorReport) {} else {println!(" identity: unavailable");}+ if let Some(posture) = report.auth_posture {+ println!(" auth: {}", posture.line());+ }if report.capture_owner_active {println!(" AI_MEMORY_CAPTURE_OWNER is active: native capture is suppressed in this process.\n \@@ -895,6 +905,7 @@ mod tests {marker_capture_problem: None,capture_owner_active: false,identity: None,+ auth_posture: None,project_coordinate: None,native_memory: Vec::new(),spool,diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rsindex ad635912..964326b6 100644--- a/crates/ai-memory-cli/src/commands/hook_spool.rs+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs@@ -2174,7 +2174,7 @@ impl<'a> ProfileTokens<'a> {/// a stale port in one is unambiguous — nothing else could have been meant. A/// remote host is left alone: re-pointing it would misdeliver a spool that was/// deliberately captured against another server.-fn is_loopback_url(url: &str) -> bool {+pub(crate) fn is_loopback_url(url: &str) -> bool {let rest = match url.split_once("://") {Some((_, rest)) => rest,None => url,diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rsindex 79cdc72b..861ff89a 100644--- a/crates/ai-memory-cli/src/commands/init.rs+++ b/crates/ai-memory-cli/src/commands/init.rs@@ -57,6 +57,56 @@ token_pepper = \"{pepper}\")}+/// The `bearer_token_file` line appended to a rendered config.+fn render_bearer_token_file_line(raw: &str) -> String {+ format!(+ "+# Root bearer token, one line in an owner-only file. A relative path resolves+# against the data dir. Written by `ai-memory init` on a fresh data dir; the+# server requires it on every route but /healthz, and hooks, the CLI and+# `ai-memory mcp-bridge` read it from there. Harness configs never hold it.+bearer_token_file = {}+",+ toml_edit::Value::from(raw)+ )+}++/// Which `bearer_token_file` a config being written should record, minting the+/// token when this is a fresh install.+///+/// - A config being rewritten with `--force` that already named a token file+/// keeps naming it, so the rewrite does not silently turn auth off.+/// - A fresh install (no config and no database yet) with no bearer supplied+/// another way gets a new token at `auth-tokens/default`.+/// - Anything else, an existing install above all, records nothing and keeps+/// the loopback no-auth behaviour it had (`ai-memory auth enable` opts in).+fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<String>> {+ if let Some(raw) = config+ .auth+ .bearer_token_file+ .as_ref()+ .filter(|raw| !raw.as_os_str().is_empty())+ {+ if let Some(path) = config.auth.token_file_path() {+ crate::local_auth::provision_root_token(path)?;+ }+ return Ok(Some(raw.to_string_lossy().into_owned()));+ }+ if !fresh || config.auth.bearer_token.is_some() {+ return Ok(None);+ }+ let root = &config.data_dir;+ let minted =+ crate::local_auth::provision_root_token(&crate::server_profiles::root_token_path(root))?;+ crate::local_auth::seed_hook_credential(root, &minted.token)?;+ println!(+ "Generated a root bearer token in {} (owner-only). The server requires it on every \+ route but /healthz; hooks, the CLI and `ai-memory mcp-bridge` read it from there.",+ minted.path.display()+ );+ Ok(Some(crate::server_profiles::ROOT_TOKEN_RELATIVE.to_owned()))+}+/// Run the `init` subcommand.////// Creates `<data_dir>/{wiki,raw,db,models}` (idempotent) and writes a default@@ -65,11 +115,20 @@ token_pepper = \"{pepper}\"/// systemd units can pass `--config /etc/ai-memory/config.toml` or/// `--config ~/.config/ai-memory/config.toml` without changing the data root.///+/// On a fresh data dir it also mints the root bearer token (see+/// [`root_bearer_for_new_config`]).+////// # Errors/// Returns an error if directories cannot be created or the config file/// cannot be written.pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Result<()> {let root = &config.data_dir;+ let cfg_path = init_config_path(root, config_path);+ // Decided before anything is created: a data dir that already has a+ // database is an existing install even when it never had a config file+ // (env-configured and container installs), and it must keep running the+ // way it did.+ let fresh = !cfg_path.exists() && !root.join("db").join(ai_memory_store::DB_FILENAME).exists();create_private_dir_all(root).with_context(|| format!("creating data root {}", root.display()))?;@@ -79,7 +138,6 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Resultracing::info!(path = %path.display(), "ensured directory");}- let cfg_path = init_config_path(root, config_path);if cfg_path.exists() && !args.force {tracing::info!(path = %cfg_path.display(),@@ -96,10 +154,14 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Resul// (anyhow's `with_context` would conflict), so map manually.let pepper = generate_token_hex(TOKEN_PEPPER_BYTES).map_err(|e| anyhow::anyhow!("generating auth token_pepper: {e}"))?;+ let bearer_line = root_bearer_for_new_config(config, fresh)?+ .map(|raw| render_bearer_token_file_line(&raw))+ .unwrap_or_default();let body = format!(- "{}{}",+ "{}{}{}",DEFAULT_CONFIG_TOML,- render_default_auth_block(&pepper)+ render_default_auth_block(&pepper),+ bearer_line);let mut f = private_config_file(&cfg_path, args.force).with_context(|| format!("creating {}", cfg_path.display()))?;@@ -327,6 +389,132 @@ mod tests {);}+ /// Load the rendered config through the production loader, with no+ /// process environment, the way the server and every client will.+ fn load(data_dir: &Path, config_path: Option<&Path>) -> Config {+ Config::load_with_runtime_env(+ config_path,+ Some(data_dir.to_path_buf()),+ crate::config::RuntimeEnv::default(),+ )+ .unwrap()+ }++ /// New-install default: a fresh data dir gets a root bearer, recorded as a relative+ /// `bearer_token_file` the loader resolves, and the hook credential files+ /// carry the same token. The token is in no rendered config.+ #[test]+ fn a_fresh_init_mints_a_root_bearer_the_loader_reads() {+ let tmp = TempDir::new().unwrap();+ let root = tmp.path().join("data");+ run(&cfg_in(&root), InitArgs { force: false }, None).unwrap();++ let token_path = crate::server_profiles::root_token_path(&root);+ let token = crate::config::read_trimmed_secret(&token_path).expect("token minted");+ let body = std::fs::read_to_string(root.join("config.toml")).unwrap();+ assert!(+ body.contains("bearer_token_file = \"auth-tokens/default\""),+ "{body}"+ );+ assert!(+ !body.contains(&token),+ "the token never goes into config.toml"+ );++ let loaded = load(&root, None);+ assert_eq!(loaded.auth.bearer_token.as_deref(), Some(token.as_str()));+ assert_eq!(+ loaded.auth.renderable_bearer_token(),+ None,+ "a file-sourced token is never handed to a harness renderer"+ );+ assert_eq!(+ crate::config::read_hook_auth_token(&root).as_deref(),+ Some(token.as_str()),+ "hooks read the same token from the files they already know"+ );+ }++ /// Re-running init leaves the token alone; `--force` rewrites the config+ /// but keeps naming (and reusing) the same token file, so a rewrite never+ /// silently turns auth off or rotates a credential clients hold.+ #[test]+ fn re_running_init_keeps_the_same_root_bearer() {+ let tmp = TempDir::new().unwrap();+ let root = tmp.path().join("data");+ run(&cfg_in(&root), InitArgs { force: false }, None).unwrap();+ let token_path = crate::server_profiles::root_token_path(&root);+ let first = crate::config::read_trimmed_secret(&token_path).unwrap();++ run(&load(&root, None), InitArgs { force: false }, None).unwrap();+ run(&load(&root, None), InitArgs { force: true }, None).unwrap();++ assert_eq!(+ crate::config::read_trimmed_secret(&token_path),+ Some(first.clone())+ );+ assert_eq!(load(&root, None).auth.bearer_token, Some(first));+ }++ /// Control: a data dir that already holds a database is an existing+ /// install, even with no config file. It gets no token and keeps the+ /// loopback no-auth behaviour.+ #[test]+ fn init_on_an_existing_install_does_not_turn_auth_on() {+ let tmp = TempDir::new().unwrap();+ let root = tmp.path().join("data");+ std::fs::create_dir_all(root.join("db")).unwrap();+ std::fs::write(root.join("db").join(ai_memory_store::DB_FILENAME), b"").unwrap();++ run(&cfg_in(&root), InitArgs { force: false }, None).unwrap();++ let body = std::fs::read_to_string(root.join("config.toml")).unwrap();+ assert!(!body.contains("bearer_token_file"), "{body}");+ assert!(!crate::server_profiles::root_token_path(&root).exists());+ assert!(crate::config::read_hook_auth_token(&root).is_none());+ assert!(load(&root, None).auth.bearer_token.is_none());+ }++ /// An operator who already supplies a bearer (`AI_MEMORY_AUTH_TOKEN` or+ /// an inline key) chose their credential; a second one would leave the+ /// hooks holding a token the server does not enforce.+ #[test]+ fn init_with_a_supplied_bearer_mints_nothing() {+ let tmp = TempDir::new().unwrap();+ let root = tmp.path().join("data");+ let mut config = cfg_in(&root);+ config.auth.bearer_token = Some("operator-token".into());++ run(&config, InitArgs { force: false }, None).unwrap();++ assert!(!crate::server_profiles::root_token_path(&root).exists());+ let body = std::fs::read_to_string(root.join("config.toml")).unwrap();+ assert!(!body.contains("bearer_token_file"), "{body}");+ }++ /// With `--config` outside the data dir the token still lives in the data+ /// dir, and the relative path resolves there.+ #[test]+ fn a_fresh_init_with_an_external_config_resolves_the_token_in_the_data_dir() {+ let tmp = TempDir::new().unwrap();+ let root = tmp.path().join("data");+ let config_path = tmp.path().join("etc").join("config.toml");+ run(+ &cfg_in(&root),+ InitArgs { force: false },+ Some(&config_path),+ )+ .unwrap();++ let token =+ crate::config::read_trimmed_secret(&crate::server_profiles::root_token_path(&root))+ .unwrap();+ assert_eq!(+ load(&root, Some(&config_path)).auth.bearer_token,+ Some(token)+ );+ }+#[cfg(unix)]#[test]fn init_creates_private_directories_and_config() {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex c55ce4c8..dc9b2903 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -568,11 +568,25 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(None};let server_url = effective_hook_server_url(config, &args, inferred.as_ref());- let auth_token_owned = args+ // A token read from `[auth].bearer_token_file` may be persisted to the+ // hook credential files below, but never rendered into the agent config+ // or a printed snippet: that file exists to keep it out of them. Only an+ // inline token (flag, `AI_MEMORY_AUTH_TOKEN`, `[auth].bearer_token`, or one+ // inferred from an existing entry) may fall back to the inline form.+ let token_file = config.auth.token_file_path();+ let renderable_token = args.auth_token.clone()- .or_else(|| config.auth.bearer_token.clone())- .or_else(|| inferred.as_ref().and_then(|mcp| mcp.auth_token.clone()));+ .or_else(|| config.auth.renderable_bearer_token().map(str::to_owned))+ .or_else(|| {+ inferred+ .as_ref()+ .filter(|_| token_file.is_none())+ .and_then(|mcp| mcp.auth_token.clone())+ });+ let auth_token_owned = renderable_token+ .clone()+ .or_else(|| token_file.and(config.auth.bearer_token.clone()));// #552: persist the bearer under the data dir (0600) and keep it OUT of// the rendered config. Before this it went onto every hook's command line —// as `--auth-token <token>` for native hooks, as an `AI_MEMORY_AUTH_TOKEN=`@@ -607,6 +621,16 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(config.data_dir.display())));}+ Err(e) if renderable_token.is_none() => {+ eprintln!(+ "[ai-memory] warning: could not persist the hook auth token under {} ({e}). \+ The token comes from [auth].bearer_token_file and is never embedded in an \+ agent config, so these hooks will not authenticate until the data dir is \+ writable and `install-hooks --apply` is re-run.",+ config.data_dir.display()+ );+ false+ }Err(e) => {eprintln!("[ai-memory] warning: could not persist the hook auth token under {} ({e}); \@@ -628,7 +652,7 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(let auth = if persisted {None} else {- auth_token_owned.as_deref()+ renderable_token.as_deref()};// P1.8 multi-user attribution: `--as-user` is metadata only — the// token stamped into the hook env block is whatever the operator@@ -9553,6 +9577,55 @@ model = "gpt-5");}+ /// New-install default: a token read from `[auth].bearer_token_file` is persisted for the+ /// hooks, and when persisting fails it is NOT embedded the way an inline+ /// token is (F5): that file exists to keep the token out of agent configs.+ #[test]+ fn a_file_sourced_token_is_persisted_but_never_embedded() {+ let home = TempDir::new().unwrap();+ let cfg_dir = TempDir::new().unwrap();+ let settings = cfg_dir.path().join("settings.json");+ let hooks_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks");+ let token = "FILE-SOURCED-ROOT-BEARER";+ let file_config = || {+ let mut config =+ crate::config::Config::load(None, Some(home.path().to_path_buf())).unwrap();+ let path = crate::server_profiles::root_token_path(&config.data_dir);+ config.auth.adopt_token_file(path, token.to_owned());+ config+ };+ let args = || InstallHooksArgs {+ agent: AgentChoice::ClaudeCode,+ apply: true,+ server_url: Some("http://127.0.0.1:49374".to_string()),+ config_file: Some(settings.clone()),+ hooks_dir: Some(hooks_dir.clone()),+ ..default_hook_args()+ };++ std::fs::write(&settings, "{}").unwrap();+ let config = file_config();+ run(&config, args()).unwrap();+ assert_eq!(+ crate::config::read_hook_auth_token(&config.data_dir).as_deref(),+ Some(token),+ "the hooks get the token through their credential files"+ );+ let rendered = std::fs::read_to_string(&settings).unwrap();+ assert!(!rendered.contains(token), "{rendered}");++ // The F5 failure shape: the credential file cannot be written.+ crate::config::clear_hook_auth_token(&config.data_dir).unwrap();+ std::fs::create_dir_all(crate::config::hook_auth_token_path_in(&config.data_dir)).unwrap();+ std::fs::write(&settings, "{}").unwrap();+ run(&config, args()).expect("a persist failure still installs the hooks");+ let rendered = std::fs::read_to_string(&settings).unwrap();+ assert!(+ !rendered.contains(token),+ "a file-sourced token must not fall back to the inline form: {rendered}"+ );+ }+/// `--scope project` lands where Claude Code reads the file: the git root/// of the checkout, even from a subdirectory. A plain directory is its own/// root. On Windows, and when the repository root is the home directory,diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex bba96faf..73a12f61 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -103,14 +103,29 @@ pub(crate) fn run_with_opencode_dialect(|entry| entry.mcp_url.clone(),)};- let args = InstallMcpArgs {+ // A token read from `[auth].bearer_token_file` is never copied into a+ // harness config: that file exists to keep it out of them (#552). An+ // inferred literal from an old entry is ignored then too, since it would+ // re-embed a stale credential.+ let token_file = config.auth.token_file_path();+ let auth_token = args+ .auth_token+ .or_else(|| config.auth.renderable_bearer_token().map(str::to_owned))+ .or_else(|| {+ inferred+ .filter(|_| token_file.is_none())+ .and_then(|entry| entry.auth_token)+ });+ let mut args = InstallMcpArgs {server_url: Some(server_url),- auth_token: args- .auth_token- .or_else(|| config.auth.bearer_token.clone())- .or_else(|| inferred.and_then(|entry| entry.auth_token)),+ auth_token,..args};+ if args.auth_token.is_none()+ && let Some(token_file) = token_file+ {+ route_file_token(&mut args, token_file)?;+ }validate_args(&args)?;if args.apply {return apply_to_config_file(&args);@@ -146,6 +161,36 @@ pub(crate) fn run_with_opencode_dialect(Ok(())}+/// 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.+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!(+ "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.",+ path = token_file.display(),+ client = args.client,+ env = PRIME_AGENT_TOKEN_ENV,+ ),+ }+ Ok(())+}+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@@ -697,11 +742,18 @@ fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {ApplyOutcome::NoOp => "already up to date",});- if matches!(args.client, McpClient::PrimeAgent) && args.auth_token.is_some() {+ if matches!(args.client, McpClient::PrimeAgent)+ && (args.auth_token.is_some() || args.token_env_var)+ {println!(" Prime Agent reads the token from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch prime-agent.");}+ if matches!(args.client, McpClient::Codex) && args.token_env_var {+ println!(+ " Codex reads the token from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch codex."+ );+ }Ok(())}@@ -1328,7 +1380,7 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {// which is ignored).entry.insert("type".into(), json!("http"));entry.insert("url".into(), json!(server_url));- if args.auth_token.is_some() {+ if args.auth_token.is_some() || args.token_env_var {entry.insert("bearerTokenEnvVar".into(), json!(PRIME_AGENT_TOKEN_ENV));}}@@ -1497,7 +1549,9 @@ fn codex_upsert_mcp_server(// override per-tool — see Codex's `[mcp_servers.X.tools]`// map.server["default_tools_approval_mode"] = value("approve");- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {+ if args.token_env_var {+ server["bearer_token_env_var"] = value(PRIME_AGENT_TOKEN_ENV);+ } else if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {let mut headers = Table::new();headers["Authorization"] = value(b);server["http_headers"] = Item::Table(headers);@@ -1628,7 +1682,12 @@ fn render_codex(args: &InstallMcpArgs) -> String {name = args.name,url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),);- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {+ if args.token_env_var {+ out.push_str(&format!(+ "bearer_token_env_var = \"{PRIME_AGENT_TOKEN_ENV}\"\n\+ # The token is read from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch codex.\n"+ ));+ } else if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {out.push_str(&format!("\n[mcp_servers.{name}.http_headers]\n\Authorization = \"{b}\"\n\@@ -1801,7 +1860,7 @@ fn render_muse(args: &InstallMcpArgs) -> Result<String> {}fn render_prime_agent(args: &InstallMcpArgs) -> Result<String> {- let auth = if args.auth_token.is_some() {+ let auth = if args.auth_token.is_some() || args.token_env_var {format!("# The token is not written: the entry names ${PRIME_AGENT_TOKEN_ENV}\n\# (bearerTokenEnvVar), so export it where you launch prime-agent.\n\@@ -2091,6 +2150,7 @@ mod tests {config_file: None,session_aware: false,flavor: None,+ token_env_var: false,}}@@ -2104,6 +2164,7 @@ mod tests {config_file: None,session_aware: false,flavor: None,+ token_env_var: false,}}@@ -3255,6 +3316,117 @@ mod tests {}}+ const FILE_TOKEN: &str = "file-token-0123456789abcdef";++ /// A config whose bearer came from `[auth].bearer_token_file`, as+ /// `Config::load` leaves it on a new install.+ fn file_token_config(dir: &Path) -> Config {+ let mut config = Config::default();+ config+ .auth+ .adopt_token_file(dir.join("auth-tokens").join("default"), FILE_TOKEN.into());+ config+ }++ fn apply_with(config: &Config, client: McpClient, file: &Path) -> Result<()> {+ let mut args = args_for(client);+ args.apply = true;+ args.config_file = Some(file.to_path_buf());+ run_with_opencode_dialect(config, args, None)+ }++ /// 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.+ #[test]+ fn a_file_sourced_token_is_wired_without_entering_any_harness_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();+ assert!(+ !text.contains(FILE_TOKEN),+ "token leaked into {}",+ file.display()+ );+ }+ }++ /// Clients that can only hold a literal header are refused, and nothing+ /// is written, rather than being given the token.+ #[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());+ }+ }++ /// Controls: an inline token (pre-default install, `AI_MEMORY_AUTH_TOKEN`) and+ /// an explicit `--auth-token` keep embedding exactly as before.+ #[test]+ fn inline_and_explicit_tokens_still_embed_as_before() {+ let tmp = tempfile::tempdir().unwrap();+ let mut inline = Config::default();+ inline.auth.bearer_token = Some("inline-token".into());+ let cursor = tmp.path().join("cursor.json");+ apply_with(&inline, McpClient::Cursor, &cursor).unwrap();+ assert!(+ std::fs::read_to_string(&cursor)+ .unwrap()+ .contains("Bearer inline-token")+ );++ let config = file_token_config(tmp.path());+ let explicit = tmp.path().join("explicit.json");+ let mut args = args_for(McpClient::Cursor);+ args.apply = true;+ args.config_file = Some(explicit.clone());+ args.auth_token = Some("explicit-token".into());+ run_with_opencode_dialect(&config, args, None).unwrap();+ let text = std::fs::read_to_string(&explicit).unwrap();+ assert!(text.contains("Bearer explicit-token"), "{text}");+ assert!(!text.contains(FILE_TOKEN), "{text}");+ }+#[test]fn mcp_server_url_defaults_to_configured_server_url() {let config = Config {diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex ac9c2d99..313ffd8e 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -31,6 +31,7 @@ pub mod api_key;pub mod apply_shared;pub mod audit_contamination;pub mod auth;+pub mod auth_enable;pub mod auto_improve;pub mod auto_improve_report;pub mod backfill;diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 21fe05cc..4b023c0d 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -312,7 +312,11 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverride} = targets;let infer_opencode_transition = opencode_dialect.is_some() && !config.server_url_configured();let server_url = (!infer_opencode_transition).then(|| config.server_url.clone());- let auth_token = config.auth.bearer_token.clone();+ // Only an inline token is handed to the installers as an explicit value.+ // One read from `[auth].bearer_token_file` stays out of rendered configs:+ // hook install persists it to the hook credential files, and MCP install+ // routes it through the bridge or an env-var reference (#552).+ let auth_token = config.auth.renderable_bearer_token().map(str::to_owned);let hook_install = |config_file: Option<PathBuf>| InstallHooksArgs {agent,hooks_dir: overrides.hooks_dir.clone(),@@ -405,6 +409,7 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverrideconfig_file: mcp_file,session_aware: false,flavor: None,+ token_env_var: false,});WireInstalls {opencode_dialect,diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex a1b59bcd..915773ec 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -639,6 +639,21 @@ fn exposure_banner(exposure: HttpExposure, local_addr: SocketAddr) -> Option<Str}}+/// A configured `[auth].bearer_token_file` that holds no token must stop the+/// server: starting without one would serve every route unauthenticated, the+/// opposite of what the key asks for.+fn refuse_a_missing_token_file(auth: &AuthSettings) -> Result<()> {+ if let Some(path) = auth.missing_token_file() {+ anyhow::bail!(+ "[auth].bearer_token_file names {}, which is missing or empty; refusing to serve \+ without the bearer token it should hold. Run `ai-memory auth enable` to create a \+ new one, or restore the file from backup.",+ path.display()+ );+ }+ Ok(())+}+/// Validate the trusted proxy's least-privilege credential and optional stable/// root identity before binding the server.fn validate_trusted_proxy_auth(auth: &AuthSettings) -> Result<()> {@@ -1113,6 +1128,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {let mut shutdown = ShutdownSignals::install();validate_web_ui_args(args.enable_web, args.web_ui_dir.as_deref())?;+ refuse_a_missing_token_file(&config.auth)?;config.require_llm_fallback_credentials()?;// Merge config + CLI CORS origins (config first, CLI adds new entries).diff --git a/crates/ai-memory-cli/src/commands/server.rs b/crates/ai-memory-cli/src/commands/server.rsindex 9709d786..236fee45 100644--- a/crates/ai-memory-cli/src/commands/server.rs+++ b/crates/ai-memory-cli/src/commands/server.rs@@ -19,6 +19,14 @@ use crate::server_profiles::{self, ProfileName};/// `servers.toml`, or a failed write.pub fn run(config: &Config, args: ServerArgs) -> Result<()> {let mut stdout = std::io::stdout();+ let root_token = config.auth.token_file_path();+ match &args.command {+ ServerCommand::Add(ServerAddArgs { name, .. })+ | ServerCommand::Remove(ServerRemoveArgs { name }) => {+ refuse_the_root_token_name(&config.data_dir, name, root_token)?;+ }+ ServerCommand::List(_) => {}+ }match args.command {ServerCommand::Add(args) => {let stdin_token = if args.auth_token_stdin {@@ -42,6 +50,24 @@ fn parse_name(raw: &str) -> Result<ProfileName> {})}+/// `auth-tokens/default` holds this install's root bearer once `init` or+/// `auth enable` provisioned it. A profile of that name would read the same+/// file, so the hook would present the root bearer to that profile's server+/// (and `server add --auth-token` would overwrite the root bearer, `server+/// remove` delete it).+fn refuse_the_root_token_name(data_dir: &Path, raw: &str, root_token: Option<&Path>) -> Result<()> {+ let Some(name) = ProfileName::parse(raw) else {+ return Ok(());+ };+ if server_profiles::profile_shares_root_token(data_dir, &name, root_token) {+ bail!(+ "`{name}` names this server's own root bearer token file ([auth].bearer_token_file); \+ choose another profile name"+ );+ }+ Ok(())+}+fn read_token_line(input: &mut impl std::io::BufRead) -> Result<String> {let mut line = String::new();input@@ -182,6 +208,19 @@ mod tests {output(|out| add(data_dir, args, stdin_token, out))}+ /// A profile named after the root bearer's file is refused while that+ /// file is the server's credential; any other name, or the same name on an+ /// install without a root bearer file, is accepted.+ #[test]+ fn the_root_bearer_file_name_cannot_be_registered_or_removed() {+ let dd = tempfile::tempdir().unwrap();+ let root = server_profiles::root_token_path(dd.path());+ let err = refuse_the_root_token_name(dd.path(), "default", Some(&root)).unwrap_err();+ assert!(err.to_string().contains("root bearer"), "{err}");+ assert!(refuse_the_root_token_name(dd.path(), "team-b", Some(&root)).is_ok());+ assert!(refuse_the_root_token_name(dd.path(), "default", None).is_ok());+ }+/// The listing reports whether a token is stored and never the token.#[test]fn list_never_prints_a_token() {diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex e29a52a4..3b79dd7a 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -80,7 +80,11 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {};let args = SetupAgentArgs {server_url,- auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),+ // Only an inline token may be printed into snippets; one read from+ // `[auth].bearer_token_file` stays out of rendered configs (#552).+ auth_token: args+ .auth_token+ .or_else(|| config.auth.renderable_bearer_token().map(str::to_owned)),..args};if matches!(@@ -388,6 +392,7 @@ fn emit_extension_setup_hint(config: &Config, args: &SetupAgentArgs) -> Result<(config_file: None,session_aware: false,flavor: None,+ token_env_var: false,},Some(dialect),)?;diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rsindex 4f7a0d49..1b3a6d65 100644--- a/crates/ai-memory-cli/src/commands/status.rs+++ b/crates/ai-memory-cli/src/commands/status.rs@@ -256,6 +256,9 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {};let (journal_pending, journal_degraded, journal_finish_failed, journal_error) =super::recovery::journal_summary(&config.data_dir);+ // `/admin/status` answered. Without a credential that can only mean the+ // server does not require one.+ let auth_posture = crate::local_auth::AuthPosture::classify(ep.auth_token.is_none(), &ep.url);if args.json {println!(@@ -269,6 +272,7 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {journal_error,capture_mode,&ep,+ auth_posture,))?);} else {@@ -277,6 +281,7 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {println!(" data-dir: {}", report.data_dir);println!(" db: {}", report.db_path);println!(" bind: {}", report.bind);+ println!(" auth: {}", auth_posture.line());println!(" pages: {} (all versions: {})",report.counts.pages_latest, report.counts.pages_all@@ -496,6 +501,7 @@ fn json_report(journal_error: Option<String>,capture_mode: &str,endpoint: &ServerEndpoint,+ auth_posture: crate::local_auth::AuthPosture,) -> serde_json::Value {serde_json::json!({"version": report.version,@@ -521,6 +527,7 @@ fn json_report("capture_mode": capture_mode,"ingest": report.ingest,"client": { "server_url": endpoint.url, "auth": endpoint.auth_token.is_some() },+ "auth_posture": { "posture": auth_posture, "fix": auth_posture.fix() },})}@@ -615,7 +622,10 @@ mod tests {None,"denylist",&endpoint,+ crate::local_auth::AuthPosture::NoneLoopback,);+ assert_eq!(value["auth_posture"]["posture"], "none_loopback");+ assert_eq!(value["auth_posture"]["fix"], "ai-memory auth enable");for key in ["version","data_dir",diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 767d837e..e2ff52ba 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -772,8 +772,12 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {);}// Server-profile tokens (#992) are read by the same hooks, so the same- // reasoning applies; the registry of URLs stays.- if let Err(error) = crate::server_profiles::clear_tokens(&config.data_dir) {+ // reasoning applies; the registry of URLs stays. The root bearer the+ // server itself reads (`[auth].bearer_token_file`) is not a hook's and+ // stays with the server's config.+ if let Err(error) =+ crate::server_profiles::clear_tokens(&config.data_dir, config.auth.token_file_path())+ {eprintln!("ai-memory uninstall warning: could not remove the stored server-profile tokens under {}: {error}",config.data_dir.display()diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 9e81d792..1812f36d 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -889,6 +889,21 @@ pub struct AuthSettings {/// `Authorization: Bearer <token>`. Generate one with/// `ai-memory generate-auth-token`.pub bearer_token: Option<String>,+ /// File holding the shared bearer token, one line, owner-only. A relative+ /// path resolves against the data dir, so a container that mounts the data+ /// dir at `/data` and a host client that sees it at its host path read the+ /// same file. `ai-memory init` on a fresh data dir and `ai-memory auth+ /// enable` set this to `auth-tokens/default`.+ ///+ /// Read once by [`Config::load`] into [`Self::bearer_token`].+ /// `AI_MEMORY_AUTH_TOKEN` still wins over it; setting it together with+ /// `bearer_token` is refused as ambiguous. A token read from here is never+ /// written into a harness config (see [`Self::renderable_bearer_token`]).+ pub bearer_token_file: Option<PathBuf>,+ /// Where `bearer_token_file` resolved to and whether it held a token. Set+ /// by [`Config::load`]; never read from or written to a config file.+ #[serde(skip)]+ pub(crate) token_file: Option<ResolvedTokenFile>,/// Create every new project `restricted` rather than `open` (#708).////// Off by default: a new project is open to every authenticated user, as@@ -967,6 +982,8 @@ impl std::fmt::Debug for AuthSettings {"bearer_token",&self.bearer_token.as_ref().map(|_| "<redacted>"),)+ .field("bearer_token_file", &self.bearer_token_file)+ .field("token_file", &self.token_file).field("secure_cookie", &self.secure_cookie).field("root_username", &self.root_username).field("root_issuer", &self.root_issuer)@@ -994,6 +1011,142 @@ impl std::fmt::Debug for AuthSettings {}}+/// `[auth].bearer_token_file` after [`Config::load`] resolved it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ResolvedTokenFile {+ /// Absolute path the token was read from.+ pub(crate) path: PathBuf,+ /// Whether the file held a non-blank token. A configured file that is+ /// missing or blank leaves [`AuthSettings::bearer_token`] unset, and+ /// `serve` refuses to start rather than run open.+ pub(crate) loaded: bool,+}++impl AuthSettings {+ /// The bearer an installer may write into a harness config or print in a+ /// snippet: one the operator supplied inline (`[auth].bearer_token` or+ /// `AI_MEMORY_AUTH_TOKEN`). A token read from `bearer_token_file` is+ /// `None` here, because that file exists to keep the secret out of+ /// harness configs (#552); those installs reach it through `ai-memory+ /// mcp-bridge`, an env-var reference, or the hook credential files.+ #[must_use]+ pub fn renderable_bearer_token(&self) -> Option<&str> {+ if self.token_file.as_ref().is_some_and(|file| file.loaded) {+ return None;+ }+ self.bearer_token.as_deref()+ }++ /// The token file this install's bearer comes from, when it comes from+ /// one (loaded or not).+ #[must_use]+ pub(crate) fn token_file_path(&self) -> Option<&Path> {+ self.token_file.as_ref().map(|file| file.path.as_path())+ }++ /// The configured token file when it could not supply a token.+ #[must_use]+ pub(crate) fn missing_token_file(&self) -> Option<&Path> {+ self.token_file+ .as_ref()+ .filter(|file| !file.loaded)+ .map(|file| file.path.as_path())+ }++ /// Record a token read from `path`, the way [`Config::load`] would have.+ /// For `auth enable`, which provisions the file after config was loaded and+ /// re-renders wiring in the same process.+ pub(crate) fn adopt_token_file(&mut self, path: PathBuf, token: String) {+ self.bearer_token = Some(token);+ self.token_file = Some(ResolvedTokenFile { path, loaded: true });+ }+}++/// What [`apply_bearer_token_file`] needs to know about the load.+struct TokenFileContext<'a> {+ data_dir: &'a Path,+ /// `AI_MEMORY_AUTH_TOKEN` was set (it already replaced `bearer_token`).+ env_token: bool,+ /// A config file exists at the path this load read.+ config_file_exists: bool,+ server_url: &'a str,+}++/// Resolve `[auth].bearer_token_file` against the final data dir and read it.+///+/// `AI_MEMORY_AUTH_TOKEN` already replaced `bearer_token` and wins here too,+/// exactly as it wins over the inline key. Both keys set in config is+/// refused: which one the server enforces must never be a guess.+///+/// With no key at all, see [`discover_root_token`].+fn apply_bearer_token_file(auth: &mut AuthSettings, ctx: &TokenFileContext<'_>) -> Result<()> {+ if ctx.env_token {+ return Ok(());+ }+ let Some(raw) = auth+ .bearer_token_file+ .as_ref()+ .filter(|path| !path.as_os_str().is_empty())+ else {+ discover_root_token(auth, ctx);+ return Ok(());+ };+ if non_empty(auth.bearer_token.as_deref()).is_some() {+ anyhow::bail!(+ "[auth].bearer_token and [auth].bearer_token_file are both set; keep only one"+ );+ }+ let path = if raw.is_absolute() {+ raw.clone()+ } else {+ ctx.data_dir.join(raw)+ };+ let token = read_trimmed_secret(&path);+ auth.token_file = Some(ResolvedTokenFile {+ path,+ loaded: token.is_some(),+ });+ auth.bearer_token = token;+ Ok(())+}++/// Find this install's root bearer when the config this command loaded does+/// not name it.+///+/// A packaged install keeps its config outside the data dir (`init --config+/// ~/.config/ai-memory/config.toml`, the systemd unit passes the same path),+/// while `install-mcp`, `status` and the bridge run without `--config` and so+/// read no config file at all. They still need the token `init` minted at+/// `<data_dir>/auth-tokens/default`. It is used, as a file-sourced token, only+/// when every one of these holds:+///+/// - no bearer is configured any other way (env, inline key, file key);+/// - no config file exists where this load looked, so no config chose to run+/// without one (an existing install with a config keeps its behaviour);+/// - the server URL is loopback, so the token can only reach this machine;+/// - no server profile named `default` is registered, whose token file this+/// would be (#992).+fn discover_root_token(auth: &mut AuthSettings, ctx: &TokenFileContext<'_>) {+ if non_empty(auth.bearer_token.as_deref()).is_some()+ || ctx.config_file_exists+ || !crate::commands::hook_spool::is_loopback_url(ctx.server_url)+ {+ return;+ }+ let path = crate::server_profiles::root_token_path(ctx.data_dir);+ let Some(token) = read_trimmed_secret(&path) else {+ return;+ };+ // An unreadable registry cannot prove the name is free.+ let profile_named_default =+ crate::server_profiles::root_token_name_is_registered(ctx.data_dir).unwrap_or(true);+ if profile_named_default {+ return;+ }+ auth.token_file = Some(ResolvedTokenFile { path, loaded: true });+ auth.bearer_token = Some(token);+}+/// `[auto_scope]` — controls how the hook-published "currently active/// project" pointer is shared across concurrent callers. The default is/// `per_actor` (since v1.39), which keys the pointer by whatever coordinate the@@ -1991,6 +2144,15 @@ impl Config {}config.data_dir = canonicalise_or_keep(&config.data_dir);+ apply_bearer_token_file(+ &mut config.auth,+ &TokenFileContext {+ data_dir: &config.data_dir,+ env_token: runtime_env.auth_token.is_some(),+ config_file_exists: resolved_config_path.exists(),+ server_url: &config.server_url,+ },+ )?;config.runtime_env = runtime_env;validate_run_profiles(&config.run)?;@@ -3414,6 +3576,194 @@ mod tests {/// A configured list parses verbatim and resolves to exactly those/// words (lowercased), replacing the default outright rather than/// extending it.+ fn load_auth(data_dir: &Path, toml: &str, env_token: Option<&str>) -> Result<Config> {+ let config_path = data_dir.join("config.toml");+ std::fs::write(&config_path, toml).unwrap();+ Config::load_with_runtime_env(+ Some(&config_path),+ Some(data_dir.to_path_buf()),+ RuntimeEnv {+ auth_token: env_token.map(str::to_owned),+ ..RuntimeEnv::default()+ },+ )+ }++ /// A relative `bearer_token_file` resolves against the data dir it was+ /// loaded with, so a container (data dir `/data`) and a host client (the+ /// host path of the same bind mount) read one file.+ #[test]+ fn a_relative_bearer_token_file_resolves_against_the_data_dir() {+ let tmp = TempDir::new().unwrap();+ for dir in ["host", "container"] {+ let dd = tmp.path().join(dir);+ std::fs::create_dir_all(dd.join("auth-tokens")).unwrap();+ std::fs::write(+ dd.join("auth-tokens").join("default"),+ format!("tok-{dir}\n"),+ )+ .unwrap();+ let config = load_auth(+ &dd,+ "[auth]\nbearer_token_file = \"auth-tokens/default\"\n",+ None,+ )+ .unwrap();+ assert_eq!(+ config.auth.bearer_token.as_deref(),+ Some(format!("tok-{dir}").as_str())+ );+ assert_eq!(config.auth.renderable_bearer_token(), None);+ assert_eq!(+ config.auth.token_file_path(),+ Some(config.data_dir.join("auth-tokens/default").as_path())+ );+ assert_eq!(config.auth.missing_token_file(), None);+ }+ }++ #[test]+ fn an_absolute_bearer_token_file_is_read_as_is() {+ let tmp = TempDir::new().unwrap();+ let elsewhere = tmp.path().join("secret");+ std::fs::write(&elsewhere, "abs-token").unwrap();+ let toml = format!(+ "[auth]\nbearer_token_file = {}\n",+ toml_edit::Value::from(elsewhere.to_string_lossy().as_ref())+ );+ let config = load_auth(tmp.path(), &toml, None).unwrap();+ assert_eq!(config.auth.bearer_token.as_deref(), Some("abs-token"));+ }++ /// A configured file that is missing or blank yields no bearer, never an+ /// empty one, and is reported so `serve` can refuse to start open.+ #[test]+ fn a_missing_or_blank_bearer_token_file_is_reported_not_guessed() {+ let tmp = TempDir::new().unwrap();+ let toml = "[auth]\nbearer_token_file = \"auth-tokens/default\"\n";+ let missing = load_auth(tmp.path(), toml, None).unwrap();+ assert!(missing.auth.bearer_token.is_none());+ assert!(missing.auth.missing_token_file().is_some());++ std::fs::create_dir_all(tmp.path().join("auth-tokens")).unwrap();+ std::fs::write(tmp.path().join("auth-tokens").join("default"), " \n").unwrap();+ let blank = load_auth(tmp.path(), toml, None).unwrap();+ assert!(blank.auth.bearer_token.is_none());+ assert!(blank.auth.missing_token_file().is_some());+ }++ /// `AI_MEMORY_AUTH_TOKEN` wins over the file, as it wins over the inline+ /// key, and then counts as an inline (renderable) token as before.+ #[test]+ fn the_env_token_wins_over_the_bearer_token_file() {+ let tmp = TempDir::new().unwrap();+ std::fs::create_dir_all(tmp.path().join("auth-tokens")).unwrap();+ std::fs::write(tmp.path().join("auth-tokens").join("default"), "file-token").unwrap();+ let config = load_auth(+ tmp.path(),+ "[auth]\nbearer_token_file = \"auth-tokens/default\"\n",+ Some("env-token"),+ )+ .unwrap();+ assert_eq!(config.auth.bearer_token.as_deref(), Some("env-token"));+ assert_eq!(config.auth.renderable_bearer_token(), Some("env-token"));+ assert_eq!(config.auth.token_file_path(), None);+ }++ #[test]+ fn an_inline_bearer_and_a_bearer_token_file_together_are_refused() {+ let tmp = TempDir::new().unwrap();+ let err = load_auth(+ tmp.path(),+ "[auth]\nbearer_token = \"inline\"\nbearer_token_file = \"auth-tokens/default\"\n",+ None,+ )+ .unwrap_err();+ assert!(format!("{err:#}").contains("both set"), "{err:#}");+ }++ fn plant_root_token(data_dir: &Path) {+ std::fs::create_dir_all(data_dir.join("auth-tokens")).unwrap();+ std::fs::write(data_dir.join("auth-tokens").join("default"), "root-token\n").unwrap();+ }++ fn load_without_config(data_dir: &Path, runtime_env: RuntimeEnv) -> Config {+ Config::load_with_runtime_env(None, Some(data_dir.to_path_buf()), runtime_env).unwrap()+ }++ /// A packaged install's client commands read no config file (it lives+ /// outside the data dir) and still find the token `init` minted, as a+ /// file-sourced token.+ #[test]+ fn a_client_without_a_config_file_discovers_the_root_bearer() {+ let tmp = TempDir::new().unwrap();+ plant_root_token(tmp.path());+ let config = load_without_config(tmp.path(), RuntimeEnv::default());+ assert_eq!(config.auth.bearer_token.as_deref(), Some("root-token"));+ assert_eq!(config.auth.renderable_bearer_token(), None);+ }++ /// Each guard on discovery, with the case above as the control.+ #[test]+ fn root_bearer_discovery_is_refused_outside_its_narrow_case() {+ // A config file exists and names no token: that install runs open.+ let tmp = TempDir::new().unwrap();+ plant_root_token(tmp.path());+ let config = load_auth(tmp.path(), "[auth]\nsecure_cookie = false\n", None).unwrap();+ assert!(+ config.auth.bearer_token.is_none(),+ "existing config keeps its posture"+ );++ // A remote server must never be handed this machine's root bearer.+ let tmp = TempDir::new().unwrap();+ plant_root_token(tmp.path());+ let remote = load_without_config(+ tmp.path(),+ RuntimeEnv {+ server_url: Some("https://memory.example".into()),+ ..RuntimeEnv::default()+ },+ );+ assert!(remote.auth.bearer_token.is_none());++ // A registered profile named `default` owns that file (#992).+ let tmp = TempDir::new().unwrap();+ let name = crate::server_profiles::ProfileName::parse("default").unwrap();+ crate::server_profiles::add(tmp.path(), &name, "https://team.example", &[], Some("team"))+ .unwrap();+ let profiled = load_without_config(tmp.path(), RuntimeEnv::default());+ assert!(+ profiled.auth.bearer_token.is_none(),+ "a profile token is not a root bearer"+ );++ // An explicit env token wins, as always.+ let tmp = TempDir::new().unwrap();+ plant_root_token(tmp.path());+ let env = load_without_config(+ tmp.path(),+ RuntimeEnv {+ auth_token: Some("env".into()),+ ..RuntimeEnv::default()+ },+ );+ assert_eq!(env.auth.bearer_token.as_deref(), Some("env"));+ assert_eq!(env.auth.token_file_path(), None);+ }++ /// Control: a pre-default config (no key) loads exactly as before, inline+ /// token renderable, no file consulted.+ #[test]+ fn a_config_without_a_bearer_token_file_loads_as_before() {+ let tmp = TempDir::new().unwrap();+ let open = load_auth(tmp.path(), "[auth]\nsecure_cookie = false\n", None).unwrap();+ assert!(open.auth.bearer_token.is_none());+ assert_eq!(open.auth.token_file_path(), None);+ let inline = load_auth(tmp.path(), "[auth]\nbearer_token = \"inline\"\n", None).unwrap();+ assert_eq!(inline.auth.renderable_bearer_token(), Some("inline"));+ }+#[test]fn hook_spool_max_attempts_config_and_runtime_override_precedence() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex 8cdc0d23..42d84f01 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -24,6 +24,7 @@ mod commands;mod config;mod http_client;mod install_layout;+mod local_auth;mod logging;mod marker;mod process_guard;@@ -182,7 +183,7 @@ pub async fn run() -> Result<()> {Command::MoveSession(args) => commands::move_session::run(&config, args).await,Command::Uninstall(args) => commands::uninstall::run(&config, args),Command::Upgrade(args) => commands::upgrade::run(&config, args).await,- Command::Auth(args) => commands::auth::run(&config, args).await,+ Command::Auth(args) => commands::auth::run(&config, args, config_path.as_deref()).await,Command::User(args) => commands::user::run(&config, args).await,Command::ApiKey(args) => commands::api_key::run(&config, args).await,Command::Project(args) => commands::project::run(&config, args).await,diff --git a/crates/ai-memory-cli/src/local_auth.rs b/crates/ai-memory-cli/src/local_auth.rsnew file mode 100644index 00000000..45eebd7b--- /dev/null+++ b/crates/ai-memory-cli/src/local_auth.rs@@ -0,0 +1,223 @@+//! This install's own root bearer: minted by `init` on a fresh data dir and by+//! `ai-memory auth enable`, stored at `<data_dir>/auth-tokens/default`, and+//! named by `[auth].bearer_token_file` so `Config::load` reads it once.+//!+//! The token is read from that file by the server and every thin client, and+//! copied into the hook credential files (`auth-token`, `auth-header`) that+//! every hook front door already reads. It never goes into a harness config or+//! onto a command line (#552).++use std::path::{Path, PathBuf};++use anyhow::{Context as _, Result};++use ai_memory_mcp::auth::generate_token_hex;++/// Bytes of OS CSPRNG entropy in a generated root bearer: 64 hex characters,+/// the same strength `ai-memory generate-auth-token` prints by default.+const ROOT_TOKEN_BYTES: usize = 32;++/// The root bearer after [`provision_root_token`].+pub(crate) struct RootToken {+ pub(crate) path: PathBuf,+ pub(crate) token: String,+ /// False when an existing token was reused.+ pub(crate) created: bool,+}++/// Reuse the token at `path`, or mint one there (`0600`, atomic) when the file+/// is missing or blank. Reuse is what makes `auth enable` idempotent and keeps+/// a forced `init` from rotating a credential every client already holds.+///+/// # Errors+/// Fails when the OS RNG fails or the file cannot be written.+pub(crate) fn provision_root_token(path: &Path) -> Result<RootToken> {+ if let Some(token) = crate::config::read_trimmed_secret(path) {+ return Ok(RootToken {+ path: path.to_path_buf(),+ token,+ created: false,+ });+ }+ let token = generate_token_hex(ROOT_TOKEN_BYTES)+ .map_err(|e| anyhow::anyhow!("generating the root bearer token: {e}"))?;+ crate::server_profiles::store_root_token(path, &token)+ .with_context(|| format!("writing the root bearer token to {}", path.display()))?;+ Ok(RootToken {+ path: path.to_path_buf(),+ token,+ created: true,+ })+}++/// What [`seed_hook_credential`] found.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum HookCredential {+ /// No hook credential was stored; the root bearer now is.+ Seeded,+ /// The stored hook credential already is the root bearer.+ Current,+ /// A different credential is stored (an `ai-memory api-key` token for+ /// attribution, say). It is left alone.+ KeptOther,+}++/// Give the installed hooks the root bearer through the files they already+/// read when `AI_MEMORY_AUTH_TOKEN` is unset: `<data_dir>/auth-token` and+/// `<data_dir>/auth-header`, both `0600`, the pair `install-hooks --apply`+/// writes. A different stored credential wins and is kept: it was put there+/// on purpose.+///+/// # Errors+/// Propagates write failures.+pub(crate) fn seed_hook_credential(data_dir: &Path, token: &str) -> Result<HookCredential> {+ match crate::config::read_hook_auth_token(data_dir) {+ Some(existing) if existing == token => Ok(HookCredential::Current),+ Some(_) => Ok(HookCredential::KeptOther),+ None => {+ crate::config::store_hook_auth_token(data_dir, token).with_context(|| {+ format!(+ "writing the hook credential files under {}",+ data_dir.display()+ )+ })?;+ Ok(HookCredential::Seeded)+ }+ }+}++/// The command `status` and `doctor` name as the fix for an unauthenticated+/// loopback server.+pub(crate) const AUTH_ENABLE_FIX: &str = "ai-memory auth enable";++/// The server's auth posture as `status` and `doctor` report it.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum AuthPosture {+ /// The server requires a bearer token (or the client sends one).+ Token,+ /// The server answered without a credential on a loopback address: safe+ /// from the network, open to every local process and browser page.+ NoneLoopback,+ /// The server answered without a credential on a non-loopback address.+ None,+}++impl AuthPosture {+ /// `server_open` is whether the server is known to answer without a+ /// credential.+ pub(crate) fn classify(server_open: bool, server_url: &str) -> Self {+ match (+ server_open,+ crate::commands::hook_spool::is_loopback_url(server_url),+ ) {+ (false, _) => Self::Token,+ (true, true) => Self::NoneLoopback,+ (true, false) => Self::None,+ }+ }++ /// `auth: ...` text, with the fix on the same line when there is one.+ pub(crate) fn line(self) -> String {+ match self {+ Self::Token => "bearer token".to_owned(),+ Self::NoneLoopback => format!("none (loopback) — fix: `{AUTH_ENABLE_FIX}`"),+ Self::None => "none — set AI_MEMORY_AUTH_TOKEN on the server".to_owned(),+ }+ }++ /// The fix command, for JSON output.+ pub(crate) fn fix(self) -> Option<&'static str> {+ matches!(self, Self::NoneLoopback).then_some(AUTH_ENABLE_FIX)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn posture_names_the_fix_only_for_an_open_loopback_server() {+ let open_local = AuthPosture::classify(true, "http://127.0.0.1:49374");+ assert_eq!(open_local, AuthPosture::NoneLoopback);+ assert_eq!(+ open_local.line(),+ "none (loopback) — fix: `ai-memory auth enable`"+ );+ assert_eq!(open_local.fix(), Some("ai-memory auth enable"));+ assert_eq!(+ AuthPosture::classify(true, "http://localhost:49374/"),+ AuthPosture::NoneLoopback+ );+ assert_eq!(+ AuthPosture::classify(true, "https://memory.example"),+ AuthPosture::None+ );+ let closed = AuthPosture::classify(false, "http://127.0.0.1:49374");+ assert_eq!(closed, AuthPosture::Token);+ assert_eq!(closed.fix(), None);+ }++ #[test]+ fn provisioning_mints_once_then_reuses() {+ let dd = tempfile::tempdir().unwrap();+ let path = crate::server_profiles::root_token_path(dd.path());++ let first = provision_root_token(&path).unwrap();+ assert!(first.created);+ assert_eq!(first.token.len(), ROOT_TOKEN_BYTES * 2);+ assert!(first.token.chars().all(|c| c.is_ascii_hexdigit()));++ let second = provision_root_token(&path).unwrap();+ assert!(+ !second.created,+ "an existing token is reused, never rotated"+ );+ assert_eq!(second.token, first.token);++ // A blank file is not a token.+ std::fs::write(&path, " \n").unwrap();+ let third = provision_root_token(&path).unwrap();+ assert!(third.created);+ assert_ne!(third.token, first.token);+ }++ #[cfg(unix)]+ #[test]+ fn the_root_bearer_is_owner_only() {+ use std::os::unix::fs::PermissionsExt as _;+ let dd = tempfile::tempdir().unwrap();+ let path = crate::server_profiles::root_token_path(dd.path());+ provision_root_token(&path).unwrap();+ let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode(&path), 0o600);+ assert_eq!(mode(path.parent().unwrap()), 0o700);+ }++ #[test]+ fn seeding_never_replaces_a_different_hook_credential() {+ let dd = tempfile::tempdir().unwrap();+ assert_eq!(+ seed_hook_credential(dd.path(), "root").unwrap(),+ HookCredential::Seeded+ );+ assert_eq!(+ crate::config::read_hook_auth_token(dd.path()).as_deref(),+ Some("root")+ );+ assert_eq!(+ seed_hook_credential(dd.path(), "root").unwrap(),+ HookCredential::Current+ );++ crate::config::store_hook_auth_token(dd.path(), "aim_user_key").unwrap();+ assert_eq!(+ seed_hook_credential(dd.path(), "root").unwrap(),+ HookCredential::KeptOther+ );+ assert_eq!(+ crate::config::read_hook_auth_token(dd.path()).as_deref(),+ Some("aim_user_key")+ );+ }+}diff --git a/crates/ai-memory-cli/src/server_profiles.rs b/crates/ai-memory-cli/src/server_profiles.rsindex 765b9f9d..471dd249 100644--- a/crates/ai-memory-cli/src/server_profiles.rs+++ b/crates/ai-memory-cli/src/server_profiles.rs@@ -131,6 +131,59 @@ fn token_path(data_dir: &Path, name: &ProfileName) -> PathBuf {data_dir.join(TOKEN_DIR).join(name.as_str())}+/// The name under `auth-tokens/` that holds this install's own root bearer+/// once `init` or `auth enable` provisions one. It shares the profile layout+/// and parsing rules, so `server add`, `server remove` and `auth enable`+/// refuse to let a registered profile of the same name share the file.+pub(crate) const ROOT_TOKEN_NAME: &str = "default";++/// `[auth].bearer_token_file` as `init` and `auth enable` record it: relative,+/// so it resolves against whichever path the data dir is mounted at.+pub(crate) const ROOT_TOKEN_RELATIVE: &str = "auth-tokens/default";++/// `<data_dir>/auth-tokens/default`.+#[must_use]+pub(crate) fn root_token_path(data_dir: &Path) -> PathBuf {+ data_dir.join(TOKEN_DIR).join(ROOT_TOKEN_NAME)+}++/// Write the root bearer to `path`: the token directory `0700`, the file+/// `0600`, replaced atomically.+///+/// # Errors+/// Propagates directory creation and write failures.+pub(crate) fn store_root_token(path: &Path, token: &str) -> Result<()> {+ if let Some(dir) = path.parent() {+ crate::commands::path_util::create_private_dir(dir)+ .context("cannot create the token directory")?;+ }+ write_private(path, &format!("{token}\n"))+}++/// Whether `servers.toml` registers a profile named [`ROOT_TOKEN_NAME`].+///+/// # Errors+/// An unreadable or invalid registry, which cannot prove the name is free.+pub(crate) fn root_token_name_is_registered(data_dir: &Path) -> Result<bool> {+ let name = ProfileName(ROOT_TOKEN_NAME.to_owned());+ Ok(load(data_dir)?.profiles.contains_key(&name))+}++/// Whether a registered profile would read the same file as the root bearer+/// at `root_token`: a profile named `default` while the root bearer lives at+/// `auth-tokens/default`. Its server would then be handed this install's root+/// credential.+pub(crate) fn profile_shares_root_token(+ data_dir: &Path,+ name: &ProfileName,+ root_token: Option<&Path>,+) -> bool {+ root_token.is_some_and(|path| {+ crate::marker::absolute_normalized(path)+ == crate::marker::absolute_normalized(&token_path(data_dir, name))+ })+}+/// Load `servers.toml`. A missing file is an empty registry; anything else/// that is not exactly the documented shape is an error, so a typo can only/// ever make routing refuse, never make it guess.@@ -397,7 +450,8 @@ pub(crate) fn remove(data_dir: &Path, name: &ProfileName) -> Result<bool> {Ok(discard_token(data_dir, name)? || existed)}-/// Remove every stored profile token, keeping the registry itself.+/// Remove every stored profile token, keeping the registry itself and the+/// server's own root bearer.////// `uninstall` removes the hooks, which are the only readers of these/// tokens; leaving them on disk would strand live credentials the same way@@ -405,10 +459,42 @@ pub(crate) fn remove(data_dir: &Path, name: &ProfileName) -> Result<bool> {/// survives, so a later reinstall lists each profile with `token: missing`/// and refuses its events until a token is stored again.///+/// `keep` is the file `[auth].bearer_token_file` names. That one is the+/// server's credential, not a hook's: removing it would leave a server that+/// refuses to start until `ai-memory auth enable` mints a new one.+////// # Errors/// Propagates IO failures other than "not found".-pub(crate) fn clear_tokens(data_dir: &Path) -> std::io::Result<()> {- match std::fs::remove_dir_all(data_dir.join(TOKEN_DIR)) {+pub(crate) fn clear_tokens(data_dir: &Path, keep: Option<&Path>) -> std::io::Result<()> {+ let dir = data_dir.join(TOKEN_DIR);+ let keep = keep.map(crate::marker::absolute_normalized);+ let entries = match std::fs::read_dir(&dir) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) => return Err(e),+ };+ let mut kept = false;+ for entry in entries {+ let path = entry?.path();+ if keep.as_ref() == Some(&crate::marker::absolute_normalized(&path)) {+ kept = true;+ continue;+ }+ let removed = if path.is_dir() {+ std::fs::remove_dir_all(&path)+ } else {+ std::fs::remove_file(&path)+ };+ match removed {+ Ok(()) => {}+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => return Err(e),+ }+ }+ if kept {+ return Ok(());+ }+ match std::fs::remove_dir(&dir) {Ok(()) => Ok(()),Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),Err(e) => Err(e),@@ -751,7 +837,7 @@ mod tests {).unwrap();- clear_tokens(dd.path()).unwrap();+ clear_tokens(dd.path(), None).unwrap();assert!(!dd.path().join(TOKEN_DIR).exists());assert_eq!(read_token(dd.path(), &name("a")), None);assert_eq!(read_token(dd.path(), &name("b")), None);@@ -762,7 +848,68 @@ mod tests {"the profile is still registered, only its token is gone");- clear_tokens(dd.path()).expect("clearing an already-clear store is not an error");+ clear_tokens(dd.path(), None).expect("clearing an already-clear store is not an error");+ }++ /// The root bearer `[auth].bearer_token_file` names is the server's own+ /// credential: uninstall clears every profile token around it and keeps+ /// it, or the next `serve` would refuse to start.+ #[test]+ fn clear_tokens_keeps_the_root_bearer_and_removes_profile_tokens() {+ let dd = tempfile::tempdir().unwrap();+ let root = root_token_path(dd.path());+ store_root_token(&root, "root-secret").unwrap();+ add(+ dd.path(),+ &name("b"),+ "https://b.example",+ &[],+ Some("tok-b"),+ )+ .unwrap();++ clear_tokens(dd.path(), Some(&root)).unwrap();+ assert_eq!(+ read_token(dd.path(), &name("b")),+ None,+ "profile token removed"+ );+ assert_eq!(+ crate::config::read_trimmed_secret(&root).as_deref(),+ Some("root-secret"),+ "the root bearer survives"+ );++ // Control: without a configured root bearer the same file is just a+ // token in the directory, and goes with the rest.+ clear_tokens(dd.path(), None).unwrap();+ assert!(!dd.path().join(TOKEN_DIR).exists());+ }++ #[test]+ fn a_default_profile_shares_the_root_bearer_only_at_its_path() {+ let dd = tempfile::tempdir().unwrap();+ let root = root_token_path(dd.path());+ assert!(profile_shares_root_token(+ dd.path(),+ &name("default"),+ Some(&root)+ ));+ assert!(!profile_shares_root_token(+ dd.path(),+ &name("team-b"),+ Some(&root)+ ));+ assert!(!profile_shares_root_token(+ dd.path(),+ &name("default"),+ None+ ));+ assert!(!profile_shares_root_token(+ dd.path(),+ &name("default"),+ Some(&dd.path().join("elsewhere"))+ ));}#[test]diff --git a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rsnew file mode 100644index 00000000..889149ef--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs@@ -0,0 +1,767 @@+//! Auth on by default for new installs, through the shipped binary+//! (`docs/security-boundaries.md` row 12).+//!+//! A fresh `ai-memory init` mints a root bearer into+//! `<data_dir>/auth-tokens/default` and records `[auth].bearer_token_file`.+//! The loopback server it configures must then refuse every unauthenticated+//! machine, API and admin route while `/healthz` stays open, and the+//! first-party clients must keep working with no token in their environment:+//! the native hook (through the hook credential files `init` seeds), thin CLI+//! commands (through config), and `ai-memory mcp-bridge` (which reads the+//! file itself). The token must appear in no harness config and no process+//! command line.+//!+//! The control is an install that predates the default: same binary, no token+//! file, and it must behave exactly as before until `auth enable` opts it in.++/// Spawns servers: seconds, not milliseconds, so the slow tier.+mod slow {+ use std::io::{BufRead as _, BufReader, Write as _};+ use std::path::{Path, PathBuf};+ use std::process::{Command, Output, Stdio};+ use std::sync::mpsc;+ use std::time::{Duration, Instant};++ use reqwest::StatusCode;+ use serde_json::{Value, json};++ use crate::e2e_support::{ServerGuard, hermetic, start_serve};++ const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");+ const WORKSPACE: &str = "authdef-ws";+ const PROJECT: &str = "authdef-project";++ /// A temp home and a data dir beside it (not inside it, so a scan of the+ /// home is a scan of harness configs only), plus a repository whose+ /// marker pins the scope the hook writes to.+ struct Install {+ _tmp: tempfile::TempDir,+ root: PathBuf,+ home: PathBuf,+ data_dir: PathBuf,+ repo: PathBuf,+ }++ impl Install {+ fn new() -> Self {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path().to_path_buf();+ let home = root.join("home");+ let repo = home.join("work").join("repo");+ std::fs::create_dir_all(&repo).unwrap();+ for dir in [".config", ".local/share", ".claude"] {+ std::fs::create_dir_all(home.join(dir)).unwrap();+ }+ std::fs::write(+ repo.join(".ai-memory.toml"),+ format!("workspace = \"{WORKSPACE}\"\nproject = \"{PROJECT}\"\n"),+ )+ .unwrap();+ Self {+ data_dir: root.join("data"),+ _tmp: tmp,+ root,+ home,+ repo,+ }+ }++ /// The operator's shell: no `AI_MEMORY_AUTH_TOKEN`, ever.+ fn cmd(&self) -> Command {+ let mut cmd = hermetic(BIN);+ cmd.env("HOME", &self.home)+ .env("USERPROFILE", &self.home)+ .env("XDG_CONFIG_HOME", self.home.join(".config"))+ .env("XDG_DATA_HOME", self.home.join(".local/share"))+ .env("AI_MEMORY_HOME", &self.home)+ .env("AI_MEMORY_DATA_DIR", &self.data_dir)+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env("AI_MEMORY_BACKFILL_ON_START", "false")+ .env("AI_MEMORY_AUTO_IMPROVE__SCHEDULER__ENABLED", "false")+ .env("RUST_LOG", "off")+ .current_dir(&self.home);+ cmd+ }++ fn run(&self, args: &[&str], base: Option<&str>, stdin: Option<&str>) -> Output {+ let mut cmd = self.cmd();+ if let Some(base) = base {+ cmd.env("AI_MEMORY_SERVER_URL", base);+ }+ let mut child = cmd+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap_or_else(|e| panic!("spawn `{}`: {e}", args.join(" ")));+ let mut pipe = child.stdin.take().expect("stdin");+ if let Some(input) = stdin {+ pipe.write_all(input.as_bytes()).expect("write stdin");+ }+ drop(pipe);+ child.wait_with_output().expect("wait")+ }++ fn run_ok(&self, args: &[&str], base: Option<&str>) -> String {+ let out = self.run(args, base, None);+ assert!(+ out.status.success(),+ "`{}` failed: {}\nstdout: {}\nstderr: {}",+ args.join(" "),+ out.status,+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr),+ );+ String::from_utf8(out.stdout).expect("stdout utf8")+ }++ async fn serve(&self, client: &reqwest::Client, log: &str) -> (ServerGuard, String) {+ self.serve_with(client, log, &[]).await+ }++ async fn serve_with(+ &self,+ client: &reqwest::Client,+ log: &str,+ global: &[&str],+ ) -> (ServerGuard, String) {+ start_serve(client, &self.root.join(log), |port| {+ let mut cmd = self.cmd();+ cmd.env_remove("RUST_LOG")+ .args(global)+ .args(["serve", "--transport", "http", "--enable-web", "--bind"])+ .arg(format!("127.0.0.1:{port}"))+ .arg("--no-watcher");+ cmd+ })+ .await+ }++ fn root_token(&self) -> Option<String> {+ let text =+ std::fs::read_to_string(self.data_dir.join("auth-tokens").join("default")).ok()?;+ let token = text.trim().to_owned();+ (!token.is_empty()).then_some(token)+ }++ /// One prompt through the native hook, as an installed hook would run+ /// it: no `--auth-token`, no token in the environment.+ fn hook_prompt(&self, base: &str, session: &str) {+ let payload = json!({+ "session_id": session,+ "cwd": self.repo,+ "prompt": "authdef hook prompt",+ })+ .to_string();+ let out = self.run(+ &[+ "hook",+ "--event",+ "user-prompt-submit",+ "--agent",+ "claude-code",+ "--server-url",+ base,+ ],+ None,+ Some(&payload),+ );+ assert!(+ out.status.success(),+ "hook failed: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ self.run_ok(&["hook-drain"], None);+ }++ /// Every file under `dir` that contains `needle`, skipping `allowed`.+ fn files_containing(dir: &Path, needle: &str, allowed: &[PathBuf]) -> Vec<PathBuf> {+ let mut hits = Vec::new();+ let mut pending = vec![dir.to_path_buf()];+ while let Some(dir) = pending.pop() {+ let Ok(entries) = std::fs::read_dir(&dir) else {+ continue;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if allowed.iter().any(|a| path.starts_with(a)) {+ continue;+ }+ if path.is_dir() {+ pending.push(path);+ } else if let Ok(bytes) = std::fs::read(&path)+ && bytes+ .windows(needle.len())+ .any(|window| window == needle.as_bytes())+ {+ hits.push(path);+ }+ }+ }+ hits+ }++ /// The token may live only in the token file and the two hook+ /// credential files. A harness config, the database, the wiki or a log+ /// carrying it would be a leak.+ fn assert_token_confined(&self, token: &str) {+ let leaks = Self::files_containing(&self.home, token, &[]);+ assert!(leaks.is_empty(), "token in harness/home files: {leaks:?}");+ let allowed = [+ self.data_dir.join("auth-tokens").join("default"),+ self.data_dir.join("auth-token"),+ self.data_dir.join("auth-header"),+ // A spooled event records the bearer it will be replayed with;+ // the spool is drained before every scan, and is 0700.+ self.data_dir.join("hook-spool"),+ ];+ let leaks = Self::files_containing(&self.data_dir, token, &allowed);+ assert!(+ leaks.is_empty(),+ "token copied inside the data dir: {leaks:?}"+ );+ }+ }++ async fn status_of(+ client: &reqwest::Client,+ method: reqwest::Method,+ url: String,+ body: Option<Value>,+ token: Option<&str>,+ ) -> StatusCode {+ let mut req = client+ .request(method, url)+ .header("accept", "application/json, text/event-stream");+ if let Some(body) = body {+ req = req.json(&body);+ }+ if let Some(token) = token {+ req = req.bearer_auth(token);+ }+ req.send().await.expect("request").status()+ }++ /// The routes a token must guard, each sent the way a first-party client+ /// would send it (JSON, no browser headers), so a refusal can only be the+ /// bearer check.+ async fn route_statuses(+ client: &reqwest::Client,+ base: &str,+ token: Option<&str>,+ ) -> Vec<(&'static str, StatusCode)> {+ use reqwest::Method;+ let initialize = json!({+ "jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18", "capabilities": {},+ "clientInfo": {"name": "authdef-e2e", "version": "0"}+ }+ });+ let hook = json!({"session_id": "authdef-route", "cwd": "/tmp", "prompt": "x"});+ vec![+ (+ "/mcp",+ status_of(client, Method::POST, format!("{base}/mcp"), Some(initialize), token)+ .await,+ ),+ (+ "/hook",+ status_of(+ client,+ Method::POST,+ format!(+ "{base}/hook?event=user-prompt-submit&agent=claude-code&workspace={WORKSPACE}&project=authdef-route-probes"+ ),+ Some(hook),+ token,+ )+ .await,+ ),+ (+ "/api/v1/projects",+ status_of(client, Method::GET, format!("{base}/api/v1/projects"), None, token)+ .await,+ ),+ (+ "/admin/status",+ status_of(client, Method::GET, format!("{base}/admin/status"), None, token).await,+ ),+ ]+ }++ async fn healthz(client: &reqwest::Client, base: &str) -> StatusCode {+ client+ .get(format!("{base}/healthz"))+ .send()+ .await+ .expect("healthz")+ .status()+ }++ async fn settled_sessions(client: &reqwest::Client, base: &str, token: &str, want: u64) -> u64 {+ let deadline = Instant::now() + Duration::from_secs(15);+ loop {+ let resp = client+ .get(format!("{base}/admin/sessions/by-agent"))+ .bearer_auth(token)+ .query(&[("workspace", WORKSPACE), ("project", PROJECT)])+ .send()+ .await+ .expect("by-agent");+ let count = if resp.status().is_success() {+ let body: Value = resp.json().await.expect("by-agent json");+ body["by_agent"]+ .as_array()+ .map(|a| a.iter().filter_map(|x| x["sessions"].as_u64()).sum())+ .unwrap_or(0)+ } else {+ assert_eq!(resp.status(), StatusCode::NOT_FOUND, "by-agent refused");+ 0+ };+ if count >= want || Instant::now() >= deadline {+ return count;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }++ #[cfg(target_os = "linux")]+ fn cmdline(pid: u32) -> String {+ std::fs::read(format!("/proc/{pid}/cmdline"))+ .map(|bytes| String::from_utf8_lossy(&bytes).replace('\0', " "))+ .unwrap_or_default()+ }++ /// Drive `ai-memory mcp-bridge` over stdio the way Claude Code does:+ /// `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")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn mcp-bridge");+ let mut stdin = child.stdin.take().expect("stdin");+ let stdout = child.stdout.take().expect("stdout");+ let (tx, rx) = mpsc::channel::<Value>();+ std::thread::spawn(move || {+ for line in BufReader::new(stdout).lines().map_while(Result::ok) {+ if let Ok(value) = serde_json::from_str::<Value>(&line)+ && tx.send(value).is_err()+ {+ break;+ }+ }+ });+ let send = |stdin: &mut std::process::ChildStdin, value: Value| {+ writeln!(stdin, "{value}").expect("write to bridge");+ stdin.flush().expect("flush bridge stdin");+ };+ let wait_for = |id: u64| -> Value {+ let deadline = Instant::now() + Duration::from_secs(30);+ loop {+ let left = deadline.saturating_duration_since(Instant::now());+ match rx.recv_timeout(left) {+ Ok(value) if value["id"] == id => return value,+ Ok(_) => {}+ Err(e) => panic!("bridge gave no reply {id}: {e}"),+ }+ }+ };+ send(+ &mut stdin,+ json!({+ "jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18", "capabilities": {},+ "clientInfo": {"name": "authdef-e2e", "version": "0"}+ }+ }),+ );+ let init = wait_for(1);+ assert!(init.get("result").is_some(), "bridge initialize: {init}");+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),+ );+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}),+ );+ let tools = wait_for(2);+ check(child.id());+ drop(stdin);+ let _ = child.kill();+ let _ = child.wait();+ tools+ }++ /// 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+ /// harnesses and running `auth enable` twice leaves the token in no+ /// harness config and no command line.+ #[tokio::test]+ async fn a_fresh_install_requires_the_token_and_its_own_clients_still_work() {+ let install = Install::new();+ install.run_ok(&["init"], None);+ let token = install.root_token().expect("init minted a root bearer");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ let mode = std::fs::metadata(install.data_dir.join("auth-tokens").join("default"))+ .unwrap()+ .permissions()+ .mode();+ assert_eq!(mode & 0o777, 0o600, "the root bearer is owner-only");+ }++ let client = reqwest::Client::new();+ let (server, base) = install.serve(&client, "serve.log").await;++ for (route, status) in route_statuses(&client, &base, None).await {+ assert_eq!(status, StatusCode::UNAUTHORIZED, "unauthenticated {route}");+ }+ assert_eq!(healthz(&client, &base).await, StatusCode::OK);+ // Control: the same requests with the token get past the gate, so the+ // 401s above are the bearer check and not a broken route.+ for (route, status) in route_statuses(&client, &base, Some(&token)).await {+ assert_ne!(status, StatusCode::UNAUTHORIZED, "authenticated {route}");+ assert!(status.is_success(), "authenticated {route}: {status}");+ }++ // The native hook authenticates through the files `init` seeded.+ install.hook_prompt(&base, "authdef-hook-session");+ assert_eq!(settled_sessions(&client, &base, &token, 1).await, 1);++ // A thin CLI command authenticates through config.+ let status = install.run_ok(&["status"], Some(&base));+ assert!(status.contains("auth: bearer token"), "{status}");++ // The bridge reads the token file itself.+ let tools = bridge_tools_list(&install, &base, |_pid| {+ #[cfg(target_os = "linux")]+ assert!(+ !cmdline(_pid).contains(&token),+ "token on the bridge's command line"+ );+ });+ let listed = tools["result"]["tools"].as_array().map_or(0, Vec::len);+ assert!(listed > 0, "bridge tools/list: {tools}");+ #[cfg(target_os = "linux")]+ assert!(+ !cmdline(server.0.id()).contains(&token),+ "token on the server's command line"+ );++ // Wire the harnesses through the normal install paths, then opt in+ // again: nothing may copy the token into a harness config.+ let hooks_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks");+ let settings = install.home.join(".claude").join("settings.json");+ install.run_ok(+ &[+ "install-hooks",+ "--agent",+ "claude-code",+ "--apply",+ "--hooks-dir",+ hooks_dir.to_str().unwrap(),+ "--config-file",+ settings.to_str().unwrap(),+ ],+ Some(&base),+ );+ install.run_ok(+ &["install-mcp", "--client", "claude-code", "--apply"],+ Some(&base),+ );+ install.run_ok(+ &["install-mcp", "--client", "codex", "--apply"],+ Some(&base),+ );+ let refused = install.run(+ &["install-mcp", "--client", "cursor", "--apply"],+ Some(&base),+ None,+ );+ assert!(+ !refused.status.success(),+ "a literal-header client is refused"+ );+ let first = install.run_ok(&["auth", "enable"], Some(&base));+ let config_after_first =+ std::fs::read_to_string(install.data_dir.join("config.toml")).unwrap();+ let claude_after_first =+ std::fs::read_to_string(install.home.join(".claude.json")).unwrap();+ let second = install.run_ok(&["auth", "enable"], Some(&base));+ assert!(first.contains("kept"), "{first}");+ assert!(second.contains("kept"), "{second}");+ assert_eq!(+ std::fs::read_to_string(install.data_dir.join("config.toml")).unwrap(),+ config_after_first+ );+ assert_eq!(+ std::fs::read_to_string(install.home.join(".claude.json")).unwrap(),+ claude_after_first,+ "a second auth enable changes nothing"+ );+ assert_eq!(install.root_token().as_deref(), Some(token.as_str()));+ let claude: Value = serde_json::from_str(&claude_after_first).unwrap();+ assert_eq!(claude["mcpServers"]["ai-memory"]["args"][0], "mcp-bridge");+ for output in [&first, &second, &status] {+ assert!(!output.contains(&token), "token printed: {output}");+ }+ install.assert_token_confined(&token);+ drop(server);+ }++ /// 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 token+ /// on for the next server start, the hooks keep delivering, Claude Code's+ /// entry becomes the bridge, and no harness config holds the token.+ #[tokio::test]+ async fn an_existing_install_is_unchanged_until_auth_enable() {+ let install = Install::new();+ std::fs::create_dir_all(install.data_dir.join("db")).unwrap();+ std::fs::write(install.data_dir.join("db").join("memory.sqlite"), b"").unwrap();+ install.run_ok(&["init"], None);+ assert_eq!(+ install.root_token(),+ None,+ "an existing install gets no token"+ );++ let client = reqwest::Client::new();+ let (server, base) = install.serve(&client, "serve-open.log").await;+ for (route, status) in route_statuses(&client, &base, None).await {+ assert!(+ status.is_success(),+ "pre-default {route} stays open: {status}"+ );+ }+ assert_eq!(healthz(&client, &base).await, StatusCode::OK);+ let status = install.run_ok(&["status"], Some(&base));+ assert!(+ status.contains("auth: none (loopback) — fix: `ai-memory auth enable`"),+ "{status}"+ );++ std::fs::write(+ install.home.join(".claude.json"),+ json!({"mcpServers": {"ai-memory": {"type": "http", "url": format!("{base}/mcp")}}})+ .to_string(),+ )+ .unwrap();+ let first = install.run_ok(&["auth", "enable"], Some(&base));+ assert!(first.contains("generated"), "{first}");+ let token = install.root_token().expect("auth enable minted a token");+ let config_after_first =+ std::fs::read_to_string(install.data_dir.join("config.toml")).unwrap();+ let claude_after_first =+ std::fs::read_to_string(install.home.join(".claude.json")).unwrap();+ let second = install.run_ok(&["auth", "enable"], Some(&base));+ assert!(second.contains("kept"), "{second}");+ assert_eq!(install.root_token().as_deref(), Some(token.as_str()));+ assert_eq!(+ std::fs::read_to_string(install.data_dir.join("config.toml")).unwrap(),+ config_after_first+ );+ assert_eq!(+ std::fs::read_to_string(install.home.join(".claude.json")).unwrap(),+ claude_after_first+ );+ let claude: Value = serde_json::from_str(&claude_after_first).unwrap();+ assert_eq!(claude["mcpServers"]["ai-memory"]["type"], "stdio");+ assert!(claude["mcpServers"]["ai-memory"].get("env").is_none());++ // The running server read its config at start; the restart applies it.+ drop(server);+ let (server, base) = install.serve(&client, "serve-closed.log").await;+ for (route, status) in route_statuses(&client, &base, None).await {+ assert_eq!(+ status,+ StatusCode::UNAUTHORIZED,+ "after auth enable {route}"+ );+ }+ assert_eq!(healthz(&client, &base).await, StatusCode::OK);+ install.hook_prompt(&base, "authdef-enabled-session");+ assert_eq!(settled_sessions(&client, &base, &token, 1).await, 1);+ for output in [&first, &second] {+ assert!(!output.contains(&token), "token printed: {output}");+ }+ install.assert_token_confined(&token);+ drop(server);+ }++ /// The packaged layout (README quick-start, systemd unit): config outside+ /// the data dir, passed to `init` and `serve` but not to the client+ /// commands an operator types next. Those still find the token, and+ /// `install-mcp` wires Claude Code through the bridge.+ #[tokio::test]+ async fn a_packaged_install_with_an_external_config_wires_its_clients() {+ let install = Install::new();+ let config = install+ .home+ .join(".config")+ .join("ai-memory")+ .join("config.toml");+ let config = config.to_str().unwrap();+ install.run_ok(&["--config", config, "init"], None);+ let token = install.root_token().expect("init minted a root bearer");+ assert!(!install.data_dir.join("config.toml").exists());++ let client = reqwest::Client::new();+ let (_server, base) = install+ .serve_with(&client, "serve-packaged.log", &["--config", config])+ .await;+ for (route, status) in route_statuses(&client, &base, None).await {+ assert_eq!(status, StatusCode::UNAUTHORIZED, "unauthenticated {route}");+ }++ let status = install.run_ok(&["status"], Some(&base));+ assert!(status.contains("auth: bearer token"), "{status}");+ install.run_ok(+ &["install-mcp", "--client", "claude-code", "--apply"],+ Some(&base),+ );+ let claude: Value = serde_json::from_str(+ &std::fs::read_to_string(install.home.join(".claude.json")).unwrap(),+ )+ .unwrap();+ assert_eq!(claude["mcpServers"]["ai-memory"]["args"][0], "mcp-bridge");+ let tools = bridge_tools_list(&install, &base, |_| {});+ assert!(+ tools["result"]["tools"]+ .as_array()+ .is_some_and(|t| !t.is_empty()),+ "{tools}"+ );+ install.hook_prompt(&base, "authdef-packaged-session");+ assert_eq!(settled_sessions(&client, &base, &token, 1).await, 1);+ install.assert_token_confined(&token);+ }++ /// Uninstalling the hooks removes the hook credential files and every+ /// profile token, but keeps the root bearer: it is the server's+ /// credential. And a server whose configured token file is gone refuses to+ /// start instead of serving open.+ #[test]+ fn uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server() {+ let install = Install::new();+ install.run_ok(&["init"], None);+ let token = install.root_token().unwrap();+ let hooks_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks");+ install.run_ok(+ &[+ "install-hooks",+ "--agent",+ "claude-code",+ "--apply",+ "--hooks-dir",+ hooks_dir.to_str().unwrap(),+ ],+ None,+ );+ install.run_ok(&["uninstall", "--apply", "--only", "hooks", "--yes"], None);+ assert_eq!(install.root_token().as_deref(), Some(token.as_str()));+ assert!(!install.data_dir.join("auth-token").exists());+ assert!(!install.data_dir.join("auth-header").exists());++ std::fs::remove_file(install.data_dir.join("auth-tokens").join("default")).unwrap();+ let mut child = install+ .cmd()+ .args([+ "serve",+ "--transport",+ "http",+ "--bind",+ "127.0.0.1:0",+ "--no-watcher",+ ])+ .stdin(Stdio::null())+ .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();+ let _ = child.wait();+ panic!("serve kept running without its configured bearer token");+ }+ 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("bearer_token_file"), "{stderr}");++ // `auth enable` repairs it.+ install.run_ok(&["auth", "enable", "--no-mcp"], None);+ assert!(install.root_token().is_some());+ }++ /// The Docker wrapper's host-client handoff: a native client pointed at a+ /// copied token file through `AI_MEMORY_AUTH__BEARER_TOKEN_FILE`, with a+ /// host data dir of its own, authenticates and still treats the token as+ /// file-sourced (it is never rendered into a harness config).+ #[tokio::test]+ async fn a_host_client_given_the_token_file_by_env_authenticates() {+ 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-host.log").await;++ let host = Install::new();+ let copy = host.root.join("server-token");+ std::fs::write(©, format!("{token}\n")).unwrap();+ let mut cmd = host.cmd();+ let out = cmd+ .env("AI_MEMORY_SERVER_URL", &base)+ .env("AI_MEMORY_AUTH__BEARER_TOKEN_FILE", ©)+ .args(["status"])+ .output()+ .unwrap();+ assert!(+ out.status.success(),+ "host status: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ let out = host+ .cmd()+ .env("AI_MEMORY_SERVER_URL", &base)+ .env("AI_MEMORY_AUTH__BEARER_TOKEN_FILE", ©)+ .args(["install-mcp", "--client", "claude-code", "--apply"])+ .output()+ .unwrap();+ assert!(+ out.status.success(),+ "{}",+ String::from_utf8_lossy(&out.stderr)+ );+ let leaks = Install::files_containing(&host.home, &token, &[]);+ assert!(leaks.is_empty(), "token in host harness files: {leaks:?}");++ // Control: without the variable the host client has no token.+ let out = host+ .cmd()+ .env("AI_MEMORY_SERVER_URL", &base)+ .args(["status"])+ .output()+ .unwrap();+ assert!(!out.status.success(), "the host client must need the token");+ }+}diff --git a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs b/crates/ai-memory-cli/tests/suite/doctor_e2e.rsindex 6700ae49..9962812a 100644--- a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs@@ -146,6 +146,10 @@ mod slow {.expect("doctor --json report");assert_eq!(report["capture_owner_active"], false);assert_eq!(report["identity"]["level"], "anonymous");+ assert_eq!(+ report["auth_posture"], "none_loopback",+ "an open loopback server is reported with the `auth enable` fix"+ );assert_eq!(report["project_coordinate"]["server"]["status"], "exact");assert_eq!(report["project_coordinate"]["server"]["requested_name"],diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 56d655d3..e4b448c6 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -5,6 +5,7 @@//! as the single `suite` target and never builds the sibling files on their own,//! so a new file must be declared here (`scripts/check-test-suites.*` enforces it).+mod auth_default_e2e;mod autoscope_env;mod backfill_dry_run;mod backfill_e2e;diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 8a73d793..4b624e25 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -732,6 +732,9 @@ profileRun `ai-memory --help` for the full tree.+`auth enable` turns on the root bearer for an install created before+new installs got one; see [`[auth]` root bearer](#auth-root-bearer).+`auto-improve-report` is read-only by default; `--stage` creates one pendingtelemetry report page for audit/approval without staging learning-memory edits.@@ -1277,6 +1280,42 @@ integration headers as chat. That endpoint's wire shape follows theOpenAI-compatible contract Copilot documents for chat, not a publishedembeddings spec, and is not covered by a live test against Copilot here.+### `[auth]` root bearer++```toml+[auth]+bearer_token_file = "auth-tokens/default" # written by `init` on a fresh data dir+ # and by `ai-memory auth enable`+# bearer_token = "..." # inline alternative; never both+```++The root bearer comes from, in order: `AI_MEMORY_AUTH_TOKEN`, then+`[auth].bearer_token` or `[auth].bearer_token_file` (setting both is a startup+error). `Config::load` reads the file once. A relative path resolves against+the data dir, so a container that mounts it at `/data` and a host client that+sees the host path read the same file. A configured file that is missing or+blank leaves no bearer, and `serve` then refuses to start. Env:+`AI_MEMORY_AUTH__BEARER_TOKEN_FILE`.++`ai-memory init` mints the token (32 random bytes, hex, `0600` under a `0700`+`auth-tokens/`) only on a fresh data dir: no config file and no database yet,+and no bearer supplied another way. An existing install keeps the loopback+no-auth behaviour until `ai-memory auth enable`, which is idempotent: it reuses+or mints the file, records the key, copies the token into the hook credential+files (`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.++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+never inlines it. Client commands of a packaged install, whose config lives+outside the data dir and so is not read without `--config`, use+`<data_dir>/auth-tokens/default` when no config file exists where they look,+the server URL is loopback and no `default` server profile is registered.+`/healthz` stays unauthenticated.+## Future work* **M9.5: local embeddings via `ort`.** Bundle `bge-small-en-v1.5`diff --git a/docs/install.md b/docs/install.mdindex 93af46dd..6f5c4f2b 100644--- a/docs/install.md+++ b/docs/install.md@@ -311,13 +311,28 @@ $EDITOR ~/.config/ai-memory/config.toml$EDITOR ~/.config/ai-memory/env```-For a loopback-only local service, bearer auth is optional. If you want one:+`init` on a fresh data dir also writes a random root bearer token to+`~/.local/share/ai-memory/auth-tokens/default` (owner-only) and records+`bearer_token_file = "auth-tokens/default"` in the config, so the service+requires it on every route except `/healthz`. You never copy it by hand:+`install-hooks --apply` and `install-mcp --apply` find it in the data dir,+the hooks read it from there, and Claude Code is registered as the+`ai-memory mcp-bridge` stdio bridge, which reads the file at launch. Codex and+Prime Agent reference `$AI_MEMORY_AUTH_TOKEN` instead; export it where you+start them:```bash-TOKEN=$(ai-memory generate-auth-token)-printf 'AI_MEMORY_AUTH_TOKEN=%s\n' "$TOKEN" >> ~/.config/ai-memory/env+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.++An install created before this default keeps running without auth.+`ai-memory status` then shows `auth: none (loopback)`; run+`ai-memory auth enable` and restart the service to turn the token on.+Start and inspect the service:```bash@@ -336,8 +351,9 @@ loginctl enable-linger "$USER"Verify the HTTP server:```bash-curl http://127.0.0.1:49374/mcp-# Expect a JSON-RPC error, which means the server is reachable.+curl -s http://127.0.0.1:49374/healthz+# Expect {"status":"ok"}. /healthz needs no token; `curl -sI http://127.0.0.1:49374/mcp`+# answers 401 without one.```### System-level service@@ -367,6 +383,17 @@ sudoedit /etc/ai-memory/envThe package installs `/etc/ai-memory/env` as root-readable only because it mayhold API keys. Keep that file out of backups or logs that other users can read.+`init` also wrote the root bearer token to+`/var/lib/ai-memory/auth-tokens/default`, readable only by the `ai-memory`+user. To wire your own login's agents to this server, copy it into your+user's data dir once; `install-mcp` and `install-hooks` then find it there:++```bash+install -d -m 0700 ~/.local/share/ai-memory/auth-tokens+sudo cat /var/lib/ai-memory/auth-tokens/default \+ | install -m 0600 /dev/stdin ~/.local/share/ai-memory/auth-tokens/default+```+For LAN exposure, set a non-loopback bind and allowed hosts in`/etc/ai-memory/config.toml`, and set a bearer token in `/etc/ai-memory/env`:@@ -2943,7 +2970,16 @@ address you published to. The `-p` above is therefore doing the real work: itis what keeps this container loopback-only. If you change it to publish on aLAN address, set `AI_MEMORY_AUTH_TOKEN` as well.-Then wire up the agent CLI. Both commands default to no auth and+A container started this way has no token, since it never ran `init`. To+require one, run `ai-memory auth enable` through the wrapper (it writes the+token into the volume), `docker restart ai-memory`, then re-run+`ai-memory install-hooks --agent <agent> --apply` so the host hooks get it.+`install-hooks` copies the token from the volume to an owner-only file under+`~/.local/share/ai-memory/native-runner/`, and the commands the wrapper runs+natively (`install-hooks`, `mcp-bridge`, `run`) read it from there, never from+a command line.++Then wire up the agent CLI. Both commands default to`http://127.0.0.1:49374` - no extra flags needed for the local case:```bashdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 13269f0b..f4c22c47 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -12,6 +12,15 @@ Factory Droid, Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no> `Authorization: Bearer <token>` header to the `headers` block when bearer auth> is enabled. The MCP wire protocol expects the `/mcp` path suffix on the URL.+> **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.+> **Transport is stateless by default.** Since v0.1.2 the HTTP transport> answers each request independently (plain JSON, no `Mcp-Session-Id`> required), so any client that points a remote URL at `/mcp`, includingdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex e0a40dae..f2e94716 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -71,14 +71,14 @@ means the boundary is not built yet.| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG || 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized, and every word that holds several words, such as a quoted `sh -c` script or a `"$(…)"` substitution, re-split to four levels by `ShellCommand::split`/`push_nested_words`, a deeper script metadata-only; ANSI-C strings decoded and a backslash before an ordinary letter dropped (`shell_words`, `push_word`); backslash-newline continuations joined (`shell_words`); a parameter default's operand, a value glued to a short flag and a `file:` URL's path read as candidates (`parameter_operands`, `shell_arguments`, `file_url_path`); PowerShell and cmd escape characters read out under the `PowerShell` tool or on a Windows host (`without_windows_escapes`); `~+` resolved to the cwd and a `~-`/`~N`/`~name` prefix metadata-only (`names_unknown_directory`); shell and interpreter options that take a value skipped while looking for a `-c` script or inline code (`takes_shell_value`, `runs_inline_code`, which also lists `lua`/`Rscript`/`osascript -e`, and `su -c`/`script -c` as script runners); paths compared without regard to case on a macOS host (`fold_case`, set by `resolve`; patterns and candidates composed to NFC and lowercased in full by `fold_path`, TS `captureFold`; client-only, the server's sentinel re-inspection never depends on it); a `file:` URL cut at its query or fragment before decoding (`file_url_path`); a parameter default nested past four levels metadata-only and a default read again after backslash removal (`parameter_operands`, `push_word_reading`); a tilde expanded or treated as an unknown directory only when the shell expands it, unquoted and in a script rather than a quoted message or argv element, every tilde under PowerShell (`marked_shell_words`, `literal_tildes`, `expand_tilde`); a file or shell read of a harness's saved tool output, or a glob that could match one, metadata-only under an active policy (`output_spool`: Claude Code `tool-results/` and `tasks/*.output`, OpenCode `tool-output/`, Pi `pi-bash-*.log`; glob segments fit a name they share a match with, `globs_intersect`, TS `captureGlobsIntersect`, and one fitting segment must spell three characters in a row of that name's distinctive text literally, `spells`, TS `captureSpells`, so `*.log` is not read as `pi-bash-*.log`, a trade-off that leaves a glob with no such literal run, `/tmp/p?-b*`, outside the rule; the TS matcher applies it to `read_many_files` entries too); every other marker governing a file-tool target (an `apply_patch`'s header paths, read after leading whitespace, `patch_paths`), a search/list tool's directory, file or path-like glob argument (`search_scope`, Hermes `file_glob` included; a grep `pattern` is not read) or a separator-bearing shell argument also inspects the call, found by the lexical marker walk from each location's nearest existing directory, each directory's answer remembered for every lookup that passes it (`marker.rs` `MarkerMemo`, TS `captureMemoMarker`, seeded with the event's own walk, `remember`, TS `captureMemoRemember`), bounded (4,096 locations, 16 markers, and 16,384 probes sharing the glob walk's 50 ms, `MAX_LOOKUP_PROBES`, TS `CAPTURE_MAX_LOOKUP_PROBES`; locations outside the own checkout are looked up first, a glob's literal root before the walk below it (whose single listing can spend the time budget on a large directory), and past a bound fail closed as under an invalid policy, while running out inside the own checkout, whose locations are looked up shallowest first, ends the lookup, its own policy governing there) and combined strictest-first (`capture_lookup_locations`, `CaptureDecision::stricter`, `hook.rs` `foreign_capture_decision`, also applied by `transcript_capture.rs` `decide_call`; TS `captureForeignConfigs`, `captureDecide`, `captureSearchScope`, `capturePatchPaths`); a location with glob syntax is looked up from its literal root and, when that root lies outside the event's `.git` checkout, every directory the glob could pass through is checked for a marker (`glob_walk`, `hook.rs` `GlobBudget::markers_below`; TS `captureGlobWalk`, `captureMarkersBelow`, `captureOwnCheckout`: a `*`/`?` segment lists the child directories it matches, a class/brace/group every child, a `**` the subtree except the event's checkout's; a glob rooted inside the event's checkout is not walked; a checkout root at or above the home directory, or the filesystem root, is never the own checkout for these rules (`own_checkout`), so a dotfiles `~/.git` does not stop the walk from `~/Projects`; symlinks never followed; 256 directories, counted as a `**` lists, 32,768 entries and 50 ms, `MAX_GLOB_TIME`, TS `CAPTURE_MAX_GLOB_MS`, injectable clock, past which, or for a brace/group spanning a separator, a `..`/`~` alternative or one a bounded brace expansion builds, `brace_alternatives`, TS `captureBraceAlternatives`, a directory alternative bash before 5.2 expands to `..` (`.{*,x}/`), or an expansion too large to list whose pieces could build one of these (`brace_overflow_could_leave`, TS `captureBraceOverflowLeaves`: integer and letter sequences cannot, so `file{1..200}.txt` is walked like any glob), the call fails closed); a `..` after a `**` is read both as the `**` matching no directory and as matching some, by the event's own matcher and the lookup (`normalize_readings`, TS `captureReadings`, at most 16 readings, past which the call fails closed), and so is a directory segment that bash before 5.2 can expand to `..` (`could_name_parent`, `class_glob_matches` with POSIX classes such as `[[:punct:]]` and extglob groups such as `@(.)`, `?(.)`, `*(.)`, `+(.)`, `!(x)`; TS `captureCouldNameParent`, `captureClassGlob`, `captureNamedClass`), read as `..` too; inside double quotes a backslash before `$` or a backquote is dropped, so a quoted script (`bash -c "…"`, `eval "…"`) re-split for its words reads an ANSI-C string as the shell it runs does (`shell_tokens`, TS `captureMarkedWords`); a zsh glob group kept in its word and ANSI-C numeric escapes decoded are fed to the lookup (`shell_tokens` with `expand`, `ShellWords::expanded`, `glob_group`, `ansi_c_numeric_escape`; TS `captureMarkedWords(…, true)`, `captureGlobGroup`, `captureAnsiNumeric`); a file tool whose targets cannot be read or resolved, and a search/list argument that is not a string, fail closed; the path of a git `REV:path` object name tried from the cwd and the marker directory (`git_object_path`); Antigravity `run_command` resolved from its `Cwd`); an invalid marker makes file, search/list and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion, a bracket class (a leading `]` included), a zsh glob group or extglob, or a numeric/control ANSI-C escape (`has_unevaluated_expansion`, also run on scripts given to `sh -c`, `eval` or a substitution), or when it runs inline interpreter code (`runs_inline_code`: `python -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `deno eval`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`, `captureShellSplit`, `captureUnevaluatedExpansion`, `captureInlineCode`, `captureGitObjectPath`, `captureGlobBelow`, the `reader` flag). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn; transcript imports (`ai-memory backfill`, including the automatic first-boot run, the `ai-memory run` ledger upload, and `ai-memory recover`'s finish-failed re-import and degraded-run replay in `recovery.rs` `recover_finish_failed`/`recover_degraded_run`, each built for the journaled checkout's `cwd`) apply the same decision table through `commands/transcript_capture.rs`: each recorded tool call is rebuilt in its agent's hook shape (`capture_policy.rs` `tool_call_payload`) and inspected by the checkout's policy, and by a reroute destination's policy too; a Drop removes the call and its result (paired by native id, else the strictest call of the turn when the result has no id; a result whose id matches no call, or with no call, follows the orphan rule: dropped under a policy, content-free without one), metadata-only posts the hook's metadata-only body with its protocol (backfill) or a withheld placeholder keeping only the family and a call id that passes the server's `valid_call_id` (ledger), and a shell call whose recorded arguments cannot be parsed drops; both imports also apply the hook's repository admission gate (`hook.rs` `checkout_admits_capture`: persisted capture mode, marker opt-in, readable routing marker — the same helpers the hook's own gate uses), so under allowlist mode an unmarked checkout imports nothing, prompts included: `backfill` stops before contacting the server and the run ledger finishes with no events; a tool the transcript names differently from the hook is rebuilt under the hook's name and fields (`capture_policy.rs` `hook_tool_call`: Codex `exec_command` `{cmd, workdir}` → `Bash` `{command, workdir}`); the Claude Code and Codex JSONL adapters label each event with its record's cwd (`transcript.rs` `stamp_record_cwd`, `RECORD_CWD_KEY`), from which the import resolves arguments, policy and reroutes, falling back to the session cwd, and which is removed before a ledger upload; a rerouted call, and an event whose record cwd lies outside the checkout, must pass that directory's admission gate, resolve to the same server-profile route as the checkout and to the same project scope (`transcript_capture.rs` `admits_elsewhere` → `hook.rs` `checkout_admits_capture` + `delivers_to_same_server`, which compares two `resolve_hook_route` results and never matches a refused selection, + `routes_to_same_project`, which compares the two `hook_scope` hint sets and, when they leave the project to the server, under `repo-root` the repository/marker anchor or the directory itself, under the default `basename` the directory itself or a destination inside the repository whose root is the source), else it drops with its result, since the import files every event under the importing project; compaction, checkpoint and annotation events answer to the same record-cwd checks; Claude Code `!` shell-mode output (a user message opening with a `<bash-stdout>`/`<bash-stderr>`/`<local-command-stdout>` block, whatever it holds) is dropped (`shell_mode_output`); the Claude Code adapter excludes harness-written background-task turns (`transcript.rs` `claude_task_notification`: `origin.kind` `task-notification` in any case, or a first text block opening with a `<task-notification` tag in any case, attributes allowed, after a byte-order mark, zero-width characters or whitespace) and records a compaction summary (`isCompactSummary` true, `"true"` or `1`, `truthy`) as a compaction event, which backfill does not post; a tool the matcher does not recognize (unknown family: MCP tools, Codex `view_image`, …) keeps only its family whatever the policy, as the live server stores for it (`EventCapture::Unrecognized`: backfill posts title `tool unknown` and body `tool_family: unknown`, the ledger a withheld placeholder), and so does a result with no call to inherit from ; in a Windows session every candidate, shell argument and `workdir` is read as the file Windows opens before matching (`windows_spelling`, `windows_segment`, `command_base`; TS `captureWindowsSpelling`/`captureResolve`/`captureBase`): Git Bash/MSYS2/Cygwin `/c/…` and `/cygdrive/c/…`, a drive-less rooted path on the cwd's drive, the `\\?\`/`\\.\`/`\??\` and `UNC` prefixes, the local administrative share (`\\localhost\C$`), and per-segment alternate-data-stream suffixes and trailing dots/spaces, any other device path unusable (metadata-only for a file tool); `/c/…` and `/cygdrive/c/…` are also read from the root of the cwd's drive, as a native tool reads them, and either reading matching drops (`windows_spellings`, `normalize_candidates`, `normalize_readings`; TS `captureWindowsSpellings`/`captureAllReadings`); the cwd, the marker directory, home and an absolute pattern get the same reading so every side shares one spelling (`normalize_root`, `compile`; TS `captureRoot`, the marker directory cut lexically); a Windows session also reads each shell command and argv element with every backslash literal, as PowerShell and cmd do, so a bare or double-quoted `\\server\share\…` or `\\?\C:\…` argument keeps its prefix (`literal_shell_words`, threaded through `push_nested_words`/`push_argv_item`; TS `captureMarkedWords(…, literal)`); the harness-spool check is linear in the path and charged to the match budget, past it fail-closed (`output_spool`, TS `captureOutputSpool`); a shell command over `MAX_SHELL_COMMAND_CHARS` (1 MiB) is metadata-only and its marker lookup unprovable (`ShellCommand::oversized`, TS `captureCommandOversized`); Hermes `execute_code` is metadata-only under an active policy (`INLINE_CODE_TOOL_NAMES`); the TS file/search/non-file/inline-code/output-reader tool lists and the command limit are generated from the native constants (`FILE_TOOL_NAMES` and siblings, spliced by `ts_capture_policy_v1`), and the TS marker reader honours every TOML spelling of the capture table toml_edit does (dotted `capture.ignore_paths`, quoted or spaced `[capture]` headers) and fails closed on the shapes it rejects (inline table, `[[capture]]`, `[capture.x]`, a second definition) (`captureTomlKey` and the `captureConfigAt` section loop), tracks every multi-line array so a line inside one (`["docs"]`) is never a header, and fails closed on a line that is neither header nor key/value, a key line swallowed by an open array, text after a continued array closes, or an inline table left open at a line end (`captureValueScan`); the TS glob walk reads a directory one entry at a time with `opendirSync`, stopping at the entry bound; in a Windows session a shell argument or `workdir` that is drive-relative (`C:docs\x`, a bare `C:`) or a device path naming no drive or share (`\\?\GLOBALROOT\…`, `\\.\HarddiskVolume3\…`) makes the command metadata-only, a POSIX shell's reading of a placeable native path (`C:\repo\x` read as `C:repox`) excused and a device reading never (`windows_unplaceable`, `match_command`, the `workdir` check in `inspect`; TS `captureWindowsUnplaceable`, `captureMatchCommand`, `captureDecide`); a PowerShell `FileSystem::`/`Microsoft.PowerShell.Core\FileSystem::` provider prefix is dropped before a Windows path is read (`strip_powershell_provider` in `candidate_raw`/`command_base`; TS `captureStripProvider` in `captureResolve`/`captureBase`); a POSIX absolute pattern in a Windows marker makes the marker invalid (`compile`; TS `captureConfigAt`) (GHSA-gcpc-88hm-3xqr) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec` and `PowerShell`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `claude_code_powershell_honors_ignored_paths_on_a_windows_host` (#1186: Windows-spelled and `-Param:value` paths drop, public-path and `git status` controls kept, invalid marker metadata-only), `gemini_cli_shell_and_read_many_files_honor_ignored_paths` (Gemini `run_shell_command` incl. `dir_path`/`directory`, and `read_many_files` globs via `match_globs`: excluded literal, mixed public+excluded, `docs/*`, recursive `**` and case-variant entries drop, an `exclude` list cannot rescue them, unsupported glob syntax and malformed lists are metadata-only, public entries kept, POSIX and Windows hosts) and `globstar_reaches_lets_double_star_span_any_depth`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell admitted for an unevaluated expansion, inactive refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`, `gemini_cli_shell_and_read_many_files_exclusions_drop_before_spool` (pre- and post-tool events with an excluded path are never spooled; public controls spool with their family); `capture_policy.rs` `read_many_files_directory_entries_cannot_reach_ignored_paths` (shared `read_many_files_directories` vectors: `docs`, `.`, `./`, `docs/`, case and `..` variants drop; `src`, `README.md`, `docs/adrx` kept), `output_reader_tools_are_metadata_only_only_under_a_policy` (active and invalid strip, inactive and an unrelated unknown tool keep), `copilot_cli_runtime_file_tools_are_scoped_to_copilot`, `unevaluated_shell_expansions_respect_quoting` (also leading-`]` classes, zsh groups and extglobs, ANSI-C numeric escapes; subshells, `$((…))`, `<(…)`, array assignments kept), the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `quoted_scripts_in_string_commands_are_read_like_command_lines` (`sh -c`, `timeout … bash -c`, `"$(…)"`, `NAME="$(…)"`, backquotes, two nested shells and an inline-interpreter literal drop; `bash -c 'cargo test'` and `"$(git rev-parse HEAD)"` kept; four levels read, a fifth metadata-only), `inline_interpreter_code_is_metadata_only_under_an_active_policy` (inline code metadata-only, kept with no policy; modules, script files and `grep -e` unaffected), `git_object_names_are_path_candidates` (`HEAD:`, `:`, `:N:` and `@{n}` names drop, also from a subdirectory; drive letters, URLs, `NAME=a:b` and flags are not object names; a public object name kept), `ansi_c_strings_and_escaped_letters_are_read_like_the_shell`, `antigravity_run_command_resolves_arguments_from_its_cwd` (absolute and relative `Cwd` drop, a public `Cwd` kept, another agent's `Cwd` key ignored), `windows_escape_characters_are_read_on_a_windows_host` (caret and backquote spellings drop on a Windows host, public controls kept, a POSIX host reads both literally), `a_case_folding_host_matches_paths_without_regard_to_case` (file tool and shell drop with folding, keep without, public control kept; folding injected through `resolve_for_host` so it runs on every CI OS), the shell fixture's continuation, PowerShell/cmd escape, option-value, runner, interpreter, glued-flag, `file:` URL, tilde, parameter-default and `fold_case` vectors with their controls, the near-miss controls added to `common_commands_stay_kept_under_an_active_policy` (also quoted tildes, a `file:` URL with a query, a shallow nested default and a scratchpad log), the shell fixture's `file:` query/fragment, deep-default, escaped-default, quoted/argv/script tilde, PowerShell tilde, harness-output and Unicode `fold_case` vectors and the `decisions` harness-output vectors with their controls, `reading_a_harness_output_spool_is_metadata_only_under_a_policy` (active and invalid strip, inactive keeps, same-named files elsewhere kept, an ignored path still drops), `capture_lookup_locations_name_every_path_a_call_spells`, the Unicode rows of `a_case_folding_host_matches_paths_without_regard_to_case`, **`hook.rs` `another_checkouts_exclusions_hold_for_a_call_made_elsewhere`** (relative, absolute, glob and unmarked-Hermes shell calls naming another checkout's excluded file never spool; a broken foreign marker and too many foreign markers spool metadata-only; public, own-file and few-marker controls spool with content), **`hook.rs` `globs_searches_and_unreadable_targets_answer_to_another_checkout`** (sibling and parent-folder `*`, brace, bracket, `**` and separator-spanning-brace shell globs, a Grep path, a Glob pattern, a parent-folder Grep filter, a Gemini `search_file_content` directory, a Codex `apply_patch` header and a target-less Read never spool content; public-glob, own-glob, own-`**`, own-search, own-Glob-`**`, public-search and own-patch controls spool with content), `transcript_capture.rs` `globs_and_searches_reaching_another_checkout_honor_its_policy`, `capture_policy.rs` `glob_walk_follows_every_segment_a_glob_could_pass_through`, `an_invalid_policy_makes_a_search_metadata_only`, `a_brace_that_builds_a_parent_step_cannot_be_walked`, `a_parent_step_after_a_globstar_is_read_both_ways`, `glob_groups_and_ansi_c_escapes_reach_the_marker_lookup`, `a_saved_output_glob_needs_its_distinctive_name_in_literal_text`, `indented_patch_headers_and_hermes_file_globs_reach_the_marker_lookup`, `a_dot_glob_directory_that_can_match_the_parent_is_read_as_it` (POSIX classes and extglob groups included), `an_oversized_brace_expansion_is_walked_unless_its_pieces_could_leave` (each attack with its control), the shell fixture's double-quoted `bash -c`/`eval` ANSI-C vectors and their controls, `marker.rs` `marker_memo_answers_like_find_marker_once_per_directory`, **`hook.rs` `a_globstar_above_the_checkout_skips_the_own_subtree`** (regression: `ls ../**/README.md` from a 300-directory checkout with no policy is not metadata-only; the sibling `cat ../**/secrets.env` drops), **`hook.rs` `marker_lookups_in_a_deep_tree_cost_one_probe_per_directory`** (regression: 300 paths in a 300-level tree cost fewer than five probes per level; out of budget inside the checkout kept, outside it metadata-only, the sibling checkout's location looked up before a long list inside the checkout, and a shallow nested marker before a deep list), **`hook.rs` `a_dotfiles_checkout_at_home_is_not_the_own_checkout`** (with `~/.git`, `cat */secrets.env` from `~/Projects` drops; a harmless glob kept), the shell fixture's dot-glob directory vectors and their controls, the shell fixture's `**`-then-`..` and `*.log` vectors and the `read_many_files_directories` `**`-then-`..` vectors, **`hook.rs` `constructed_parent_steps_answer_to_another_checkout`** (a `..` after a `**` through a shell, a Glob pattern and a Grep filter, four brace expansions that build a parent step, two zsh glob groups, hex and octal ANSI-C escapes, two dot-glob directory segments, a POSIX-class and four extglob dot-glob segments, a brace-built dot-glob, an oversized brace sequence over `.`, ANSI-C strings in a double-quoted `bash -c` and `eval`, an indented `apply_patch` header next to an unindented one and a Hermes `file_glob` never spool content; the same shapes inside the checkout spool with it, and so do four brace expansions too large to list that cannot leave it, which v2.6.3 kept), **`hook.rs` `a_monorepo_glob_inside_the_own_checkout_is_not_walked`** (in a 300-package checkout, with and without a policy of its own, `packages/*` shell globs stay kept and the sibling `../*/secrets.env` and `../a/*.env` attacks still drop), `hook.rs` `a_glob_walk_outside_the_checkout_stops_at_its_bounds` (directory bound counted while a `**` lists, time budget through an injected clock, no walk inside the checkout), the Node evidence test's `monorepo-*`, `walk-*`, `con-*`, `globstar-*`, `deep-*` and `dotfiles-*` checks, and the Node evidence test's `glob-*`, `search-*`, `patch-*` and `unreadable-target` checks with their controls and `transcript_capture.rs` `a_shell_command_naming_another_checkouts_file_honors_its_policy`, both failing with the foreign lookup disabled, and the Node evidence test's `cross-*` and `fold-unicode` checks, which fail with `captureForeignConfigs` disabled, and the shell fixture's quoted-script, git-object, ANSI-C, escaped-letter and inline-interpreter vectors with their controls (`cargo test`, `git status`/`log`, `pytest`, `python3 -m pytest`, `node build.js`, `npm run test`, a quoted commit message with braces); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 and Gemini `read_many_files`/`run_shell_command` vectors, plus unsupported-glob, empty-list and recursive-`**` checks, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved); **`backfill.rs` `backfill_never_posts_tool_content_the_capture_policy_excludes`** (planted Claude transcript: the excluded read's call and output never reach `/hook/batch`, a malformed read posts only the metadata-only body, public read control posted) and **`run.rs` `ledger_upload_drops_tool_content_the_capture_policy_excludes`** (excluded call and output absent from the finish request, public control present, cursor still advances), both failing with the guard removed; **`recovery.rs` `finish_failed_recovery_never_posts_content_the_capture_policy_excludes`** and **`degraded_run_recovery_never_posts_content_the_capture_policy_excludes`** (a full `recover` pass over a journaled Claude transcript with exact digests and cursor, marker `ignore_paths = ["secrets/**"]`: the excluded read's path and `SENTINEL_RECOVERY_MUST_NOT_POST` output never reach `/workstream/runs/{id}/recover` or `/hook/batch`, the public read's output does; each fails when its own call site's capture is built for `/` instead of the entry's `cwd`, on the control since a foreign-scoped capture fails closed, and both fail on the sentinel when `for_checkout` loses the marker's policy); `transcript_capture.rs` `an_excluded_read_drops_its_call_and_result_by_id`, `id_less_results_take_the_strictest_call_of_their_turn`, `unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy`, `a_call_into_another_checkout_honors_its_policy`, `ledger_events_are_dropped_or_stripped_before_upload`, `without_a_policy_every_event_is_kept` (control); `capture_policy.rs` `tool_call_payload_reaches_the_live_decision_for_every_supported_agent`; **`backfill.rs` `allowlist_mode_backfills_nothing_from_an_unmarked_checkout`** (no request reaches the server; marked-checkout and denylist controls do), **`run.rs` `ledger_upload_under_allowlist_mode_carries_nothing_from_an_unmarked_checkout`** (finish carries no prompt or tool content; marked and denylist controls upload both), `transcript_capture.rs` `allowlist_mode_admits_nothing_from_an_unmarked_checkout`, all failing with the admission gate removed; **`backfill.rs` `backfill_inspects_codex_exec_command_as_the_hook_shell_call`** and **`run.rs` `ledger_upload_inspects_codex_exec_command_as_the_hook_shell_call`** (a planted Codex `exec_command` whose `workdir`-relative argument names an ignored file never posts its call or output; the same command from a public `workdir` does), `capture_policy.rs` `codex_transcript_exec_command_is_inspected_as_the_hook_bash_call` (absolute, relative and absent `workdir` and an argv `cmd` drop, public control kept, the `workdir` locates the call, another agent's `exec_command` stays unknown), all failing with `hook_tool_call` removed; **`backfill.rs` `backfill_resolves_each_call_from_its_record_cwd`** (`cat adr/x.md` recorded from `docs/` never posts; the same command from the root does) and `transcript.rs` `jsonl_events_carry_their_record_cwd` (Claude per line, Codex per turn context, a relative cwd ignored), failing with the record cwd ignored or unstamped; **`backfill.rs` `backfill_drops_reroutes_the_live_hook_would_not_deliver_here`** (under allowlist mode, reads rerouted to an unmarked git repository, to a marker selecting an unregistered profile, and to a marker selecting a registered profile while the source uses the install default are never posted; a read in a marked checkout with no server selection is the posted control), failing with either the admission check or the route comparison removed (each refused case checked on its own); `transcript_capture.rs` `a_record_cwd_answers_to_the_hook_admission_gate_there` (prompt, call and result recorded in an unmarked repository drop under allowlist; a subdirectory of the opted-in checkout is kept and its record cwd never reaches the ledger) and `claude_shell_mode_output_is_not_imported` (stdout, stderr, local-command and size-capped blocks drop; `<bash-input>`, a prompt quoting a tag, and another agent's message kept); **`backfill.rs` `backfill_posts_no_content_for_unrecognized_tools`** (a planted Codex MCP call's arguments and output never post, the call and output post as `tool unknown`; a recognized shell output is the posted control) and `transcript_capture.rs` `unrecognized_tools_keep_no_content_with_or_without_a_policy` (no policy and an active one; ledger content withheld; public read kept; a call-less result content-free), failing with the unknown-family rule removed, the backfill one also with its content-free body removed; **`backfill.rs` `backfill_keeps_reroutes_to_the_same_server_profile_only`** (a reroute into a checkout selecting the source's registered profile and project is posted; one selecting a different registered profile is not, nor one of another project on the same profile, nor a prompt recorded there), failing with the profile comparison forced either way and with the project comparison removed; `transcript_capture.rs` `a_record_cwd_in_another_project_is_dropped` and `a_reroute_into_another_project_is_dropped` (prompt, call and result recorded in, or a read reaching into, a checkout declaring another project drop; one declaring the same project is kept), failing with `routes_to_same_project` removed; `hook.rs` `subdirectories_of_one_repository_are_one_project_only_under_repo_root` (two subdirectories of an unmarked repository, and a subdirectory importing its root, are two projects; the same directory, the root importing a subdirectory and a `repo-root` marker agree), failing with the basename rule removed; **`backfill.rs` `backfill_posts_no_task_notification_or_compact_summary_as_a_prompt`** and `transcript.rs` `claude_adapter_keeps_task_notifications_and_compact_summaries_out_of_prompts` (a monitored command's notification, a background agent's report and an origin-tagged notice are excluded, also behind a byte-order mark and zero-width characters, in another case, with attributes, after a non-text block, or with an origin kind in another case; a compact summary, also flagged `"true"` or `1`, becomes a compaction event; the typed prompt, also one quoting the tag, and a look-alike tag are the controls), failing with either adapter rule removed or with the spelling rules reverted; `transcript_capture.rs` `boundary_events_answer_to_the_record_cwd_admission_gate` (compaction and annotation recorded in a refused directory drop; in the checkout kept), `a_result_whose_id_matches_no_call_is_an_orphan` (an unmatched id cannot borrow a public read's keep; the read's own result kept), `claude_shell_mode_output_is_not_imported` (a block holding a literal closing tag drops) and `unrecognized_tools_keep_no_content_with_or_without_a_policy` (ledger keeps no tool name and no invalid call id), each failing with its rule reverted; `windows_spelling_fixture_vectors` (shared `capture-policy.json` `windows` drop vectors for every spelling above, file tool and shell, with other-drive, other-share, longer-name and pipe controls, and `windows_posix_controls` proving a POSIX session keeps `/c/…`, trailing-dot and colon names; `windows_scopes` drop vectors for a `\\?\C:\`, `\\?\UNC\…`, `\\localhost\C$\…` or UNC cwd and marker directory with relative patterns, a `\\?\C:\…` absolute pattern from `C:\repo`, bare and double-quoted `\\server\share\…`/`\\?\…`/`\\.\…`/`\\localhost\c$\…` PowerShell, cmd, `run_shell_command` and argv commands, and both readings of `/a/x` from `D:\a\…`, each with public-path, other-drive and other-share keep controls; the Node runtime evidence runs the same vectors with the marker spelled in the Windows cwd), `tool_family_fixture_vectors` (shared `tool_families`, every native name per family), new `decisions` vectors (`execute_code` metadata-only, `read_file`/`patch`/`fs_read` operations drop, `write_to_file`/`browser_navigate` keep), `output_spool_work_is_linear_and_budgeted` (a 2,040-wildcard-segment path stays under a linear work bound; 32 such paths fail closed; one long or 32 short paths keep), `an_oversized_shell_command_is_unprovable` (one character over the limit is metadata-only and unlooked-up, at the limit keeps, argv summed, inactive untouched), `inline_code_tools_are_unprovable_under_a_policy`, `hook_capture::capture_section_spellings_match_toml_semantics` (shared `marker_spellings`, including a nested-array line `["docs"]` before a dotted `capture.ignore_paths` that must still drop, and a key line inside an open array, text after a closed array and a multi-line inline table that must fail closed), and the Node evidence test running all of these vectors against the generated TypeScript plus its entry-bound read count for the directory walk; each fails with its rule reverted (Windows reading off, spool memo dropped or budget failing open, length check off, inline-code rule off, a name dropped from the list, TS dotted key or inline-table rule reverted, TS walk back on `readdirSync`, Windows reading of the cwd/marker directory or of an absolute pattern off, literal-backslash reading off, the cwd-drive reading of `/a/x` off, TS array tracking or any `captureValueScan` refusal off, Rust and TS alike); new `windows_scopes` vectors (drive-relative, device-namespace and Git Bash doubled-backslash shell words and a `C:docs` `workdir` metadata-only, `FileSystem::` file paths, shell words and `workdir` dropping, a POSIX absolute pattern in a Windows marker failing closed, with `type README.md`, `dir /s /q`, `git status`, a URL, `type C:\repo\README.md` and `Get-Content -Path C:\repo\README.md` kept) and `windows_marker_rejects_posix_absolute_patterns` (the same pattern stays active in a POSIX marker) fail natively and in the Node evidence test with the unplaceable check, its device branch, the `workdir` check, the provider strip or the marker rejection removed; removing the POSIX-reading excusal makes `type C:\repo\README.md` metadata-only, and excusing a device reading keeps the doubled-backslash device path; `capture_policy.rs` `windows_lookup_locations_keep_glob_segments_whole` (a Windows session trims trailing dots from plain segments only, so `{.,}.` still reaches `..` and the sibling checkout's marker; bites with the glob-segment exemption removed) | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and the output of a command substitution, a `cd` inside the command, a script read from a file or a heredoc fed to an interpreter (read only for the words it spells out), git's repository root approximated by the marker directory, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, a search tool rooted at a literal directory above another checkout (it is not walked) and a glob whose literal root lies inside the event's own checkout reaching a checkout nested there (it is not walked), a marker nested inside the own checkout below what the lookup budget reaches, a `.git` the same command creates (`touch .git; cat */x`: the hook reads the tree after the command ran, so that directory counts as the own checkout; a `.git` at or above the home directory never does), a parameter expansion next to glob syntax (`${X}/*/x`, not walked), a glob through a symlinked directory, a tool's own directory option (`git -C`), script runners and interpreters the matcher does not list (their words are still read, but expansion or inline code in them is not recognized), a value glued after the first letter of a short-flag cluster, non-ASCII percent-escapes in a `file:` URL, a bare word naming another checkout's directory (only separator-bearing arguments are looked up for another marker), harness output files outside the listed default locations, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, adapters that record no per-record cwd (Pi, OMP, OpenCode, Crush, Kimi Code, Command Code, Kiro, Grok) judge every event from the session cwd, a Codex ledger upload resumed from a mid-file cursor judges the events before the next turn context from the session cwd, and id-less adapters over-drop a whole turn's results when one call is excluded, and when the routing hints leave the project to the server, events from inside one repository count as the importing project even where the server has a separate project registered for a subdirectory (anywhere under `repo-root`; under `basename` only when the import runs from the repository root); a metadata-only import keeps an `event_id` (ledger) and `ingest_key` (backfill) derived from a SHA-256 of the original content plus session and record ids, left in place because those ids are the retry-dedupe keys and a content-free id would merge distinct events — it only confirms a guess of low-entropy content. Under allowlist mode a refused checkout's `ai-memory run` still records repository checkpoint metadata (HEAD, branch, a status hash and changed-path names, never file content), which the run also sends at launch. Re-splitting quoted words over-drops a quoted message naming an ignored path, and inline interpreter code is metadata-only under an active policy. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects. Bite checks: removing the nested re-split, the git object path or its marker-root base, Antigravity's `Cwd` key, the leading-`]` rule, either zsh-group rule, ANSI-C decoding or its numeric-escape rule, the `\o` reading, the inline-code rule, the nesting-depth rule, the nested-script scan, the line-continuation join, the Windows escape reading, the shell-option and interpreter-option value skips, the added runners and interpreters, the glued-flag value, the `file:` URL path, the `~+` resolution, the unknown-tilde rule, the parameter-default reading or case folding each fails the Rust tests, and each TypeScript counterpart fails the Node evidence test; so does reverting the `file:` URL cut, the deep-default rule, the escaped-default reading, the quoted-tilde rule, the harness-output rule or Unicode folding (the new fixture vectors fail against the previous matchers in both languages), and disabling the foreign-marker lookup fails the native, import and Node cross-checkout tests; reading every glob location as literal, skipping search/list locations, or skipping a file tool whose targets cannot be read each fails the native, import and Node glob/search/unreadable tests, removing `apply_patch` header reading fails the own-patch control, and reverting the saved-output glob rule fails the new fixture vectors in both languages; walking globs rooted inside the event's checkout fails the monorepo tests, accepting any literal text for a saved-output glob fails the `*.log` vectors, removing the time budget or counting a `**`'s directories only after it lists fails the bounds tests, and removing the `**`-then-`..` readings, the brace-expansion check, the expanded lookup words, the patch-header trim, the `file_glob` key or the dot-glob parent reading each fails the Rust tests and the Node evidence test; treating every oversized brace expansion as leaving, dropping the brace-built dot-glob check, listing the own checkout's subtree under a `**`, looking up locations in their given order (outside before inside, then shallowest first), dropping the per-directory memo, counting a checkout at home as the own one, keeping the backslash before `$` in double quotes, or dropping the POSIX-class or extglob reading each fails its Rust test and the Node evidence test; in a Windows session a shell `workdir` spelled `/c/x` is read only as Git Bash reads it, so arguments resolved from it miss a native tool's `D:\c\x` reading, the TS marker reader rejects structural errors anywhere in the marker but does not validate other values' TOML (`x = nope` invalidates the policy only natively), an administrative share reached through a loopback or host alias other than `localhost`/`127.0.0.1` (`\\127.0.0.2\c$`, `\\127.1\c$`, `\\<hostname>\c$`) or a `\\wsl$\…` path is matched as the UNC path it spells, Windows matching folds ASCII case only, and a drive-relative word counts as placed when a placeable argument's POSIX reading spells it; a `**/` matches one or more directories, never zero (documented in `marker-file.md`) || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |-| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |+| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL; once `[auth].bearer_token_file` names `auth-tokens/default` (this install's root bearer), `commands/server.rs` `refuse_the_root_token_name` refuses `server add default` and `server remove default` so no profile can be handed, overwrite or delete the root bearer | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does); `server.rs` `the_root_bearer_file_name_cannot_be_registered_or_removed` (refused at the root bearer path; another name and an install without a root bearer file are the controls); `server_profiles.rs` `a_default_profile_shares_the_root_bearer_only_at_its_path`, `clear_tokens_keeps_the_root_bearer_and_removes_profile_tokens` | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` || 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG || 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI || 11g | Cross-project tool attribution cannot bypass source or destination capture, or destination server routing (#932, #1199) | `ai-memory-hooks/src/capture_policy.rs` `absolute_tool_location_paths` accepts only bounded, recognized, absolute locations: file-tool targets, a search/list tool's explicit `path`, or a shell command's structured `workdir` (command text is never parsed for a location); `ai-memory-cli/src/commands/hook.rs` `tool_location_routing_cwd` requires every path to prove the same repository/marker boundary, refuses the reroute when the payload cwd's own capture policy would not keep the event (source `ignore_paths` may name paths outside the source checkout, and a command may name source files while its `workdir` points elsewhere), and resolves that destination before capture policy, allowlist marker, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths`, `workdir_reroute_applies_the_destination_capture_policy` (a `workdir`-rerouted command reading a destination-excluded path is dropped, public control kept), **`a_reroute_cannot_escape_the_source_capture_exclusions`** (adversarial: a file read under a source pattern that names another project's directory, and a shell command naming an excluded source file with `workdir` in another project, are both refused; public file and shell controls still reroute; fails with the source-policy check removed), `hermes_tool_location_finds_the_marker_the_process_cwd_lacks` (Hermes `terminal` `workdir`, `read_file` `path` and `search_files` `path` reach the repository marker under allowlist; no-workdir, relative-workdir and relative-search controls stay with the unmarked process cwd); `capture_policy.rs` `absolute_tool_location_paths_cover_search_dirs_and_shell_workdirs` (relative workdir, command-text paths, workdir without a command, and Hermes `process` yield no location) | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |-| 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 | `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 | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |+| 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 | `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` | `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 | STRONG |+| 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 || 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 f535ff85..10548b12 100644--- a/docs/security.md+++ b/docs/security.md@@ -2,9 +2,22 @@> The full security model. Moved from the README front page; the README keeps a summary.-Loopback-only (`127.0.0.1:49374`) with no auth is the default because-it is safe for a single-user laptop: no process outside the machine can-reach the server.+A new install requires a bearer token. `ai-memory init` on a fresh data+dir writes a random root bearer to `<data_dir>/auth-tokens/default` (owner+only) and records `[auth].bearer_token_file`; the server then refuses every+route 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.++An install created before this default keeps its loopback-only+(`127.0.0.1:49374`), no-auth behaviour. That stays safe from the network, but+every 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 server afterwards.Unauthenticated non-loopback HTTP now fails closed. Set`AI_MEMORY_AUTH_TOKEN` or bind loopback; `--allow-insecure-no-auth` is andiff --git a/docs/users.md b/docs/users.mdindex 0b86563e..2989acec 100644--- a/docs/users.md+++ b/docs/users.md@@ -56,8 +56,8 @@ Every HTTP request is resolved to one of four authentication tiers:| Rung | Trigger | What the request gets ||---|---|---|-| **0 — Anonymous** | No `[auth].bearer_token` set. | Allowed, no identity. Same as pre-multi-user defaults. |-| **1 — Root** | Bearer matches `[auth].bearer_token`. | Allowed as **root**. When `[auth].root_username` is set, writes attribute to that name; otherwise attribution stays anonymous. |+| **0 — Anonymous** | No root bearer configured (`AI_MEMORY_AUTH_TOKEN`, `[auth].bearer_token` or `[auth].bearer_token_file`). | Allowed, no identity. Same as pre-multi-user defaults. A fresh `ai-memory init` skips this rung by minting a root bearer; an older install stays here until `ai-memory auth enable`. |+| **1 — Root** | Bearer matches the root bearer (`AI_MEMORY_AUTH_TOKEN`, `[auth].bearer_token`, or the token in `[auth].bearer_token_file`). | Allowed as **root**. When `[auth].root_username` is set, writes attribute to that name; otherwise attribution stays anonymous. || **1b — Proxy-asserted user** | Bearer matches the distinct `[auth].actor_proxy_bearer_token`. | Identity is taken from trusted `X-Memory-Actor-*` headers. The request is a **user** unless its OIDC issuer/subject pair exactly matches the configured root pair. Missing or malformed identity is rejected. || **2 — DB user** | Bearer doesn't match root, matches an active `api_credentials.token_hash` (SHA-256 of the secret + `[auth].token_pepper`). Native keys use the `aim_` prefix. | Allowed as **that user** for normal read/write APIs. Native keys always resolve as `AuthLevel::User`, even when the owning identity is `role=root`. All `/admin/*` endpoints are root-only in multi-user mode. The audit log records the username/email/name. || **3 — 401** | Bearer present but matches nothing. | Rejected. This closes the bypass: unknown bearers can't slip through as anonymous. |diff --git a/scripts/check-native-packaging.sh b/scripts/check-native-packaging.shindex 3f9695ed..56d6f5fa 100755--- a/scripts/check-native-packaging.sh+++ b/scripts/check-native-packaging.sh@@ -137,6 +137,94 @@ main() {fail "AI_MEMORY_NATIVE_BIN pointing to the wrapper must be refused instead of recursing"fi+ log "Checking the wrapper hands host commands the volume's root bearer"+ # New-install default: a server initialized on the named volume keeps its token at+ # /data/auth-tokens/default. Host-native commands must receive it as a+ # 0600 token file named by AI_MEMORY_AUTH__BEARER_TOKEN_FILE, never in argv.+ local token_docker token_native token_log token_docker_log token_home bind_dir+ token_docker="${TMP_ROOT}/token-docker"+ token_native="${TMP_ROOT}/token-native"+ token_log="${TMP_ROOT}/token-native.log"+ token_docker_log="${TMP_ROOT}/token-docker.log"+ token_home="${TMP_ROOT}/token-home"+ bind_dir="${TMP_ROOT}/bind-data"+ mkdir -p "${token_home}" "${bind_dir}"+ cat >"${token_docker}" <<'FAKE'+#!/usr/bin/env bash+printf '%s\n' "$*" >>"${AI_MEMORY_DOCKER_TEST_LOG}"+case "$*" in+ *"--entrypoint /bin/sh"*) printf 'VOLUME-ROOT-TOKEN\n' ;;+esac+FAKE+ cat >"${token_native}" <<'FAKE'+#!/usr/bin/env bash+{+ printf 'argv=%s\n' "$*"+ printf 'file=%s\n' "${AI_MEMORY_AUTH__BEARER_TOKEN_FILE:-}"+ printf 'data_dir=%s\n' "${AI_MEMORY_DATA_DIR:-}"+ if [ -n "${AI_MEMORY_AUTH__BEARER_TOKEN_FILE:-}" ]; then+ printf 'content=%s\n' "$(cat "${AI_MEMORY_AUTH__BEARER_TOKEN_FILE}")"+ printf 'mode=%s\n' "$(stat -c '%a' "${AI_MEMORY_AUTH__BEARER_TOKEN_FILE}" 2>/dev/null || stat -f '%Lp' "${AI_MEMORY_AUTH__BEARER_TOKEN_FILE}")"+ fi+} >>"${AI_MEMORY_WRAPPER_TEST_LOG}"+FAKE+ chmod 0755 "${token_docker}" "${token_native}"+ for cmd in "install-hooks --agent claude-code --apply" "run codex" \+ "mcp-bridge --server-url http://127.0.0.1:49374/mcp"; do+ : >"${token_log}"+ case "${cmd}" in install-hooks*) ;; *) : >"${token_docker_log}" ;; esac+ # shellcheck disable=SC2086 # the command string is split on purpose+ HOME="${token_home}" XDG_DATA_HOME="${token_home}/.local/share" \+ AI_MEMORY_DOCKER="${token_docker}" AI_MEMORY_NATIVE_BIN="${token_native}" \+ AI_MEMORY_DOCKER_TEST_LOG="${token_docker_log}" AI_MEMORY_WRAPPER_TEST_LOG="${token_log}" \+ bin/ai-memory ${cmd}+ assert_contains "${token_log}" "file=${token_home}/.local/share/ai-memory/native-runner/server-token"+ assert_contains "${token_log}" "content=VOLUME-ROOT-TOKEN"+ assert_contains "${token_log}" "mode=600"+ if grep -F 'argv=' "${token_log}" | grep -Fq 'VOLUME-ROOT-TOKEN'; then+ fail "the volume token reached the native client's argv for: ${cmd}"+ fi+ # Only the setup step asks the container; the managed host commands and+ # the per-session bridge read the copy it left.+ case "${cmd}" in+ install-hooks*) ;;+ *) [ ! -s "${token_docker_log}" ] || fail "${cmd} reached the container engine" ;;+ esac+ done+ : >"${token_docker_log}"+ HOME="${token_home}" XDG_DATA_HOME="${token_home}/.local/share" \+ AI_MEMORY_DOCKER="${token_docker}" AI_MEMORY_NATIVE_BIN="${token_native}" \+ AI_MEMORY_DOCKER_TEST_LOG="${token_docker_log}" AI_MEMORY_WRAPPER_TEST_LOG="${token_log}" \+ bin/ai-memory install-hooks --agent claude-code --apply+ assert_contains "${token_docker_log}" "-v ai-memory-data:/data:ro"++ # Control: a bind-mounted data dir is read directly by the native client;+ # the wrapper neither asks the container nor sets a token file.+ : >"${token_log}"+ : >"${token_docker_log}"+ HOME="${token_home}" XDG_DATA_HOME="${token_home}/.local/share" \+ AI_MEMORY_DATA_DIR="${bind_dir}" \+ AI_MEMORY_DOCKER="${token_docker}" AI_MEMORY_NATIVE_BIN="${token_native}" \+ AI_MEMORY_DOCKER_TEST_LOG="${token_docker_log}" AI_MEMORY_WRAPPER_TEST_LOG="${token_log}" \+ bin/ai-memory install-hooks --agent claude-code --apply+ assert_contains "${token_log}" "data_dir=${bind_dir}"+ assert_contains "${token_log}" "file="+ if grep -Fq 'file=/' "${token_log}" || [ -s "${token_docker_log}" ]; then+ fail "a bind-mounted data dir must not go through the volume token copy"+ fi++ # Control: an explicit AI_MEMORY_AUTH_TOKEN wins; no copy is made.+ : >"${token_log}"+ : >"${token_docker_log}"+ HOME="${token_home}" XDG_DATA_HOME="${token_home}/.local/share" \+ AI_MEMORY_AUTH_TOKEN="explicit" \+ AI_MEMORY_DOCKER="${token_docker}" AI_MEMORY_NATIVE_BIN="${token_native}" \+ AI_MEMORY_DOCKER_TEST_LOG="${token_docker_log}" AI_MEMORY_WRAPPER_TEST_LOG="${token_log}" \+ bin/ai-memory install-hooks --agent claude-code --apply+ if grep -Fq 'file=/' "${token_log}" || [ -s "${token_docker_log}" ]; then+ fail "an explicit AI_MEMORY_AUTH_TOKEN must win over the volume token copy"+ fi+log "Creating temporary alternate root"mkdir -p \"${TMP_ROOT}/etc" \