Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(cli): add server profile registry and `ai-memory server` (#992)

Talysson de Oliveira Cassianoa9e166f35703
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 0e2ab73c..0c8cba45 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -253,6 +253,10 @@ pub enum Command {
/// or `restricted` (root and grant holders) (#708). Requires the root
/// bearer token.
Project(ProjectArgs),
+ /// Manage local server profiles, which a repository's `.ai-memory.toml`
+ /// selects with `server = "<name>"` to route its hook capture to a
+ /// different ai-memory server.
+ Server(ServerArgs),
/// Print a shell-completion script to stdout. Generated from this
/// binary's own command tree, so it never drifts from the real CLI
/// surface. See `docs/shell-completions.md` for install paths.
@@ -981,6 +985,61 @@ pub struct ApiKeyArgs {
pub command: ApiKeyCommand,
}
+/// Arguments for `server`.
+#[derive(Debug, Args)]
+pub struct ServerArgs {
+ /// Server-profile action to run.
+ #[command(subcommand)]
+ pub command: ServerCommand,
+}
+
+/// Subcommands for `server`.
+#[derive(Debug, Subcommand)]
+pub enum ServerCommand {
+ /// Register a server profile, or replace one with the same name.
+ Add(ServerAddArgs),
+ /// List server profiles (never prints a token).
+ List(ServerListArgs),
+ /// Remove a server profile and its stored token.
+ Remove(ServerRemoveArgs),
+}
+
+/// Arguments for `server add`.
+#[derive(Debug, Args)]
+pub struct ServerAddArgs {
+ /// Profile name a marker selects: lowercase letters, digits, `-`, `_`.
+ pub name: String,
+ /// Server URL, e.g. `https://memory.example.com`.
+ #[arg(long)]
+ pub url: String,
+ /// Directory allowed to select this profile (repeatable; absolute or
+ /// `~/`). Required once more than one profile is registered.
+ #[arg(long = "root")]
+ pub roots: Vec<String>,
+ /// Bearer token for this server. Prefer `--auth-token-stdin`, which
+ /// keeps it out of shell history and the process table.
+ #[arg(long, hide_env_values = true, conflicts_with = "auth_token_stdin")]
+ pub auth_token: Option<String>,
+ /// Read the bearer token from the first line of stdin.
+ #[arg(long)]
+ pub auth_token_stdin: bool,
+}
+
+/// Arguments for `server list`.
+#[derive(Debug, Args)]
+pub struct ServerListArgs {
+ /// Emit the list as JSON.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `server remove`.
+#[derive(Debug, Args)]
+pub struct ServerRemoveArgs {
+ /// Profile name to remove.
+ pub name: String,
+}
+
/// Subcommands for `api-key`.
#[derive(Debug, Subcommand)]
pub enum ApiKeyCommand {
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 3c7ff8ef..fd53a4d0 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -81,6 +81,7 @@ pub mod run;
pub mod run_autowire;
pub mod search;
pub mod serve;
+pub mod server;
pub mod setup_agent;
pub mod show;
pub mod status;
diff --git a/crates/ai-memory-cli/src/commands/server.rs b/crates/ai-memory-cli/src/commands/server.rs
new file mode 100644
index 00000000..9709d786
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/server.rs
@@ -0,0 +1,268 @@
+//! `ai-memory server add|list|remove` — manage local server profiles (#992).
+//!
+//! Local-only: writes `<data_dir>/servers.toml` and `<data_dir>/auth-tokens/`,
+//! never contacts a server. See `server_profiles` for the routing rules.
+
+use std::io::Write;
+use std::path::Path;
+
+use anyhow::{Context, Result, anyhow, bail};
+
+use crate::cli::{ServerAddArgs, ServerArgs, ServerCommand, ServerListArgs, ServerRemoveArgs};
+use crate::config::Config;
+use crate::server_profiles::{self, ProfileName};
+
+/// Run a `server` subcommand.
+///
+/// # Errors
+/// Returns an error for an invalid name, URL, or root, an invalid existing
+/// `servers.toml`, or a failed write.
+pub fn run(config: &Config, args: ServerArgs) -> Result<()> {
+ let mut stdout = std::io::stdout();
+ match args.command {
+ ServerCommand::Add(args) => {
+ let stdin_token = if args.auth_token_stdin {
+ Some(read_token_line(&mut std::io::stdin().lock())?)
+ } else {
+ None
+ };
+ add(&config.data_dir, args, stdin_token, &mut stdout)
+ }
+ ServerCommand::List(args) => list(&config.data_dir, &args, &mut stdout),
+ ServerCommand::Remove(args) => remove(&config.data_dir, &args, &mut stdout),
+ }
+}
+
+fn parse_name(raw: &str) -> Result<ProfileName> {
+ ProfileName::parse(raw).ok_or_else(|| {
+ anyhow!(
+ "`{raw}` is not a valid profile name: use 1-64 lowercase letters, digits, `-` or `_`, \
+ starting with a letter or digit"
+ )
+ })
+}
+
+fn read_token_line(input: &mut impl std::io::BufRead) -> Result<String> {
+ let mut line = String::new();
+ input
+ .read_line(&mut line)
+ .context("reading the token from stdin")?;
+ let token = line.trim();
+ if token.is_empty() {
+ bail!("--auth-token-stdin was given but stdin had no token");
+ }
+ Ok(token.to_owned())
+}
+
+fn add(
+ data_dir: &Path,
+ args: ServerAddArgs,
+ stdin_token: Option<String>,
+ out: &mut impl Write,
+) -> Result<()> {
+ let name = parse_name(&args.name)?;
+ let token = stdin_token.or(args.auth_token);
+ let outcome = server_profiles::add(data_dir, &name, &args.url, &args.roots, token.as_deref())?;
+ writeln!(out, "Registered server profile `{name}`.")?;
+ if outcome.roots_kept {
+ writeln!(
+ out,
+ "Kept the roots already registered for `{name}`; pass --root to replace them."
+ )?;
+ }
+ if outcome.token_discarded {
+ writeln!(
+ out,
+ "The URL changed, so the token stored for the previous URL was removed."
+ )?;
+ }
+ if server_profiles::read_token(data_dir, &name).is_none() {
+ writeln!(
+ out,
+ "No token is stored for `{name}`: repositories selecting it drop their capture \
+ until one is added with `ai-memory server add {name} --url … --auth-token-stdin`."
+ )?;
+ }
+ let registry = server_profiles::load(data_dir)?;
+ let unrooted: Vec<&str> = registry
+ .profiles
+ .iter()
+ .filter(|(_, profile)| profile.roots.is_empty())
+ .map(|(name, _)| name.as_str())
+ .collect();
+ if registry.profiles.len() > 1 && !unrooted.is_empty() {
+ writeln!(
+ out,
+ "Several profiles are registered, so a profile without --root is refused. \
+ Add roots to: {}",
+ unrooted.join(", ")
+ )?;
+ }
+ Ok(())
+}
+
+fn list(data_dir: &Path, args: &ServerListArgs, out: &mut impl Write) -> Result<()> {
+ let registry = server_profiles::load(data_dir)?;
+ if args.json {
+ let rows: Vec<_> = registry
+ .profiles
+ .iter()
+ .map(|(name, profile)| {
+ serde_json::json!({
+ "name": name.as_str(),
+ "url": profile.url,
+ "roots": profile.roots,
+ "token": token_state(data_dir, name),
+ })
+ })
+ .collect();
+ writeln!(out, "{}", serde_json::to_string_pretty(&rows)?)?;
+ return Ok(());
+ }
+ if registry.profiles.is_empty() {
+ writeln!(out, "No server profiles registered.")?;
+ return Ok(());
+ }
+ for (name, profile) in &registry.profiles {
+ let roots = if profile.roots.is_empty() {
+ "(any)".to_owned()
+ } else {
+ profile.roots.join(", ")
+ };
+ writeln!(
+ out,
+ "{name}\n url: {}\n roots: {roots}\n token: {}",
+ profile.url,
+ token_state(data_dir, name)
+ )?;
+ }
+ Ok(())
+}
+
+fn token_state(data_dir: &Path, name: &ProfileName) -> &'static str {
+ if server_profiles::read_token(data_dir, name).is_some() {
+ "stored"
+ } else {
+ "missing"
+ }
+}
+
+fn remove(data_dir: &Path, args: &ServerRemoveArgs, out: &mut impl Write) -> Result<()> {
+ let name = parse_name(&args.name)?;
+ if server_profiles::remove(data_dir, &name)? {
+ writeln!(out, "Removed server profile `{name}`.")?;
+ } else {
+ writeln!(out, "No server profile named `{name}`.")?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn add_args(name: &str, url: &str, roots: &[&str], token: Option<&str>) -> ServerAddArgs {
+ ServerAddArgs {
+ name: name.to_owned(),
+ url: url.to_owned(),
+ roots: roots.iter().map(|r| (*r).to_owned()).collect(),
+ auth_token: token.map(str::to_owned),
+ auth_token_stdin: false,
+ }
+ }
+
+ fn output(run: impl FnOnce(&mut Vec<u8>) -> Result<()>) -> String {
+ let mut out = Vec::new();
+ run(&mut out).unwrap();
+ String::from_utf8(out).unwrap()
+ }
+
+ /// `server add` that must succeed; returns what it printed.
+ fn add_ok(data_dir: &Path, args: ServerAddArgs, stdin_token: Option<String>) -> String {
+ output(|out| add(data_dir, args, stdin_token, out))
+ }
+
+ /// The listing reports whether a token is stored and never the token.
+ #[test]
+ fn list_never_prints_a_token() {
+ let dd = tempfile::tempdir().unwrap();
+ let root = dd.path().join("b").to_string_lossy().into_owned();
+ add_ok(
+ dd.path(),
+ add_args("team-b", "https://b.example", &[&root], Some("SECRET-B")),
+ None,
+ );
+ add_ok(
+ dd.path(),
+ add_args("team-c", "https://c.example", &[&root], None),
+ None,
+ );
+
+ for json in [false, true] {
+ let listed = output(|out| list(dd.path(), &ServerListArgs { json }, out));
+ assert!(!listed.contains("SECRET-B"), "{listed}");
+ assert!(listed.contains("https://b.example"), "{listed}");
+ assert!(listed.contains("stored"), "{listed}");
+ assert!(listed.contains("missing"), "{listed}");
+ }
+ }
+
+ #[test]
+ fn a_token_from_stdin_wins_and_is_stored() {
+ let dd = tempfile::tempdir().unwrap();
+ let token = read_token_line(&mut std::io::Cursor::new("from-stdin\n")).unwrap();
+ add_ok(
+ dd.path(),
+ add_args("a", "https://a.example", &[], None),
+ Some(token),
+ );
+ let name = ProfileName::parse("a").unwrap();
+ assert_eq!(
+ server_profiles::read_token(dd.path(), &name).as_deref(),
+ Some("from-stdin")
+ );
+ assert!(read_token_line(&mut std::io::Cursor::new("\n")).is_err());
+ }
+
+ #[test]
+ fn adding_a_second_unrooted_profile_warns_that_it_will_be_refused() {
+ let dd = tempfile::tempdir().unwrap();
+ add_ok(
+ dd.path(),
+ add_args("a", "https://a.example", &[], Some("t")),
+ None,
+ );
+ let text = add_ok(
+ dd.path(),
+ add_args("b", "https://b.example", &[], Some("t")),
+ None,
+ );
+ assert!(text.contains("Add roots to: a, b"), "{text}");
+ }
+
+ #[test]
+ fn invalid_names_are_refused_before_anything_is_written() {
+ let dd = tempfile::tempdir().unwrap();
+ let mut out = Vec::new();
+ let bad = add_args("../x", "https://a.example", &[], Some("t"));
+ assert!(add(dd.path(), bad, None, &mut out).is_err());
+ assert!(!dd.path().join("servers.toml").exists());
+ let remove_bad = ServerRemoveArgs {
+ name: "../x".into(),
+ };
+ assert!(remove(dd.path(), &remove_bad, &mut out).is_err());
+ }
+
+ #[test]
+ fn remove_reports_whether_the_profile_existed() {
+ let dd = tempfile::tempdir().unwrap();
+ add_ok(
+ dd.path(),
+ add_args("a", "https://a.example", &[], Some("t")),
+ None,
+ );
+ let args = ServerRemoveArgs { name: "a".into() };
+ assert!(output(|out| remove(dd.path(), &args, out)).contains("Removed"));
+ assert!(output(|out| remove(dd.path(), &args, out)).contains("No server profile"));
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index ea8f1bf0..fe827220 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -723,6 +723,14 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {
config.data_dir.display()
);
}
+ // 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) {
+ eprintln!(
+ "ai-memory uninstall warning: could not remove the stored server-profile tokens under {}: {error}",
+ config.data_dir.display()
+ );
+ }
if args.purge_data {
for path in data_purge::purge_data_dirs(&config.data_dir)? {
diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rs
index d89eef1a..972abfeb 100644
--- a/crates/ai-memory-cli/src/lib.rs
+++ b/crates/ai-memory-cli/src/lib.rs
@@ -28,6 +28,7 @@ mod install_layout;
mod logging;
mod marker;
mod process_guard;
+mod server_profiles;
use cli::{Cli, Command};
use config::Config;
@@ -176,6 +177,7 @@ pub async fn run() -> Result<()> {
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,
+ Command::Server(args) => commands::server::run(&config, args),
// `Completions` is handled in the fast-path above (before config/tracing).
Command::Completions(args) => commands::completions::run(args),
}
diff --git a/crates/ai-memory-cli/src/server_profiles.rs b/crates/ai-memory-cli/src/server_profiles.rs
new file mode 100644
index 00000000..765b9f9d
--- /dev/null
+++ b/crates/ai-memory-cli/src/server_profiles.rs
@@ -0,0 +1,802 @@
+//! Named server profiles: per-repository routing of hook capture (#992).
+//!
+//! A machine can register several ai-memory servers under local names in
+//! `<data_dir>/servers.toml`; a repository's `.ai-memory.toml` then selects one
+//! with `server = "<name>"`. The marker is committed repository content — so
+//! untrusted input — which is why it carries only a *name*: a cloned repository
+//! can choose among servers this operator registered, never introduce a new
+//! destination, and never see a credential.
+//!
+//! Every failure resolves to a [`Rejection`] and the caller drops the event.
+//! Falling back to the install-time `--server-url` would deliver one team's
+//! capture to another team's server, which is the exact outcome profiles exist
+//! to prevent.
+//!
+//! Tokens live one per file under `<data_dir>/auth-tokens/<name>`, `0600`, and
+//! never in `servers.toml`, a rendered hook config, or a process argv.
+//!
+//! Read on the hook hot path, so parsing uses `toml_edit` over this one file
+//! and nothing else — no figment merge, no environment — for the same reason
+//! `hook_spool::configured_server_url` does.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context as _, Result, bail};
+
+/// `<data_dir>/servers.toml`.
+const REGISTRY_FILE: &str = "servers.toml";
+/// `<data_dir>/auth-tokens/` — one owner-only file per profile.
+const TOKEN_DIR: &str = "auth-tokens";
+/// A registry is a handful of short tables; anything larger is not one.
+const MAX_REGISTRY_BYTES: u64 = 64 * 1024;
+const MAX_NAME_CHARS: usize = 64;
+
+/// A validated profile name: `[a-z0-9][a-z0-9_-]{0,63}`, and not a Windows
+/// reserved device name.
+///
+/// Parsed once, because the name becomes a file name under `auth-tokens/`: a
+/// marker naming `../auth-token` must never reach the filesystem as a path,
+/// and `nul` or `con` would open a device instead of a file on Windows. The
+/// device names are refused on every platform so a registry stays portable.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub(crate) struct ProfileName(String);
+
+impl ProfileName {
+ pub(crate) fn parse(raw: &str) -> Option<Self> {
+ let mut chars = raw.chars();
+ let first = chars.next()?;
+ let valid = raw.len() <= MAX_NAME_CHARS
+ && (first.is_ascii_lowercase() || first.is_ascii_digit())
+ && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
+ && !ai_memory_core::is_dos_device_name(raw);
+ valid.then(|| Self(raw.to_owned()))
+ }
+
+ pub(crate) fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl std::fmt::Display for ProfileName {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+/// One registered server.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct Profile {
+ /// Server URL, trailing slashes trimmed.
+ pub(crate) url: String,
+ /// Directories allowed to select this profile, as written (`~/` allowed).
+ pub(crate) roots: Vec<String>,
+}
+
+/// The parsed `servers.toml`. An absent file is an empty registry.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub(crate) struct Registry {
+ pub(crate) profiles: BTreeMap<ProfileName, Profile>,
+}
+
+/// Why a marker's `server` selection was refused. Each one drops the event.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Rejection {
+ /// The marker's value is not a valid profile name.
+ InvalidName,
+ /// `servers.toml` is unreadable, oversized, or malformed.
+ InvalidRegistry,
+ /// No profile by that name is registered.
+ UnknownProfile,
+ /// The profile has no stored token.
+ NoToken,
+ /// Several profiles are registered and this one declares no `roots`, so
+ /// any repository could select it.
+ RootsRequired,
+ /// The marker sits outside every one of the profile's `roots`.
+ OutsideRoots,
+ /// A marker on the walk exists but could not be read, so whether it
+ /// selects a profile is unknown.
+ UnreadableMarker,
+}
+
+impl Rejection {
+ /// Stable, secret-free label for `hook --check-capture` and warnings.
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Self::InvalidName => "rejected-invalid-profile-name",
+ Self::InvalidRegistry => "rejected-invalid-registry",
+ Self::UnknownProfile => "rejected-unknown-profile",
+ Self::NoToken => "rejected-no-token",
+ Self::RootsRequired => "rejected-roots-required",
+ Self::OutsideRoots => "rejected-outside-roots",
+ Self::UnreadableMarker => "rejected-unreadable-marker",
+ }
+ }
+}
+
+/// A selection that passed every check: where to deliver, and with what.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ResolvedServer {
+ pub(crate) name: ProfileName,
+ pub(crate) url: String,
+ pub(crate) token: String,
+}
+
+fn registry_path(data_dir: &Path) -> PathBuf {
+ data_dir.join(REGISTRY_FILE)
+}
+
+fn token_path(data_dir: &Path, name: &ProfileName) -> PathBuf {
+ data_dir.join(TOKEN_DIR).join(name.as_str())
+}
+
+/// 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.
+pub(crate) fn load(data_dir: &Path) -> Result<Registry> {
+ read_bounded(&registry_path(data_dir))?.map_or_else(
+ || Ok(Registry::default()),
+ |text| validate(&parse_doc(&text)?),
+ )
+}
+
+fn read_bounded(path: &Path) -> Result<Option<String>> {
+ let meta = match std::fs::metadata(path) {
+ Ok(meta) => meta,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(e) => return Err(e).with_context(|| format!("cannot read {REGISTRY_FILE}")),
+ };
+ if meta.len() > MAX_REGISTRY_BYTES {
+ bail!("{REGISTRY_FILE} exceeds {MAX_REGISTRY_BYTES} bytes");
+ }
+ std::fs::read_to_string(path)
+ .map(Some)
+ .with_context(|| format!("cannot read {REGISTRY_FILE}"))
+}
+
+fn parse_doc(text: &str) -> Result<toml_edit::DocumentMut> {
+ text.parse()
+ .with_context(|| format!("{REGISTRY_FILE} is not valid TOML"))
+}
+
+fn validate(doc: &toml_edit::DocumentMut) -> Result<Registry> {
+ let mut registry = Registry::default();
+ for (key, item) in doc.iter() {
+ if key != "servers" {
+ bail!("unknown top-level key `{key}` in {REGISTRY_FILE}");
+ }
+ let servers = item
+ .as_table_like()
+ .with_context(|| format!("`servers` in {REGISTRY_FILE} must be a table"))?;
+ for (raw_name, entry) in servers.iter() {
+ let name = ProfileName::parse(raw_name)
+ .with_context(|| format!("invalid profile name `{raw_name}`"))?;
+ let table = entry
+ .as_table_like()
+ .with_context(|| format!("profile `{name}` must be a table"))?;
+ let profile = parse_profile(table).with_context(|| format!("profile `{name}`"))?;
+ registry.profiles.insert(name, profile);
+ }
+ }
+ Ok(registry)
+}
+
+fn parse_profile(table: &dyn toml_edit::TableLike) -> Result<Profile> {
+ let mut url = None;
+ let mut roots = Vec::new();
+ for (key, value) in table.iter() {
+ match key {
+ "url" => {
+ url = Some(validate_url(
+ value.as_str().context("`url` must be a string")?,
+ )?);
+ }
+ "roots" => {
+ for root in value.as_array().context("`roots` must be an array")? {
+ let root = root
+ .as_str()
+ .context("every `roots` entry must be a string")?;
+ validate_root(root)?;
+ roots.push(root.to_owned());
+ }
+ }
+ other => bail!("unknown key `{other}`"),
+ }
+ }
+ Ok(Profile {
+ url: url.context("no `url`")?,
+ roots,
+ })
+}
+
+/// Accept only `http(s)://` URLs with a host, normalised without trailing
+/// slashes — rejected here rather than on every hook request.
+fn validate_url(raw: &str) -> Result<String> {
+ let trimmed = raw.trim().trim_end_matches('/');
+ let parsed = reqwest::Url::parse(trimmed).with_context(|| format!("`{raw}` is not a URL"))?;
+ if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none_or(str::is_empty) {
+ bail!("`{raw}` is not an http:// or https:// URL with a host");
+ }
+ Ok(trimmed.to_owned())
+}
+
+/// A root must be absolute or `~/`-relative: a relative root would resolve
+/// against whatever directory the hook happened to run in.
+fn validate_root(raw: &str) -> Result<()> {
+ if raw == "~" || raw.starts_with("~/") || Path::new(raw).is_absolute() {
+ Ok(())
+ } else {
+ bail!("root `{raw}` must be absolute or start with `~/`")
+ }
+}
+
+fn expand_root(raw: &str, home: Option<&Path>) -> Option<PathBuf> {
+ let path = if raw == "~" {
+ home?.to_path_buf()
+ } else if let Some(rest) = raw.strip_prefix("~/") {
+ home?.join(rest)
+ } else {
+ PathBuf::from(raw)
+ };
+ Some(crate::marker::absolute_normalized(&path))
+}
+
+/// Read a profile's stored token. Trailing newline trimmed; blank is `None`.
+pub(crate) fn read_token(data_dir: &Path, name: &ProfileName) -> Option<String> {
+ crate::config::read_trimmed_secret(&token_path(data_dir, name))
+}
+
+/// Resolve a marker's `server` selection.
+///
+/// `marker_dir` is the directory of the marker that declared the key, in the
+/// same lexical namespace as the hook's cwd (see `marker::absolute_normalized`);
+/// `roots` are compared against it component-wise, so `~/work/team-b` admits
+/// `~/work/team-b/repo` but not `~/work/team-bb`.
+pub(crate) fn resolve(
+ data_dir: &Path,
+ raw_name: &str,
+ marker_dir: &Path,
+ home: Option<&Path>,
+) -> Result<ResolvedServer, Rejection> {
+ let name = ProfileName::parse(raw_name).ok_or(Rejection::InvalidName)?;
+ let registry = load(data_dir).map_err(|_| Rejection::InvalidRegistry)?;
+ let profile = registry
+ .profiles
+ .get(&name)
+ .ok_or(Rejection::UnknownProfile)?;
+ if profile.roots.is_empty() {
+ if registry.profiles.len() > 1 {
+ return Err(Rejection::RootsRequired);
+ }
+ } else {
+ let marker_dir = crate::marker::absolute_normalized(marker_dir);
+ let admitted = profile
+ .roots
+ .iter()
+ .filter_map(|root| expand_root(root, home))
+ .any(|root| marker_dir.starts_with(&root));
+ if !admitted {
+ return Err(Rejection::OutsideRoots);
+ }
+ }
+ with_token(data_dir, name, profile)
+}
+
+/// A registered profile's URL and stored token, without the `roots` check.
+///
+/// For a caller acting on a selection the hook already vetted against the
+/// marker that made it — the backfill the hook spawned.
+pub(crate) fn lookup(data_dir: &Path, name: &ProfileName) -> Result<ResolvedServer, Rejection> {
+ let registry = load(data_dir).map_err(|_| Rejection::InvalidRegistry)?;
+ let profile = registry
+ .profiles
+ .get(name)
+ .ok_or(Rejection::UnknownProfile)?;
+ with_token(data_dir, name.clone(), profile)
+}
+
+fn with_token(
+ data_dir: &Path,
+ name: ProfileName,
+ profile: &Profile,
+) -> Result<ResolvedServer, Rejection> {
+ let token = read_token(data_dir, &name).ok_or(Rejection::NoToken)?;
+ Ok(ResolvedServer {
+ name,
+ url: profile.url.clone(),
+ token,
+ })
+}
+
+/// Register or replace a profile, keeping any hand-written comments and other
+/// profiles in `servers.toml` intact, then store its token when one is given.
+///
+/// The file is validated before it is rewritten, so `add` refuses to build on
+/// a registry the hook would already reject as a whole.
+pub(crate) fn add(
+ data_dir: &Path,
+ name: &ProfileName,
+ url: &str,
+ roots: &[String],
+ token: Option<&str>,
+) -> Result<AddOutcome> {
+ let url = validate_url(url)?;
+ let roots_were_omitted = roots.is_empty();
+ for root in roots {
+ validate_root(root)?;
+ }
+ let path = registry_path(data_dir);
+ let mut doc = parse_doc(&read_bounded(&path)?.unwrap_or_default())?;
+ let existing = validate(&doc)?.profiles.remove(name);
+ // Re-running `add` to rotate a token or fix a URL must not silently lift
+ // the roots restriction: omitted roots keep the ones already registered.
+ let roots = match &existing {
+ Some(profile) if roots_were_omitted => profile.roots.clone(),
+ _ => roots.to_vec(),
+ };
+ // A stored token belongs to the URL it was registered with. Once the URL
+ // changes it is discarded *before* the new URL is written, so there is no
+ // moment at which one server's credential is paired with another server.
+ let token = token.map(str::trim).filter(|t| !t.is_empty());
+ let url_changed = existing.as_ref().is_some_and(|profile| profile.url != url);
+ let token_discarded = url_changed && discard_token(data_dir, name)? && token.is_none();
+ let servers = doc
+ .entry("servers")
+ .or_insert_with(|| {
+ let mut table = toml_edit::Table::new();
+ table.set_implicit(true);
+ toml_edit::Item::Table(table)
+ })
+ .as_table_mut()
+ .with_context(|| format!("`servers` in {REGISTRY_FILE} must be a table"))?;
+ let mut entry = toml_edit::Table::new();
+ entry.insert("url", toml_edit::value(url));
+ if !roots.is_empty() {
+ let array: toml_edit::Array = roots.iter().map(String::as_str).collect();
+ entry.insert("roots", toml_edit::value(array));
+ }
+ servers.insert(name.as_str(), toml_edit::Item::Table(entry));
+ write_private(&path, &doc.to_string())?;
+ if let Some(token) = token {
+ crate::commands::path_util::create_private_dir(&data_dir.join(TOKEN_DIR))
+ .context("cannot create the token directory")?;
+ write_private(&token_path(data_dir, name), token)?;
+ }
+ Ok(AddOutcome {
+ token_discarded,
+ roots_kept: roots_were_omitted && !roots.is_empty(),
+ })
+}
+
+/// What `add` did beyond writing what it was given.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct AddOutcome {
+ /// The URL changed without a new token, so the old server's token was
+ /// removed and the profile refuses events until a token is added.
+ pub(crate) token_discarded: bool,
+ /// No roots were given, so the profile kept its registered ones.
+ pub(crate) roots_kept: bool,
+}
+
+/// Remove a profile and its token. Returns whether the profile existed.
+pub(crate) fn remove(data_dir: &Path, name: &ProfileName) -> Result<bool> {
+ let path = registry_path(data_dir);
+ let mut existed = false;
+ if let Some(text) = read_bounded(&path)? {
+ let mut doc = parse_doc(&text)?;
+ existed = doc
+ .get_mut("servers")
+ .and_then(toml_edit::Item::as_table_like_mut)
+ .and_then(|servers| servers.remove(name.as_str()))
+ .is_some();
+ if existed {
+ write_private(&path, &doc.to_string())?;
+ }
+ }
+ Ok(discard_token(data_dir, name)? || existed)
+}
+
+/// Remove every stored profile token, keeping the registry itself.
+///
+/// `uninstall` removes the hooks, which are the only readers of these
+/// tokens; leaving them on disk would strand live credentials the same way
+/// the single hook token used to (#552). The registry holds no secrets and
+/// survives, so a later reinstall lists each profile with `token: missing`
+/// and refuses its events until a token is stored again.
+///
+/// # 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)) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e),
+ }
+}
+
+/// Delete a profile's token file. Returns whether one was there.
+fn discard_token(data_dir: &Path, name: &ProfileName) -> Result<bool> {
+ match std::fs::remove_file(token_path(data_dir, name)) {
+ Ok(()) => Ok(true),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
+ Err(e) => Err(e).context("cannot remove token"),
+ }
+}
+
+/// Atomic replace through the canonical [`ai_memory_wiki::write_atomic`]. Its
+/// temp file is created `0600`, so replacing an existing file never inherits
+/// wider permissions from it.
+fn write_private(path: &Path, contents: &str) -> Result<()> {
+ ai_memory_wiki::write_atomic(path, contents.as_bytes())
+ .map(|_| ())
+ .with_context(|| format!("cannot write {}", path.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn store_token(data_dir: &Path, name: &ProfileName, token: &str) -> Result<()> {
+ crate::commands::path_util::create_private_dir(&data_dir.join(TOKEN_DIR))?;
+ write_private(&token_path(data_dir, name), token)
+ }
+
+ fn name(raw: &str) -> ProfileName {
+ ProfileName::parse(raw).unwrap()
+ }
+
+ #[test]
+ fn profile_names_cannot_become_paths() {
+ for bad in [
+ "",
+ "../auth-token",
+ "a/b",
+ "Team",
+ "-x",
+ "a b",
+ "a.b",
+ &"a".repeat(65),
+ "con",
+ "nul",
+ "aux",
+ "prn",
+ "com1",
+ "lpt9",
+ ] {
+ assert!(
+ ProfileName::parse(bad).is_none(),
+ "{bad:?} must be rejected"
+ );
+ }
+ for good in [
+ "team-a", "b", "0", "team_b-2", "console", "com", "com10", "nul-1",
+ ] {
+ assert!(
+ ProfileName::parse(good).is_some(),
+ "{good:?} must be accepted"
+ );
+ }
+ }
+
+ #[test]
+ fn a_missing_registry_is_empty_and_an_unknown_profile_is_refused() {
+ let dd = tempfile::tempdir().unwrap();
+ assert_eq!(load(dd.path()).unwrap(), Registry::default());
+ assert_eq!(
+ resolve(dd.path(), "team-a", dd.path(), None),
+ Err(Rejection::UnknownProfile)
+ );
+ }
+
+ #[test]
+ fn a_malformed_registry_refuses_every_selection() {
+ let dd = tempfile::tempdir().unwrap();
+ for text in [
+ "[servers.a]\nurl = \"https://a.example\"\ntoken = \"leak\"\n",
+ "server_url = \"https://a.example\"\n",
+ "[servers.a]\nurl = \"ftp://a.example\"\n",
+ "[servers.a]\nroots = [\"~/x\"]\n",
+ "[servers.a]\nurl = \"https://a.example\"\nroots = [\"relative\"]\n",
+ "[servers.\"Bad\"]\nurl = \"https://a.example\"\n",
+ "not toml [",
+ ] {
+ std::fs::write(dd.path().join(REGISTRY_FILE), text).unwrap();
+ store_token(dd.path(), &name("a"), "tok").unwrap();
+ assert_eq!(
+ resolve(dd.path(), "a", dd.path(), None),
+ Err(Rejection::InvalidRegistry),
+ "{text}"
+ );
+ }
+ }
+
+ #[test]
+ fn an_oversized_registry_is_refused() {
+ let dd = tempfile::tempdir().unwrap();
+ let mut text = String::from("[servers.a]\nurl = \"https://a.example\"\n");
+ text.push_str(&"#".repeat(usize::try_from(MAX_REGISTRY_BYTES).unwrap()));
+ std::fs::write(dd.path().join(REGISTRY_FILE), text).unwrap();
+ assert!(load(dd.path()).is_err());
+ }
+
+ /// A platform-absolute path string under `base`.
+ fn under(base: &Path, rel: &str) -> String {
+ base.join(rel).to_string_lossy().into_owned()
+ }
+
+ #[test]
+ fn a_single_profile_without_roots_resolves_with_its_own_token() {
+ let dd = tempfile::tempdir().unwrap();
+ add(
+ dd.path(),
+ &name("a"),
+ "https://a.example/",
+ &[],
+ Some("tok-a"),
+ )
+ .unwrap();
+ let resolved = resolve(dd.path(), "a", &dd.path().join("anywhere"), None).unwrap();
+ assert_eq!(resolved.url, "https://a.example");
+ assert_eq!(resolved.token, "tok-a");
+ }
+
+ #[test]
+ fn a_profile_without_a_token_is_refused() {
+ let dd = tempfile::tempdir().unwrap();
+ add(dd.path(), &name("a"), "https://a.example", &[], None).unwrap();
+ assert_eq!(
+ resolve(dd.path(), "a", &dd.path().join("anywhere"), None),
+ Err(Rejection::NoToken)
+ );
+ }
+
+ #[test]
+ fn roots_are_required_once_a_second_profile_exists() {
+ let dd = tempfile::tempdir().unwrap();
+ let work = dd.path().join("work");
+ add(
+ dd.path(),
+ &name("a"),
+ "https://a.example",
+ &[],
+ Some("tok-a"),
+ )
+ .unwrap();
+ add(
+ dd.path(),
+ &name("b"),
+ "https://b.example",
+ &[under(&work, "b")],
+ Some("tok-b"),
+ )
+ .unwrap();
+ assert_eq!(
+ resolve(dd.path(), "a", &work.join("a"), None),
+ Err(Rejection::RootsRequired)
+ );
+ assert!(resolve(dd.path(), "b", &work.join("b").join("repo"), None).is_ok());
+ }
+
+ #[test]
+ fn roots_match_whole_components_and_expand_home() {
+ let dd = tempfile::tempdir().unwrap();
+ let home = dd.path().join("home");
+ add(
+ dd.path(),
+ &name("b"),
+ "https://b.example",
+ &["~/work/team-b".to_owned()],
+ Some("tok-b"),
+ )
+ .unwrap();
+ let team_b = home.join("work").join("team-b");
+ assert!(resolve(dd.path(), "b", &team_b, Some(&home)).is_ok());
+ assert!(resolve(dd.path(), "b", &team_b.join("x").join("y"), Some(&home)).is_ok());
+ for outside in [
+ home.join("work").join("team-bb"),
+ home.join("work"),
+ team_b.join("..").join("team-a"),
+ dd.path().join("elsewhere").join("work").join("team-b"),
+ ] {
+ assert_eq!(
+ resolve(dd.path(), "b", &outside, Some(&home)),
+ Err(Rejection::OutsideRoots),
+ "{}",
+ outside.display()
+ );
+ }
+ assert_eq!(
+ resolve(dd.path(), "b", &team_b, None),
+ Err(Rejection::OutsideRoots),
+ "a `~` root cannot match when home is unknown"
+ );
+ }
+
+ #[test]
+ fn add_preserves_other_profiles_and_comments_and_remove_deletes_the_token() {
+ let dd = tempfile::tempdir().unwrap();
+ let root_a = toml_edit::Value::from(under(dd.path(), "a"));
+ std::fs::write(
+ dd.path().join(REGISTRY_FILE),
+ format!(
+ "# managed by hand\n[servers.a]\nurl = \"https://a.example\"\nroots = [{root_a}]\n"
+ ),
+ )
+ .unwrap();
+ add(
+ dd.path(),
+ &name("b"),
+ "https://b.example",
+ &[under(dd.path(), "b")],
+ Some("tok-b"),
+ )
+ .unwrap();
+ let text = std::fs::read_to_string(dd.path().join(REGISTRY_FILE)).unwrap();
+ assert!(text.contains("# managed by hand"), "{text}");
+ assert!(
+ !text.contains("tok-b"),
+ "tokens never go in the registry: {text}"
+ );
+ let registry = load(dd.path()).unwrap();
+ assert_eq!(registry.profiles.len(), 2);
+
+ assert!(remove(dd.path(), &name("b")).unwrap());
+ assert!(read_token(dd.path(), &name("b")).is_none());
+ assert_eq!(load(dd.path()).unwrap().profiles.len(), 1);
+ assert!(!remove(dd.path(), &name("b")).unwrap());
+ }
+
+ /// Moving a profile to a new URL without a new token must not pair the
+ /// old server's token with the new server.
+ #[test]
+ fn changing_the_url_without_a_token_discards_the_old_token() {
+ let dd = tempfile::tempdir().unwrap();
+ add(
+ dd.path(),
+ &name("b"),
+ "https://old.example",
+ &[],
+ Some("tok-old"),
+ )
+ .unwrap();
+
+ let outcome = add(dd.path(), &name("b"), "https://new.example", &[], None).unwrap();
+ assert!(outcome.token_discarded);
+ assert_eq!(read_token(dd.path(), &name("b")), None);
+ assert_eq!(
+ resolve(dd.path(), "b", dd.path(), None),
+ Err(Rejection::NoToken)
+ );
+
+ let outcome = add(
+ dd.path(),
+ &name("b"),
+ "https://new.example",
+ &[],
+ Some("tok-new"),
+ )
+ .unwrap();
+ assert!(!outcome.token_discarded);
+ assert_eq!(
+ resolve(dd.path(), "b", dd.path(), None).unwrap().token,
+ "tok-new"
+ );
+
+ let outcome = add(dd.path(), &name("b"), "https://new.example/", &[], None).unwrap();
+ assert!(!outcome.token_discarded, "the same URL keeps its token");
+ assert_eq!(
+ read_token(dd.path(), &name("b")).as_deref(),
+ Some("tok-new")
+ );
+ }
+
+ /// Re-running `add` without `--root` (for a token rotation) keeps the
+ /// registered roots instead of lifting the restriction.
+ #[test]
+ fn omitted_roots_keep_the_registered_ones() {
+ let dd = tempfile::tempdir().unwrap();
+ let root = under(dd.path(), "b");
+ add(
+ dd.path(),
+ &name("b"),
+ "https://b.example",
+ std::slice::from_ref(&root),
+ Some("t1"),
+ )
+ .unwrap();
+
+ let outcome = add(dd.path(), &name("b"), "https://b.example", &[], Some("t2")).unwrap();
+ assert!(outcome.roots_kept);
+ assert_eq!(
+ load(dd.path()).unwrap().profiles[&name("b")].roots,
+ vec![root]
+ );
+
+ let other = under(dd.path(), "c");
+ let outcome = add(
+ dd.path(),
+ &name("b"),
+ "https://b.example",
+ std::slice::from_ref(&other),
+ None,
+ )
+ .unwrap();
+ assert!(!outcome.roots_kept);
+ assert_eq!(
+ load(dd.path()).unwrap().profiles[&name("b")].roots,
+ vec![other]
+ );
+ }
+
+ /// Uninstall removes the tokens and nothing else; the registry stays so
+ /// the profiles are listed as tokenless rather than forgotten.
+ #[test]
+ fn clear_tokens_removes_every_token_and_keeps_the_registry() {
+ let dd = tempfile::tempdir().unwrap();
+ add(
+ dd.path(),
+ &name("a"),
+ "https://a.example",
+ &[],
+ Some("tok-a"),
+ )
+ .unwrap();
+ add(
+ dd.path(),
+ &name("b"),
+ "https://b.example",
+ &[under(dd.path(), "b")],
+ Some("tok-b"),
+ )
+ .unwrap();
+
+ clear_tokens(dd.path()).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);
+ assert_eq!(load(dd.path()).unwrap().profiles.len(), 2);
+ assert_eq!(
+ resolve(dd.path(), "b", &dd.path().join("b"), None),
+ Err(Rejection::NoToken),
+ "the profile is still registered, only its token is gone"
+ );
+
+ clear_tokens(dd.path()).expect("clearing an already-clear store is not an error");
+ }
+
+ #[test]
+ fn add_refuses_to_build_on_an_invalid_registry() {
+ let dd = tempfile::tempdir().unwrap();
+ std::fs::write(dd.path().join(REGISTRY_FILE), "stray = 1\n").unwrap();
+ assert!(add(dd.path(), &name("a"), "https://a.example", &[], None).is_err());
+ assert_eq!(
+ std::fs::read_to_string(dd.path().join(REGISTRY_FILE)).unwrap(),
+ "stray = 1\n"
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn tokens_are_owner_only_even_when_replacing_a_wider_file() {
+ use std::os::unix::fs::PermissionsExt as _;
+ let dd = tempfile::tempdir().unwrap();
+ store_token(dd.path(), &name("a"), "old").unwrap();
+ let path = token_path(dd.path(), &name("a"));
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
+ store_token(dd.path(), &name("a"), "new").unwrap();
+ assert_eq!(
+ std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ assert_eq!(
+ std::fs::metadata(dd.path().join(TOKEN_DIR))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o700
+ );
+ assert_eq!(read_token(dd.path(), &name("a")).as_deref(), Some("new"));
+ }
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ac0a0f86..9fc3f104 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -564,6 +564,7 @@ completions handoffs purge-session
compact api-key export-okf
message doctor backfill
project reclaim-ledger-versions repair-backfill-timestamps
+server
```
Run `ai-memory --help` for the full tree.