Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): harden marker scope and project purge
AkitaOnRailsf69e896ec28d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fc09f617..a0dd9a2a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0no 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. (#259)+- Marker discovery now stays inside its trust boundary when the caller's cwd+ is outside `$HOME`: it walks no higher than the nearest checkout root, or+ checks only cwd for a non-git directory. Workspace-only markers also keep+ the hooks' documented `project = basename(cwd)` behavior for CLI commands,+ including subdirectories and linked worktrees. (#259)### Fixed- `purge-project` no longer deletes a project out from under a running agent.@@ -32,14 +37,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`409 managed run lease is not active` and the session's transcript neverreached the ledger. The purge now refuses with a `409` naming the offendingworkstreams 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. 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+ `workstreams` and `managed_runs` the cascade removes; their+ `raw/workstreams/<id>/` directories are now removed server-side and included+ in the same filesystem success/failure report instead of being orphaned.+ Those counters previously showed `0 pages, 0 sessions, …` and made such a+ scope look safe 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`'scopy-purge merge surfaces the same conflict as a `409` naming how many- pages were already copied, instead of a `500`. (#259)+ pages were already copied, instead of a `500`; its `--force` flag only+ overrides the active-project guard and never destroys a live managed-run+ lease. (#259)## [1.19.0] - 2026-07-25diff --git a/bin/ai-memory b/bin/ai-memoryindex 94511ff4..6578d168 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -489,6 +489,32 @@ elseDATA_ARGS+=(-v "${DATA_VOLUME}:/data")fi+# `AI_MEMORY_HOST_CWD` keeps project identity stable inside the helper, while+# `AI_MEMORY_SCOPE_CWD` names the same directory inside a bounded read-only+# mount used for marker discovery. $HOME is already mounted below. For+# checkouts outside it, expose no more than the nearest git root (or the exact+# cwd outside git), matching the marker walk's trust bound.+SCOPE_ARGS=()+case "${PWD}" in+ "${HOME}"|"${HOME}"/*) ;;+ *)+ SCOPE_ROOT="${PWD}"+ if command -v git >/dev/null 2>&1; then+ DETECTED_SCOPE_ROOT=$(git -C "${PWD}" rev-parse --show-toplevel 2>/dev/null || true)+ [ -n "${DETECTED_SCOPE_ROOT}" ] && SCOPE_ROOT="${DETECTED_SCOPE_ROOT}"+ fi+ case "${PWD}" in+ "${SCOPE_ROOT}") SCOPE_REL="" ;;+ "${SCOPE_ROOT}"/*) SCOPE_REL="${PWD#"${SCOPE_ROOT}"}" ;;+ *) SCOPE_ROOT="${PWD}"; SCOPE_REL="" ;;+ esac+ SCOPE_ARGS+=(+ -v "${SCOPE_ROOT}:/scope:ro"+ -e "AI_MEMORY_SCOPE_CWD=/scope${SCOPE_REL}"+ )+ ;;+esac+# Mount $HOME at the same path inside the container so:# - dirs::home_dir() resolves identically (Claude's default paths and any# CLAUDE_CONFIG_DIR beneath $HOME work without extra path flags)@@ -522,6 +548,7 @@ HELPER_ARGS+=(-e HOME="${HOME}"-e AI_MEMORY_HOST_CWD="${PWD}")+HELPER_ARGS+=(${SCOPE_ARGS[@]+"${SCOPE_ARGS[@]}"})HELPER_ARGS+=(${USER_ARGS[@]+"${USER_ARGS[@]}"})HELPER_ARGS+=("${DATA_ARGS[@]}")HELPER_ARGS+=(${ENV_ARGS[@]+"${ENV_ARGS[@]}"})diff --git a/bin/ai-memory.ps1 b/bin/ai-memory.ps1index 57579642..65193830 100644--- a/bin/ai-memory.ps1+++ b/bin/ai-memory.ps1@@ -44,6 +44,40 @@ $HomePath = (Resolve-Path -LiteralPath $HOME).Path$WorkPath = (Get-Location).Path$HookHostRoot = ($HomePath -replace '\\', '/') + "/.local/share/ai-memory/hooks"+$HomeRoot = $HomePath.TrimEnd([char[]]@('/', '\\'))+$HomePrefix = $HomeRoot + [IO.Path]::DirectorySeparatorChar+$InsideHome = $WorkPath.Equals($HomeRoot, [StringComparison]::OrdinalIgnoreCase) -or+ $WorkPath.StartsWith($HomePrefix, [StringComparison]::OrdinalIgnoreCase)+$ScopeMountArgs = @()+if ($InsideHome) {+ $ScopeSuffix = if ($WorkPath.Length -eq $HomeRoot.Length) {+ ""+ } else {+ $WorkPath.Substring($HomeRoot.Length) -replace '\\', '/'+ }+ $ScopeCwd = "/host-home$ScopeSuffix"+} else {+ $ScopeRoot = $WorkPath+ if (Get-Command git -ErrorAction SilentlyContinue) {+ $DetectedScopeRoot = (& git -C $WorkPath rev-parse --show-toplevel 2>$null)+ if (-not [string]::IsNullOrWhiteSpace($DetectedScopeRoot)) {+ $ScopeRoot = [IO.Path]::GetFullPath($DetectedScopeRoot.Trim())+ }+ }+ $ScopeRoot = $ScopeRoot.TrimEnd([char[]]@('/', '\\'))+ $ScopePrefix = $ScopeRoot + [IO.Path]::DirectorySeparatorChar+ if ($WorkPath.Equals($ScopeRoot, [StringComparison]::OrdinalIgnoreCase)) {+ $ScopeSuffix = ""+ } elseif ($WorkPath.StartsWith($ScopePrefix, [StringComparison]::OrdinalIgnoreCase)) {+ $ScopeSuffix = $WorkPath.Substring($ScopeRoot.Length) -replace '\\', '/'+ } else {+ $ScopeRoot = $WorkPath+ $ScopeSuffix = ""+ }+ $ScopeMountArgs = @("-v", "${ScopeRoot}:/scope:ro")+ $ScopeCwd = "/scope$ScopeSuffix"+}+$DockerArgs = @("run", "--rm", "-i")# Keep stdin attached in every mode. `AI_MEMORY_NO_TTY` suppresses only the# pseudo-terminal allocation.@@ -57,10 +91,12 @@ $DockerArgs += @("-w", "/work","-e", "HOME=/host-home","-e", "AI_MEMORY_HOST_CWD=$WorkPath",+ "-e", "AI_MEMORY_SCOPE_CWD=$ScopeCwd","-e", "AI_MEMORY_DATA_DIR=/data","-e", "AI_MEMORY_HOOK_PLATFORM=windows","-e", "AI_MEMORY_HOOKS_HOST_ROOT=$HookHostRoot")+$DockerArgs += $ScopeMountArgsif ($env:AI_MEMORY_DATA_DIR -and (Test-Path -LiteralPath $env:AI_MEMORY_DATA_DIR -PathType Container)) {$DataPath = (Resolve-Path -LiteralPath $env:AI_MEMORY_DATA_DIR).Pathdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex b1671d6a..9e9e43a8 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -527,10 +527,9 @@ pub struct MoveProjectArgs {/// source, both irreversible. Without this flag the CLI errors out.#[arg(long)]pub confirm: bool,- /// Override the live-session guard. By default the server refuses (409) to- /// move the project a hook session is actively writing to; `--force`- /// proceeds anyway (still safe — the move keeps the active pointer correct- /// and the schema rejects any stale write).+ /// Override the active-project guard. In a copy-purge merge this never+ /// overrides a live managed-workstream lease, because deleting that lease+ /// would strand the running agent's transcript.#[arg(long)]pub force: bool,/// Merge conflict policy (copy-purge path only): what to do when a sourcediff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 5bbce6b6..86a7562e 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -822,13 +822,13 @@ drop_subagent_captures = "true"#[test]fn marker_query_suffix_repo_root_non_git_keeps_project_implicit() {let tmp = tempfile::TempDir::new().unwrap();+ let child = tmp.path().join("plain-dir");+ std::fs::create_dir_all(&child).unwrap();std::fs::write(- tmp.path().join(".ai-memory.toml"),+ child.join(".ai-memory.toml"),"workspace = \"oss\"\nproject_strategy = \"repo-root\"\n",).unwrap();- let child = tmp.path().join("plain-dir");- std::fs::create_dir_all(&child).unwrap();let qs = marker_query_suffix(child.to_str().unwrap(), None);assert!(qs.contains("&workspace=oss"), "{qs}");assert!(!qs.contains("&project="), "{qs}");@@ -877,11 +877,6 @@ drop_subagent_captures = "true"let worktrees = tmp.path().join("worktrees");std::fs::create_dir_all(&worktrees).unwrap();- std::fs::write(- worktrees.join(".ai-memory.toml"),- "workspace = \"oss\"\nproject_strategy = \"repo-root\"\n",- )- .unwrap();let wt = worktrees.join("acme-api/wt-feature");std::fs::create_dir_all(wt.parent().unwrap()).unwrap();if !std::process::Command::new("git")@@ -895,6 +890,11 @@ drop_subagent_captures = "true"{return;}+ std::fs::write(+ wt.join(".ai-memory.toml"),+ "workspace = \"oss\"\nproject_strategy = \"repo-root\"\n",+ )+ .unwrap();let qs = marker_query_suffix(wt.to_str().unwrap(), None);assert!(qs.contains("&workspace=oss"), "{qs}");diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 1cd88dcc..98667b8e 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1776,7 +1776,7 @@ fn build_opencode_plugin(import type {{ Plugin }} from "@opencode-ai/plugin";import {{ execFileSync }} from "node:child_process";import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";-import {{ basename, dirname, join, resolve }} from "node:path";+import {{ basename, dirname, join, resolve, sep }} from "node:path";import {{ homedir }} from "node:os";const SERVER = {server_literal}.replace(/\/+$/, "");@@ -1884,10 +1884,24 @@ function findMarker(cwd: string | undefined): string | undefined {{if (!cwd) return undefined;let dir = resolve(cwd);const home = homedir();+ let boundary: string | undefined;+ if (home && (dir === home || dir.startsWith(home.endsWith(sep) ? home : home + sep))) {{+ boundary = home;+ }} else if (home) {{+ let probe = dir;+ while (probe && probe !== dirname(probe)) {{+ if (existsSync(join(probe, ".git"))) {{+ boundary = probe;+ break;+ }}+ probe = dirname(probe);+ }}+ boundary ??= dir;+ }}while (dir && dir !== dirname(dir)) {{const marker = join(dir, ".ai-memory.toml");if (existsSync(marker)) return marker;- if (home && dir === home) return undefined;+ if (boundary && dir === boundary) return undefined;dir = dirname(dir);}}return undefined;@@ -2361,7 +2375,7 @@ fn build_omp_extension(import {{ execFileSync }} from "node:child_process";import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";-import {{ basename, dirname, join, resolve }} from "node:path";+import {{ basename, dirname, join, resolve, sep }} from "node:path";import {{ homedir }} from "node:os";const SERVER = {server_literal}.replace(/\/+$/, "");@@ -2447,10 +2461,24 @@ function findMarker(cwd: string | undefined): string | undefined {{if (!cwd) return undefined;let dir = resolve(cwd);const home = homedir();+ let boundary: string | undefined;+ if (home && (dir === home || dir.startsWith(home.endsWith(sep) ? home : home + sep))) {{+ boundary = home;+ }} else if (home) {{+ let probe = dir;+ while (probe && probe !== dirname(probe)) {{+ if (existsSync(join(probe, ".git"))) {{+ boundary = probe;+ break;+ }}+ probe = dirname(probe);+ }}+ boundary ??= dir;+ }}while (dir && dir !== dirname(dir)) {{const marker = join(dir, ".ai-memory.toml");if (existsSync(marker)) return marker;- if (home && dir === home) return undefined;+ if (boundary && dir === boundary) return undefined;dir = dirname(dir);}}return undefined;@@ -4499,7 +4527,11 @@ model = "gpt-5""OpenCode bus events must be handled through the `event` hook");assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));- assert!(plugin.contains("import { basename, dirname, join, resolve } from \"node:path\";"));+ assert!(+ plugin.contains("import { basename, dirname, join, resolve, sep } from \"node:path\";")+ );+ assert!(plugin.contains("if (existsSync(join(probe, \".git\")))"));+ assert!(plugin.contains("boundary ??= dir;"));assert!(plugin.contains("function repoRootProject"));assert!(plugin.contains("--git-common-dir"));assert!(@@ -4597,8 +4629,11 @@ model = "gpt-5"assert!(extension.contains("Bearer ${TOKEN}"));assert!(extension.contains("tok"));assert!(- extension.contains("import { basename, dirname, join, resolve } from \"node:path\";")+ extension+ .contains("import { basename, dirname, join, resolve, sep } from \"node:path\";"));+ assert!(extension.contains("if (existsSync(join(probe, \".git\")))"));+ assert!(extension.contains("boundary ??= dir;"));assert!(extension.contains("import { execFileSync } from \"node:child_process\";"));assert!(extension.contains("function repoRootProject"));assert!(extension.contains("--git-common-dir"));diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 6ff19e9d..ca41f339 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -62,8 +62,8 @@ pub mod write_page;////// 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.+/// or the hook-compatible derived project when the marker leaves it+/// unpinned (`basename(cwd)` by default, main repo root for `repo-root`)./// 3. Today's fallbacks: [`crate::config::DEFAULT_WORKSPACE`] and/// [`resolve_project_name`]'s cwd chain.///@@ -95,7 +95,7 @@ pub(crate) fn resolve_scope(Some(explicit) => explicit.to_string(),None => match marker.as_ref()- .and_then(|(scope, _)| scope.workspace.clone())+ .and_then(|(scope, _, _)| scope.workspace.clone()){Some(declared) => {decided.push("workspace");@@ -108,20 +108,24 @@ pub(crate) fn resolve_scope(let project = match explicit_proj {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()- })- });+ // A marker's explicit `project` pins the name for its whole tree.+ // Otherwise derive exactly as the hook does: basename(cwd) by+ // default, or the main repository root for `repo-root`.+ let declared = marker+ .as_ref()+ .and_then(|(scope, identity_cwd, lookup_cwd)| {+ scope.project.clone().or_else(|| {+ if scope.is_repo_root() {+ crate::marker::repo_root_project(lookup_cwd)+ } else {+ ai_memory_consolidate::derive_project_name(+ std::path::Path::new(identity_cwd),+ ai_memory_consolidate::ProjectNameStrategy::Basename,+ )+ .map(|(name, _)| name)+ }+ })+ });match declared {Some(name) => {decided.push("project");@@ -132,7 +136,7 @@ pub(crate) fn resolve_scope(}};- if let Some((scope, _)) = marker.as_ref().filter(|_| !decided.is_empty()) {+ 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!(@@ -153,7 +157,7 @@ pub(crate) fn resolve_workspace(config: &Config, explicit_ws: Option<&str>) -> Sreturn explicit.to_string();}match marker_scope(config) {- Some((scope, _)) => match scope.workspace {+ Some((scope, _, _)) => match scope.workspace {Some(declared) => {eprintln!("ai-memory: workspace {declared} (workspace from {})",@@ -168,10 +172,23 @@ pub(crate) fn resolve_workspace(config: &Config, explicit_ws: Option<&str>) -> S}/// 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))+fn marker_scope(config: &Config) -> Option<(crate::marker::MarkerScope, String, String)> {+ let identity_cwd = scope_cwd(config)?;+ // The Docker wrapper preserves the host cwd for identity but binds the+ // checkout at /work. Check the host path when its bounded root is mounted;+ // otherwise use the physical cwd so a marker in the /work bind is still+ // visible. Project derivation keeps using the host identity either way.+ let lookup_cwd = if let Some(scope_cwd) = config.runtime_env.scope_cwd() {+ scope_cwd.to_string()+ } else if std::path::Path::new(&identity_cwd).exists() {+ identity_cwd.clone()+ } else {+ std::env::current_dir()+ .ok()+ .map(|cwd| cwd.to_string_lossy().into_owned())?+ };+ let scope = crate::marker::read_scope(&lookup_cwd, &config.runtime_env)?;+ Some((scope, identity_cwd, lookup_cwd))}/// The directory marker discovery walks up from.@@ -328,6 +345,51 @@ mod tests {);}+ #[test]+ fn workspace_only_marker_uses_hook_basename_from_a_subdirectory() {+ let tmp = tempfile::TempDir::new().unwrap();+ std::fs::write(tmp.path().join(".ai-memory.toml"), "workspace = \"acme\"\n").unwrap();+ let subdir = tmp.path().join("crates").join("cli");+ std::fs::create_dir_all(&subdir).unwrap();+ let config = Config {+ runtime_env: RuntimeEnv::with_host_cwd_for_tests(subdir.to_str().unwrap()),+ ..Config::default()+ };++ assert_eq!(+ resolve_scope(&config, None, None).unwrap(),+ ("acme".to_string(), "cli".to_string())+ );+ assert_eq!(+ resolve_scope(&config, Some("flagged"), None).unwrap(),+ ("flagged".to_string(), "cli".to_string()),+ "an explicit workspace must not restore the main-repo fallback"+ );+ }++ #[test]+ fn workspace_only_marker_uses_linked_worktree_directory_name() {+ let tmp = tempfile::TempDir::new().unwrap();+ let worktree = tmp.path().join("feature-worktree");+ std::fs::create_dir_all(&worktree).unwrap();+ std::fs::write(+ worktree.join(".git"),+ "gitdir: /repo/.git/worktrees/feature\n",+ )+ .unwrap();+ std::fs::write(worktree.join(".ai-memory.toml"), "workspace = \"acme\"\n").unwrap();+ let config = Config {+ runtime_env: RuntimeEnv::with_host_cwd_for_tests(worktree.to_str().unwrap()),+ ..Config::default()+ };++ assert_eq!(+ resolve_scope(&config, None, None).unwrap(),+ ("acme".to_string(), "feature-worktree".to_string()),+ "workspace-only markers preserve the hook's basename worktree identity"+ );+ }+/// A marker that pins `project` overrides the cwd-derived name for its/// whole tree.#[test]diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex 7b8d5a3e..7054349d 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -297,7 +297,7 @@ fn build_plugin(import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";import {{ execFileSync }} from "node:child_process";import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";-import {{ basename, dirname, join, resolve }} from "node:path";+import {{ basename, dirname, join, resolve, sep }} from "node:path";import {{ homedir }} from "node:os";const SERVER = {server_literal}.replace(/\/+$/, "");@@ -319,10 +319,24 @@ function findMarker(cwd: string | undefined): string | undefined {{if (!cwd) return undefined;let dir = resolve(cwd);const home = homedir();+ let boundary: string | undefined;+ if (home && (dir === home || dir.startsWith(home.endsWith(sep) ? home : home + sep))) {{+ boundary = home;+ }} else if (home) {{+ let probe = dir;+ while (probe && probe !== dirname(probe)) {{+ if (existsSync(join(probe, ".git"))) {{+ boundary = probe;+ break;+ }}+ probe = dirname(probe);+ }}+ boundary ??= dir;+ }}while (dir && dir !== dirname(dir)) {{const marker = join(dir, ".ai-memory.toml");if (existsSync(marker)) return marker;- if (home && dir === home) return undefined;+ if (boundary && dir === boundary) return undefined;dir = dirname(dir);}}return undefined;@@ -555,7 +569,11 @@ mod tests {assert!(plugin.contains("tomlFlag(body, \"inject_on_session_start\")"));assert!(plugin.contains("url.searchParams.set(\"briefing_budget\", briefingBudget)"));assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));- assert!(plugin.contains("import { basename, dirname, join, resolve } from \"node:path\";"));+ assert!(+ plugin.contains("import { basename, dirname, join, resolve, sep } from \"node:path\";")+ );+ assert!(plugin.contains("if (existsSync(join(probe, \".git\")))"));+ assert!(plugin.contains("boundary ??= dir;"));assert!(plugin.contains("function repoRootProject"));assert!(plugin.contains("--git-common-dir"));assert!(diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex b2e22719..8323064f 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -198,6 +198,7 @@ pub struct RuntimeEnv {server_url: Option<String>,auth_token: Option<String>,host_cwd: Option<String>,+ scope_cwd: Option<String>,ignore_marker: bool,project_strategy: Option<String>,claude_code_session_id: Option<String>,@@ -223,6 +224,7 @@ 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"),+ scope_cwd: env_string("AI_MEMORY_SCOPE_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")@@ -260,6 +262,18 @@ impl RuntimeEnv {self.host_cwd.as_deref()}+ /// Container-visible cwd used only for marker discovery.+ #[must_use]+ pub fn scope_cwd(&self) -> Option<&str> {+ self.scope_cwd.as_deref()+ }++ /// Operator home captured by the single config-read path.+ #[must_use]+ pub fn home_dir(&self) -> Option<&str> {+ self.home_dir.as_deref()+ }+/// Whether `AI_MEMORY_IGNORE_MARKER` asked this invocation to resolve its/// scope as if no `.ai-memory.toml` existed.#[must_use]diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex 5953e6d2..5ac01d94 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -72,7 +72,7 @@ pub(crate) fn read_scope(cwd: &str, env: &RuntimeEnv) -> Option<MarkerScope> {if env.ignore_marker() {return None;}- let path = find_marker(cwd)?;+ let path = find_marker_with_home(cwd, env.home_dir().map(Path::new))?;// 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()?;@@ -103,19 +103,31 @@ pub(crate) fn repo_root_project(cwd: &str) -> Option<String> {.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`).+/// Walk up from `cwd` toward `$HOME` looking for `.ai-memory.toml`.+/// Checkouts outside `$HOME` stop at their nearest `.git` root; a non-git+/// directory outside `$HOME` checks only `cwd`. When home is unavailable the+/// historical filesystem-root walk remains the fallback.pub(crate) fn find_marker(cwd: &str) -> Option<PathBuf> {let home = home_dir();- let mut dir = Path::new(cwd);+ find_marker_with_home(cwd, home.as_deref())+}++fn find_marker_with_home(cwd: &str, home: Option<&Path>) -> Option<PathBuf> {+ let start = absolute_normalized(Path::new(cwd));+ let home = home.map(absolute_normalized);+ let boundary = match home.as_deref() {+ Some(home) if start.starts_with(home) => Some(home.to_path_buf()),+ Some(_) => Some(checkout_root(&start).unwrap_or_else(|| start.clone())),+ None => None,+ };++ let mut dir = start.as_path();loop {let candidate = dir.join(".ai-memory.toml");if candidate.is_file() {return Some(candidate);}- if home.as_deref() == Some(dir) {+ if boundary.as_deref() == Some(dir) {return None;}match dir.parent() {@@ -125,6 +137,31 @@ pub(crate) fn find_marker(cwd: &str) -> Option<PathBuf> {}}+fn absolute_normalized(path: &Path) -> PathBuf {+ path.canonicalize().unwrap_or_else(|_| {+ if path.is_absolute() {+ path.to_path_buf()+ } else {+ std::env::current_dir()+ .map(|cwd| cwd.join(path))+ .unwrap_or_else(|_| path.to_path_buf())+ }+ })+}++fn checkout_root(start: &Path) -> Option<PathBuf> {+ let mut dir = start;+ loop {+ if dir.join(".git").exists() {+ return Some(dir.to_path_buf());+ }+ 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.@@ -210,7 +247,7 @@ mod tests {fs::create_dir_all(&nested).unwrap();assert_eq!(- find_marker(nested.to_str().unwrap()),+ find_marker_with_home(nested.to_str().unwrap(), Some(&root)),Some(marker),"a marker in any ancestor wins");@@ -222,6 +259,53 @@ mod tests {assert_eq!(find_marker(tmp.path().to_str().unwrap()), None);}+ #[test]+ fn marker_walk_outside_home_stops_at_checkout_root() {+ let tmp = TempDir::new().unwrap();+ let home = tmp.path().join("home");+ let outer = tmp.path().join("outside");+ let repo = outer.join("repo");+ let nested = repo.join("src");+ fs::create_dir_all(repo.join(".git")).unwrap();+ fs::create_dir_all(&nested).unwrap();+ fs::create_dir_all(&home).unwrap();+ let outer_marker = write_marker(&outer, "workspace = \"wrong\"\n");+ let repo_marker = write_marker(&repo, "workspace = \"right\"\n");++ assert_eq!(+ find_marker_with_home(nested.to_str().unwrap(), Some(&home)),+ Some(repo_marker)+ );+ fs::remove_file(repo.join(".ai-memory.toml")).unwrap();+ assert_eq!(+ find_marker_with_home(nested.to_str().unwrap(), Some(&home)),+ None,+ "a marker above the checkout boundary must not leak in"+ );+ assert!(outer_marker.exists());+ }++ #[test]+ fn marker_walk_outside_home_checks_only_cwd_without_a_checkout() {+ let tmp = TempDir::new().unwrap();+ let home = tmp.path().join("home");+ let outer = tmp.path().join("outside");+ let cwd = outer.join("plain");+ fs::create_dir_all(&home).unwrap();+ fs::create_dir_all(&cwd).unwrap();+ write_marker(&outer, "workspace = \"wrong\"\n");++ assert_eq!(+ find_marker_with_home(cwd.to_str().unwrap(), Some(&home)),+ None+ );+ let local = write_marker(&cwd, "workspace = \"right\"\n");+ assert_eq!(+ find_marker_with_home(cwd.to_str().unwrap(), Some(&home)),+ Some(local)+ );+ }+/// Happy-path TOML parser: extracts each declared root-level/// `key = "value"` pair. Mirrors the shell `ai_memory_parse_toml_key`.#[test]diff --git a/crates/ai-memory-cli/tests/marker_scope.rs b/crates/ai-memory-cli/tests/marker_scope.rsindex f0a0a54d..abc1d2ce 100644--- a/crates/ai-memory-cli/tests/marker_scope.rs+++ b/crates/ai-memory-cli/tests/marker_scope.rs@@ -45,6 +45,7 @@ fn search_stderr(cwd: &Path, data_dir: &Path, extra_env: &[(&str, &str)], args:// 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_SCOPE_CWD").env_remove("AI_MEMORY_IGNORE_MARKER").env_remove("AI_MEMORY_PROJECT_STRATEGY");for (key, value) in extra_env {@@ -76,8 +77,8 @@ fn marker_workspace_is_used_and_announced() {"the notice names the marker that decided it: {stderr}");assert!(- stderr.contains("workspace from"),- "the notice names which half the marker decided: {stderr}"+ stderr.contains("workspace + project from"),+ "a workspace-only marker also selects hook-compatible basename(cwd): {stderr}");}@@ -127,3 +128,34 @@ fn a_tree_without_a_marker_is_unchanged() {"no marker means no scope notice and no behaviour change: {stderr}");}++#[test]+fn mounted_scope_cwd_reads_marker_while_host_cwd_keeps_project_identity() {+ let root = TempDir::new().expect("scope root");+ let data = TempDir::new().expect("data dir");+ std::fs::write(+ root.path().join(".ai-memory.toml"),+ "workspace = \"acme\"\n",+ )+ .unwrap();+ let mounted_cwd = root.path().join("crates/cli");+ std::fs::create_dir_all(&mounted_cwd).unwrap();+ let mounted_cwd = mounted_cwd.canonicalize().unwrap();+ let root = real_path(&root);+ let data = real_path(&data);+ let stderr = search_stderr(+ &mounted_cwd,+ &data,+ &[+ ("AI_MEMORY_HOST_CWD", "/host/repo/crates/cli"),+ ("AI_MEMORY_SCOPE_CWD", mounted_cwd.to_str().unwrap()),+ ("HOME", root.to_str().unwrap()),+ ],+ &[],+ );++ assert!(+ stderr.contains("scope acme/cli"),+ "lookup must use the mounted path and naming must use host cwd: {stderr}"+ );+}diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rsindex 7a471339..54b81c60 100644--- a/crates/ai-memory-cli/tests/packaging.rs+++ b/crates/ai-memory-cli/tests/packaging.rs@@ -283,6 +283,16 @@ fn wrapper_keeps_stdin_attached_when_it_is_a_pipe() {!flags.contains(&"-t") && !flags.contains(&"-it"),"no TTY may be requested when stdin is a pipe; got {args}");+ assert!(+ flags+ .iter()+ .any(|arg| arg.starts_with("AI_MEMORY_SCOPE_CWD=/scope")),+ "an outside-home checkout must expose its bounded marker path; got {args}"+ );+ assert!(+ flags.iter().any(|arg| arg.ends_with(":/scope:ro")),+ "the marker scope mount must be read-only; got {args}"+ );}#[test]@@ -304,6 +314,9 @@ fn docker_wrappers_keep_stdin_attached_independently_of_tty_allocation() {posix.contains("CLAUDE_CODE_SESSION_ID"),"POSIX wrapper must forward Claude's session id into the bridge container");+ assert!(posix.contains("git -C \"${PWD}\" rev-parse --show-toplevel"));+ assert!(posix.contains("AI_MEMORY_SCOPE_CWD=/scope${SCOPE_REL}"));+ assert!(posix.contains("${SCOPE_ROOT}:/scope:ro"));let powershell = read_repo("bin/ai-memory.ps1");assert!(@@ -322,6 +335,8 @@ fn docker_wrappers_keep_stdin_attached_independently_of_tty_allocation() {powershell.contains("\"CLAUDE_CODE_SESSION_ID\""),"PowerShell wrapper must forward Claude's session id into the bridge container");+ assert!(powershell.contains("AI_MEMORY_SCOPE_CWD=$ScopeCwd"));+ assert!(powershell.contains("${ScopeRoot}:/scope:ro"));}#[cfg(unix)]diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex a75328dd..4652f52d 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -2887,8 +2887,8 @@ pub struct PurgeProjectReport {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.+ /// Ids of the deleted workstreams whose `raw/workstreams/<id>/` segment+ /// directories were included in the post-commit cleanup.pub workstream_ids: Vec<String>,/// Paths removed from disk (the project's UUID-namespaced directory).pub files_deleted: Vec<String>,@@ -2902,6 +2902,60 @@ pub struct PurgeProjectReport {pub checkpoint: Option<String>,}+async fn remove_purged_project_storage(+ state: &AdminState,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ workstream_ids: &[String],+ operation: &'static str,+) -> (Vec<String>, Vec<String>) {+ let project_root = state.wiki.project_root(workspace_id, project_id);+ let project_root_display = project_root.display().to_string();+ let mut deleted = Vec::with_capacity(workstream_ids.len() + 1);+ let mut failed = Vec::new();++ match state+ .wiki+ .remove_project_dir(workspace_id, project_id)+ .await+ {+ Ok(()) => deleted.push(project_root_display.clone()),+ Err(error) => {+ warn!(+ operation,+ path = %project_root_display,+ error = %error,+ "project purge failed to remove wiki directory"+ );+ failed.push(project_root_display);+ }+ }++ for workstream_id in workstream_ids {+ let path = state+ .data_dir+ .join("raw")+ .join("workstreams")+ .join(workstream_id);+ let path_display = path.display().to_string();+ match tokio::fs::remove_dir_all(&path).await {+ Ok(()) => deleted.push(path_display),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => {+ warn!(+ operation,+ path = %path_display,+ error = %error,+ "project purge failed to remove workstream segment directory"+ );+ failed.push(path_display);+ }+ }+ }++ (deleted, failed)+}+async fn handle_purge_project(State(state): State<Arc<AdminState>>,actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,@@ -2976,25 +3030,17 @@ async fn handle_purge_project(Err(e) => return internal_err(e.to_string()),};- // Remove the entire per-project directory: <wiki_root>/<ws_uuid>/<proj_uuid>/.- // DB cascade already deleted all rows. Directory removal remains best-effort- // and is reported separately, matching the pre-admission purge contract.- let proj_root_str = state- .wiki- .project_root(ws_id, proj_id)- .display()- .to_string();- let mut files_deleted: Vec<String> = Vec::new();- let mut files_failed: Vec<String> = Vec::new();- match state.wiki.remove_project_dir(ws_id, proj_id).await {- Ok(()) => {- files_deleted.push(proj_root_str);- }- Err(e) => {- warn!(path = %proj_root_str, error = %e, "purge-project: failed to remove project dir");- files_failed.push(proj_root_str);- }- }+ // DB cascade already deleted all rows. Remove both the wiki project root+ // and every raw managed-workstream segment directory best-effort, reporting+ // partial failures without disguising the committed database purge.+ let (files_deleted, files_failed) = remove_purged_project_storage(+ &state,+ ws_id,+ proj_id,+ &summary.workstream_ids,+ "purge-project",+ )+ .await;// Mirrors that track filesystem reality (a git-push mirror) want to// know the on-disk dir is still present even though the DB rows are// gone, so they can refuse to drop their own copy in violation of@@ -3392,12 +3438,13 @@ struct MoveProjectRequest {/// Mandatory confirmation flag. The move PURGES the source after/// copying, so without `confirm: true` the server returns 400.confirm: bool,- /// Override the live-session guard. By default the server refuses (409)+ /// Override the active-project guard. By default the server refuses (409)/// to move the project the hook router is currently writing to, since a/// live session's next observation would carry a stale workspace id./// `force: true` proceeds anyway (still safe: the move republishes the/// active pointer and the (workspace_id, project_id) trigger makes any- /// stale write fail cleanly rather than corrupt).+ /// stale write fail cleanly rather than corrupt). It never overrides a+ /// live managed-workstream lease in the destructive copy-purge path.#[serde(default)]force: bool,/// Policy for the copy-purge MERGE path when a source page's path already@@ -4190,20 +4237,21 @@ 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.+ // A live managed run under the source always blocks the destructive+ // second leg. `force` only overrides the active-project guard; unlike+ // a true move, copy-purge would delete the lease and strand the raw+ // transcript. The pages are already copied, so a later retry is+ // idempotent and leaves the source intact meanwhile.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.",+ {label} could not be purged: {e}. The source is intact. \+ move-project --force cannot delete a live managed \+ workstream during a copy-purge merge; finish or cancel \+ the managed run, then retry.",req.to_workspace, req.project,)})),@@ -4212,24 +4260,17 @@ async fn copy_purge_merge(Err(e) => return Err(internal_err(e.to_string())),};- // Remove the source's on-disk dir, then dispatch the non-blocking- // purge webhook. Pass the workspace/project NAMES we cached in- // `resolved_purge_ctx` — the DB rows have just been deleted, so a- // name-resolution lookup at dispatch time would find nothing.- let proj_root_str = state- .wiki- .project_root(src_ws, src_proj)- .display()- .to_string();- let mut files_deleted: Vec<String> = Vec::new();- let mut files_failed: Vec<String> = Vec::new();- match state.wiki.remove_project_dir(src_ws, src_proj).await {- Ok(()) => files_deleted.push(proj_root_str),- Err(e) => {- warn!(path = %proj_root_str, error = %e, "move-project: failed to remove source dir");- files_failed.push(proj_root_str);- }- }+ // Remove the source's wiki and raw-workstream directories, then dispatch+ // the non-blocking purge webhook. Pass the workspace/project names cached+ // in `resolved_purge_ctx`; the DB rows no longer exist for lookup.+ let (files_deleted, files_failed) = remove_purged_project_storage(+ state,+ src_ws,+ src_proj,+ &summary.workstream_ids,+ "move-project",+ )+ .await;// See `handle_purge_project` for the rationale on `partial_failure`.let mut dispatch_ctx = resolved_purge_ctx;if !files_failed.is_empty()diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rsindex 52cc50ab..74774654 100644--- a/crates/ai-memory-mcp/tests/admin_move.rs+++ b/crates/ai-memory-mcp/tests/admin_move.rs@@ -13,9 +13,9 @@//! both versions survive), then purge the source — there the episodic rows//! (sessions/observations/handoffs) are dropped by the purge.-use ai_memory_core::{PagePath, Sanitized, Sanitizer, Tier};+use ai_memory_core::{AgentKind, PagePath, Sanitized, Sanitizer, Tier};use ai_memory_mcp::{AdminState, admin_router};-use ai_memory_store::{DecayParams, Store};+use ai_memory_store::{DecayParams, PrepareWorkstreamRun, Store, WorkstreamSelection};use ai_memory_wiki::{AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig, Wiki, WritePageRequest,};@@ -913,6 +913,80 @@ async fn move_active_project_with_force_succeeds_and_republishes() {);}+#[tokio::test]+async fn copy_purge_force_never_deletes_a_live_managed_workstream() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "source").await;+ seed_page(+ &store,+ &state.wiki,+ "dst",+ "proj",+ "notes/keep.md",+ "destination",+ )+ .await;+ let (src_ws, src_proj) = ids(&store, "src", "proj").await;+ state.active_project.set(src_ws, src_proj);+ let prepared = store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ workspace_id: src_ws,+ project_id: src_proj,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: vec![AgentKind::Codex],+ selection: WorkstreamSelection::Current,+ lease_owner: "test".into(),+ })+ .await+ .unwrap();++ let resp = post(+ state,+ "/admin/move-project",+ json!({+ "from_workspace": "src",+ "project": "proj",+ "to_workspace": "dst",+ "confirm": true,+ "force": true+ }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::CONFLICT);+ let body = body_json(resp).await;+ assert!(+ body["error"]+ .as_str()+ .unwrap_or("")+ .contains("--force cannot delete a live managed workstream"),+ "the force boundary must be explicit: {body}"+ );+ assert_eq!(+ store+ .reader+ .find_project(src_ws, "proj".into())+ .await+ .unwrap(),+ Some(src_proj),+ "the source must remain intact"+ );+ assert!(+ store+ .reader+ .managed_run_status(prepared.run_id)+ .await+ .unwrap()+ .is_some(),+ "the managed lease row must survive"+ );+}+/// Build an AdminState over an already-open store (lets one test drive two/// routers — e.g. a move then a re-run — against the same SQLite file).fn build_state(store: &Store, tmp: &TempDir) -> AdminState {diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rsindex 598d401c..b781162b 100644--- a/crates/ai-memory-mcp/tests/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@ -9,7 +9,7 @@ use ai_memory_core::{Sanitized, Sanitizer, SessionId, Tier, WorkspaceId,};use ai_memory_mcp::{AdminState, admin_router};-use ai_memory_store::{DecayParams, Store};+use ai_memory_store::{DecayParams, PrepareWorkstreamRun, Store, WorkstreamSelection};use ai_memory_wiki::{AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig, Wiki, WritePageRequest,};@@ -309,6 +309,70 @@ async fn purge_project_deletes_data_and_files() {);}+#[tokio::test]+async fn purge_project_removes_raw_workstream_segments() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ let (workspace_id, _keep, project_id) = seed_two_projects(&store, &state.wiki).await;+ let prepared = store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ workspace_id,+ project_id,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: vec![AgentKind::Codex],+ selection: WorkstreamSelection::Current,+ lease_owner: "test".into(),+ })+ .await+ .unwrap();+ assert!(+ store+ .writer+ .cancel_managed_run(prepared.run_id)+ .await+ .unwrap()+ );+ let raw_dir = tmp+ .path()+ .join("raw/workstreams")+ .join(prepared.workstream_id.to_string());+ std::fs::create_dir_all(&raw_dir).unwrap();+ std::fs::write(raw_dir.join("000001.jsonl"), "event\n").unwrap();++ let resp = post(+ state,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "doomed", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);+ let body = body_json(resp).await;++ assert!(+ !raw_dir.exists(),+ "raw workstream directory must be removed"+ );+ assert_eq!(body["workstreams_deleted"], 1);+ assert_eq!(body["managed_runs_deleted"], 1);+ assert_eq!(+ body["workstream_ids"],+ json!([prepared.workstream_id.to_string()])+ );+ assert!(+ body["files_deleted"]+ .as_array()+ .unwrap()+ .iter()+ .any(|path| path.as_str() == Some(raw_dir.to_string_lossy().as_ref())),+ "raw cleanup must be visible in the report: {body}"+ );+}+/// A reject-policy purge webhook must be able to abort before DB rows or files/// are deleted. This guards the destructive-operation ordering.#[tokio::test]diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex e064f168..60340ba8 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -62,10 +62,9 @@ pub struct PurgeSummary {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 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.+ /// Ids of the deleted workstreams. The admin layer uses these typed,+ /// pre-delete identifiers to remove `raw/workstreams/<id>/` after the SQL+ /// transaction commits and to report any filesystem partial failure.pub workstream_ids: Vec<String>,}use jiff::Timestamp;@@ -1615,10 +1614,11 @@ pub fn purge_project(};// Same idea for the workstream segment directories: the rows go with the- // 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.+ // cascade but `raw/workstreams/<id>/` needs post-commit filesystem+ // cleanup. 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 cleanup list.let workstream_ids: Vec<String> = {let mut stmt = tx.prepare("SELECT id FROM workstreams WHERE project_id = ?1")?;let rows = stmt@@ -4237,7 +4237,7 @@ mod tests {assert_eq!(summary.workstream_ids,vec![prepared.workstream_id.to_string()],- "the orphaned raw/workstreams/<id>/ dir is reported for cleanup"+ "the raw/workstreams/<id>/ dir is reported for post-commit cleanup");}diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex e51a9786..f243c469 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. Refuses with `409` while a managed workstream under the project holds a live run lease — `--force` overrides. |+| `purge-project --confirm` | ✅ yes | the one project's data | no | Deletes the UUID-namespaced wiki root and raw workstream segments; sibling projects remain 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. |@@ -92,17 +92,17 @@ What happens, in order:4. Single `DELETE FROM projects WHERE id = ?` - the V01 + V05`ON DELETE CASCADE` foreign keys propagate to every dependenttable in one transaction.-5. `std::fs::remove_dir_all(<wiki_root>/<workspace_id>/<project_id>)`- wipes the on-disk project root.+5. Best-effort filesystem cleanup removes both the UUID-namespaced wiki root+ and every `<data_dir>/raw/workstreams/<workstream_id>/` segment directory.6. Returns a summary: `{label, pages_deleted, sessions_deleted, …,workstreams_deleted, managed_runs_deleted, workstream_ids,- files_deleted: [<project_root>], files_failed: [...]}`.+ files_deleted: [<project_root>, <raw_workstream_dir>, ...],+ 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.+`workstream_ids` remains in the report for auditability. Each corresponding+raw segment directory is removed on the server and appears in+`files_deleted`; a failed removal appears in `files_failed` alongside wiki+cleanup failures.Failure modes:@@ -269,6 +269,11 @@ deploy — the admission/git-mirror webhooks all fire), source embeddingsare carried over verbatim, and only then is the source purged(`merged_into_existing: true`, `source_purged: true`).+`--force` overrides only the hook router's active-project guard. It never+deletes a live managed-workstream lease during this destructive path; finish+or cancel that run before retrying. A true move keeps the same project and+lease ids, so it does not need this additional guard.+Copy-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 safediff --git a/docs/marker-file.md b/docs/marker-file.mdindex deac47b7..13384548 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -23,10 +23,12 @@ ai-memory or running CLI commands per directory.## Where to put it-`.ai-memory.toml` in **any ancestor** of your `cwd`. Lifecycle hooks-walk up from `cwd` toward `$HOME` (or `/` if `$HOME` is unset) and-use the **first** marker found. Closer markers override outer ones. When-a marker is found, hook scripts also forward the current `cwd` so+`.ai-memory.toml` in **any allowed ancestor** of your `cwd`. Lifecycle hooks+walk up from `cwd` toward `$HOME` (or `/` if `$HOME` is unset) and use the+**first** marker found. When cwd is outside `$HOME`, the walk stops at the+nearest checkout root (`.git` file or directory); outside a checkout, only cwd+itself is checked. Closer markers override outer ones. When a marker is found,+hook scripts also forward the current `cwd` soworkspace-only markers can still resolve `project = basename(cwd)` forhandoff lookups.@@ -383,8 +385,10 @@ hook events that arrive without a usable one.*default* can still be baked into an install without a marker via`install-hooks --project-strategy repo-root`, but that is install-timeconfig, 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.+- ❌ No reach outside the trust boundary. The walk stops at `$HOME`; a+ checkout outside it stops at that checkout's root and needs a marker inside+ the checkout. A non-git directory outside `$HOME` needs a marker in its+ exact cwd.## Troubleshootingdiff --git a/hooks/_lib.sh b/hooks/_lib.shindex 6c1d64bc..6f2d1962 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -8,16 +8,37 @@# Walk up from "$1" toward $HOME (or /) looking for `.ai-memory.toml`.# Prints the absolute path of the first marker found, or nothing.# Stops at $HOME to avoid leaking declarations from a shared system-# user's home into another user's session on multi-user boxes.+# user's home into another user's session on multi-user boxes. When cwd is+# outside HOME, stop at the nearest checkout root (`.git` file/dir); a plain+# non-git directory checks only cwd. This keeps unrelated parent markers out.ai_memory_find_marker() {dir="$1"[ -z "$dir" ] && return 0+ boundary=""+ if [ -n "${HOME:-}" ]; then+ case "$dir" in+ "$HOME"|"$HOME"/*) boundary="$HOME" ;;+ *)+ probe="$dir"+ while [ -n "$probe" ] && [ "$probe" != "/" ]; do+ if [ -e "$probe/.git" ]; then+ boundary="$probe"+ break+ fi+ parent=$(dirname "$probe")+ [ "$parent" = "$probe" ] && break+ probe="$parent"+ done+ [ -n "$boundary" ] || boundary="$dir"+ ;;+ esac+ fiwhile [ -n "$dir" ] && [ "$dir" != "/" ]; doif [ -f "$dir/.ai-memory.toml" ]; thenprintf '%s\n' "$dir/.ai-memory.toml"return 0fi- if [ -n "${HOME:-}" ] && [ "$dir" = "$HOME" ]; then+ if [ -n "$boundary" ] && [ "$dir" = "$boundary" ]; thenreturn 0fiparent=$(dirname "$dir")diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 30a24dba..b50a0ace 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -39,11 +39,34 @@ function Get-AiMemoryMarkerToml {param([string] $Cwd)if (-not $Cwd) { return $null }$dir = $Cwd+ $home = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }+ $boundary = $null+ if ($home) {+ $homePrefix = $home.TrimEnd([char[]]@('/', '\')) + [IO.Path]::DirectorySeparatorChar+ $insideHome = ($dir -eq $home) -or $dir.StartsWith(+ $homePrefix,+ [StringComparison]::OrdinalIgnoreCase+ )+ if ($insideHome) {+ $boundary = $home+ } else {+ $probe = $dir+ while ($probe -and (Test-Path $probe)) {+ if (Test-Path (Join-Path $probe ".git")) {+ $boundary = $probe+ break+ }+ $parent = Split-Path $probe -Parent+ if (-not $parent -or $parent -eq $probe) { break }+ $probe = $parent+ }+ if (-not $boundary) { $boundary = $dir }+ }+ }while ($dir -and (Test-Path $dir)) {$candidate = Join-Path $dir ".ai-memory.toml"if (Test-Path $candidate -PathType Leaf) { return $candidate }- if ($env:HOME -and $dir -eq $env:HOME) { return $null }- if ($env:USERPROFILE -and $dir -eq $env:USERPROFILE) { return $null }+ if ($boundary -and $dir -eq $boundary) { return $null }$parent = Split-Path $dir -Parentif (-not $parent -or $parent -eq $dir) { return $null }$dir = $parentdiff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 789ed09d..8c655a99 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -17,6 +17,7 @@ TMP=$(mktemp -d)ORIG_HOME=${HOME:-}HOME="$TMP"export HOME+unset AI_MEMORY_RUN_ID AI_MEMORY_MANAGED_WORKSTREAM_ID AI_MEMORY_MANAGED_WORKSTREAM_NAMEtrap 'rm -rf "$TMP"; HOME=$ORIG_HOME' EXITassert_eq() {@@ -54,6 +55,27 @@ assert_eq "walks up to find marker" "$TMP/a/.ai-memory.toml" \assert_eq "no marker returns empty" "" \"$(ai_memory_find_marker "$TMP/nonexistent/path")"+# A checkout outside HOME may inherit a marker inside its own git tree, but+# never one from an unrelated parent. A plain directory outside HOME checks+# only its exact cwd.+OUTSIDE_HOME="$TMP/account-home"+mkdir -p "$OUTSIDE_HOME" "$TMP/outside/repo/src" "$TMP/outside/plain"+printf 'workspace = "wrong"\n' >"$TMP/outside/.ai-memory.toml"+mkdir -p "$TMP/outside/repo/.git"+printf 'workspace = "right"\n' >"$TMP/outside/repo/.ai-memory.toml"+HOME="$OUTSIDE_HOME"+export HOME+assert_eq "outside HOME finds marker within checkout" \+ "$TMP/outside/repo/.ai-memory.toml" \+ "$(ai_memory_find_marker "$TMP/outside/repo/src")"+rm -f "$TMP/outside/repo/.ai-memory.toml"+assert_eq "outside HOME stops at checkout root" "" \+ "$(ai_memory_find_marker "$TMP/outside/repo/src")"+assert_eq "outside HOME plain dir rejects parent marker" "" \+ "$(ai_memory_find_marker "$TMP/outside/plain")"+HOME="$TMP"+export HOME+# --- extract_cwd ------------------------------------------------------PAYLOAD='{"session_id":"x","cwd":"/home/u/foo","tool":"Read"}'assert_eq "extract cwd from payload" "/home/u/foo" "$(ai_memory_extract_cwd "$PAYLOAD")"