Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): grant and access-mode commands; 403 is final for captures (#708)
luisfnicolau57c98b44d3ad
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 00d0ce97..1d56b978 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -227,6 +227,10 @@ pub enum Command {/// the root bearer token and `[auth].token_pepper`.#[command(name = "api-key")]ApiKey(ApiKeyArgs),+ /// Project settings. `project access` sets a project `open` (any user)+ /// or `restricted` (root and grant holders) (#708). Requires the root+ /// bearer token.+ Project(ProjectArgs),/// 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.@@ -668,6 +672,94 @@ pub struct UserArgs {pub command: UserCommand,}+/// Arguments for `user grant`.+#[derive(Debug, Args)]+pub struct UserGrantArgs {+ /// The user, by username.+ #[arg(long)]+ pub user: String,+ /// The workspace the project lives in.+ #[arg(long, default_value = "default")]+ pub workspace: String,+ /// The project, by name.+ #[arg(long)]+ pub project: String,+ /// `read` or `write`. Required: a level left unsaid is not guessed at.+ #[arg(long)]+ pub level: String,+}++/// Arguments for `user revoke`.+#[derive(Debug, Args)]+pub struct UserRevokeArgs {+ /// The user, by username.+ #[arg(long)]+ pub user: String,+ /// The workspace the project lives in.+ #[arg(long, default_value = "default")]+ pub workspace: String,+ /// The project, by name.+ #[arg(long)]+ pub project: String,+}++/// Arguments for `user grants`.+#[derive(Debug, Args)]+pub struct UserGrantsArgs {+ /// Only this user's grants. Omit for every grant on the server.+ #[arg(long)]+ pub user: Option<String>,+ /// Emit the response as JSON instead of a table.+ #[arg(long)]+ pub json: bool,+}++/// Arguments for `project`.+#[derive(Debug, Args)]+pub struct ProjectArgs {+ /// Project action to run.+ #[command(subcommand)]+ pub command: ProjectCommand,+}++/// `project` subcommands.+#[derive(Debug, Subcommand)]+pub enum ProjectCommand {+ /// Set a project `open` or `restricted`.+ Access(ProjectAccessArgs),+ /// List who holds a grant on one project.+ Grants(ProjectGrantsArgs),+}++/// Arguments for `project grants`.+#[derive(Debug, Args)]+pub struct ProjectGrantsArgs {+ /// The workspace the project lives in.+ #[arg(long, default_value = "default")]+ pub workspace: String,+ /// The project, by name.+ #[arg(long)]+ pub project: String,+ /// Emit the response as JSON instead of a table.+ #[arg(long)]+ pub json: bool,+}++/// Arguments for `project access`.+#[derive(Debug, Args)]+pub struct ProjectAccessArgs {+ /// The workspace the project lives in.+ #[arg(long, default_value = "default")]+ pub workspace: String,+ /// The project, by name.+ #[arg(long)]+ pub project: String,+ /// `open` (any authenticated user) or `restricted` (root and grant+ /// holders). Required: a mode left unsaid is not guessed at.+ #[arg(long)]+ pub mode: String,+}+/// Arguments for `completions`.#[derive(Debug, Args)]pub struct CompletionsArgs {@@ -707,6 +799,14 @@ pub enum UserCommand {Enable(UserEnableArgs),/// Update display name, email, and/or role (`root` or `user`).Patch(UserPatchArgs),+ /// Grant a user `read` or `write` on a project, or change the level they+ /// hold (#708). Grants decide access to `restricted` projects; an `open`+ /// project admits every user — see `ai-memory project access`.+ Grant(UserGrantArgs),+ /// Take away whatever a user holds on a project.+ Revoke(UserRevokeArgs),+ /// List grants: one user's with `--user`, else every grant on the server.+ Grants(UserGrantsArgs),}/// Arguments for `user add`.@@ -2632,6 +2732,73 @@ mod tests {use clap::{CommandFactory, Parser};use std::collections::BTreeSet;+ /// The management surface uses the design's spelling (#708):+ /// `user grant --user … --workspace … --project … --level …`, `user revoke`,+ /// and listings under `user grants` / `project grants`. A level is never+ /// defaulted, and the former top-level `grant` command is gone.+ #[test]+ fn grant_commands_use_the_designs_spelling() {+ let parsed = Cli::try_parse_from([+ "ai-memory",+ "user",+ "grant",+ "--user",+ "alice",+ "--workspace",+ "acme",+ "--project",+ "api",+ "--level",+ "write",+ ])+ .expect("user grant parses");+ let Command::User(UserArgs {+ command: UserCommand::Grant(args),+ }) = parsed.command+ else {+ panic!("expected user grant");+ };+ assert_eq!(+ (+ args.user.as_str(),+ args.workspace.as_str(),+ args.project.as_str(),+ args.level.as_str()+ ),+ ("alice", "acme", "api", "write")+ );+ assert!(+ Cli::try_parse_from([+ "ai-memory",+ "user",+ "grant",+ "--user",+ "alice",+ "--project",+ "api"+ ])+ .is_err(),+ "a level left unsaid is not guessed at"+ );+ for argv in [+ &[+ "ai-memory",+ "user",+ "revoke",+ "--user",+ "alice",+ "--project",+ "api",+ ][..],+ &["ai-memory", "user", "grants"][..],+ &["ai-memory", "user", "grants", "--user", "alice"][..],+ &["ai-memory", "project", "grants", "--project", "api"][..],+ ] {+ Cli::try_parse_from(argv).unwrap_or_else(|e| panic!("{argv:?}: {e}"));+ }+ assert!(Cli::try_parse_from(["ai-memory", "grant", "list"]).is_err());+ }+#[test]fn serve_parses_insecure_no_auth_override() {let parsed = Cli::try_parse_from([diff --git a/crates/ai-memory-cli/src/commands/grant.rs b/crates/ai-memory-cli/src/commands/grant.rsnew file mode 100644index 00000000..be14dadc--- /dev/null+++ b/crates/ai-memory-cli/src/commands/grant.rs@@ -0,0 +1,185 @@+//! Grant management for `ai-memory user grant|revoke|grants` and `ai-memory+//! project grants` (#708).+//!+//! Thin HTTP client over `/admin/users/{username}/grant|revoke|grants` and+//! `/admin/projects/grants`. The caller's bearer token must authenticate as+//! root: grants are an operator action, and the server is usually somewhere the+//! operator's laptop cannot open the database directly.++use anyhow::{Context, Result};+use serde::{Deserialize, Serialize};++use crate::cli::{ProjectGrantsArgs, UserGrantArgs, UserGrantsArgs, UserRevokeArgs};+use crate::commands::user::url_encode;+use crate::http_client::{ServerEndpoint, get_json, post_json};++#[derive(Debug, Serialize)]+struct GrantRequest<'a> {+ workspace: &'a str,+ project: &'a str,+ #[serde(skip_serializing_if = "Option::is_none")]+ level: Option<&'a str>,+}++#[derive(Debug, Deserialize, Serialize)]+struct GrantRow {+ username: String,+ workspace: String,+ project: String,+ level: String,+}++#[derive(Debug, Deserialize)]+struct GrantList {+ grants: Vec<GrantRow>,+}++fn print_grants(grants: &[GrantRow], json: bool) -> Result<()> {+ if json {+ println!("{}", serde_json::to_string_pretty(grants)?);+ return Ok(());+ }+ if grants.is_empty() {+ // Say what empty means: nothing is lost on an open project.+ println!("(no grants)");+ println!(+ "Open projects admit every user regardless; a restricted project with no \+ grants admits only root."+ );+ return Ok(());+ }+ let project_w = grants+ .iter()+ .map(|g| g.workspace.len() + 1 + g.project.len())+ .max()+ .unwrap_or(7)+ .max(7);+ let user_w = grants+ .iter()+ .map(|g| g.username.len())+ .max()+ .unwrap_or(8)+ .max(8);+ println!("{:<project_w$} {:<user_w$} LEVEL", "PROJECT", "USERNAME");+ for g in grants {+ let project = format!("{}/{}", g.workspace, g.project);+ println!(+ "{project:<project_w$} {:<user_w$} {}",+ g.username, g.level+ );+ }+ Ok(())+}++/// `ai-memory user grants [--user NAME]`.+///+/// # Errors+/// Transport failures, a non-root token, or an unknown user.+pub async fn list_for_user(ep: &ServerEndpoint, args: &UserGrantsArgs) -> Result<()> {+ let resp: GrantList = match &args.user {+ Some(user) => get_json(+ ep,+ &format!("/admin/users/{}/grants", url_encode(user)),+ &[],+ )+ .await+ .with_context(|| format!("listing {user}'s grants"))?,+ None => get_json(ep, "/admin/projects/grants", &[])+ .await+ .context("listing grants")?,+ };+ print_grants(&resp.grants, args.json)+}++/// `ai-memory project grants --workspace W --project P`.+///+/// # Errors+/// Transport failures, a non-root token, or an unknown project.+pub async fn list_for_project(ep: &ServerEndpoint, args: &ProjectGrantsArgs) -> Result<()> {+ let resp: GrantList = get_json(+ ep,+ "/admin/projects/grants",+ &[("workspace", &args.workspace), ("project", &args.project)],+ )+ .await+ .with_context(|| format!("listing grants on {}/{}", args.workspace, args.project))?;+ print_grants(&resp.grants, args.json)+}++#[derive(Debug, Deserialize)]+struct GrantResponse {+ level: String,+ changed: bool,+ previous: Option<String>,+}++/// `ai-memory user grant --user U --workspace W --project P --level L`.+///+/// # Errors+/// Transport failures, a non-root token, an unknown user, project or level.+pub async fn grant(ep: &ServerEndpoint, args: &UserGrantArgs) -> Result<()> {+ let body = GrantRequest {+ workspace: &args.workspace,+ project: &args.project,+ level: Some(&args.level),+ };+ let resp: GrantResponse = post_json(+ ep,+ &format!("/admin/users/{}/grant", url_encode(&args.user)),+ &body,+ )+ .await+ .with_context(|| {+ format!(+ "granting {} on {}/{}",+ args.user, args.workspace, args.project+ )+ })?;+ let who = &args.user;+ let project = format!("{}/{}", args.workspace, args.project);+ match (resp.changed, resp.previous) {+ (false, _) => println!(+ "{who} already holds {} on {project}; nothing changed.",+ resp.level+ ),+ (true, Some(previous)) => println!("{who}: {previous} -> {} on {project}.", resp.level),+ (true, None) => println!("{who} now holds {} on {project}.", resp.level),+ }+ Ok(())+}++#[derive(Debug, Deserialize)]+struct RevokeResponse {+ revoked: bool,+}++/// `ai-memory user revoke --user U --workspace W --project P`.+///+/// # Errors+/// Transport failures, a non-root token, an unknown user or project.+pub async fn revoke(ep: &ServerEndpoint, args: &UserRevokeArgs) -> Result<()> {+ let body = GrantRequest {+ workspace: &args.workspace,+ project: &args.project,+ level: None,+ };+ let resp: RevokeResponse = post_json(+ ep,+ &format!("/admin/users/{}/revoke", url_encode(&args.user)),+ &body,+ )+ .await+ .with_context(|| {+ format!(+ "revoking {} on {}/{}",+ args.user, args.workspace, args.project+ )+ })?;+ let project = format!("{}/{}", args.workspace, args.project);+ if resp.revoked {+ println!("{} no longer holds anything on {project}.", args.user);+ } else {+ println!("{} held nothing on {project}; nothing changed.", args.user);+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 3fb87181..7ffed060 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -363,6 +363,17 @@ pub enum PostOutcome {/// so the drain can skip past them instead of stopping at the first one/// (#493).Unreachable,+ /// `403` — the server understood the request and will never accept it.+ /// Today that means the author may not write the project+ /// the event belongs to.+ ///+ /// Terminal, and that is the whole point of separating it from+ /// [`Self::Failed`]. A refusal that counts as a failure gets re-sent until+ /// it exhausts `MAX_ATTEMPTS`, and every one of those attempts is+ /// guaranteed to be refused for the same reason. Retrying something that+ /// cannot succeed is how a parse failure once cost this project 10.7M+ /// tokens in a day. The entry is dropped on the spot.+ Refused,/// `401` — the server rejected the bearer. Distinguished from/// [`Self::Failed`] because it says something about the *credential*/// rather than the entry: a spooled event carries the token frozen at@@ -398,6 +409,7 @@ pub async fn post_hook(PostOutcome::Saturated}Ok(resp) if resp.status() == reqwest::StatusCode::UNAUTHORIZED => PostOutcome::Unauthorized,+ Ok(resp) if resp.status() == reqwest::StatusCode::FORBIDDEN => PostOutcome::Refused,Ok(_) => PostOutcome::Failed,Err(_) => PostOutcome::Unreachable,}@@ -555,6 +567,19 @@ pub async fn get_handoff(return None;}};+ if resp.status() == reqwest::StatusCode::FORBIDDEN {+ // Not authorized for this repository (#708). Same reasoning as the+ // transport warning above: silence here would read as "nothing was+ // handed off", when the truth is "you cannot see what was". The body+ // is the server's reason and goes to stderr, never into context.+ let reason = resp.text().await.unwrap_or_default();+ eprintln!(+ "ai-memory hook warning: not authorized for this project's memory ({}); \+ nothing was injected",+ reason.trim()+ );+ return None;+ }if !resp.status().is_success() {return None;}@@ -679,6 +704,36 @@ mod tests {assert_eq!(outcome, PostOutcome::Delivered);}+ #[tokio::test]+ async fn post_hook_refused_on_403_is_terminal_not_a_failure() {+ // 403 means the server will never accept this event. Classifying it as+ // `Failed` would re-send it until it burnt `MAX_ATTEMPTS`, and every+ // attempt would be refused identically — the shape of retry loop that+ // once cost this project 10.7M tokens in a day. It must be its own+ // outcome so the drain can drop it on the spot.+ let url = serve_once("403 Forbidden", "capture not authorized").await;+ let outcome = post_hook(&build_client(), &url, "{}", None, Duration::from_secs(1)).await;+ assert_eq!(outcome, PostOutcome::Refused);+ assert_ne!(+ outcome,+ PostOutcome::Failed,+ "a refusal must never be charged a retry attempt"+ );+ }++ #[tokio::test]+ async fn get_handoff_never_injects_a_refusal() {+ // A 403 carries the server's reason (#708). It is reported on stderr+ // and must not reach the agent as context.+ let url = serve_once(+ "403 Forbidden",+ "not authorized for scratch. This is an access problem, not an empty memory",+ )+ .await;+ let got = get_handoff(&build_client(), &url, None, Duration::from_secs(1)).await;+ assert!(got.is_none(), "a refusal must not become context");+ }+#[tokio::test]async fn get_handoff_ignores_non_success_status() {let url = serve_once("401 Unauthorized", "unauthorized").await;diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rsindex 0763f08a..29b64d81 100644--- a/crates/ai-memory-cli/src/commands/hook_spool.rs+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs@@ -738,6 +738,13 @@ pub async fn drain_with_live_token(PostOutcome::Failed => {bump_or_drop(path, entry, &mut result);}+ PostOutcome::Refused => {+ // Never retried: see `PostOutcome::Refused`.+ // Dropped rather than charged an attempt, so+ // it cannot sit in the spool being re-sent.+ let _ = std::fs::remove_file(path);+ result.dropped += 1;+ }PostOutcome::Unreachable => {// Same reasoning as the batch arm: the address// is dead, not the entry. Charge it once, then@@ -916,6 +923,11 @@ pub async fn drain_with_live_token(PostOutcome::Saturated => {result.remaining += 1;}+ PostOutcome::Refused => {+ // Terminal; see `PostOutcome::Refused`.+ let _ = std::fs::remove_file(path);+ result.dropped += 1;+ }PostOutcome::Failed => {bump_or_drop(&path, &entry, &mut result);}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex e9576392..59903bf3 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -40,6 +40,7 @@ pub mod export_okf;pub mod finalize_session;pub mod forget_sweep;pub mod generate_auth_token;+pub mod grant;pub mod handoffs;pub mod hook;pub mod hook_capture;@@ -59,6 +60,7 @@ pub mod move_session;pub mod openclaw_plugin;pub mod path_util;pub mod pending_writes;+pub mod project;pub mod project_registry;pub mod purge_project;pub mod purge_session;diff --git a/crates/ai-memory-cli/src/commands/project.rs b/crates/ai-memory-cli/src/commands/project.rsnew file mode 100644index 00000000..05a56771--- /dev/null+++ b/crates/ai-memory-cli/src/commands/project.rs@@ -0,0 +1,65 @@+//! `ai-memory project` — project settings (#708).+//!+//! Thin HTTP client over `/admin/projects/*`, root-only like `ai-memory+//! grant`: access is an operator decision, made against the server rather than+//! a database the operator's laptop usually cannot open.++use anyhow::{Context, Result};+use serde::Deserialize;++use crate::cli::{ProjectAccessArgs, ProjectArgs, ProjectCommand};+use crate::config::Config;+use crate::http_client::{ServerEndpoint, post_json};++/// Dispatch a `project` subcommand.+///+/// # Errors+/// Transport failures, a non-root token, an unknown project or mode.+pub async fn run(config: &Config, args: ProjectArgs) -> Result<()> {+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;+ match args.command {+ ProjectCommand::Access(args) => access(&ep, args).await,+ ProjectCommand::Grants(args) => crate::commands::grant::list_for_project(&ep, &args).await,+ }+}++#[derive(Debug, Deserialize)]+struct AccessResponse {+ mode: String,+ previous: String,+ changed: bool,+ without_access: Vec<String>,+}++async fn access(ep: &ServerEndpoint, args: ProjectAccessArgs) -> Result<()> {+ let resp: AccessResponse = post_json(+ ep,+ "/admin/projects/access",+ &serde_json::json!({+ "workspace": args.workspace,+ "project": args.project,+ "mode": args.mode,+ }),+ )+ .await+ .context("setting project access")?;+ let repo = format!("{}/{}", args.workspace, args.project);+ if resp.changed {+ println!("{repo} is now {} (was {}).", resp.mode, resp.previous);+ } else {+ println!("{repo} was already {}; nothing changed.", resp.mode);+ }+ if !resp.without_access.is_empty() {+ println!();+ println!("These users have written to {repo} and hold no grant, so they are now refused:");+ for name in &resp.without_access {+ println!(" {name}");+ }+ println!(+ "Grant the ones who should keep access: ai-memory user grant --user <name> \+ --workspace {} --project {} --level write",+ args.workspace, args.project+ );+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 9e02f4f1..0229bd2b 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1360,6 +1360,14 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {// the users-table lookup, including before the first user is// created. Admin mode separately switches on a fresh// store-backed users-exist read.+ store+ .writer+ .set_new_project_mode(if config.auth.new_projects_restricted {+ ai_memory_store::AccessMode::Restricted+ } else {+ ai_memory_store::AccessMode::Open+ })+ .await?;let mut auth_state = AuthState::new(config.auth.bearer_token.clone()).with_secure_cookie(config.auth.secure_cookie);let root_user = configdiff --git a/crates/ai-memory-cli/src/commands/user.rs b/crates/ai-memory-cli/src/commands/user.rsindex 34f33f3c..88a788be 100644--- a/crates/ai-memory-cli/src/commands/user.rs+++ b/crates/ai-memory-cli/src/commands/user.rs@@ -95,6 +95,9 @@ pub async fn run(config: &Config, args: UserArgs) -> Result<()> {UserCommand::Disable(args) => disable(&ep, args).await,UserCommand::Enable(args) => enable(&ep, args).await,UserCommand::Patch(args) => patch(&ep, args).await,+ UserCommand::Grant(args) => crate::commands::grant::grant(&ep, &args).await,+ UserCommand::Revoke(args) => crate::commands::grant::revoke(&ep, &args).await,+ UserCommand::Grants(args) => crate::commands::grant::list_for_user(&ep, &args).await,}}@@ -409,7 +412,7 @@ fn confirm(prompt: &str) -> Result<()> {Ok(())}-fn url_encode(s: &str) -> String {+pub(crate) fn url_encode(s: &str) -> String {let mut out = String::with_capacity(s.len());for &b in s.as_bytes() {if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.') {diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex d92eb107..23bdd3a2 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -771,6 +771,15 @@ pub struct AuthSettings {/// `Authorization: Bearer <token>`. Generate one with/// `ai-memory generate-auth-token`.pub bearer_token: Option<String>,+ /// Create every new project `restricted` rather than `open` (#708).+ ///+ /// Off by default: a new project is open to every authenticated user, as+ /// every project was before per-project access existed. On, a new project+ /// admits only its creator — who is granted `write` on it — and root,+ /// until someone grants others. Existing projects are never changed by+ /// this; an operator restricts one with `ai-memory project access`. The+ /// reserved `scratch` and global-preferences projects are always open.+ pub new_projects_restricted: bool,/// Mark the browser session cookie `Secure`. Human authentication on a/// non-loopback listener requires this explicit HTTPS reverse-proxy/// posture. It may be false only for direct loopback smoke/development.diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex 1350a46c..2e636dec 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -169,6 +169,7 @@ pub async fn run() -> Result<()> {Command::Auth(args) => commands::auth::run(&config, args).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,// `Completions` is handled in the fast-path above (before config/tracing).Command::Completions(args) => commands::completions::run(args),}