Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): correct scope-resolution and purge-guard review findings
milesibastos3fe60ec7f7b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 814fceba..aaf0192c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,8 +16,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0resolved into `default` — the same repository split across two scopes, with`ai-memory run`'s managed workstream stranded on the wrong side. Each fieldstill 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:+ announces the resolved scope on stderr, naming which half the marker+ decided. `AI_MEMORY_IGNORE_MARKER=1` restores the previous resolution for+ one invocation (client commands only — the hooks keep reading the marker).+ `embed --force` without `--project` still fans out across the workspace and+ no longer needs a derivable project name. `ai-memory serve` is unchanged:it has no caller cwd, and its `--workspace` / `--project` remain the bakedfallback for hook events without a usable one.@@ -32,7 +35,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`workstreams` and `managed_runs` the cascade removes plus the`raw/workstreams/<id>/` directories left orphaned on disk — counters thatpreviously showed `0 pages, 0 sessions, …` and made such a scope look safe- to delete.+ to delete. Liveness is the lease, not the row state: a crashed wrapper+ leaves `state = 'active'` behind until the next `ai-memory run` sweeps it,+ so only a lease that has not yet expired blocks the purge. `move-project`'s+ copy-purge merge surfaces the same conflict as a `409` naming how many+ pages were already copied, instead of a `500`.## [1.19.0] - 2026-07-25diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0fd1d8c2..b1671d6a 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -636,8 +636,9 @@ pub struct BootstrapArgs {/// any subdir of the project works).#[arg(long)]pub repo_path: Option<PathBuf>,- /// Workspace name. Defaults to `default` (the single workspace- /// all hook-captured sessions land in today).+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's+ /// `workspace`, else `default` — the same resolution the lifecycle hooks+ /// use, so bootstrap pages land where the session captures do.#[arg(long)]pub workspace: Option<String>,/// Project name. When omitted, auto-derived from the basename of@@ -820,9 +821,10 @@ pub struct DeletePageArgs {/// Exact wiki path to delete (e.g. `notes/foo.md`).#[arg(long)]pub path: String,- /// 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.+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's+ /// `workspace`, else `default`. Resolution is announced on stderr so a+ /// cross-workspace project-name collision can never silently route the+ /// delete to the wrong slot.#[arg(long)]pub workspace: Option<String>,/// Project name. When omitted, auto-derived from the current projectdiff --git a/crates/ai-memory-cli/src/commands/embed.rs b/crates/ai-memory-cli/src/commands/embed.rsindex d215b726..20765d79 100644--- a/crates/ai-memory-cli/src/commands/embed.rs+++ b/crates/ai-memory-cli/src/commands/embed.rs@@ -32,14 +32,18 @@ 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()+ // The fan-out still targets one workspace, and the marker decides which —+ // but only the workspace half is resolved there. Resolving the pair would+ // make `--force` fail on a cwd whose project name cannot be derived (the+ // stale-docker-wrapper bail, or a non-repo dir) for a name it then throws+ // away, and would announce a project the request never carries.+ let (workspace, project) = if all_projects {+ (+ super::resolve_workspace(config, args.workspace.as_deref()),+ String::new(),+ )} else {- resolved_project+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?};let report: serde_json::Value = post_json(&endpoint,diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 7f6860ae..6ff19e9d 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -81,25 +81,31 @@ pub(crate) fn resolve_scope(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 explicit_ws = explicit_ws.filter(|s| !s.is_empty());+ let explicit_proj = explicit_proj.filter(|s| !s.is_empty());+ // Both halves pinned on the command line: the marker cannot change the+ // answer, so skip the walk and the file reads entirely.+ if let (Some(workspace), Some(project)) = (explicit_ws, explicit_proj) {+ return Ok((workspace.to_string(), project.to_string()));+ }+ let marker = marker_scope(config);- let mut from_marker = false;- let workspace = match explicit_ws.filter(|s| !s.is_empty()) {+ let mut decided: Vec<&str> = Vec::with_capacity(2);+ let workspace = match explicit_ws {Some(explicit) => explicit.to_string(),None => match marker.as_ref().and_then(|(scope, _)| scope.workspace.clone()){Some(declared) => {- from_marker = true;+ decided.push("workspace");declared}None => crate::config::DEFAULT_WORKSPACE.to_string(),},};- let project = match explicit_proj.filter(|s| !s.is_empty()) {+ let project = match explicit_proj {Some(explicit) => explicit.to_string(),None => {// A marker's explicit `project` pins the name for its whole tree;@@ -118,7 +124,7 @@ pub(crate) fn resolve_scope(});match declared {Some(name) => {- from_marker = true;+ decided.push("project");name}None => resolve_project_name(config, None)?,@@ -126,15 +132,48 @@ pub(crate) fn resolve_scope(}};- if from_marker && let Some((scope, _)) = marker.as_ref() {+ if let Some((scope, _)) = marker.as_ref().filter(|_| !decided.is_empty()) {+ // Name only the halves the marker actually decided: an explicit flag+ // that was honoured must not read as if the file overrode it.eprintln!(- "ai-memory: scope {workspace}/{project} declared by {}",+ "ai-memory: scope {workspace}/{project} ({} from {})",+ decided.join(" + "),scope.path.display());}Ok((workspace, project))}+/// Resolve only the workspace half, for the one command whose project half is+/// deliberately absent (`embed --force` fans out across every project in the+/// workspace). Resolving the pair there would make the command fail on the+/// cwd-derived project name it is about to throw away.+pub(crate) fn resolve_workspace(config: &Config, explicit_ws: Option<&str>) -> String {+ if let Some(explicit) = explicit_ws.filter(|s| !s.is_empty()) {+ return explicit.to_string();+ }+ match marker_scope(config) {+ Some((scope, _)) => match scope.workspace {+ Some(declared) => {+ eprintln!(+ "ai-memory: workspace {declared} (workspace from {})",+ scope.path.display()+ );+ declared+ }+ None => crate::config::DEFAULT_WORKSPACE.to_string(),+ },+ None => crate::config::DEFAULT_WORKSPACE.to_string(),+ }+}++/// The nearest scope-declaring marker plus the cwd the walk started from.+fn marker_scope(config: &Config) -> Option<(crate::marker::MarkerScope, String)> {+ let cwd = scope_cwd(config)?;+ let scope = crate::marker::read_scope(&cwd, &config.runtime_env)?;+ Some((scope, cwd))+}+/// The directory marker discovery walks up from.////// Prefers `AI_MEMORY_HOST_CWD` for the same reason [`resolve_project_name`]diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex b0b96f44..b2e22719 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -198,6 +198,8 @@ pub struct RuntimeEnv {server_url: Option<String>,auth_token: Option<String>,host_cwd: Option<String>,+ ignore_marker: bool,+ project_strategy: Option<String>,claude_code_session_id: Option<String>,anthropic_api_key: Option<SecretString>,anthropic_oauth_token: Option<SecretString>,@@ -221,6 +223,14 @@ impl RuntimeEnv {server_url: env_string("AI_MEMORY_SERVER_URL"),auth_token: env_string("AI_MEMORY_AUTH_TOKEN"),host_cwd: env_string("AI_MEMORY_HOST_CWD"),+ // One-invocation escape hatch: run a command against the fallback+ // scope without editing (or leaving) the marker's tree.+ ignore_marker: env_string("AI_MEMORY_IGNORE_MARKER")+ .is_some_and(|value| crate::marker::is_truthy(&value)),+ // Install-wide project strategy, matching what `install-hooks+ // --project-strategy` bakes into the generated hook commands.+ // Consulted only when a marker does not pin one.+ project_strategy: env_string("AI_MEMORY_PROJECT_STRATEGY"),claude_code_session_id: env_string("CLAUDE_CODE_SESSION_ID"),anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),// CLAUDE_CODE_OAUTH_TOKEN is what `claude setup-token` writes;@@ -250,6 +260,19 @@ impl RuntimeEnv {self.host_cwd.as_deref()}+ /// Whether `AI_MEMORY_IGNORE_MARKER` asked this invocation to resolve its+ /// scope as if no `.ai-memory.toml` existed.+ #[must_use]+ pub fn ignore_marker(&self) -> bool {+ self.ignore_marker+ }++ /// Install-wide `--project-strategy` default baked into the environment.+ #[must_use]+ pub fn project_strategy(&self) -> Option<&str> {+ self.project_strategy.as_deref()+ }+/// Claude Code lifecycle session id inherited by an stdio MCP subprocess.#[must_use]pub fn claude_code_session_id(&self) -> Option<&str> {diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex 981fa082..5953e6d2 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -21,16 +21,7 @@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";+use crate::config::RuntimeEnv;/// The scope fields a marker declares, plus where it was found.///@@ -69,39 +60,39 @@ impl MarkerScope {/// Read the nearest marker's scope declaration, honouring/// `AI_MEMORY_IGNORE_MARKER`.///+/// Both env knobs arrive through [`RuntimeEnv`] rather than being read here:+/// `Config::load()` is the one config-read path, and routing them through it+/// is also what makes the caller's unit tests hermetic against a developer's+/// exported `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() {+pub(crate) fn read_scope(cwd: &str, env: &RuntimeEnv) -> Option<MarkerScope> {+ if env.ignore_marker() {return None;}let path = find_marker(cwd)?;+ // One read, three keys: the marker is re-read per key nowhere else on a+ // hot path, but this one runs on every client command.+ let text = std::fs::read_to_string(&path).ok()?;let mut scope = MarkerScope {- workspace: parse_toml_key(&path, "workspace"),- project: parse_toml_key(&path, "project"),- project_strategy: parse_toml_key(&path, "project_strategy"),+ workspace: parse_key_in(&text, "workspace"),+ project: parse_key_in(&text, "project"),+ project_strategy: parse_key_in(&text, "project_strategy"),path,};if scope.project_strategy.is_none() {- scope.project_strategy = install_default_strategy();+ // The install-wide `--project-strategy` default, if one was baked into+ // the environment. Empty values are treated as unset.+ scope.project_strategy = env+ .project_strategy()+ .filter(|value| !value.trim().is_empty())+ .map(str::to_owned);}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> {@@ -138,7 +129,12 @@ pub(crate) fn find_marker(cwd: &str) -> Option<PathBuf> {/// 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()?;+ parse_key_in(&std::fs::read_to_string(file).ok()?, key)+}++/// [`parse_toml_key`] over already-read marker text, so a caller that needs+/// several keys pays for one read.+fn parse_key_in(text: &str, key: &str) -> Option<String> {for line in text.lines() {let trimmed = line.trim_start();let Some(after_key) = trimmed.strip_prefix(key) else {diff --git a/crates/ai-memory-cli/tests/marker_scope.rs b/crates/ai-memory-cli/tests/marker_scope.rsindex fd5b9474..f0a0a54d 100644--- a/crates/ai-memory-cli/tests/marker_scope.rs+++ b/crates/ai-memory-cli/tests/marker_scope.rs@@ -9,7 +9,7 @@//! 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::path::{Path, PathBuf};use std::process::Command;use tempfile::TempDir;@@ -17,6 +17,14 @@ fn bin() -> &'static str {env!("CARGO_BIN_EXE_ai-memory")}+/// The tempdir's real path. `TempDir` hands back `/var/folders/…` on macOS+/// while the child's `getcwd()` reports the resolved `/private/var/folders/…`+/// — without canonicalising, `$HOME` never equals any directory the walk+/// visits and the marker search escapes all the way to `/`.+fn real_path(dir: &TempDir) -> PathBuf {+ dir.path().canonicalize().expect("canonicalising tempdir")+}+/// 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@@ -33,6 +41,9 @@ fn search_stderr(cwd: &Path, data_dir: &Path, extra_env: &[(&str, &str)], args:// 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")+ // `AI_MEMORY_HOME` outranks `$HOME` in `path_util::home_dir`, so an+ // exported one on the developer's machine would unpin the walk.+ .env_remove("AI_MEMORY_HOME").env_remove("AI_MEMORY_HOST_CWD").env_remove("AI_MEMORY_IGNORE_MARKER").env_remove("AI_MEMORY_PROJECT_STRATEGY");@@ -54,7 +65,7 @@ fn marker_tree(body: &str) -> (TempDir, TempDir) {fn marker_workspace_is_used_and_announced() {let (cwd, data) = marker_tree("workspace = \"acme\"\n");- let stderr = search_stderr(cwd.path(), data.path(), &[], &[]);+ let stderr = search_stderr(&real_path(&cwd), &real_path(&data), &[], &[]);assert!(stderr.contains("scope acme/"),@@ -64,6 +75,10 @@ fn marker_workspace_is_used_and_announced() {stderr.contains(".ai-memory.toml"),"the notice names the marker that decided it: {stderr}");+ assert!(+ stderr.contains("workspace from"),+ "the notice names which half the marker decided: {stderr}"+ );}#[test]@@ -71,8 +86,8 @@ fn ignore_marker_env_restores_the_default_workspace() {let (cwd, data) = marker_tree("workspace = \"acme\"\n");let stderr = search_stderr(- cwd.path(),- data.path(),+ &real_path(&cwd),+ &real_path(&data),&[("AI_MEMORY_IGNORE_MARKER", "1")],&[],);@@ -87,7 +102,12 @@ fn ignore_marker_env_restores_the_default_workspace() {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"]);+ let stderr = search_stderr(+ &real_path(&cwd),+ &real_path(&data),+ &[],+ &["--workspace", "default"],+ );assert!(!stderr.contains("scope acme/"),@@ -100,10 +120,10 @@ 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(), &[], &[]);+ let stderr = search_stderr(&real_path(&cwd), &real_path(&data), &[], &[]);assert!(- !stderr.contains("declared by"),+ !stderr.contains("ai-memory: scope "),"no marker means no scope notice and no behaviour change: {stderr}");}diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex e9d7361c..a75328dd 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -4190,6 +4190,25 @@ async fn copy_purge_merge(.await{Ok(s) => s,+ // A live managed run under the source blocks the second leg exactly+ // as it blocks a standalone purge. The pages are already copied at+ // this point, so say so: re-running after the session finishes is+ // idempotent (copied pages just supersede) and leaves the source+ // intact meanwhile. `409` matches `handle_purge_project`; a `500`+ // here would read as a server fault for an operator-fixable state.+ Err(e @ StoreError::ManagedRunActive { .. }) => {+ return Err((+ StatusCode::CONFLICT,+ Json(serde_json::json!({+ "error": format!(+ "{pages_copied} page(s) were copied to {}/{}, but the source \+ {label} could not be purged: {e}. The source is intact — \+ re-run the move once the session ends.",+ req.to_workspace, req.project,+ )+ })),+ ));+ }Err(e) => return Err(internal_err(e.to_string())),};diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 2f863b9f..e064f168 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -63,9 +63,9 @@ pub struct PurgeSummary {/// 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.+ /// directories survive the SQL delete and are NOT removed by any caller+ /// today — they stay on disk with no row pointing at them. Reported so the+ /// purge can name them instead of leaving them silently orphaned.pub workstream_ids: Vec<String>,}use jiff::Timestamp;@@ -1509,9 +1509,14 @@ pub fn insert_wiki_migration(/// admin handler has the human-readable names; the writer only has IDs) and/// forwarded verbatim into [`PurgeSummary::label`] for logging.///+/// `force` overrides the live-managed-run guard (step 0): `workstreams`+/// cascades out of `projects`, so purging a scope whose lease is still live+/// would delete the lease row out from under a running agent.+////// # Errors-/// Returns [`StoreError`] if any SQL statement fails. The transaction is-/// rolled back automatically on error.+/// Returns [`StoreError::ManagedRunActive`] when a managed run's lease is+/// still live and `force` is false, or [`StoreError`] if any SQL statement+/// fails. The transaction is rolled back automatically on error.pub fn purge_project(conn: &mut Connection,workspace_id: &WorkspaceId,@@ -1536,13 +1541,22 @@ pub fn purge_project(// 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.+ //+ // `state = 'active'` alone is NOT liveness: a crashed wrapper leaves that+ // row untouched, and the only sweep that flips it to `'expired'` runs+ // inside `workstream::prepare_run`. Without the lease-expiry predicate a+ // single crashed agent would block every future purge of the project+ // until someone launched another managed run. The lease is short (90s,+ // extended by heartbeat), so `lease_expires_at > now` is the real signal.+ let now = Timestamp::now().as_microsecond();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'",+ WHERE w.project_id = ?1 AND mr.state = 'active' \+ AND mr.lease_expires_at > ?2",)?;- stmt.query_map(rusqlite::params![&pid[..]], |row| {+ stmt.query_map(rusqlite::params![&pid[..], now], |row| {Ok((row.get(0)?, row.get(1)?))})?.collect::<rusqlite::Result<Vec<_>>>()?@@ -1601,18 +1615,18 @@ pub fn purge_project(};// Same idea for the workstream segment directories: the rows go with the- // cascade but `raw/workstreams/<id>/` does not.+ // cascade but `raw/workstreams/<id>/` does not. Decode through the typed+ // id so the reported string matches the directory name `write_segment`+ // builds from `WorkstreamId::to_string`; a malformed blob is a corrupt+ // row, so surface it rather than silently shortening the orphan list.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()+ let rows = stmt+ .query_map(rusqlite::params![&pid[..]], |row| row.get::<_, Vec<u8>>(0))?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ rows.into_iter()+ .map(|raw| ai_memory_core::WorkstreamId::from_slice(&raw).map(|id| id.to_string()))+ .collect::<Result<Vec<_>, _>>()?};// Cascade handles pages / sessions / observations / handoffs /@@ -4227,6 +4241,29 @@ mod tests {);}+ /// A crashed wrapper leaves `state = 'active'` behind forever — the only+ /// sweep that flips it to `'expired'` lives in `prepare_run`. Guarding on+ /// the state alone would let one dead session block every future purge of+ /// the project, so the guard must read the lease expiry too.+ #[test]+ fn purge_project_ignores_a_managed_run_whose_lease_expired() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ open_managed_run(&mut conn, &ws, &proj);+ // Simulate the crash: the row still says 'active', but nothing has+ // heartbeated it, so its lease lapsed.+ conn.execute(+ "UPDATE managed_runs SET lease_expires_at = ?1 WHERE state = 'active'",+ rusqlite::params![Timestamp::now().as_microsecond() - 1],+ )+ .unwrap();++ let summary = purge_project(&mut conn, &ws, &proj, "default/scratch", None, false)+ .expect("a lapsed lease is not a running agent");++ assert_eq!(summary.workstreams_deleted, 1);+ assert_eq!(summary.managed_runs_deleted, 1);+ }+/// A `rename_project` writes an attributed audit row, committed/// atomically with the rename.#[test]diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex f8f6100a..e51a9786 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -8,7 +8,7 @@ on a homelab box where mistakes are harder to undo.| Command | Safe with server **running**? | Wipes data? | Reversible? | Notes ||---|---|---|---|---|-| `purge-project --confirm` | ✅ yes | the one project's data | no | Atomic `rm -rf <project_root>` on the namespaced disk path; sibling projects untouched. |+| `purge-project --confirm` | ✅ yes | the one project's data | no | Atomic `rm -rf <project_root>` on the namespaced disk path; sibling projects untouched. Refuses with `409` while a managed workstream under the project holds a live run lease — `--force` overrides. || `rename-project --from --to` | ✅ yes | no | yes (rename back) | Column-only update on `projects.name`. The on-disk dir is keyed by `project_id` (UUID), so the rename never moves a file. || `/admin/rename-workspace` | ✅ yes | no | yes (rename back) | Column-only update on `workspaces.name`; refreshes `_meta.md` scope manifests and checkpoints the wiki tree. || `/admin/delete-workspace` | ✅ yes | the workspace and every child project | no | Runs `purge_workspace` admission first, deletes SQLite rows in one cascade, removes the UUID-keyed workspace directory, reports filesystem partial failures, and dispatches mirror notification after durable work. |@@ -77,20 +77,40 @@ What happens, in order:1. Server looks up `(workspace_id, project_id)` by name. Returns 404if either is missing.-2. Counts rows that will cascade (`pages`, `sessions`,- `observations`, `handoffs`, `page_embeddings`).-3. Single `DELETE FROM projects WHERE id = ?` - the V01 + V05+2. Refuses with 409 when a managed workstream under the project still+ holds a **live** run lease (`managed_runs.state = 'active'` AND+ `lease_expires_at` in the future). `workstreams` cascades out of+ `projects` and `managed_runs` cascades out of `workstreams`, so+ purging would delete a running agent's lease row: its heartbeat+ would then fail with `409 managed run lease is not active` for the+ rest of the session and the transcript would never reach the ledger.+ A lapsed lease (crashed wrapper) does **not** block the purge.+ `--force` purges anyway.+3. Counts rows that will cascade (`pages`, `sessions`,+ `observations`, `handoffs`, `page_embeddings`, plus `workstreams`+ and `managed_runs`).+4. Single `DELETE FROM projects WHERE id = ?` - the V01 + V05`ON DELETE CASCADE` foreign keys propagate to every dependenttable in one transaction.-4. `std::fs::remove_dir_all(<wiki_root>/<workspace_id>/<project_id>)`+5. `std::fs::remove_dir_all(<wiki_root>/<workspace_id>/<project_id>)`wipes the on-disk project root.-5. Returns a summary: `{label, pages_deleted, sessions_deleted, …,+6. Returns a summary: `{label, pages_deleted, sessions_deleted, …,+ workstreams_deleted, managed_runs_deleted, workstream_ids,files_deleted: [<project_root>], files_failed: [...]}`.+`workstream_ids` is reported, not deleted: the managed-run segment+directories live under `<data_dir>/raw/workstreams/<workstream_id>/`,+outside the wiki root the purge removes, so they survive as orphans+with no row pointing at them. Remove them by hand on the **server's**+data dir if you want the raw event ledger gone too.+Failure modes:- **Workspace or project name not found** → 404, no mutation.- **Confirmation flag omitted** → 400, no mutation.+- **Live managed run, no `--force`** → 409 naming the workstreams, no+ mutation. Finish or cancel the session, or re-run with `--force`+ (the running agent then stops being able to save its history).- **`remove_dir_all` partial failure** (e.g. permissions) → DBrows are already gone but `files_failed` is populated. Re-runthe command with the same args is idempotent; the second call@@ -252,7 +272,10 @@ are carried over verbatim, and only then is the source purgedCopy-before-purge means any copy failure aborts **before** the purge,leaving the source intact. An unreadable source file is skipped and alsoblocks the purge (`source_purged: false`) so a fixed re-run is safe-(re-running is idempotent — copied pages just supersede).+(re-running is idempotent — copied pages just supersede). A **live managed+run** under the source blocks the purge leg the same way: the move returns+409 saying how many pages were already copied, and the source stays intact+until the session ends and the move is re-run.**Same-path conflicts (`on_conflict`).** When a source page's path alreadyexists in the destination with a different body, frontmatter, title, tier, ordiff --git a/docs/marker-file.md b/docs/marker-file.mdindex 7fe12c38..deac47b7 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -351,15 +351,20 @@ Each field is resolved independently: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:+the resolved scope, which half (or halves) the marker decided, and the+marker that decided it:```console$ ai-memory search "scope resolver"-ai-memory: scope acme/api declared by /Users/dev/projects/acme/.ai-memory.toml+ai-memory: scope acme/api (workspace + project from /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.+pre-v1.20 resolution without editing or leaving the marker's tree. It+applies to **client commands only** — the lifecycle hooks still forward the+marker's fields on every event, so an invocation run with it set resolves+into a different scope than the session captures around it. Use it for+one-off reads, not as a way to relocate a repository's memory.`ai-memory serve` is deliberately excluded: the server has no caller cwd towalk up from, and its `--workspace` / `--project` are the baked fallback for