Skip to content

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

Rust

fix(cli): honor .ai-memory.toml scope in every client command

milesibastos3d8b9b48f678
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b80785de..814fceba 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Changed
+- Client CLI commands now resolve their `(workspace, project)` from the
+ nearest `.ai-memory.toml` marker, not just the lifecycle hooks. Previously
+ only the hook path read the marker, so a checkout declaring
+ `workspace = "acme"` had its captures land in `acme` while `run`,
+ `bootstrap`, `search`, `write-page` and every other scope-taking command
+ resolved into `default` — the same repository split across two scopes, with
+ `ai-memory run`'s managed workstream stranded on the wrong side. Each field
+ still prefers an explicit flag; when the marker decides one, the command
+ announces the resolved scope on stderr. `AI_MEMORY_IGNORE_MARKER=1` restores
+ the previous resolution for one invocation. `ai-memory serve` is unchanged:
+ it has no caller cwd, and its `--workspace` / `--project` remain the baked
+ fallback for hook events without a usable one.
+
+### Fixed
+- `purge-project` no longer deletes a project out from under a running agent.
+ `workstreams` cascades from `projects` and `managed_runs` cascades from
+ `workstreams`, so purging a scope that still held a live managed run tore
+ out its lease row: the wrapper then failed every heartbeat with
+ `409 managed run lease is not active` and the session's transcript never
+ reached the ledger. The purge now refuses with a `409` naming the offending
+ workstreams unless `--force` is passed, and its report counts the
+ `workstreams` and `managed_runs` the cascade removes plus the
+ `raw/workstreams/<id>/` directories left orphaned on disk — counters that
+ previously showed `0 pages, 0 sessions, …` and made such a scope look safe
+ to delete.
+
## [1.19.0] - 2026-07-25
### Fixed
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index ca69259e..0fd1d8c2 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -174,9 +174,10 @@ pub enum Command {
#[derive(Debug, Args)]
#[command(trailing_var_arg = true)]
pub struct RunArgs {
- /// Workspace containing the managed workstream.
- #[arg(long, default_value = "default")]
- pub workspace: String,
+ /// Workspace containing the managed workstream. Defaults to the nearest
+ /// `.ai-memory.toml` marker's `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project override. Defaults to the current repository project.
#[arg(long)]
pub project: Option<String>,
@@ -469,9 +470,15 @@ pub struct ReorgArgs {
/// Arguments for `purge-project`.
#[derive(Debug, Args)]
pub struct PurgeProjectArgs {
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Purge even when a managed workstream under this project still holds a
+ /// live run lease. Workstreams cascade out of the project row, so without
+ /// this the purge refuses rather than deleting a running session's lease.
+ #[arg(long)]
+ pub force: bool,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
#[arg(long)]
@@ -485,9 +492,10 @@ pub struct PurgeProjectArgs {
/// Arguments for `rename-project`.
#[derive(Debug, Args)]
pub struct RenameProjectArgs {
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Current project name. When omitted, auto-derives from the
/// basename of the current git repo root (or CWD) — handy when
/// running `ai-memory rename-project --to new-name` from a dir
@@ -503,9 +511,11 @@ pub struct RenameProjectArgs {
/// Arguments for `move-project`.
#[derive(Debug, Args)]
pub struct MoveProjectArgs {
- /// Source workspace. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub from_workspace: String,
+ /// Source workspace. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`. Only the source is marker-resolved;
+ /// `--to-workspace` names the destination and stays literal.
+ #[arg(long)]
+ pub from_workspace: Option<String>,
/// Project name to move. When omitted, auto-derived from the basename
/// of the current git repo root (or CWD if no git repo).
#[arg(long)]
@@ -628,8 +638,8 @@ pub struct BootstrapArgs {
pub repo_path: Option<PathBuf>,
/// Workspace name. Defaults to `default` (the single workspace
/// all hook-captured sessions land in today).
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the resolved repo path — same heuristic the hook router uses
/// to bucket per-cwd observations, so the bootstrap pages land
@@ -768,9 +778,10 @@ pub struct AuditContaminationArgs {
pub struct SearchArgs {
/// FTS5 query string (e.g. `"karpathy wiki"` or `quick OR slow`).
pub query: String,
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the current project.
#[arg(long)]
pub project: Option<String>,
@@ -791,9 +802,10 @@ pub struct ReadPageArgs {
/// Exact wiki path (e.g. `notes/foo.md`). Takes precedence over `query`.
#[arg(long)]
pub path: Option<String>,
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the current project.
#[arg(long)]
pub project: Option<String>,
@@ -811,8 +823,8 @@ pub struct DeletePageArgs {
/// Workspace name. Defaults to `default`. Required (no auto-detect) so
/// a cross-workspace project-name collision can never silently route
/// the delete to the wrong slot.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the current project
/// (same heuristic write-page/read-page use).
#[arg(long)]
@@ -866,9 +878,10 @@ pub struct RestorePageArgs {
/// Git checkpoint/revision to restore from.
#[arg(long)]
pub from: String,
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the current project.
#[arg(long)]
pub project: Option<String>,
@@ -991,9 +1004,10 @@ pub struct FinalizeSessionArgs {
/// true SessionEnd hook.
#[arg(long, value_enum, default_value_t = AgentChoice::Codex)]
pub agent: AgentChoice,
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the current project.
#[arg(long)]
pub project: Option<String>,
@@ -1108,8 +1122,8 @@ pub struct EmbedArgs {
#[arg(long)]
pub force: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo). Matches the
/// hook router's per-cwd convention so this command targets the
@@ -1125,8 +1139,8 @@ pub struct ForgetSweepArgs {
#[arg(long)]
pub dry_run: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
#[arg(long)]
@@ -1145,8 +1159,8 @@ pub struct LintArgs {
#[arg(long)]
pub no_llm: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
#[arg(long)]
@@ -1162,9 +1176,10 @@ pub struct CuratorArgs {
/// Stage one pending curator report page for approval.
#[arg(long)]
pub stage: bool,
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
#[arg(long)]
@@ -1177,9 +1192,10 @@ pub struct CuratorArgs {
/// Arguments for `auto-improve-report`.
#[derive(Debug, Args)]
pub struct AutoImproveReportArgs {
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
#[arg(long)]
@@ -1204,9 +1220,10 @@ pub struct AutoImproveArgs {
/// Completed session UUID to review.
#[arg(long)]
pub session_id: String,
- /// Workspace name. Defaults to `default`.
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
+ /// `workspace`, else `default`.
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
#[arg(long)]
@@ -1251,8 +1268,8 @@ pub enum PendingWritesCommand {
#[derive(Debug, Args)]
pub struct PendingWritesListArgs {
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
#[arg(long)]
pub project: Option<String>,
#[arg(long)]
@@ -1266,8 +1283,8 @@ pub struct PendingWritesListArgs {
#[derive(Debug, Args)]
pub struct PendingWriteIdArgs {
pub id: String,
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
#[arg(long)]
pub project: Option<String>,
#[arg(long)]
@@ -1277,8 +1294,8 @@ pub struct PendingWriteIdArgs {
#[derive(Debug, Args)]
pub struct PendingWriteRejectArgs {
pub id: String,
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
#[arg(long)]
pub project: Option<String>,
#[arg(long, default_value = "rejected by reviewer")]
@@ -1515,6 +1532,10 @@ pub struct ServeArgs {
#[arg(long)]
pub no_watcher: bool,
/// Workspace name (auto-created).
+ ///
+ /// Not marker-aware, unlike the client commands: the server has no
+ /// caller cwd to walk up from, and this is the baked fallback for hook
+ /// events that arrive without a usable one.
#[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name within the workspace (auto-created).
@@ -1595,8 +1616,8 @@ pub struct WritePageArgs {
#[arg(long)]
pub pinned: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
- pub workspace: String,
+ #[arg(long)]
+ pub workspace: Option<String>,
/// Project name within the workspace. When omitted, auto-detect from the
/// current project using the same resolver as read-page/search.
#[arg(long)]
diff --git a/crates/ai-memory-cli/src/commands/auto_improve.rs b/crates/ai-memory-cli/src/commands/auto_improve.rs
index ed21af26..00563bf6 100644
--- a/crates/ai-memory-cli/src/commands/auto_improve.rs
+++ b/crates/ai-memory-cli/src/commands/auto_improve.rs
@@ -61,10 +61,11 @@ struct ProposalOutcome {
/// Returns an error if the server is unreachable or rejects the review request.
pub async fn run(config: &Config, args: AutoImproveArgs) -> Result<()> {
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let settings = &config.auto_improve;
let request = AutoImproveRequest {
- workspace: args.workspace,
+ workspace,
project: project.clone(),
session_id: args.session_id,
min_observations: args.min_observations.unwrap_or(settings.min_observations),
diff --git a/crates/ai-memory-cli/src/commands/auto_improve_report.rs b/crates/ai-memory-cli/src/commands/auto_improve_report.rs
index 8f5ec974..e2455560 100644
--- a/crates/ai-memory-cli/src/commands/auto_improve_report.rs
+++ b/crates/ai-memory-cli/src/commands/auto_improve_report.rs
@@ -31,9 +31,10 @@ struct AutoImproveReportStageResponse {
/// Returns an error if the server is unreachable or rejects the read-only report request.
pub async fn run(config: &Config, args: AutoImproveReportArgs) -> Result<()> {
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let request = AutoImproveReportRequest {
- workspace: args.workspace,
+ workspace,
project: project.clone(),
since_days: args.days,
limit: args.limit,
diff --git a/crates/ai-memory-cli/src/commands/bootstrap.rs b/crates/ai-memory-cli/src/commands/bootstrap.rs
index 669363a9..35168f5f 100644
--- a/crates/ai-memory-cli/src/commands/bootstrap.rs
+++ b/crates/ai-memory-cli/src/commands/bootstrap.rs
@@ -73,8 +73,9 @@ pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
}
// ---- project — auto-derive from repo basename if absent -------
- let project = super::resolve_project_name(config, args.project.as_deref())?;
- info!(workspace = %args.workspace, project = %project, repo_path = %repo_path.display(), git = has_git, "bootstrap target");
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
+ info!(workspace = %workspace, project = %project, repo_path = %repo_path.display(), git = has_git, "bootstrap target");
// ---- collect sources locally ----------------------------------
let sources = collect_sources(
@@ -122,7 +123,7 @@ pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
args.max_input_tokens,
args.chunk_input_tokens,
);
- print_human_report(&outcome, &args.workspace, &project);
+ print_human_report(&outcome, &workspace, &project);
let report = serde_json::to_string_pretty(&outcome)?;
println!("\n--- machine-readable ---\n{report}");
return Ok(());
@@ -130,7 +131,7 @@ pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
// ---- POST to server -------------------------------------------
let body = serde_json::json!({
- "workspace": args.workspace,
+ "workspace": workspace,
"project": project,
"sources": sources,
"sources_collected": collected,
@@ -141,7 +142,7 @@ pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
});
let outcome: BootstrapOutcome = post_json(&ep, "/admin/bootstrap", &body).await?;
- print_human_report(&outcome, &args.workspace, &project);
+ print_human_report(&outcome, &workspace, &project);
let report = serde_json::to_string_pretty(&outcome)?;
println!("\n--- machine-readable ---\n{report}");
Ok(())
diff --git a/crates/ai-memory-cli/src/commands/curator.rs b/crates/ai-memory-cli/src/commands/curator.rs
index 634829a6..e7215239 100644
--- a/crates/ai-memory-cli/src/commands/curator.rs
+++ b/crates/ai-memory-cli/src/commands/curator.rs
@@ -35,9 +35,10 @@ pub async fn run(config: &Config, args: CuratorArgs) -> Result<()> {
}
let dry_run = args.dry_run || !args.stage;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let request = CuratorRequest {
- workspace: args.workspace,
+ workspace,
project: project.clone(),
dry_run,
stage: args.stage,
diff --git a/crates/ai-memory-cli/src/commands/delete_page.rs b/crates/ai-memory-cli/src/commands/delete_page.rs
index 4edadc78..a2a34ef6 100644
--- a/crates/ai-memory-cli/src/commands/delete_page.rs
+++ b/crates/ai-memory-cli/src/commands/delete_page.rs
@@ -37,14 +37,15 @@ pub async fn run(config: &Config, args: DeletePageArgs) -> Result<()> {
// Resolve the project the same way write-page/read-page do: explicit
// flag wins, otherwise derive the current project from host cwd / repo
// root. Keeps delete + read-back pairs targeting the same project.
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let resp: DeletePageResponseBody = post_json(
&endpoint,
"/admin/delete-page",
&DeletePageBody {
- workspace: args.workspace.clone(),
+ workspace: workspace.clone(),
project: project.clone(),
path: args.path.clone(),
},
@@ -53,9 +54,6 @@ pub async fn run(config: &Config, args: DeletePageArgs) -> Result<()> {
.context("deleting page via server")?;
let status = if resp.deleted { "✓ deleted" } else { "no-op" };
- println!(
- "{} {} under {}/{}",
- status, resp.path, args.workspace, project
- );
+ println!("{} {} under {}/{}", status, resp.path, workspace, project);
Ok(())
}
diff --git a/crates/ai-memory-cli/src/commands/embed.rs b/crates/ai-memory-cli/src/commands/embed.rs
index 5cfb68a8..d215b726 100644
--- a/crates/ai-memory-cli/src/commands/embed.rs
+++ b/crates/ai-memory-cli/src/commands/embed.rs
@@ -32,16 +32,20 @@ pub async fn run(config: &Config, args: EmbedArgs) -> Result<()> {
// Without an explicit `--project`, `--force` / `--reembed` fans out
// across the whole workspace instead of the CWD-derived project only.
let all_projects = args.force && args.project.is_none();
+ // Resolve the scope even in the fan-out case: `--force` without
+ // `--project` still targets one workspace, and the marker decides which.
+ let (workspace, resolved_project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let project = if all_projects {
String::new()
} else {
- super::resolve_project_name(config, args.project.as_deref())?
+ resolved_project
};
let report: serde_json::Value = post_json(
&endpoint,
"/admin/embed",
&EmbedRequest {
- workspace: args.workspace,
+ workspace,
project,
// The CLI flag was historically named `force`; the server
// field is `reembed` — map them here.
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index 0e285620..2828de7a 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -53,12 +53,12 @@ struct FinalizeSessionReport {
/// sessions or rejects a synthetic `session-end` hook.
pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
let agent = args.agent.kind();
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let sessions =
- fetch_open_sessions(&endpoint, &args.workspace, &project, agent, args.all).await?;
+ let sessions = fetch_open_sessions(&endpoint, &workspace, &project, agent, args.all).await?;
if sessions.is_empty() {
- return print_report(args, project, agent, Vec::new());
+ return print_report(args, workspace, project, agent, Vec::new());
}
let client = reqwest::Client::new();
@@ -70,7 +70,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
&endpoint,
session,
fallback_cwd.as_str(),
- &args.workspace,
+ &workspace,
&project,
agent,
)
@@ -78,7 +78,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
finalized.push(session.session_id.clone());
}
- print_report(args, project, agent, finalized)
+ print_report(args, workspace, project, agent, finalized)
}
/// List open sessions for the scope + agent via the server. An unknown
@@ -119,12 +119,13 @@ async fn fetch_open_sessions(
fn print_report(
args: FinalizeSessionArgs,
+ workspace: String,
project: String,
agent: AgentKind,
finalized: Vec<String>,
) -> Result<()> {
let report = FinalizeSessionReport {
- workspace: args.workspace,
+ workspace,
project,
agent: agent.as_str().to_string(),
finalized,
diff --git a/crates/ai-memory-cli/src/commands/forget_sweep.rs b/crates/ai-memory-cli/src/commands/forget_sweep.rs
index 9ebf6072..affa806e 100644
--- a/crates/ai-memory-cli/src/commands/forget_sweep.rs
+++ b/crates/ai-memory-cli/src/commands/forget_sweep.rs
@@ -25,12 +25,13 @@ struct ForgetSweepRequest {
/// response.
pub async fn run(config: &Config, args: ForgetSweepArgs) -> Result<()> {
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let report: serde_json::Value = post_json(
&endpoint,
"/admin/forget-sweep",
&ForgetSweepRequest {
- workspace: args.workspace,
+ workspace,
project,
dry_run: args.dry_run,
},
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 9ee58d49..5bbce6b6 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -11,6 +11,7 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::commands::path_util::home_dir;
+use crate::marker::{find_marker, is_truthy, parse_toml_flag, parse_toml_key, repo_root_project};
use ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;
use ai_memory_hooks::{CaptureConfig, CapturePolicy, CaptureSource};
@@ -301,94 +302,6 @@ fn marker_query_suffix_impl(
qs
}
-/// Parse a root-level `key = <value>` line, accepting a quoted string
-/// (`key = "true"`) OR a bare token (`key = true` / `key = 1`), so a
-/// `[recall] default_global = true` marker works whether or not the operator
-/// quotes the value. Line-based like [`parse_toml_key`], so section headers
-/// are ignored; strips an optional trailing `# comment`.
-fn parse_toml_flag(file: &Path, key: &str) -> Option<String> {
- let text = std::fs::read_to_string(file).ok()?;
- for line in text.lines() {
- let trimmed = line.trim_start();
- let Some(after_key) = trimmed.strip_prefix(key) else {
- continue;
- };
- let Some(rest) = after_key.trim_start().strip_prefix('=') else {
- continue;
- };
- let val = rest
- .split('#')
- .next()
- .unwrap_or("")
- .trim()
- .trim_matches('"');
- if !val.is_empty() {
- return Some(val.to_string());
- }
- }
- None
-}
-
-fn is_truthy(value: &str) -> bool {
- matches!(
- value.trim().to_ascii_lowercase().as_str(),
- "1" | "true" | "yes" | "on"
- )
-}
-
-fn repo_root_project(cwd: &str) -> Option<String> {
- let root = ai_memory_consolidate::discover_main_repo_root(Path::new(cwd)).ok()?;
- root.file_name()
- .and_then(|s| s.to_str())
- .filter(|s| !s.is_empty())
- .map(str::to_owned)
-}
-
-/// Walk up from `cwd` toward `$HOME` (or the filesystem root) looking
-/// for `.ai-memory.toml`. Stops at `$HOME` to avoid leaking a parent
-/// user's declaration on shared machines (parity with
-/// `ai_memory_find_marker`).
-fn find_marker(cwd: &str) -> Option<PathBuf> {
- let home = home_dir();
- let mut dir = Path::new(cwd);
- loop {
- let candidate = dir.join(".ai-memory.toml");
- if candidate.is_file() {
- return Some(candidate);
- }
- if home.as_deref() == Some(dir) {
- return None;
- }
- match dir.parent() {
- Some(parent) if parent != dir => dir = parent,
- _ => return None,
- }
- }
-}
-
-/// Parse a root-level `key = "value"` line (no nesting, arrays, or
-/// tables), mirroring `ai_memory_parse_toml_key`. Returns the first
-/// match. Avoids pulling in a TOML parser dependency.
-fn parse_toml_key(file: &Path, key: &str) -> Option<String> {
- let text = std::fs::read_to_string(file).ok()?;
- for line in text.lines() {
- let trimmed = line.trim_start();
- let Some(after_key) = trimmed.strip_prefix(key) else {
- continue;
- };
- let Some(rest) = after_key.trim_start().strip_prefix('=') else {
- continue;
- };
- let Some(rest) = rest.trim_start().strip_prefix('"') else {
- continue;
- };
- if let Some(end) = rest.find('"') {
- return Some(rest[..end].to_string());
- }
- }
- None
-}
-
/// Build a reqwest client for the hook's one-shot requests. `no_proxy`
/// skips Windows proxy auto-detection (registry / WinINET lookups), which
/// is pure overhead for a loopback/LAN POST. Built once per invocation and
@@ -716,69 +629,9 @@ mod tests {
assert!(got.is_none(), "non-2xx body must not become context");
}
- /// Happy-path TOML parser: extracts each declared root-level
- /// `key = "value"` pair. Mirrors the shell `ai_memory_parse_toml_key`.
- #[test]
- fn parse_toml_key_extracts_root_level_strings() {
- let tmp = tempfile::TempDir::new().unwrap();
- let marker = tmp.path().join(".ai-memory.toml");
- std::fs::write(
- &marker,
- r#"
-workspace = "acme"
-project = "infra"
-project_strategy = "repo-root"
-"#,
- )
- .unwrap();
- assert_eq!(
- parse_toml_key(&marker, "workspace").as_deref(),
- Some("acme")
- );
- assert_eq!(parse_toml_key(&marker, "project").as_deref(), Some("infra"));
- assert_eq!(
- parse_toml_key(&marker, "project_strategy").as_deref(),
- Some("repo-root")
- );
- assert_eq!(parse_toml_key(&marker, "absent"), None);
- }
-
- /// Shapes the naive parser deliberately doesn't handle (parity with
- /// the shell `_lib.sh` helper) — pin the contract so a future
- /// "robustify" refactor doesn't silently start matching them.
- #[test]
- fn parse_toml_key_skips_unsupported_shapes() {
- let tmp = tempfile::TempDir::new().unwrap();
- let marker = tmp.path().join(".ai-memory.toml");
- std::fs::write(
- &marker,
- r#"
-# Single-quoted values are not honoured.
-workspace = 'acme'
-# Comments after the value are not stripped.
-project = "infra" # this is fine
-"#,
- )
- .unwrap();
- assert_eq!(parse_toml_key(&marker, "workspace"), None);
- // The trailing comment is appended to the value because the parser
- // looks for the first `"` — pin it so the contract is explicit.
- assert_eq!(parse_toml_key(&marker, "project").as_deref(), Some("infra"));
- }
-
- /// `find_marker` walks up from `cwd` until it finds `.ai-memory.toml`
- /// or reaches `$HOME`. Verify the walking — drop the marker two dirs
- /// above the simulated cwd and confirm it's found.
- #[test]
- fn find_marker_walks_up_from_cwd() {
- let tmp = tempfile::TempDir::new().unwrap();
- let marker = tmp.path().join(".ai-memory.toml");
- std::fs::write(&marker, "workspace = \"w\"\n").unwrap();
- let deep = tmp.path().join("a/b/c");
- std::fs::create_dir_all(&deep).unwrap();
- let found = find_marker(deep.to_str().unwrap());
- assert_eq!(found.as_deref(), Some(marker.as_path()));
- }
+ // The marker parser's own tests (`parse_toml_key`, `find_marker`) moved to
+ // `crate::marker` along with the code. What stays here is hook-specific:
+ // the strict `[capture]` section and the query-string suffix.
#[test]
fn capture_section_is_strict_and_marker_read_is_bounded() {
diff --git a/crates/ai-memory-cli/src/commands/lint.rs b/crates/ai-memory-cli/src/commands/lint.rs
index a73c28db..ae3c40af 100644
--- a/crates/ai-memory-cli/src/commands/lint.rs
+++ b/crates/ai-memory-cli/src/commands/lint.rs
@@ -23,12 +23,13 @@ struct LintRequest {
/// response.
pub async fn run(config: &Config, args: LintArgs) -> Result<()> {
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let report: serde_json::Value = post_json(
&endpoint,
"/admin/lint",
&LintRequest {
- workspace: args.workspace,
+ workspace,
project,
dry_run: args.dry_run,
no_llm: args.no_llm,
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 6344f9e4..7f6860ae 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -56,8 +56,105 @@ pub mod user;
pub mod workstream_search;
pub mod write_page;
+/// Resolve the effective `(workspace, project)` pair for a client command.
+///
+/// Each field is resolved independently, in this order:
+///
+/// 1. The explicit flag (`--workspace` / `--project`) when non-empty.
+/// 2. The nearest `.ai-memory.toml` marker: `workspace`, and `project` —
+/// or, when the marker only pins `project_strategy = "repo-root"`, the
+/// main repository root's basename.
+/// 3. Today's fallbacks: [`crate::config::DEFAULT_WORKSPACE`] and
+/// [`resolve_project_name`]'s cwd chain.
+///
+/// Rung 2 is why this function exists. Before it, only the lifecycle hooks
+/// read the marker, so a checkout declaring `workspace = "acme"` still had
+/// every CLI command resolve into `default` — the same repository ended up
+/// split across two scopes, with `run`'s managed workstream on one side and
+/// the hook-captured sessions on the other.
+///
+/// Resolution is announced on stderr whenever the marker decides a field, so
+/// a scope that differs from the flags the user typed is never silent.
+/// `AI_MEMORY_IGNORE_MARKER=1` skips rung 2 entirely.
+pub(crate) fn resolve_scope(
+ config: &Config,
+ explicit_ws: Option<&str>,
+ explicit_proj: Option<&str>,
+) -> Result<(String, String)> {
+ let marker =
+ scope_cwd(config).and_then(|cwd| crate::marker::read_scope(&cwd).map(|scope| (scope, cwd)));
+
+ let mut from_marker = false;
+ let workspace = match explicit_ws.filter(|s| !s.is_empty()) {
+ Some(explicit) => explicit.to_string(),
+ None => match marker
+ .as_ref()
+ .and_then(|(scope, _)| scope.workspace.clone())
+ {
+ Some(declared) => {
+ from_marker = true;
+ declared
+ }
+ None => crate::config::DEFAULT_WORKSPACE.to_string(),
+ },
+ };
+
+ let project = match explicit_proj.filter(|s| !s.is_empty()) {
+ Some(explicit) => explicit.to_string(),
+ None => {
+ // A marker's explicit `project` pins the name for its whole tree;
+ // `project_strategy = "repo-root"` instead asks for the main repo
+ // root, collapsing linked worktrees and subdirectories onto one
+ // project. Rung 3 already resolves by main repo root, so the
+ // strategy only matters when it disagrees with an inherited
+ // `AI_MEMORY_HOST_CWD` basename.
+ let declared = marker.as_ref().and_then(|(scope, cwd)| {
+ scope.project.clone().or_else(|| {
+ scope
+ .is_repo_root()
+ .then(|| crate::marker::repo_root_project(cwd))
+ .flatten()
+ })
+ });
+ match declared {
+ Some(name) => {
+ from_marker = true;
+ name
+ }
+ None => resolve_project_name(config, None)?,
+ }
+ }
+ };
+
+ if from_marker && let Some((scope, _)) = marker.as_ref() {
+ eprintln!(
+ "ai-memory: scope {workspace}/{project} declared by {}",
+ scope.path.display()
+ );
+ }
+ Ok((workspace, project))
+}
+
+/// The directory marker discovery walks up from.
+///
+/// Prefers `AI_MEMORY_HOST_CWD` for the same reason [`resolve_project_name`]
+/// does: inside the docker wrapper the container's own `current_dir()` is the
+/// `/work` bind mount, which would find the wrong marker (or none).
+fn scope_cwd(config: &Config) -> Option<String> {
+ if let Some(host_cwd) = config.runtime_env.host_cwd() {
+ return Some(host_cwd.to_string());
+ }
+ std::env::current_dir()
+ .ok()
+ .map(|cwd| cwd.to_string_lossy().into_owned())
+}
+
/// Resolve the effective project name for a client command.
///
+/// Prefer [`resolve_scope`] for new call sites: this resolves only half the
+/// scope and never consults the marker, so a command that uses it alone still
+/// pairs its project with whatever workspace the caller passed.
+///
/// Precedence:
/// 1. `explicit` (the user's `--project` flag) when non-empty.
/// 2. `AI_MEMORY_HOST_CWD` env var. The docker wrapper sets this
@@ -160,4 +257,104 @@ mod tests {
assert_eq!(resolve_project_name(&config, None).unwrap(), "my-project");
}
+
+ /// Build a config whose scope resolution walks up from `cwd`, and drop a
+ /// marker there when `marker` is given.
+ fn config_at(dir: &std::path::Path, marker: Option<&str>) -> Config {
+ if let Some(body) = marker {
+ std::fs::write(dir.join(".ai-memory.toml"), body).unwrap();
+ }
+ Config {
+ runtime_env: RuntimeEnv::with_host_cwd_for_tests(dir.to_str().unwrap()),
+ ..Config::default()
+ }
+ }
+
+ /// The bug this whole path exists for: a checkout whose marker declares a
+ /// workspace used to resolve into `default` for every CLI command, while
+ /// the lifecycle hooks — the only marker reader at the time — sent that
+ /// same checkout's captures to the declared workspace.
+ #[test]
+ fn resolve_scope_takes_the_workspace_from_the_marker() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = config_at(tmp.path(), Some("workspace = \"acme\"\n"));
+
+ let (workspace, project) = resolve_scope(&config, None, None).unwrap();
+
+ assert_eq!(workspace, "acme");
+ assert_eq!(
+ project,
+ tmp.path().file_name().unwrap().to_str().unwrap(),
+ "an unpinned project still comes from the cwd chain"
+ );
+ }
+
+ /// A marker that pins `project` overrides the cwd-derived name for its
+ /// whole tree.
+ #[test]
+ fn resolve_scope_takes_a_pinned_project_from_the_marker() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = config_at(
+ tmp.path(),
+ Some("workspace = \"acme\"\nproject = \"pinned\"\n"),
+ );
+
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("acme".to_string(), "pinned".to_string())
+ );
+ }
+
+ /// Explicit flags are rung 1: they beat the marker on both halves, and
+ /// each half is resolved independently.
+ #[test]
+ fn resolve_scope_prefers_explicit_flags_over_the_marker() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = config_at(
+ tmp.path(),
+ Some("workspace = \"acme\"\nproject = \"pinned\"\n"),
+ );
+
+ assert_eq!(
+ resolve_scope(&config, Some("flagged"), Some("flagged-proj")).unwrap(),
+ ("flagged".to_string(), "flagged-proj".to_string())
+ );
+ assert_eq!(
+ resolve_scope(&config, Some("flagged"), None).unwrap(),
+ ("flagged".to_string(), "pinned".to_string()),
+ "an explicit workspace must not drag the project along with it"
+ );
+ assert_eq!(
+ resolve_scope(&config, None, Some("flagged-proj")).unwrap(),
+ ("acme".to_string(), "flagged-proj".to_string()),
+ "and vice versa"
+ );
+ }
+
+ /// No marker means the previous behaviour, byte for byte.
+ #[test]
+ fn resolve_scope_without_a_marker_keeps_the_old_fallbacks() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = config_at(tmp.path(), None);
+
+ let (workspace, project) = resolve_scope(&config, None, None).unwrap();
+
+ assert_eq!(workspace, crate::config::DEFAULT_WORKSPACE);
+ assert_eq!(project, tmp.path().file_name().unwrap().to_str().unwrap());
+ }
+
+ /// A marker carrying only `[capture]` rules declares no scope, so it must
+ /// not pull the command out of the default workspace.
+ #[test]
+ fn resolve_scope_ignores_a_marker_without_scope_keys() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = config_at(
+ tmp.path(),
+ Some("[capture]\nignore_paths = [\"secret/**\"]\n"),
+ );
+
+ let (workspace, _) = resolve_scope(&config, None, None).unwrap();
+
+ assert_eq!(workspace, crate::config::DEFAULT_WORKSPACE);
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rs
index c01fcc27..71058cd9 100644
--- a/crates/ai-memory-cli/src/commands/move_project.rs
+++ b/crates/ai-memory-cli/src/commands/move_project.rs
@@ -29,7 +29,11 @@ struct MoveProjectRequest {
/// 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<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (from_workspace, project) = super::resolve_scope(
+ config,
+ args.from_workspace.as_deref(),
+ args.project.as_deref(),
+ )?;
if !args.confirm {
bail!(
@@ -41,10 +45,10 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
Re-run with --confirm to proceed:\n\n \
ai-memory move-project --from-workspace {} --project {} \
--to-workspace {} --confirm",
- args.from_workspace,
+ from_workspace,
project,
args.to_workspace,
- args.from_workspace,
+ from_workspace,
project,
args.to_workspace,
);
@@ -55,7 +59,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
&endpoint,
"/admin/move-project",
&MoveProjectRequest {
- from_workspace: args.from_workspace.clone(),
+ from_workspace: from_workspace.clone(),
project: project.clone(),
to_workspace: args.to_workspace.clone(),
confirm: true,
@@ -75,7 +79,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
println!(
"Moved {}/{} → {}/{}: {pages} pages re-stamped (true move — \
sessions, observations and history preserved).",
- args.from_workspace, project, args.to_workspace, project,
+ from_workspace, project, args.to_workspace, project,
);
} else {
// copy-purge (merge into an existing same-named project).
@@ -89,7 +93,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
println!(
"Moved {}/{} → {}/{}: {pages} pages copied (merged into existing \
project){tail}.",
- args.from_workspace, project, args.to_workspace, project,
+ from_workspace, project, args.to_workspace, project,
);
if skipped_count > 0 {
println!(
diff --git a/crates/ai-memory-cli/src/commands/pending_writes.rs b/crates/ai-memory-cli/src/commands/pending_writes.rs
index dcae2c68..1fb6f28b 100644
--- a/crates/ai-memory-cli/src/commands/pending_writes.rs
+++ b/crates/ai-memory-cli/src/commands/pending_writes.rs
@@ -46,10 +46,11 @@ pub async fn run(config: &Config, args: PendingWritesArgs) -> Result<()> {
}
async fn list(config: &Config, ep: &ServerEndpoint, args: PendingWritesListArgs) -> Result<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let limit = args.limit.to_string();
let mut query = vec![
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
("limit", limit.as_str()),
];
@@ -70,12 +71,13 @@ async fn list(config: &Config, ep: &ServerEndpoint, args: PendingWritesListArgs)
}
async fn show(config: &Config, ep: &ServerEndpoint, args: PendingWriteIdArgs) -> Result<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let detail: ProposalDetail = get_json(
ep,
&format!("/admin/pending-writes/{}", args.id),
&[
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
],
)
@@ -96,12 +98,13 @@ async fn show(config: &Config, ep: &ServerEndpoint, args: PendingWriteIdArgs) ->
}
async fn diff(config: &Config, ep: &ServerEndpoint, args: PendingWriteIdArgs) -> Result<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let resp: DiffResponse = get_json(
ep,
&format!("/admin/pending-writes/{}/diff", args.id),
&[
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
],
)
@@ -115,12 +118,13 @@ async fn diff(config: &Config, ep: &ServerEndpoint, args: PendingWriteIdArgs) ->
}
async fn approve(config: &Config, ep: &ServerEndpoint, args: PendingWriteIdArgs) -> Result<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let resp: serde_json::Value = post_json_with_query(
ep,
&format!("/admin/pending-writes/{}/approve", args.id),
&[
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
],
&serde_json::json!({}),
@@ -135,12 +139,13 @@ async fn approve(config: &Config, ep: &ServerEndpoint, args: PendingWriteIdArgs)
}
async fn reject(config: &Config, ep: &ServerEndpoint, args: PendingWriteRejectArgs) -> Result<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let resp: serde_json::Value = post_json_with_query(
ep,
&format!("/admin/pending-writes/{}/reject", args.id),
&[
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
],
&serde_json::json!({ "reason": args.reason }),
diff --git a/crates/ai-memory-cli/src/commands/purge_project.rs b/crates/ai-memory-cli/src/commands/purge_project.rs
index 14c9422d..6ffca85a 100644
--- a/crates/ai-memory-cli/src/commands/purge_project.rs
+++ b/crates/ai-memory-cli/src/commands/purge_project.rs
@@ -13,6 +13,8 @@ struct PurgeProjectRequest {
workspace: String,
project: String,
confirm: bool,
+ /// Purge even when a managed workstream still holds a live run lease.
+ force: bool,
}
/// Run the `purge-project` subcommand.
@@ -25,14 +27,15 @@ struct PurgeProjectRequest {
/// 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: PurgeProjectArgs) -> Result<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
if !args.confirm {
bail!(
"purge-project is destructive and irreversible.\n\
Re-run with --confirm to proceed:\n\n \
ai-memory purge-project --workspace {} --project {} --confirm",
- args.workspace,
+ workspace,
project,
);
}
@@ -42,25 +45,43 @@ pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
&endpoint,
"/admin/purge-project",
&PurgeProjectRequest {
- workspace: args.workspace.clone(),
+ workspace: workspace.clone(),
project: project.clone(),
confirm: true,
+ force: args.force,
},
)
.await?;
// Human-friendly one-liner followed by the raw JSON for scripting.
- let fallback_label = format!("{}/{}", args.workspace, project);
+ let fallback_label = format!("{}/{}", workspace, project);
let label = report["label"].as_str().unwrap_or(&fallback_label);
let pages = report["pages_deleted"].as_u64().unwrap_or(0);
let sessions = report["sessions_deleted"].as_u64().unwrap_or(0);
let observations = report["observations_deleted"].as_u64().unwrap_or(0);
let handoffs = report["handoffs_deleted"].as_u64().unwrap_or(0);
let embeddings = report["embeddings_deleted"].as_u64().unwrap_or(0);
+ // Workstreams cascade out of the project row, so a scope that looks empty
+ // by every other counter can still be carrying a managed workstream and
+ // its portable event ledger. Always name them.
+ let workstreams = report["workstreams_deleted"].as_u64().unwrap_or(0);
+ let managed_runs = report["managed_runs_deleted"].as_u64().unwrap_or(0);
println!(
"Purged {label}: {pages} pages, {sessions} sessions, \
- {observations} observations, {handoffs} handoffs, {embeddings} embeddings."
+ {observations} observations, {handoffs} handoffs, {embeddings} embeddings, \
+ {workstreams} workstreams, {managed_runs} managed runs."
);
+ if let Some(ids) = report["workstream_ids"].as_array()
+ && !ids.is_empty()
+ {
+ println!(
+ "The following workstream segment directories are now orphaned under \
+ <data_dir>/raw/workstreams/ and can be removed:"
+ );
+ for id in ids.iter().filter_map(serde_json::Value::as_str) {
+ println!(" - {id}");
+ }
+ }
if let Some(failed) = report["files_failed"].as_array()
&& !failed.is_empty()
{
diff --git a/crates/ai-memory-cli/src/commands/read_page.rs b/crates/ai-memory-cli/src/commands/read_page.rs
index 70e84dd3..424449ab 100644
--- a/crates/ai-memory-cli/src/commands/read_page.rs
+++ b/crates/ai-memory-cli/src/commands/read_page.rs
@@ -37,14 +37,15 @@ struct PageContent {
/// or neither `--path` nor a query is supplied.
pub async fn run(config: &Config, args: ReadPageArgs) -> Result<()> {
let ep = ServerEndpoint::from_config_resolving_auth(config).await;
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let page: PageContent = if let Some(ref raw_path) = args.path {
get_json(
&ep,
"/admin/read-page",
&[
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
("path", raw_path.as_str()),
],
@@ -55,7 +56,7 @@ pub async fn run(config: &Config, args: ReadPageArgs) -> Result<()> {
&ep,
"/admin/read-page",
&[
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
("q", query.as_str()),
],
diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rs
index 64f0d61d..6824c74d 100644
--- a/crates/ai-memory-cli/src/commands/rename_project.rs
+++ b/crates/ai-memory-cli/src/commands/rename_project.rs
@@ -17,9 +17,13 @@ use crate::http_client::{ServerEndpoint, post_json};
/// response (e.g. 404 workspace/project not found, 422 name taken or invalid).
pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let from = super::resolve_project_name(config, args.from.as_deref())?;
+ // 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
+ // new project, it does not select a scope.
+ let (workspace, from) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.from.as_deref())?;
let body = serde_json::json!({
- "workspace": args.workspace,
+ "workspace": workspace,
"from": from,
"to": args.to,
});
@@ -27,7 +31,7 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
let pages = summary["pages"].as_u64().unwrap_or(0);
println!(
"Renamed {}/{} → {}/{} ({} pages now under the new name).",
- args.workspace, from, args.workspace, args.to, pages
+ workspace, from, workspace, args.to, pages
);
Ok(())
}
diff --git a/crates/ai-memory-cli/src/commands/restore_page.rs b/crates/ai-memory-cli/src/commands/restore_page.rs
index c9554be6..83b1684a 100644
--- a/crates/ai-memory-cli/src/commands/restore_page.rs
+++ b/crates/ai-memory-cli/src/commands/restore_page.rs
@@ -32,13 +32,14 @@ struct RestorePageResponse {
/// Returns an error if the server is unreachable, the checkpoint/path cannot be
/// restored, or the restored page cannot be reindexed.
pub async fn run(config: &Config, args: RestorePageArgs) -> Result<()> {
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let resp: RestorePageResponse = post_json(
&endpoint,
"/admin/restore-page",
&RestorePageRequest {
- workspace: args.workspace.clone(),
+ workspace: workspace.clone(),
project: project.clone(),
path: args.path.clone(),
rev: args.from.clone(),
@@ -55,7 +56,7 @@ pub async fn run(config: &Config, args: RestorePageArgs) -> Result<()> {
println!(
"restored {} under {}/{} from {} (page_id={})",
resp.path,
- args.workspace,
+ workspace,
project,
resp.restored_from,
&resp.page_id[..resp.page_id.len().min(8)]
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index aefddadb..574da5ef 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -23,7 +23,7 @@ use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
use crate::cli::{RunArgs, RunHarnessChoice};
-use crate::commands::{path_util, resolve_project_name};
+use crate::commands::{path_util, resolve_scope};
use crate::config::Config;
use crate::http_client::{
ServerEndpoint, ServerResponseError, get_json, post_empty, post_json, post_json_no_content,
@@ -87,11 +87,16 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
};
let executable = args.executable.map(PathBuf::into_os_string);
ensure_executable_available(provisional_harness, executable.as_deref())?;
- let project = resolve_project_name(config, args.project.as_deref())?;
+ // Resolve BOTH halves here. `--workspace` used to default to a literal
+ // `default`, so a checkout whose marker declared another workspace put its
+ // managed workstream in one scope while its hook-captured sessions went to
+ // another — the same repository split in two.
+ let (workspace, project) =
+ resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let may_adopt_native_session = args.new_workstream.is_none() && !force_fresh;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let prepare = PrepareManagedRunRequest {
- workspace: args.workspace,
+ workspace,
project,
cwd: repository.cwd.to_string_lossy().into_owned(),
repo_fingerprint: repository.repo_fingerprint,
diff --git a/crates/ai-memory-cli/src/commands/search.rs b/crates/ai-memory-cli/src/commands/search.rs
index fc81ce4d..e3b0b09a 100644
--- a/crates/ai-memory-cli/src/commands/search.rs
+++ b/crates/ai-memory-cli/src/commands/search.rs
@@ -25,14 +25,15 @@ struct Hit {
/// Returns an error if the server is unreachable or returns non-2xx.
pub async fn run(config: &Config, args: SearchArgs) -> Result<()> {
let ep = ServerEndpoint::from_config_resolving_auth(config).await;
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let limit_str = args.limit.to_string();
let hits: Vec<Hit> = get_json(
&ep,
"/admin/search",
&[
("q", args.query.as_str()),
- ("workspace", args.workspace.as_str()),
+ ("workspace", workspace.as_str()),
("project", project.as_str()),
("limit", limit_str.as_str()),
],
diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rs
index c91e225c..cf02a0b1 100644
--- a/crates/ai-memory-cli/src/commands/write_page.rs
+++ b/crates/ai-memory-cli/src/commands/write_page.rs
@@ -53,14 +53,15 @@ pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {
// Resolve the project the same way read-page/search do: explicit flag wins,
// otherwise derive the current project from host cwd / repo root. This keeps
// write + read-back pairs from silently targeting different projects.
- let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let resp: WritePageResponseBody = post_json(
&endpoint,
"/admin/write-page",
&WritePageBody {
- workspace: args.workspace.clone(),
+ workspace: workspace.clone(),
project: project.clone(),
path: args.path.clone(),
body: body_text,
@@ -77,7 +78,7 @@ pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {
let short_id = &resp.page_id[..resp.page_id.len().min(8)];
println!(
"✓ wrote {} (page_id={}) under {}/{}",
- resp.path, short_id, args.workspace, project
+ resp.path, short_id, workspace, project
);
Ok(())
}
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 36792a72..dd835a7a 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -19,6 +19,7 @@ mod commands;
mod config;
mod http_client;
mod logging;
+mod marker;
mod process_guard;
use cli::{Cli, Command};
diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rs
new file mode 100644
index 00000000..981fa082
--- /dev/null
+++ b/crates/ai-memory-cli/src/marker.rs
@@ -0,0 +1,330 @@
+//! `.ai-memory.toml` marker discovery and the scope it declares.
+//!
+//! One reader shared by both entry points that care about a repository's
+//! declared identity:
+//!
+//! - the native hook path (`commands::hook_capture`), which forwards the
+//! marker's fields to the server as query params, and
+//! - the thin-client CLI commands, which resolve `(workspace, project)`
+//! locally before calling `/admin/*` (see `commands::resolve_scope`).
+//!
+//! Before this module existed only the hook path read the marker, so a
+//! repository could declare `workspace = "x"` and still have `run`,
+//! `bootstrap`, `search` and friends silently resolve into `default` —
+//! splitting one checkout across two scopes.
+//!
+//! Parsing is deliberately line-based (`parse_toml_key` / `parse_toml_flag`)
+//! and mirrors `hooks/lib/_lib.sh`, so the native binary and the POSIX shell
+//! hooks agree on what a marker means. `[capture]` is the one section parsed
+//! strictly, with a real TOML parser, and stays in `hook_capture`.
+
+use std::path::{Path, PathBuf};
+
+use crate::commands::path_util::home_dir;
+
+/// Set when the operator wants a marker ignored for one invocation — an
+/// escape hatch for running a command against the fallback scope without
+/// editing (or moving out of) the marker's tree.
+const IGNORE_MARKER_ENV: &str = "AI_MEMORY_IGNORE_MARKER";
+
+/// Install-wide project strategy, matching what `install-hooks
+/// --project-strategy` bakes into the generated hook commands. Consulted
+/// only when the marker itself does not pin one.
+const PROJECT_STRATEGY_ENV: &str = "AI_MEMORY_PROJECT_STRATEGY";
+
+/// The scope fields a marker declares, plus where it was found.
+///
+/// `project` is what the marker pins directly; a marker that only sets
+/// `project_strategy = "repo-root"` leaves it `None` and lets the caller
+/// derive the name (see [`repo_root_project`]).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct MarkerScope {
+ /// Absolute path of the marker file the walk settled on.
+ pub(crate) path: PathBuf,
+ /// `workspace = "…"`.
+ pub(crate) workspace: Option<String>,
+ /// `project = "…"`.
+ pub(crate) project: Option<String>,
+ /// `project_strategy = "…"`, or the install-wide env default.
+ pub(crate) project_strategy: Option<String>,
+}
+
+impl MarkerScope {
+ /// Whether this marker declares anything that changes scope resolution.
+ /// A marker that only carries `[capture]` rules does not.
+ pub(crate) fn declares_scope(&self) -> bool {
+ self.workspace.is_some() || self.project.is_some() || self.is_repo_root()
+ }
+
+ /// Whether the effective strategy asks for repo-root project naming.
+ /// Accepts both spellings, matching the shell hooks.
+ pub(crate) fn is_repo_root(&self) -> bool {
+ matches!(
+ self.project_strategy.as_deref(),
+ Some("repo-root" | "repo_root")
+ )
+ }
+}
+
+/// Read the nearest marker's scope declaration, honouring
+/// `AI_MEMORY_IGNORE_MARKER`.
+///
+/// Returns `None` when no marker is found, when the operator disabled marker
+/// resolution, or when the marker declares nothing scope-related — callers
+/// then keep their existing fallbacks untouched.
+pub(crate) fn read_scope(cwd: &str) -> Option<MarkerScope> {
+ if marker_ignored() {
+ return None;
+ }
+ let path = find_marker(cwd)?;
+ let mut scope = MarkerScope {
+ workspace: parse_toml_key(&path, "workspace"),
+ project: parse_toml_key(&path, "project"),
+ project_strategy: parse_toml_key(&path, "project_strategy"),
+ path,
+ };
+ if scope.project_strategy.is_none() {
+ scope.project_strategy = install_default_strategy();
+ }
+ scope.declares_scope().then_some(scope)
+}
+
+/// Whether `AI_MEMORY_IGNORE_MARKER` is set to a truthy value.
+pub(crate) fn marker_ignored() -> bool {
+ std::env::var(IGNORE_MARKER_ENV).is_ok_and(|value| is_truthy(&value))
+}
+
+/// The install-wide `--project-strategy` default, if one was baked into the
+/// environment. Empty values are treated as unset.
+fn install_default_strategy() -> Option<String> {
+ std::env::var(PROJECT_STRATEGY_ENV)
+ .ok()
+ .filter(|value| !value.trim().is_empty())
+}
+
+/// Derive a project name from the **main** repository root, so linked
+/// worktrees and subdirectories collapse onto one project.
+pub(crate) fn repo_root_project(cwd: &str) -> Option<String> {
+ let root = ai_memory_consolidate::discover_main_repo_root(Path::new(cwd)).ok()?;
+ root.file_name()
+ .and_then(|s| s.to_str())
+ .filter(|s| !s.is_empty())
+ .map(str::to_owned)
+}
+
+/// Walk up from `cwd` toward `$HOME` (or the filesystem root) looking
+/// for `.ai-memory.toml`. Stops at `$HOME` to avoid leaking a parent
+/// user's declaration on shared machines (parity with
+/// `ai_memory_find_marker`).
+pub(crate) fn find_marker(cwd: &str) -> Option<PathBuf> {
+ let home = home_dir();
+ let mut dir = Path::new(cwd);
+ loop {
+ let candidate = dir.join(".ai-memory.toml");
+ if candidate.is_file() {
+ return Some(candidate);
+ }
+ if home.as_deref() == Some(dir) {
+ return None;
+ }
+ match dir.parent() {
+ Some(parent) if parent != dir => dir = parent,
+ _ => return None,
+ }
+ }
+}
+
+/// Parse a root-level `key = "value"` line (no nesting, arrays, or
+/// tables), mirroring `ai_memory_parse_toml_key`. Returns the first
+/// match. Avoids pulling in a TOML parser dependency.
+pub(crate) fn parse_toml_key(file: &Path, key: &str) -> Option<String> {
+ let text = std::fs::read_to_string(file).ok()?;
+ for line in text.lines() {
+ let trimmed = line.trim_start();
+ let Some(after_key) = trimmed.strip_prefix(key) else {
+ continue;
+ };
+ let Some(rest) = after_key.trim_start().strip_prefix('=') else {
+ continue;
+ };
+ let Some(rest) = rest.trim_start().strip_prefix('"') else {
+ continue;
+ };
+ if let Some(end) = rest.find('"') {
+ return Some(rest[..end].to_string());
+ }
+ }
+ None
+}
+
+/// Parse a root-level `key = <value>` line, accepting a quoted string
+/// (`key = "true"`) OR a bare token (`key = true` / `key = 1`), so a
+/// `[recall] default_global = true` marker works whether or not the operator
+/// quotes the value. Line-based like [`parse_toml_key`], so section headers
+/// are ignored; strips an optional trailing `# comment`.
+pub(crate) fn parse_toml_flag(file: &Path, key: &str) -> Option<String> {
+ let text = std::fs::read_to_string(file).ok()?;
+ for line in text.lines() {
+ let trimmed = line.trim_start();
+ let Some(after_key) = trimmed.strip_prefix(key) else {
+ continue;
+ };
+ let Some(rest) = after_key.trim_start().strip_prefix('=') else {
+ continue;
+ };
+ let val = rest
+ .split('#')
+ .next()
+ .unwrap_or("")
+ .trim()
+ .trim_matches('"');
+ if !val.is_empty() {
+ return Some(val.to_string());
+ }
+ }
+ None
+}
+
+/// Shell-parity truthiness for marker flags and the ignore switch.
+pub(crate) fn is_truthy(value: &str) -> bool {
+ matches!(
+ value.trim().to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+ use tempfile::TempDir;
+
+ fn write_marker(dir: &Path, body: &str) -> PathBuf {
+ let path = dir.join(".ai-memory.toml");
+ fs::write(&path, body).unwrap();
+ path
+ }
+
+ #[test]
+ fn find_marker_walks_up_from_cwd() {
+ let tmp = TempDir::new().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ let marker = write_marker(&root, "workspace = \"acme\"\n");
+ let nested = root.join("a").join("b");
+ fs::create_dir_all(&nested).unwrap();
+
+ assert_eq!(
+ find_marker(nested.to_str().unwrap()),
+ Some(marker),
+ "a marker in any ancestor wins"
+ );
+ }
+
+ #[test]
+ fn find_marker_returns_none_without_one() {
+ let tmp = TempDir::new().unwrap();
+ assert_eq!(find_marker(tmp.path().to_str().unwrap()), None);
+ }
+
+ /// Happy-path TOML parser: extracts each declared root-level
+ /// `key = "value"` pair. Mirrors the shell `ai_memory_parse_toml_key`.
+ #[test]
+ fn parse_toml_key_extracts_root_level_strings() {
+ let tmp = TempDir::new().unwrap();
+ let marker = write_marker(
+ tmp.path(),
+ r#"
+workspace = "acme"
+project = "infra"
+project_strategy = "repo-root"
+"#,
+ );
+ assert_eq!(
+ parse_toml_key(&marker, "workspace").as_deref(),
+ Some("acme")
+ );
+ assert_eq!(parse_toml_key(&marker, "project").as_deref(), Some("infra"));
+ assert_eq!(
+ parse_toml_key(&marker, "project_strategy").as_deref(),
+ Some("repo-root")
+ );
+ assert_eq!(parse_toml_key(&marker, "absent"), None);
+ }
+
+ /// Shapes the naive parser deliberately doesn't handle (parity with
+ /// the shell `_lib.sh` helper) — pin the contract so a future
+ /// "robustify" refactor doesn't silently start matching them.
+ #[test]
+ fn parse_toml_key_skips_unsupported_shapes() {
+ let tmp = TempDir::new().unwrap();
+ let marker = write_marker(
+ tmp.path(),
+ r#"
+# Single-quoted values are not honoured.
+workspace = 'acme'
+# Comments after the value are not stripped.
+project = "infra" # this is fine
+"#,
+ );
+ assert_eq!(parse_toml_key(&marker, "workspace"), None);
+ // The trailing comment is appended to the value because the parser
+ // looks for the first `"` — pin it so the contract is explicit.
+ assert_eq!(parse_toml_key(&marker, "project").as_deref(), Some("infra"));
+ }
+
+ #[test]
+ fn parse_toml_flag_accepts_bare_and_quoted_tokens() {
+ let tmp = TempDir::new().unwrap();
+ let marker = write_marker(
+ tmp.path(),
+ "[recall]\ndefault_global = true\nmax_chars = 4000 # budget\n",
+ );
+
+ assert_eq!(
+ parse_toml_flag(&marker, "default_global").as_deref(),
+ Some("true")
+ );
+ assert_eq!(
+ parse_toml_flag(&marker, "max_chars").as_deref(),
+ Some("4000"),
+ "trailing comments are stripped"
+ );
+ }
+
+ #[test]
+ fn is_truthy_matches_shell_parity_tokens() {
+ for value in ["1", "true", "TRUE", " yes ", "on"] {
+ assert!(is_truthy(value), "{value} should be truthy");
+ }
+ for value in ["0", "false", "", "maybe"] {
+ assert!(!is_truthy(value), "{value} should not be truthy");
+ }
+ }
+
+ #[test]
+ fn scope_declares_repo_root_for_both_spellings() {
+ let base = MarkerScope {
+ path: PathBuf::from("/tmp/.ai-memory.toml"),
+ workspace: None,
+ project: None,
+ project_strategy: None,
+ };
+
+ for spelling in ["repo-root", "repo_root"] {
+ let scope = MarkerScope {
+ project_strategy: Some(spelling.to_string()),
+ ..base.clone()
+ };
+ assert!(scope.is_repo_root(), "{spelling} should select repo-root");
+ assert!(
+ scope.declares_scope(),
+ "{spelling} alone still changes resolution"
+ );
+ }
+
+ assert!(
+ !base.declares_scope(),
+ "a marker with only [capture] rules must not change scope"
+ );
+ }
+}
diff --git a/crates/ai-memory-cli/tests/marker_scope.rs b/crates/ai-memory-cli/tests/marker_scope.rs
new file mode 100644
index 00000000..fd5b9474
--- /dev/null
+++ b/crates/ai-memory-cli/tests/marker_scope.rs
@@ -0,0 +1,109 @@
+//! Subprocess tests for `.ai-memory.toml` scope resolution in client commands.
+//!
+//! The unit tests in `commands::tests` cover the precedence table directly.
+//! What needs a real process is the env-var wiring — `AI_MEMORY_IGNORE_MARKER`
+//! is read from the process environment, and `$HOME` bounds the marker walk,
+//! so both have to be set before the binary starts.
+//!
+//! Each test runs a command that resolves its scope and then fails to reach a
+//! server. That is deliberate: resolution happens first, so the stderr notice
+//! is emitted regardless, and the test never needs a live engine.
+
+use std::path::Path;
+use std::process::Command;
+use tempfile::TempDir;
+
+fn bin() -> &'static str {
+ env!("CARGO_BIN_EXE_ai-memory")
+}
+
+/// Run `search` from `cwd` with a deliberately dead server and return stderr.
+///
+/// `$HOME` is pinned to `cwd` so the marker walk cannot reach the developer's
+/// real `~/.ai-memory.toml`, and the data dir is redirected for the same
+/// reason — neither test should read or write the machine's actual install.
+fn search_stderr(cwd: &Path, data_dir: &Path, extra_env: &[(&str, &str)], args: &[&str]) -> String {
+ let mut cmd = Command::new(bin());
+ cmd.arg("search")
+ .arg("anything")
+ .args(args)
+ .current_dir(cwd)
+ .env("HOME", cwd)
+ .env("AI_MEMORY_DATA_DIR", data_dir)
+ // Port 1 is reserved and never listening: the command resolves its
+ // scope, prints the notice, then fails on connect.
+ .env("AI_MEMORY_SERVER_URL", "http://127.0.0.1:1")
+ .env_remove("AI_MEMORY_HOST_CWD")
+ .env_remove("AI_MEMORY_IGNORE_MARKER")
+ .env_remove("AI_MEMORY_PROJECT_STRATEGY");
+ for (key, value) in extra_env {
+ cmd.env(key, value);
+ }
+ let output = cmd.output().expect("running ai-memory search");
+ String::from_utf8_lossy(&output.stderr).into_owned()
+}
+
+fn marker_tree(body: &str) -> (TempDir, TempDir) {
+ let cwd = TempDir::new().expect("tempdir for cwd");
+ let data = TempDir::new().expect("tempdir for data dir");
+ std::fs::write(cwd.path().join(".ai-memory.toml"), body).expect("writing marker");
+ (cwd, data)
+}
+
+#[test]
+fn marker_workspace_is_used_and_announced() {
+ let (cwd, data) = marker_tree("workspace = \"acme\"\n");
+
+ let stderr = search_stderr(cwd.path(), data.path(), &[], &[]);
+
+ assert!(
+ stderr.contains("scope acme/"),
+ "the resolved scope must come from the marker and be announced: {stderr}"
+ );
+ assert!(
+ stderr.contains(".ai-memory.toml"),
+ "the notice names the marker that decided it: {stderr}"
+ );
+}
+
+#[test]
+fn ignore_marker_env_restores_the_default_workspace() {
+ let (cwd, data) = marker_tree("workspace = \"acme\"\n");
+
+ let stderr = search_stderr(
+ cwd.path(),
+ data.path(),
+ &[("AI_MEMORY_IGNORE_MARKER", "1")],
+ &[],
+ );
+
+ assert!(
+ !stderr.contains("scope acme/"),
+ "AI_MEMORY_IGNORE_MARKER=1 must skip the marker entirely: {stderr}"
+ );
+}
+
+#[test]
+fn explicit_workspace_flag_beats_the_marker() {
+ let (cwd, data) = marker_tree("workspace = \"acme\"\n");
+
+ let stderr = search_stderr(cwd.path(), data.path(), &[], &["--workspace", "default"]);
+
+ assert!(
+ !stderr.contains("scope acme/"),
+ "an explicit --workspace wins, so no marker notice: {stderr}"
+ );
+}
+
+#[test]
+fn a_tree_without_a_marker_is_unchanged() {
+ let cwd = TempDir::new().expect("tempdir for cwd");
+ let data = TempDir::new().expect("tempdir for data dir");
+
+ let stderr = search_stderr(cwd.path(), data.path(), &[], &[]);
+
+ assert!(
+ !stderr.contains("declared by"),
+ "no marker means no scope notice and no behaviour change: {stderr}"
+ );
+}
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index d1760acc..4b9051be 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -4768,7 +4768,7 @@ mod tests {
// points at it (exactly the purge-on-live-server scenario).
state
.writer
- .purge_project(ws, proj, "default/heal-project", None)
+ .purge_project(ws, proj, "default/heal-project", None, false)
.await
.unwrap();
assert!(
@@ -4951,7 +4951,7 @@ mod tests {
state
.writer
- .purge_project(ws, proj, "default/repo-root-project", None)
+ .purge_project(ws, proj, "default/repo-root-project", None, false)
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index bdbc8616..e9d7361c 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -2861,6 +2861,11 @@ struct PurgeProjectRequest {
/// Mandatory confirmation flag. Without `confirm: true` the server
/// returns 400 — purging is destructive and irreversible.
confirm: bool,
+ /// Purge even when a managed workstream under this project still holds a
+ /// live run lease. Off by default: the cascade would delete that lease row
+ /// out from under a running agent, which then cannot save its history.
+ #[serde(default)]
+ force: bool,
}
/// Wire-format summary returned by `POST /admin/purge-project`.
@@ -2878,6 +2883,13 @@ pub struct PurgeProjectReport {
pub handoffs_deleted: u64,
/// Number of `page_embeddings` rows deleted.
pub embeddings_deleted: u64,
+ /// Number of managed `workstreams` rows deleted via cascade.
+ pub workstreams_deleted: u64,
+ /// Number of `managed_runs` rows deleted via cascade.
+ pub managed_runs_deleted: u64,
+ /// Ids of the deleted workstreams, whose `raw/workstreams/<id>/` segment
+ /// directories the operator may still want to remove.
+ pub workstream_ids: Vec<String>,
/// Paths removed from disk (the project's UUID-namespaced directory).
pub files_deleted: Vec<String>,
/// Paths that could not be removed from disk (non-fatal; DB rows are gone).
@@ -2948,10 +2960,19 @@ async fn handle_purge_project(
let summary = match state
.writer
- .purge_project(ws_id, proj_id, &label, author_id)
+ .purge_project(ws_id, proj_id, &label, author_id, req.force)
.await
{
Ok(s) => s,
+ // A live managed run is a conflict, not a server fault: the operator
+ // can finish the session or retry with `force`. Same status the
+ // heartbeat itself returns when a lease is gone, so the two agree.
+ Err(e @ StoreError::ManagedRunActive { .. }) => {
+ return (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ );
+ }
Err(e) => return internal_err(e.to_string()),
};
@@ -3000,6 +3021,9 @@ async fn handle_purge_project(
observations_deleted: summary.observations_deleted,
handoffs_deleted: summary.handoffs_deleted,
embeddings_deleted: summary.embeddings_deleted,
+ workstreams_deleted: summary.workstreams_deleted,
+ managed_runs_deleted: summary.managed_runs_deleted,
+ workstream_ids: summary.workstream_ids,
files_deleted,
files_failed,
pre_checkpoint,
@@ -4162,7 +4186,7 @@ async fn copy_purge_merge(
// `purge_project` here, so the audit author is left NULL.
let summary = match state
.writer
- .purge_project(src_ws, src_proj, &label, None)
+ .purge_project(src_ws, src_proj, &label, None, false)
.await
{
Ok(s) => s,
diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rs
index 9b643d07..587b0eee 100644
--- a/crates/ai-memory-store/src/error.rs
+++ b/crates/ai-memory-store/src/error.rs
@@ -82,6 +82,26 @@ pub enum StoreError {
#[error("workspace still has {0} project(s); pass force to delete anyway")]
WorkspaceNotEmpty(u64),
+ /// A project purge was rejected because one of its managed workstreams
+ /// still holds a live run lease. `workstreams` is `ON DELETE CASCADE` from
+ /// `projects`, and `managed_runs` cascades from `workstreams`, so the
+ /// purge would delete the lease row out from under a running agent — whose
+ /// heartbeat then fails with `409 managed run lease is not active` for the
+ /// rest of the session and whose transcript never reaches the ledger.
+ /// Carries the offending workstream names so the operator can find the
+ /// session before retrying with force.
+ #[error(
+ "project has {count} active managed run(s) in workstream(s) {workstreams}; \
+ finish or cancel them first, or pass force to purge anyway (the running \
+ agent will stop being able to save its history)"
+ )]
+ ManagedRunActive {
+ /// How many `managed_runs` rows are still `state = 'active'`.
+ count: u64,
+ /// Comma-separated workstream names holding those runs.
+ workstreams: String,
+ },
+
/// A workspace rename was rejected because the destination name is already
/// in use by another workspace (`workspaces.name` is UNIQUE).
#[error("workspace name '{0}' is already taken")]
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 6c08c160..2f863b9f 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -55,6 +55,18 @@ pub struct PurgeSummary {
pub handoffs_deleted: u64,
/// Number of `page_embeddings` rows deleted (cascades through pages).
pub embeddings_deleted: u64,
+ /// Number of `workstreams` rows deleted. These cascade from `projects`,
+ /// so a project that looks empty by page/session/observation count can
+ /// still take a managed workstream — and its portable event ledger — down
+ /// with it. Counted so the caller can say so out loud.
+ pub workstreams_deleted: u64,
+ /// Number of `managed_runs` rows deleted (cascades through workstreams).
+ pub managed_runs_deleted: u64,
+ /// Ids of the deleted workstreams. Their `raw/workstreams/<id>/` segment
+ /// directories survive the SQL delete, so the caller removes them the same
+ /// way it removes [`Self::page_paths`]; otherwise they stay orphaned on
+ /// disk with no row pointing at them.
+ pub workstream_ids: Vec<String>,
}
use jiff::Timestamp;
use rusqlite::{Connection, OptionalExtension, Transaction, params};
@@ -1506,6 +1518,7 @@ pub fn purge_project(
project_id: &ProjectId,
workspace_project_label: &str,
author_id: Option<ai_memory_core::UserId>,
+ force: bool,
) -> StoreResult<PurgeSummary> {
let tx = conn.transaction()?;
@@ -1517,6 +1530,35 @@ pub fn purge_project(
};
let pid = project_id.as_bytes();
+
+ // Managed workstreams cascade out of `projects`, and `managed_runs`
+ // cascades out of them. A live run's lease row would go with them, which
+ // leaves the running agent heartbeating a run id that no longer exists —
+ // `409 managed run lease is not active`, every 30s, with its transcript
+ // unable to reach any ledger. Refuse unless the operator insists.
+ let active_runs: Vec<(String, String)> = {
+ let mut stmt = tx.prepare(
+ "SELECT w.name, mr.agent_kind FROM managed_runs mr \
+ JOIN workstreams w ON w.id = mr.workstream_id \
+ WHERE w.project_id = ?1 AND mr.state = 'active'",
+ )?;
+ stmt.query_map(rusqlite::params![&pid[..]], |row| {
+ Ok((row.get(0)?, row.get(1)?))
+ })?
+ .collect::<rusqlite::Result<Vec<_>>>()?
+ };
+ if !active_runs.is_empty() && !force {
+ let mut names: Vec<String> = active_runs
+ .iter()
+ .map(|(workstream, agent)| format!("'{workstream}' ({agent})"))
+ .collect();
+ names.sort();
+ names.dedup();
+ return Err(StoreError::ManagedRunActive {
+ count: active_runs.len() as u64,
+ workstreams: names.join(", "),
+ });
+ }
let pages_deleted = count("SELECT COUNT(*) FROM pages WHERE project_id = ?1", &pid[..])?;
let sessions_deleted = count(
"SELECT COUNT(*) FROM sessions WHERE project_id = ?1",
@@ -1537,6 +1579,16 @@ pub fn purge_project(
&pid[..],
)?;
+ let workstreams_deleted = count(
+ "SELECT COUNT(*) FROM workstreams WHERE project_id = ?1",
+ &pid[..],
+ )?;
+ let managed_runs_deleted = count(
+ "SELECT COUNT(*) FROM managed_runs WHERE workstream_id IN \
+ (SELECT id FROM workstreams WHERE project_id = ?1)",
+ &pid[..],
+ )?;
+
// Collect all distinct on-disk paths for the caller to clean up.
// We use DISTINCT because multiple versions of the same logical page
// share a path; the file only exists once. The statement must be
@@ -1548,6 +1600,21 @@ pub fn purge_project(
.collect::<rusqlite::Result<Vec<String>>>()?
};
+ // Same idea for the workstream segment directories: the rows go with the
+ // cascade but `raw/workstreams/<id>/` does not.
+ let workstream_ids: Vec<String> = {
+ let mut stmt = tx.prepare("SELECT id FROM workstreams WHERE project_id = ?1")?;
+ stmt.query_map(rusqlite::params![&pid[..]], |row| row.get::<_, Vec<u8>>(0))?
+ .collect::<rusqlite::Result<Vec<_>>>()?
+ .into_iter()
+ .filter_map(|raw| {
+ <[u8; 16]>::try_from(raw.as_slice())
+ .ok()
+ .map(|bytes| uuid::Uuid::from_bytes(bytes).to_string())
+ })
+ .collect()
+ };
+
// Cascade handles pages / sessions / observations / handoffs /
// page_embeddings. The workspace row is intentionally left intact —
// other projects may still live there.
@@ -1578,6 +1645,9 @@ pub fn purge_project(
observations_deleted,
handoffs_deleted,
embeddings_deleted,
+ workstreams_deleted,
+ managed_runs_deleted,
+ workstream_ids,
})
}
@@ -4003,7 +4073,7 @@ mod tests {
let (_tmp, mut conn, ws, proj) = fresh_db();
// Simulate the post-purge state: project row gone.
// `purge_project` drives the cascading deletes we want here.
- let _ = purge_project(&mut conn, &ws, &proj, "default/scratch", None)
+ let _ = purge_project(&mut conn, &ws, &proj, "default/scratch", None, false)
.expect("purge of fresh project should succeed");
// Now try to rename the project that no longer exists. The
// pre-fix code returned `Ok(())` because `UPDATE` affected
@@ -4058,8 +4128,15 @@ mod tests {
let (_tmp, mut conn, ws, proj) = fresh_db();
let author = seed_user(&conn, "alice");
- purge_project(&mut conn, &ws, &proj, "default/scratch", Some(author))
- .expect("purge should succeed");
+ purge_project(
+ &mut conn,
+ &ws,
+ &proj,
+ "default/scratch",
+ Some(author),
+ false,
+ )
+ .expect("purge should succeed");
let (count, op_author) = audit_row_for(&conn, "purge_project");
assert_eq!(count, 1, "exactly one purge_project audit row");
@@ -4070,6 +4147,86 @@ mod tests {
);
}
+ /// Open one managed run on `proj` so the purge guard has something to
+ /// refuse. Mirrors what `ai-memory run` does on launch.
+ fn open_managed_run(
+ conn: &mut Connection,
+ ws: &ai_memory_core::WorkspaceId,
+ proj: &ai_memory_core::ProjectId,
+ ) -> crate::workstream::PreparedWorkstreamRun {
+ crate::workstream::prepare_run(
+ conn,
+ &crate::workstream::PrepareWorkstreamRun {
+ workspace_id: *ws,
+ project_id: *proj,
+ repo_fingerprint: "repo-fp".to_string(),
+ worktree_fingerprint: "worktree-fp".to_string(),
+ cwd: "/tmp/checkout".to_string(),
+ agent: ai_memory_core::AgentKind::ClaudeCode,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: crate::workstream::WorkstreamSelection::Current,
+ lease_owner: "test".to_string(),
+ },
+ )
+ .expect("opening a managed run should succeed")
+ }
+
+ /// `workstreams` cascades out of `projects` and `managed_runs` cascades
+ /// out of `workstreams`, so purging a project silently tore the lease row
+ /// out from under a live agent: its heartbeat then failed with
+ /// `409 managed run lease is not active` every 30s and its transcript
+ /// never reached the ledger. The purge must refuse instead.
+ #[test]
+ fn purge_project_refuses_while_a_managed_run_is_active() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ open_managed_run(&mut conn, &ws, &proj);
+
+ let err = purge_project(&mut conn, &ws, &proj, "default/scratch", None, false)
+ .expect_err("an active managed run must block the purge");
+
+ match err {
+ StoreError::ManagedRunActive { count, workstreams } => {
+ assert_eq!(count, 1, "one active run");
+ assert!(
+ workstreams.contains("default"),
+ "the error names the workstream so the operator can find the session: {workstreams}"
+ );
+ }
+ other => panic!("expected ManagedRunActive, got {other:?}"),
+ }
+
+ let survived: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM projects WHERE id = ?1",
+ rusqlite::params![&proj.as_bytes()[..]],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(survived, 1, "a refused purge must not delete anything");
+ }
+
+ /// `force` is the deliberate override, and the summary must account for
+ /// what the cascade took with it — the counters the pre-fix report showed
+ /// (`0 pages, 0 sessions, …`) made a scope carrying a live workstream look
+ /// safe to delete.
+ #[test]
+ fn forced_purge_reports_the_workstreams_it_cascaded() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let prepared = open_managed_run(&mut conn, &ws, &proj);
+
+ let summary = purge_project(&mut conn, &ws, &proj, "default/scratch", None, true)
+ .expect("force purges regardless of the live lease");
+
+ assert_eq!(summary.workstreams_deleted, 1);
+ assert_eq!(summary.managed_runs_deleted, 1);
+ assert_eq!(
+ summary.workstream_ids,
+ vec![prepared.workstream_id.to_string()],
+ "the orphaned raw/workstreams/<id>/ dir is reported for cleanup"
+ );
+ }
+
/// A `rename_project` writes an attributed audit row, committed
/// atomically with the rename.
#[test]
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 0a31bc59..fb41f415 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -183,6 +183,8 @@ pub(crate) enum WriteCmd {
/// Authenticated operator recorded in the `audit_log` row (NULL when
/// single-user / unauthenticated).
author_id: Option<ai_memory_core::UserId>,
+ /// Purge even when a managed workstream still holds a live run lease.
+ force: bool,
reply: oneshot::Sender<StoreResult<PurgeSummary>>,
},
/// Delete a workspace row (its `workspace_id` FKs cascade projects/pages/
@@ -751,6 +753,7 @@ impl WriterHandle {
project_id: ProjectId,
label: impl Into<String>,
author_id: Option<ai_memory_core::UserId>,
+ force: bool,
) -> StoreResult<PurgeSummary> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::PurgeProject {
@@ -758,6 +761,7 @@ impl WriterHandle {
project_id,
label: label.into(),
author_id,
+ force,
reply: tx,
})
.await?;
@@ -1461,10 +1465,17 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
project_id,
label,
author_id,
+ force,
reply,
} => {
- let result =
- ops::purge_project(&mut conn, &workspace_id, &project_id, &label, author_id);
+ let result = ops::purge_project(
+ &mut conn,
+ &workspace_id,
+ &project_id,
+ &label,
+ author_id,
+ force,
+ );
send_or_warn(reply, result, "purge_project");
}
WriteCmd::DeleteWorkspace {
diff --git a/docs/install.md b/docs/install.md
index 841cd743..b7961cdc 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1352,8 +1352,10 @@ remote or uses a custom host/port.
```
--repo-path <PATH> (default: git rev-parse --show-toplevel)
---workspace <NAME> (default: "default")
---project <NAME> (default: derived from cwd — main repo root's
+--workspace <NAME> (default: the nearest `.ai-memory.toml` marker's
+ `workspace`, else "default")
+--project <NAME> (default: the marker's `project` when pinned,
+ else derived from cwd — main repo root's
basename via `git rev-parse --show-toplevel`,
or basename(cwd) when no repo is found.
"scratch" only as a defensive fallback for
diff --git a/docs/marker-file.md b/docs/marker-file.md
index f7540c4c..7fe12c38 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -325,6 +325,46 @@ runtime override (which was deliberately rejected in #16). The flag accepts
Precedence is unchanged: a marker's explicit `project_strategy` or `project`
still wins over the install default.
+## Who reads the marker
+
+Both entry points, as of v1.20:
+
+- **Lifecycle hooks** forward the marker's fields to the server on every
+ event, so session captures land in the declared scope.
+- **Client CLI commands** resolve `(workspace, project)` locally before
+ calling the server — `run`, `bootstrap`, `search`, `read-page`,
+ `write-page`, `lint`, `curator`, `embed`, `pending-writes`,
+ `forget-sweep`, `auto-improve`, `purge-project`, `rename-project`,
+ `move-project` (source side), and friends.
+
+Before v1.20 only the hooks read it. A checkout declaring
+`workspace = "acme"` therefore had its captures land in `acme` while every
+CLI command resolved into `default` — the same repository split across two
+scopes, with `ai-memory run`'s managed workstream on the wrong side of the
+split.
+
+Each field is resolved independently:
+
+1. The explicit flag (`--workspace` / `--project`).
+2. The nearest marker: `workspace`, and `project` — or the main repo root's
+ basename when only `project_strategy = "repo-root"` is set.
+3. The previous fallbacks: `default`, and the cwd-derived project name.
+
+When rung 2 decides a field, the command prints one line to stderr naming
+the marker and the resolved scope:
+
+```console
+$ ai-memory search "scope resolver"
+ai-memory: scope acme/api declared by /Users/dev/projects/acme/.ai-memory.toml
+```
+
+`AI_MEMORY_IGNORE_MARKER=1` skips rung 2 for one invocation, restoring the
+pre-v1.20 resolution without editing or leaving the marker's tree.
+
+`ai-memory serve` is deliberately excluded: the server has no caller cwd to
+walk up from, and its `--workspace` / `--project` are the baked fallback for
+hook events that arrive without a usable one.
+
## What the marker file does NOT do
- ❌ No glob patterns. Walk-up by literal ancestry only.
@@ -338,6 +378,8 @@ still wins over the install default.
*default* can still be baked into an install without a marker via
`install-hooks --project-strategy repo-root`, but that is install-time
config, not a runtime override the user sets in their shell.)
+- ❌ No reach outside `$HOME`. The walk stops there, so a checkout that
+ lives outside the account's home directory needs its own marker.
## Troubleshooting