Skip to content

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

Rust

fix(cli): refuse an empty scope flag on a purge and warn on a derived target

AkitaOnRails1a1142344693
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 50863fa1..a88a750a 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -167,6 +167,28 @@ pub(crate) fn humanize_age_secs(seconds: i64) -> String {
format!("{value} {unit}{} ago", if value == 1 { "" } else { "s" })
}
+/// Refuse an explicitly empty scope flag on a destructive command.
+///
+/// [`resolve_scope`] treats an empty string as absent, so a harness that
+/// fills an unset variable with `""` still resolves the scope it would have
+/// resolved without the flag. That is the right reading for a read, and the
+/// wrong one for a delete: `--project "" --confirm` would aim the purge at
+/// whatever the current directory resolves to, which is exactly the target
+/// nobody typed. These commands ask for the flag to be omitted instead.
+///
+/// # Errors
+/// Returns an error naming `flag` when it was passed as an empty or
+/// whitespace-only value.
+pub(crate) fn refuse_empty_explicit(value: Option<&str>, flag: &str) -> Result<()> {
+ if value.is_some_and(|v| v.trim().is_empty()) {
+ bail!(
+ "{flag} was passed empty; omit it to use the scope this directory resolves to, \
+ or name the project explicitly"
+ );
+ }
+ Ok(())
+}
+
/// `AI_MEMORY_IGNORE_MARKER=1` skips rung 2 entirely.
pub(crate) fn resolve_scope(
config: &Config,
diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rs
index 32a75e6c..08920d97 100644
--- a/crates/ai-memory-cli/src/commands/move_project.rs
+++ b/crates/ai-memory-cli/src/commands/move_project.rs
@@ -69,6 +69,10 @@ fn confirm_command(from_workspace: &str, target_flag: &str, args: &MoveProjectAr
/// Returns an error when `--confirm` is absent, the server is unreachable,
/// or the server returns a non-2xx response.
pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
+ super::refuse_empty_explicit(args.from_workspace.as_deref(), "--from-workspace")?;
+ super::refuse_empty_explicit(Some(args.to_workspace.as_str()), "--to-workspace")?;
+ super::refuse_empty_explicit(args.project.as_deref(), "--project")?;
+ super::refuse_empty_explicit(args.project_id.as_deref(), "--project-id")?;
let (from_workspace, project, project_id) = match &args.project_id {
Some(id) => (
super::resolve_workspace(config, args.from_workspace.as_deref())?,
diff --git a/crates/ai-memory-cli/src/commands/purge_project.rs b/crates/ai-memory-cli/src/commands/purge_project.rs
index 98b7a6f4..52776fb3 100644
--- a/crates/ai-memory-cli/src/commands/purge_project.rs
+++ b/crates/ai-memory-cli/src/commands/purge_project.rs
@@ -118,6 +118,29 @@ fn preview_message(outcome: &PreviewOutcome, fallback_label: &str) -> Option<Str
}
}
+/// Warning printed when `--confirm` is used without naming the target.
+///
+/// The derived name is correct only when the operator is standing in the
+/// checkout they mean. `--confirm` typed from the wrong directory deletes
+/// that directory's project, and nothing in the request distinguishes the two
+/// cases, so the command names what it resolved and how to say it explicitly
+/// (#1642). Enforcing the explicit name outright would remove an existing
+/// invocation, so this stays a deprecation until the next major.
+fn derived_target_warning(
+ workspace: &str,
+ target_flag: &str,
+ target_label: &str,
+ args: &PurgeProjectArgs,
+) -> String {
+ format!(
+ "warning: purge-project --confirm without --project or --project-id is deprecated and \
+ will be refused in ai-memory 4.0.\n\
+ This directory resolves to {workspace}/{target_label}\n\n\
+ If that is the project to purge, name it:\n\n {}",
+ confirm_command(workspace, target_flag, args),
+ )
+}
+
/// Run the `purge-project` subcommand.
///
/// Resolves the project name (auto-derived from the git repo root when
@@ -146,6 +169,9 @@ fn preview_message(outcome: &PreviewOutcome, fallback_label: &str) -> Option<Str
/// preview surfaced), the server is unreachable, or the server returns a
/// non-2xx response.
pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
+ super::refuse_empty_explicit(args.workspace.as_deref(), "--workspace")?;
+ super::refuse_empty_explicit(args.project.as_deref(), "--project")?;
+ super::refuse_empty_explicit(args.project_id.as_deref(), "--project-id")?;
// An id target skips name resolution entirely: `resolve_scope` would
// auto-derive a project name from the CWD, which is exactly the ambiguity
// `--project-id` exists to sidestep. The workspace still resolves the
@@ -207,6 +233,14 @@ pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
}
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
+ // The name was derived, not typed: say so before the irreparable step, and
+ // name the exact command that would have been unambiguous (#1642).
+ if args.project.is_none() && args.project_id.is_none() {
+ eprintln!(
+ "{}",
+ derived_target_warning(&workspace, &target_flag, &target_label, &args)
+ );
+ }
let report: serde_json::Value = post_json(
&endpoint,
"/admin/purge-project",
@@ -575,4 +609,111 @@ mod tests {
assert!(matches!(outcome, PreviewOutcome::Unreachable));
assert!(preview_message(&outcome, "default/scratch").is_none());
}
+
+ // -----------------------------------------------------------------
+ // #1642: `--confirm` without a named target.
+ //
+ // Making the name mandatory removes an invocation a script may rely on,
+ // so this ships as a deprecation: the purge still happens, and it now says
+ // what it resolved and how to name it. An explicitly empty flag, which
+ // silently resolved to the same derived target, is refused outright.
+ // -----------------------------------------------------------------
+
+ #[test]
+ fn derived_target_warning_names_the_resolved_project_and_the_command() {
+ let mut a = args();
+ a.project = None;
+ a.confirm = true;
+ let warning = derived_target_warning("default", "--project api", "api", &a);
+ assert!(
+ warning.contains("deprecated and will be refused in ai-memory 4.0"),
+ "the warning must say when it starts refusing: {warning}"
+ );
+ assert!(
+ warning.contains("This directory resolves to default/api"),
+ "the warning must name the target the delete would reach: {warning}"
+ );
+ assert!(
+ warning.contains("ai-memory purge-project --workspace default --project api --confirm"),
+ "the warning must hand over the unambiguous command: {warning}"
+ );
+ }
+
+ /// The empty string is the whole bypass: `resolve_scope` reads it as
+ /// absent, so `--project ""` used to purge the derived target while
+ /// looking like a named run. Nothing may reach the wire.
+ #[tokio::test]
+ async fn an_empty_project_flag_is_refused_before_any_request() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (url, hits) = spawn_counting_server().await;
+ let mut a = args();
+ a.project = Some(String::new());
+ a.project_id = None;
+ a.confirm = true;
+ let error = run(&config_for(&tmp, url), a).await.unwrap_err();
+ assert!(
+ error.to_string().contains("--project was passed empty"),
+ "unexpected error: {error}"
+ );
+ assert_eq!(
+ *hits.lock().await,
+ 0,
+ "the refusal must precede the request"
+ );
+ }
+
+ /// The behaviour this release keeps: a confirmed purge whose target came
+ /// from the checkout still runs, and lands on the derived project.
+ #[tokio::test]
+ async fn a_confirmed_purge_with_a_derived_target_still_purges() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let checkout = tmp.path().join("checkout");
+ std::fs::create_dir(&checkout).unwrap();
+ std::fs::write(checkout.join(".ai-memory.toml"), "project = \"scratch\"\n").unwrap();
+ let (url, hits) = spawn_counting_server().await;
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ server_url: url,
+ runtime_env: crate::config::RuntimeEnv::with_host_cwd_for_tests(
+ checkout.to_str().unwrap(),
+ ),
+ ..Config::default()
+ };
+ let mut a = args();
+ a.project = None;
+ a.workspace = None;
+ a.confirm = true;
+ run(&config, a).await.unwrap();
+ assert_eq!(*hits.lock().await, 1, "the confirmed purge must be sent");
+ }
+
+ /// Serves the purge report and counts the requests that reached it.
+ async fn spawn_counting_server() -> (String, std::sync::Arc<tokio::sync::Mutex<u32>>) {
+ let hits = std::sync::Arc::new(tokio::sync::Mutex::new(0_u32));
+ let counter = std::sync::Arc::clone(&hits);
+ let app = axum::Router::new().route(
+ "/admin/purge-project",
+ axum::routing::post(move || {
+ let counter = std::sync::Arc::clone(&counter);
+ async move {
+ *counter.lock().await += 1;
+ axum::Json(serde_json::json!({
+ "label": "default/scratch",
+ "pages_deleted": 1, "sessions_deleted": 0, "observations_deleted": 0,
+ "handoffs_deleted": 0, "embeddings_deleted": 0,
+ "collateral_observations_deleted": 0, "collateral_handoffs_denulled": 0,
+ "workstreams_deleted": 0, "managed_runs_deleted": 0,
+ "workstream_ids": [], "files_deleted": [], "files_failed": [],
+ "compacted": false, "dry_run": false,
+ }))
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ (format!("http://{addr}"), hits)
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/purge_session.rs b/crates/ai-memory-cli/src/commands/purge_session.rs
index 32992797..3d984906 100644
--- a/crates/ai-memory-cli/src/commands/purge_session.rs
+++ b/crates/ai-memory-cli/src/commands/purge_session.rs
@@ -112,6 +112,8 @@ fn preview_message(outcome: &PreviewOutcome, label: &str) -> Option<String> {
/// UUID, the server is unreachable, or the server returns a non-2xx
/// response (including `404` for a session outside the named scope).
pub async fn run(config: &Config, args: PurgeSessionArgs) -> Result<()> {
+ super::refuse_empty_explicit(args.workspace.as_deref(), "--workspace")?;
+ super::refuse_empty_explicit(args.project.as_deref(), "--project")?;
let (workspace, project) =
super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rs
index c3333c0f..08a3aaec 100644
--- a/crates/ai-memory-cli/src/commands/rename_project.rs
+++ b/crates/ai-memory-cli/src/commands/rename_project.rs
@@ -19,6 +19,9 @@ use crate::http_client::{ServerEndpoint, post_json};
/// Returns an error when the server is unreachable or returns a non-2xx
/// response (e.g. 404 workspace/project not found, 422 name taken or invalid).
pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
+ super::refuse_empty_explicit(args.workspace.as_deref(), "--workspace")?;
+ super::refuse_empty_explicit(args.from.as_deref(), "--from")?;
+ super::refuse_empty_explicit(args.project_id.as_deref(), "--project-id")?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
// Rename happens inside one workspace, so the marker resolves it the same
// way it does for every other command. `--to` stays literal: it names the