Skip to content

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

Rust

fix(admin): add --project-id to purge/rename/move project

yubr-zzh7bb68d6cb6b6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c672ab4..497ad56e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -155,6 +155,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
unedited files of an earlier export in place. (#1164)
### Fixed
+- Fixed the admin project operations being unaddressable when a NAME is
+ ambiguous. `purge-project`, `rename-project` and `move-project` resolved
+ their target by name alone, so a legacy twin row whose name collides with
+ another project's `legacy_name` (the empty leftover an older migration
+ leaves behind) could not be reached: the lookup answered with whichever row
+ it found first. Each endpoint now also accepts `project_id` (a UUID) as an
+ alternative to `project`/`from`, and the CLI exposes it as `--project-id`,
+ mutually exclusive with the name flag. Sending both or neither is a 400, a
+ malformed UUID is a 400, and an id that names no row in the workspace is a
+ 404, so a foreign-scope id is refused rather than guessed at.
+ `list-projects` now prints each project's id so an operator can copy it
+ into `--project-id`. (#1208)
- Fixed the cross-project profile harvester treating pages the auto-improve
scheduler auto-approved as curated human input: model output nobody
reviewed fed the profile like a hand-written rule. A page stamped from an
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 032bb6be..40cc5ebe 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1517,8 +1517,16 @@ pub struct PurgeProjectArgs {
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)]
+ #[arg(long, conflicts_with = "project_id")]
pub project: Option<String>,
+ /// Project id (UUID) to purge, as an alternative to `--project`.
+ ///
+ /// Use this when the NAME lookup is ambiguous: a legacy row whose name
+ /// collides with another project's `legacy_name` resolves to the wrong
+ /// row, so only the id reaches the intended one. Find it in the
+ /// `list-projects` output. Mutually exclusive with `--project`.
+ #[arg(long)]
+ pub project_id: Option<String>,
/// REQUIRED for the purge to run. Without this flag the CLI errors
/// out — purging is destructive and irreversible.
///
@@ -1607,8 +1615,16 @@ pub struct RenameProjectArgs {
/// running `ai-memory rename-project --to new-name` from a dir
/// that was JUST renamed (the basename will be the new name, so
/// you'll want to pass --from explicitly in that workflow).
- #[arg(long)]
+ #[arg(long, conflicts_with = "project_id")]
pub from: Option<String>,
+ /// Project id (UUID) to rename, as an alternative to `--from`.
+ ///
+ /// Use this when the NAME lookup is ambiguous: a legacy row whose name
+ /// collides with another project's `legacy_name` resolves to the wrong
+ /// row, so only the id reaches the intended one. Find it in the
+ /// `list-projects` output. Mutually exclusive with `--from`.
+ #[arg(long)]
+ pub project_id: Option<String>,
/// New project name. Must be non-empty and contain no slashes.
#[arg(long)]
pub to: String,
@@ -1624,8 +1640,16 @@ pub struct MoveProjectArgs {
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)]
+ #[arg(long, conflicts_with = "project_id")]
pub project: Option<String>,
+ /// Project id (UUID) to move, as an alternative to `--project`.
+ ///
+ /// Use this when the NAME lookup is ambiguous: a legacy row whose name
+ /// collides with another project's `legacy_name` resolves to the wrong
+ /// row, so only the id reaches the intended one. Find it in the
+ /// `list-projects` output. Mutually exclusive with `--project`.
+ #[arg(long)]
+ pub project_id: Option<String>,
/// Destination workspace. Auto-created if it doesn't exist.
#[arg(long)]
pub to_workspace: String,
@@ -4845,4 +4869,89 @@ mod tests {
assert_eq!(args.version.as_deref(), Some("v2.3.2"));
assert!(args.force);
}
+
+ /// #1208: each destructive project op takes `--project-id` as an
+ /// alternative to its name flag, and the two are mutually exclusive so an
+ /// ambiguous request never reaches the server to be guessed at.
+ #[test]
+ fn project_id_flags_parse_and_conflict_with_their_name_flags() {
+ let id = "11111111-2222-3333-4444-555555555555";
+
+ let cli = Cli::try_parse_from(["ai-memory", "purge-project", "--project-id", id]).unwrap();
+ let Command::PurgeProject(args) = cli.command else {
+ panic!("expected purge-project");
+ };
+ assert_eq!(args.project_id.as_deref(), Some(id));
+ assert!(args.project.is_none());
+ assert!(
+ Cli::try_parse_from([
+ "ai-memory",
+ "purge-project",
+ "--project",
+ "doomed",
+ "--project-id",
+ id,
+ ])
+ .is_err(),
+ "--project and --project-id must not both be accepted"
+ );
+
+ let cli = Cli::try_parse_from([
+ "ai-memory",
+ "rename-project",
+ "--project-id",
+ id,
+ "--to",
+ "new",
+ ])
+ .unwrap();
+ let Command::RenameProject(args) = cli.command else {
+ panic!("expected rename-project");
+ };
+ assert_eq!(args.project_id.as_deref(), Some(id));
+ assert!(args.from.is_none());
+ assert!(
+ Cli::try_parse_from([
+ "ai-memory",
+ "rename-project",
+ "--from",
+ "old",
+ "--project-id",
+ id,
+ "--to",
+ "new",
+ ])
+ .is_err(),
+ "--from and --project-id must not both be accepted"
+ );
+
+ let cli = Cli::try_parse_from([
+ "ai-memory",
+ "move-project",
+ "--project-id",
+ id,
+ "--to-workspace",
+ "elsewhere",
+ ])
+ .unwrap();
+ let Command::MoveProject(args) = cli.command else {
+ panic!("expected move-project");
+ };
+ assert_eq!(args.project_id.as_deref(), Some(id));
+ assert!(args.project.is_none());
+ assert!(
+ Cli::try_parse_from([
+ "ai-memory",
+ "move-project",
+ "--project",
+ "movable",
+ "--project-id",
+ id,
+ "--to-workspace",
+ "elsewhere",
+ ])
+ .is_err(),
+ "--project and --project-id must not both be accepted"
+ );
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/list_projects.rs b/crates/ai-memory-cli/src/commands/list_projects.rs
index e39cbc34..007d750e 100644
--- a/crates/ai-memory-cli/src/commands/list_projects.rs
+++ b/crates/ai-memory-cli/src/commands/list_projects.rs
@@ -60,16 +60,26 @@ fn render_human(rows: &[ProjectRow]) -> String {
.max()
.unwrap_or(0)
.max("PROJECT".len());
+ // The id column carries what `--project-id` takes. A row from an older
+ // server has no id; render `-` rather than hiding the column, so the
+ // header stays stable across server versions. (#1208)
+ let id_width = rows
+ .iter()
+ .map(|row| row.project_id.as_deref().unwrap_or("-").len())
+ .max()
+ .unwrap_or(0)
+ .max("PROJECT ID".len());
let mut out = format!(
- "{:workspace_width$} {:project_width$} {:>6} LAST UPDATED\n",
- "WORKSPACE", "PROJECT", "PAGES"
+ "{:workspace_width$} {:project_width$} {:id_width$} {:>6} LAST UPDATED\n",
+ "WORKSPACE", "PROJECT", "PROJECT ID", "PAGES"
);
for row in rows {
out += &format!(
- "{:workspace_width$} {:project_width$} {:>6} {}\n",
+ "{:workspace_width$} {:project_width$} {:id_width$} {:>6} {}\n",
row.workspace_name,
row.project_name,
+ row.project_id.as_deref().unwrap_or("-"),
row.page_count,
row.last_updated.as_deref().unwrap_or("-")
);
@@ -83,13 +93,49 @@ mod tests {
fn row(workspace: &str, project: &str, pages: u64, last_updated: Option<&str>) -> ProjectRow {
ProjectRow {
+ workspace_id: Some(format!("{workspace}-id")),
workspace_name: workspace.to_owned(),
+ project_id: Some(format!("{project}-id")),
project_name: project.to_owned(),
page_count: pages,
last_updated: last_updated.map(str::to_owned),
}
}
+ /// The id column is what makes `--project-id` usable: the operator reads
+ /// the UUID here and passes it to the destructive admin commands. (#1208)
+ #[test]
+ fn render_human_includes_the_project_id_needed_by_project_id_flags() {
+ let rows = vec![row("default", "acme-api", 12, None)];
+ let out = render_human(&rows);
+ assert!(out.contains("PROJECT ID"), "{out}");
+ assert!(
+ out.contains("acme-api-id"),
+ "the id is what an operator passes to --project-id: {out}"
+ );
+ }
+
+ /// A row from a server that predates the id fields still renders: the
+ /// column shows `-` instead of collapsing or panicking.
+ #[test]
+ fn render_human_shows_a_dash_for_a_row_from_an_older_server() {
+ let rows = vec![ProjectRow {
+ workspace_id: None,
+ workspace_name: "default".to_owned(),
+ project_id: None,
+ project_name: "legacy".to_owned(),
+ page_count: 1,
+ last_updated: None,
+ }];
+ let out = render_human(&rows);
+ let data_line = out.lines().nth(1).expect("one data line");
+ assert!(data_line.contains("legacy"), "{data_line}");
+ assert!(
+ data_line.matches(" - ").count() >= 1,
+ "a missing id renders as a dash, not an empty column: {data_line}"
+ );
+ }
+
#[test]
fn render_human_reports_an_empty_server() {
assert_eq!(render_human(&[]), "No projects found.\n");
diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rs
index 96bc697c..e99918a7 100644
--- a/crates/ai-memory-cli/src/commands/move_project.rs
+++ b/crates/ai-memory-cli/src/commands/move_project.rs
@@ -11,7 +11,14 @@ use crate::http_client::{ServerEndpoint, post_json};
#[derive(Serialize)]
struct MoveProjectRequest {
from_workspace: String,
- project: String,
+ /// Exactly one of `project` / `project_id` is `Some`. `--project-id`
+ /// bypasses the server's name/legacy/canonical lookup, which is the point:
+ /// a legacy row whose name collides with another project's `legacy_name`
+ /// is otherwise unreachable by name. (#1208)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ project: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ project_id: Option<String>,
to_workspace: String,
confirm: bool,
force: bool,
@@ -21,19 +28,41 @@ struct MoveProjectRequest {
/// Run the `move-project` subcommand.
///
/// Resolves the source project name (auto-derived from the git repo root
-/// when `--project` is omitted), requires `--confirm` before sending the
-/// request (a true-move re-stamp or a copy+purge merge, both irreversible),
-/// then prints the report.
+/// when `--project` is omitted) -- or, when `--project-id` is given, skips
+/// name resolution and moves that id directly, the only way to reach a legacy
+/// row whose name is shadowed by another project's `legacy_name` -- requires
+/// `--confirm` before sending the request (a true-move re-stamp or a
+/// copy+purge merge, both irreversible), then prints the report.
///
/// # Errors
/// 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 (from_workspace, project) = super::resolve_scope(
- config,
- args.from_workspace.as_deref(),
- args.project.as_deref(),
- )?;
+ let (from_workspace, project, project_id) = match args.project_id {
+ Some(id) => (
+ super::resolve_workspace(config, args.from_workspace.as_deref())?,
+ None,
+ Some(id),
+ ),
+ None => {
+ let (ws, project) = super::resolve_scope(
+ config,
+ args.from_workspace.as_deref(),
+ args.project.as_deref(),
+ )?;
+ (ws, Some(project), None)
+ }
+ };
+ let target_flag = match (&project, &project_id) {
+ (Some(project), _) => format!("--project {project}"),
+ (None, Some(id)) => format!("--project-id {id}"),
+ (None, None) => unreachable!("clap requires one of --project/--project-id"),
+ };
+ let target_label = match (&project, &project_id) {
+ (Some(project), _) => project.clone(),
+ (None, Some(id)) => id.clone(),
+ (None, None) => unreachable!("clap requires one of --project/--project-id"),
+ };
if !args.confirm {
bail!(
@@ -43,13 +72,13 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
already has one, the pages are copied in and merged, then the \
source is PURGED. Both are irreversible.\n\
Re-run with --confirm to proceed:\n\n \
- ai-memory move-project --from-workspace {} --project {} \
+ ai-memory move-project --from-workspace {} {} \
--to-workspace {} --confirm",
from_workspace,
- project,
+ target_flag,
args.to_workspace,
from_workspace,
- project,
+ target_flag,
args.to_workspace,
);
}
@@ -61,6 +90,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
&MoveProjectRequest {
from_workspace: from_workspace.clone(),
project: project.clone(),
+ project_id: project_id.clone(),
to_workspace: args.to_workspace.clone(),
confirm: true,
force: args.force,
@@ -82,9 +112,9 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
config,
&endpoint,
&from_workspace,
- &project,
+ &target_label,
&args.to_workspace,
- &project,
+ &target_label,
)
{
eprintln!(
@@ -97,7 +127,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
println!(
"Moved {}/{} → {}/{}: {pages} pages re-stamped (true move — \
sessions, observations and history preserved).",
- from_workspace, project, args.to_workspace, project,
+ from_workspace, target_label, args.to_workspace, target_label,
);
} else {
// copy-purge (merge into an existing same-named project).
@@ -111,7 +141,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
println!(
"Moved {}/{} → {}/{}: {pages} pages copied (merged into existing \
project){tail}.",
- from_workspace, project, args.to_workspace, project,
+ from_workspace, target_label, args.to_workspace, target_label,
);
if skipped_count > 0 {
println!(
diff --git a/crates/ai-memory-cli/src/commands/purge_project.rs b/crates/ai-memory-cli/src/commands/purge_project.rs
index 91f31890..40d5ebeb 100644
--- a/crates/ai-memory-cli/src/commands/purge_project.rs
+++ b/crates/ai-memory-cli/src/commands/purge_project.rs
@@ -12,7 +12,16 @@ use crate::http_client::{ServerEndpoint, post_json};
#[derive(Serialize)]
struct PurgeProjectRequest {
workspace: String,
- project: String,
+ /// Exactly one of `project` / `project_id` is `Some`; the other is omitted
+ /// from the wire so an older server's `project: String` still sees what it
+ /// expects when the operator used the name form. (#1208)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ project: Option<String>,
+ /// Set instead of `project` when the operator passed `--project-id`: the
+ /// server resolves the row by id, bypassing the name/legacy/canonical
+ /// lookup that a collision would otherwise send to the wrong row. (#1208)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ project_id: Option<String>,
confirm: bool,
/// Purge even when a managed workstream still holds a live run lease.
force: bool,
@@ -88,8 +97,11 @@ fn preview_message(outcome: &PreviewOutcome, fallback_label: &str) -> Option<Str
/// Run the `purge-project` subcommand.
///
/// Resolves the project name (auto-derived from the git repo root when
-/// `--project` is omitted), requires `--confirm` before sending the
-/// destructive request, then prints the JSON summary.
+/// `--project` is omitted) -- or, when `--project-id` is given, skips name
+/// resolution and targets that id directly, which is the only way to reach a
+/// legacy row whose name is shadowed by another project's `legacy_name` --
+/// requires `--confirm` before sending the destructive request, then prints
+/// the JSON summary.
///
/// Without `--confirm`, first asks the server for a preview (`dry_run:
/// true`, which wins over `confirm` server-side): the server reports the
@@ -110,29 +122,58 @@ fn preview_message(outcome: &PreviewOutcome, fallback_label: &str) -> Option<Str
/// preview surfaced), the server is unreachable, or the server returns a
/// non-2xx response.
pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
- let (workspace, project) =
- super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
+ // An id target skips name resolution entirely: `resolve_scope` would
+ // auto-derive a project name from the CWD, which is exactly the ambiguity
+ // `--project-id` exists to sidestep. The workspace still resolves the
+ // normal way (marker, else `default`), since the server needs it to scope
+ // the id lookup.
+ let (workspace, project, project_id) = match args.project_id {
+ Some(id) => (
+ super::resolve_workspace(config, args.workspace.as_deref())?,
+ None,
+ Some(id),
+ ),
+ None => {
+ let (ws, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
+ (ws, Some(project), None)
+ }
+ };
+ // The flag that names the target, for the refusal's "re-run with" line and
+ // the preview's fallback label. A `--project-id` run has no resolved name
+ // to print, so the id stands in.
+ let target_flag = match (&project, &project_id) {
+ (Some(project), _) => format!("--project {project}"),
+ (None, Some(id)) => format!("--project-id {id}"),
+ (None, None) => unreachable!("clap requires one of --project/--project-id"),
+ };
+ let target_label = match (&project, &project_id) {
+ (Some(project), _) => project.clone(),
+ (None, Some(id)) => id.clone(),
+ (None, None) => unreachable!("clap requires one of --project/--project-id"),
+ };
if !args.confirm {
let request = PurgeProjectRequest {
workspace: workspace.clone(),
project: project.clone(),
+ project_id: project_id.clone(),
confirm: false,
force: args.force,
compact: args.compact,
dry_run: true,
};
let outcome = run_preview(config, "/admin/purge-project", &request).await;
- let fallback_label = format!("{}/{}", workspace, project);
+ let fallback_label = format!("{}/{}", workspace, target_label);
if let Some(line) = preview_message(&outcome, &fallback_label) {
println!("{line}");
}
bail!(
"purge-project is destructive and irreversible.\n\
Re-run with --confirm to proceed:\n\n \
- ai-memory purge-project --workspace {} --project {} --confirm",
+ ai-memory purge-project --workspace {} {} --confirm",
workspace,
- project,
+ target_flag,
);
}
@@ -143,6 +184,7 @@ pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
&PurgeProjectRequest {
workspace: workspace.clone(),
project: project.clone(),
+ project_id: project_id.clone(),
confirm: true,
force: args.force,
compact: args.compact,
@@ -152,7 +194,7 @@ pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
.await?;
// Human-friendly one-liner followed by the raw JSON for scripting.
- let fallback_label = format!("{}/{}", workspace, project);
+ let fallback_label = format!("{}/{}", workspace, target_label);
let label = report["label"].as_str().unwrap_or(&fallback_label);
println!("{}", purge_summary_line("Purged", label, &report));
if let Some(ids) = report["workstream_ids"].as_array()
@@ -360,7 +402,8 @@ mod tests {
fn preview_request() -> PurgeProjectRequest {
PurgeProjectRequest {
workspace: "default".into(),
- project: "scratch".into(),
+ project: Some("scratch".into()),
+ project_id: None,
confirm: false,
force: false,
compact: false,
diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rs
index be47d4dc..3536eb1a 100644
--- a/crates/ai-memory-cli/src/commands/rename_project.rs
+++ b/crates/ai-memory-cli/src/commands/rename_project.rs
@@ -9,8 +9,11 @@ use crate::http_client::{ServerEndpoint, post_json};
/// Run the `rename-project` subcommand.
///
/// Resolves the current project name (auto-derived from the git repo root
-/// when `--from` is omitted), sends the rename request to the server, then
-/// prints a human-readable confirmation line.
+/// when `--from` is omitted) -- or, when `--project-id` is given, skips name
+/// resolution and renames that id directly, which is the only way to reach a
+/// legacy row whose name is shadowed by another project's `legacy_name` --
+/// sends the rename request to the server, then prints a human-readable
+/// confirmation line.
///
/// # Errors
/// Returns an error when the server is unreachable or returns a non-2xx
@@ -20,11 +23,31 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
// 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 (workspace, from, project_id) = match args.project_id {
+ Some(id) => (
+ super::resolve_workspace(config, args.workspace.as_deref())?,
+ None,
+ Some(id),
+ ),
+ None => {
+ let (ws, from) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.from.as_deref())?;
+ (ws, Some(from), None)
+ }
+ };
+ // What the report and the client-local rekey name as the source. With
+ // `--project-id` this is the id itself: the old name is only known to the
+ // server, and a wrong name in the local rekey would miss the link it was
+ // supposed to move.
+ let target_label = match (&from, &project_id) {
+ (Some(from), _) => from.clone(),
+ (None, Some(id)) => id.clone(),
+ (None, None) => unreachable!("clap requires one of --from/--project-id"),
+ };
let body = serde_json::json!({
"workspace": workspace,
"from": from,
+ "project_id": project_id,
"to": args.to,
});
let summary: serde_json::Value = post_json(&endpoint, "/admin/rename-project", &body).await?;
@@ -33,7 +56,12 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
eprintln!("ai-memory: warning: {warning}");
}
if let Err(error) = super::project_registry::rekey_scope(
- config, &endpoint, &workspace, &from, &workspace, &args.to,
+ config,
+ &endpoint,
+ &workspace,
+ &target_label,
+ &workspace,
+ &args.to,
) {
eprintln!(
"ai-memory: project renamed, but the client-local checkout link could not be updated ({error:#})"
@@ -41,7 +69,7 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
}
println!(
"Renamed {}/{} → {}/{} ({} pages now under the new name).",
- workspace, from, workspace, args.to, pages
+ workspace, target_label, workspace, args.to, pages
);
Ok(())
}
diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rs
index 111af70e..0c683465 100644
--- a/crates/ai-memory-cli/src/commands/show.rs
+++ b/crates/ai-memory-cli/src/commands/show.rs
@@ -52,7 +52,16 @@ const NEW_PROJECT_LABEL: &str = "+ New project";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ProjectRow {
+ /// Workspace id, when the server sent one. `Option` so an older server
+ /// that predates these fields still deserializes (they are additive on
+ /// the wire). (#1208)
+ #[serde(default)]
+ pub(crate) workspace_id: Option<String>,
pub(crate) workspace_name: String,
+ /// Project id, the ambiguous-name escape hatch an operator can pass to
+ /// `--project-id` on the destructive admin commands. (#1208)
+ #[serde(default)]
+ pub(crate) project_id: Option<String>,
pub(crate) project_name: String,
pub(crate) page_count: u64,
pub(crate) last_updated: Option<String>,
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index cc8d9ca8..f6728d76 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1996,6 +1996,67 @@ async fn lookup_ws_no_create(
.map_err(scope_err)
}
+/// Resolve the `(workspace_id, project_id)` pair for an admin operation from
+/// either a project name (the historic path) or a project id (the new
+/// `#1208` path). Exactly one of `project_name` and `project_id` must be
+/// `Some`; sending both or neither is a 400. When `project_id` is `Some`,
+/// the workspace is resolved by name (still 404 if absent) and the project
+/// is looked up by id within the workspace (404 on miss, so a foreign-scope
+/// id is correctly refused). The bad-UUID case is a 400, mirroring how
+/// `lookup_ws_proj_no_create` already maps unparseable names to 400.
+async fn resolve_target_for_admin(
+ state: &AdminState,
+ workspace: &str,
+ project_name: Option<&str>,
+ project_id: Option<&str>,
+) -> Result<(WorkspaceId, ProjectId), (StatusCode, Json<serde_json::Value>)> {
+ match (project_name, project_id) {
+ (Some(_), Some(_)) => Err((
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "project and project_id are mutually exclusive"
+ })),
+ )),
+ (None, None) => Err((
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "either project or project_id is required"
+ })),
+ )),
+ (Some(name), None) => lookup_ws_proj_no_create(state, workspace, name).await,
+ (None, Some(id_str)) => {
+ let parsed = match id_str.parse::<ProjectId>() {
+ Ok(p) => p,
+ Err(e) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": format!("invalid project id: {e}")
+ })),
+ ));
+ }
+ };
+ let ws_id = match lookup_ws_no_create(state, workspace).await {
+ Ok(ws) => ws,
+ Err(e) => return Err(e),
+ };
+ match state.reader.project_name_by_id(ws_id, parsed).await {
+ Ok(Some(_)) => Ok((ws_id, parsed)),
+ Ok(None) => Err((
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({
+ "error": "project not found in workspace"
+ })),
+ )),
+ Err(e) => Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ )),
+ }
+ }
+ }
+}
+
fn with_manifest_warning(
(status, Json(mut body)): (StatusCode, Json<serde_json::Value>),
warning: Option<&ai_memory_core::repository_identity::ManifestWarning>,
@@ -4747,7 +4808,16 @@ struct PurgeProjectRequest {
/// Workspace name. The workspace must already exist; we 404 if absent.
workspace: String,
/// Project name. The project must already exist; we 404 if absent.
- project: String,
+ /// Mutually exclusive with `project_id`; the CLI sends whichever the
+ /// operator chose and leaves the other `None`. (#1208)
+ #[serde(default)]
+ project: Option<String>,
+ /// Project id (UUID string). Bypasses the name/legacy/canonical lookup
+ /// and targets the row directly, so an operator can disambiguate a name
+ /// collision. Server returns 400 on bad UUID parse, 404 on unknown id or
+ /// foreign-scope id. (#1208)
+ #[serde(default)]
+ project_id: Option<String>,
/// Mandatory confirmation flag. Without `confirm: true` the server
/// returns 400 — purging is destructive and irreversible.
confirm: bool,
@@ -4933,13 +5003,29 @@ async fn handle_purge_project(
}
// Look up workspace and project IDs without auto-creating.
- let (ws_id, proj_id) =
- match lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await {
- Ok(ids) => ids,
- Err(e) => return e,
- };
+ let (ws_id, proj_id) = match resolve_target_for_admin(
+ &state,
+ &req.workspace,
+ req.project.as_deref(),
+ req.project_id.as_deref(),
+ )
+ .await
+ {
+ Ok(ids) => ids,
+ Err(e) => return e,
+ };
+ // Look up the project name after resolving by id, so display labels and
+ // admission contexts can carry it regardless of whether the operator
+ // reached us via `project = "<name>"` or `project_id = "<uuid>"`. (#1208)
+ let project_name: String = state
+ .reader
+ .project_name_by_id(ws_id, proj_id)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| proj_id.to_string());
- let label = format!("{}/{}", req.workspace, req.project);
+ let label = format!("{}/{}", req.workspace, project_name);
// Admission must run before any destructive work. A reject-policy webhook
// is allowed to abort the purge while DB rows and files are still intact.
@@ -4952,7 +5038,7 @@ async fn handle_purge_project(
.unwrap_or_else(ai_memory_core::ActorContext::anonymous);
let purge_ctx = AdmissionContext {
workspace: req.workspace.clone(),
- project: req.project.clone(),
+ project: project_name.clone(),
op: AdmissionOp::PurgeProject,
actor,
..Default::default()
@@ -5092,13 +5178,29 @@ async fn purge_project_preview(
req: &PurgeProjectRequest,
author_id: Option<ai_memory_core::UserId>,
) -> (StatusCode, Json<serde_json::Value>) {
- let (ws_id, proj_id) = match lookup_ws_proj_no_create(state, &req.workspace, &req.project).await
+ let (ws_id, proj_id) = match resolve_target_for_admin(
+ state,
+ &req.workspace,
+ req.project.as_deref(),
+ req.project_id.as_deref(),
+ )
+ .await
{
Ok(ids) => ids,
Err(e) => return e,
};
+ // Look up the project name after resolving by id, so display labels and
+ // admission contexts can carry it regardless of whether the operator
+ // reached us via `project = "<name>"` or `project_id = "<uuid>"`. (#1208)
+ let project_name: String = state
+ .reader
+ .project_name_by_id(ws_id, proj_id)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| proj_id.to_string());
- let label = format!("{}/{}", req.workspace, req.project);
+ let label = format!("{}/{}", req.workspace, project_name);
let summary = match state
.writer
@@ -5724,8 +5826,16 @@ async fn delete_workspace_preview(
struct RenameProjectRequest {
/// Workspace name (must exist; we don't auto-create on rename).
workspace: String,
- /// Current project name.
- from: String,
+ /// Current project name. Mutually exclusive with `project_id`; the CLI
+ /// sends whichever the operator chose and leaves the other `None`.
+ /// (#1208)
+ #[serde(default)]
+ from: Option<String>,
+ /// Project id (UUID string). Bypasses the name/legacy/canonical lookup
+ /// and targets the row directly. Same contract as
+ /// `PurgeProjectRequest::project_id`. (#1208)
+ #[serde(default)]
+ project_id: Option<String>,
/// New project name. Must be non-empty, no slashes.
to: String,
}
@@ -5757,10 +5867,27 @@ async fn handle_rename_project(
) -> impl IntoResponse {
let author_id = author_ext.map(|axum::Extension(u)| u);
// Look up workspace + source project; 404 if either is absent.
- let (ws_id, proj_id) = match lookup_ws_proj_no_create(&state, &req.workspace, &req.from).await {
+ let (ws_id, proj_id) = match resolve_target_for_admin(
+ &state,
+ &req.workspace,
+ req.from.as_deref(),
+ req.project_id.as_deref(),
+ )
+ .await
+ {
Ok(ids) => ids,
Err(e) => return e,
};
+ // Look up the project name after resolving by id, so display labels and
+ // admission contexts can carry it regardless of whether the operator
+ // reached us via `from = "<name>"` or `project_id = "<uuid>"`. (#1208)
+ let project_name: String = state
+ .reader
+ .project_name_by_id(ws_id, proj_id)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| proj_id.to_string());
// Step 3: execute the rename. The writer validates the name and
// returns ProjectNameTaken / InvalidProjectName on conflicts. A
@@ -5827,7 +5954,7 @@ async fn handle_rename_project(
};
let summary = RenameProjectSummary {
workspace: req.workspace.clone(),
- from: req.from.clone(),
+ from: project_name.clone(),
to: req.to.clone(),
pages,
checkpoint,
@@ -5849,7 +5976,14 @@ struct MoveProjectRequest {
/// Source workspace. Must already exist; we 404 if absent.
from_workspace: String,
/// Project name to move. Must already exist in `from_workspace`; 404 if absent.
- project: String,
+ /// Mutually exclusive with `project_id`; the CLI sends whichever the
+ /// operator chose and leaves the other `None`. (#1208)
+ #[serde(default)]
+ project: Option<String>,
+ /// Project id (UUID string) in the source workspace. Bypasses the
+ /// name/legacy/canonical lookup and targets the row directly. (#1208)
+ #[serde(default)]
+ project_id: Option<String>,
/// Destination workspace. Auto-created if absent.
to_workspace: String,
/// Mandatory confirmation flag. The move PURGES the source after
@@ -5971,6 +6105,7 @@ type MoveErr = (StatusCode, Json<serde_json::Value>);
async fn true_move_project(
state: &Arc<AdminState>,
req: &MoveProjectRequest,
+ project_name: &str,
src_ws: WorkspaceId,
src_proj: ProjectId,
pre_checkpoint: Option<String>,
@@ -6014,9 +6149,9 @@ async fn true_move_project(
let move_ctx = AdmissionContext {
workspace: req.from_workspace.clone(),
- project: req.project.clone(),
+ project: project_name.to_string(),
destination_workspace: Some(req.to_workspace.clone()),
- destination_project: Some(req.project.clone()),
+ destination_project: Some(project_name.to_string()),
op: AdmissionOp::MoveProject,
actor,
..Default::default()
@@ -6066,13 +6201,13 @@ async fn true_move_project(
&state.wiki,
format!(
"move-project {}/{} -> {}/{}",
- req.from_workspace, req.project, req.to_workspace, req.project
+ req.from_workspace, project_name, req.to_workspace, project_name
),
);
let report = MoveProjectReport {
- from: format!("{}/{}", req.from_workspace, req.project),
- to: format!("{}/{}", req.to_workspace, req.project),
+ from: format!("{}/{}", req.from_workspace, project_name),
+ to: format!("{}/{}", req.to_workspace, project_name),
merged_into_existing: false,
moved_via: "true-move",
pages_copied: summary.pages_moved,
@@ -6293,9 +6428,10 @@ async fn move_project_core(
// A private profile is found as `default/_profile.<user id>`; moving it to
// another workspace would orphan it. (A workspace `_profile` may move with
// its workspace: it lands in, or merges into, the target's own profile.)
- if req
- .project
- .starts_with(ai_memory_core::profile::USER_PROFILE_PROJECT_PREFIX)
+ // Checked on the requested NAME first so a nonexistent profile project is
+ // still refused as 422 rather than surfacing the lookup's 404.
+ if let Some(name) = req.project.as_deref()
+ && name.starts_with(ai_memory_core::profile::USER_PROFILE_PROJECT_PREFIX)
{
return Err((
StatusCode::UNPROCESSABLE_ENTITY,
@@ -6306,8 +6442,38 @@ async fn move_project_core(
}
// Resolve the SOURCE without auto-creating — 404 on a typo.
- let (src_ws, src_proj) =
- lookup_ws_proj_no_create(state, &req.from_workspace, &req.project).await?;
+ let (src_ws, src_proj) = match resolve_target_for_admin(
+ state,
+ &req.from_workspace,
+ req.project.as_deref(),
+ req.project_id.as_deref(),
+ )
+ .await
+ {
+ Ok(ids) => ids,
+ Err(e) => return Err(MoveErr::from(e)),
+ };
+ // Look up the project name after resolving by id, so display labels and
+ // admission contexts can carry it regardless of whether the operator
+ // reached us via `project = "<name>"` or `project_id = "<uuid>"`. (#1208)
+ let project_name: String = state
+ .reader
+ .project_name_by_id(src_ws, src_proj)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| src_proj.to_string());
+
+ // Same guard on the RESOLVED name, so the `project_id` path (which has no
+ // name to inspect up front) is refused identically.
+ if project_name.starts_with(ai_memory_core::profile::USER_PROFILE_PROJECT_PREFIX) {
+ return Err((
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({
+ "error": "a private cross-project profile stays in the default workspace and cannot be moved"
+ })),
+ ));
+ }
// Live-session guard: refuse to move the project the hook router is
// currently writing to. A live session's next observation/log would carry
@@ -6321,7 +6487,7 @@ async fn move_project_core(
"error": format!(
"{}/{} is the active session's project; a live move risks stale-cache writes. \
Re-run with force=true to proceed.",
- req.from_workspace, req.project
+ req.from_workspace, project_name
)
})),
));
@@ -6330,7 +6496,7 @@ async fn move_project_core(
// Detect MERGE: does the destination workspace already hold a same-named
// project? (find_workspace may be None when the dest ws doesn't exist yet.)
let merged_into_existing =
- match lookup_existing_scope(&state.reader, &req.to_workspace, &req.project).await {
+ match lookup_existing_scope(&state.reader, &req.to_workspace, &project_name).await {
Ok(_) => true,
Err(error) if error.is_not_found() => false,
Err(error) => return Err(scope_err(error)),
@@ -6340,7 +6506,7 @@ async fn move_project_core(
&state.wiki,
format!(
"pre-move-project {}/{} -> {}/{}",
- req.from_workspace, req.project, req.to_workspace, req.project
+ req.from_workspace, project_name, req.to_workspace, project_name
),
)?;
@@ -6353,19 +6519,29 @@ async fn move_project_core(
// case, where two project_ids can't be re-stamped into one
// (UNIQUE(workspace_id, name) collision).
if !merged_into_existing {
- return true_move_project(state, req, src_ws, src_proj, pre_checkpoint, actor).await;
+ return true_move_project(
+ state,
+ req,
+ &project_name,
+ src_ws,
+ src_proj,
+ pre_checkpoint,
+ actor,
+ )
+ .await;
}
// MERGE: the destination already holds a same-named project. Get-or-create
// it (auto-creating the destination workspace) and copy the source's
// latest pages into it, then purge the source.
- let destination = create_ws_proj(state, &req.to_workspace, &req.project).await?;
+ let destination = create_ws_proj(state, &req.to_workspace, &project_name).await?;
let (dst_ws, dst_proj) = destination.scope.as_tuple();
let warning = destination.manifest_warning;
copy_purge_merge(
state,
req,
+ &project_name,
src_ws,
src_proj,
dst_ws,
@@ -7286,9 +7462,18 @@ struct PreparedSourcePage {
/// its path collides with a different page at the destination. Both
/// the `Block` pre-check and the copy loop drive off the returned
/// vector, so each page is read at most once.
+///
+/// The argument list mirrors one prepared row: the request (for its
+/// workspace name), the resolved `project_name` (which may differ from
+/// `req.project` when the operator targeted `project_id` instead), the
+/// source scope to read from, and the destination scope to compare
+/// against. Splitting it into a struct would only move the same fields
+/// one level down. (#1208)
+#[allow(clippy::too_many_arguments)]
async fn prepare_source_pages(
state: &AdminState,
req: &MoveProjectRequest,
+ project_name: &str,
src_ws: WorkspaceId,
src_proj: ProjectId,
dst_ws: WorkspaceId,
@@ -7313,7 +7498,10 @@ async fn prepare_source_pages(
};
let tier: Tier = s.tier.parse().unwrap_or(Tier::Semantic);
let pinned = matches!(
- state.reader.page_meta(&req.from_workspace, &req.project, &s.path).await,
+ state
+ .reader
+ .page_meta(&req.from_workspace, project_name, &s.path)
+ .await,
Ok(Some(ref m)) if m.pinned
);
let md = state.wiki.read_page(src_ws, src_proj, &path).ok();
@@ -7360,6 +7548,7 @@ async fn prepare_source_pages(
async fn copy_purge_merge(
state: &AdminState,
req: &MoveProjectRequest,
+ project_name: &str,
src_ws: WorkspaceId,
src_proj: ProjectId,
dst_ws: WorkspaceId,
@@ -7371,7 +7560,7 @@ async fn copy_purge_merge(
// Enumerate the source's latest pages (authoritative on is_latest).
let summaries = match state
.reader
- .list_pages(&req.from_workspace, &req.project)
+ .list_pages(&req.from_workspace, project_name)
.await
{
Ok(s) => s,
@@ -7381,8 +7570,17 @@ async fn copy_purge_merge(
// Single pass over the source: load each page's metadata + body
// AND classify the destination conflict, so the block pre-check
// and the copy loop don't re-query the same rows.
- let prepared =
- prepare_source_pages(state, req, src_ws, src_proj, dst_ws, dst_proj, &summaries).await;
+ let prepared = prepare_source_pages(
+ state,
+ req,
+ project_name,
+ src_ws,
+ src_proj,
+ dst_ws,
+ dst_proj,
+ &summaries,
+ )
+ .await;
// Under the default `block` policy, abort the WHOLE move now —
// before anything is copied — so the source stays intact and the
@@ -7580,12 +7778,12 @@ async fn copy_purge_merge(
&state.wiki,
format!(
"move-project-partial {}/{} -> {}/{}",
- req.from_workspace, req.project, req.to_workspace, req.project
+ req.from_workspace, project_name, req.to_workspace, project_name
),
);
let report = MoveProjectReport {
- from: format!("{}/{}", req.from_workspace, req.project),
- to: format!("{}/{}", req.to_workspace, req.project),
+ from: format!("{}/{}", req.from_workspace, project_name),
+ to: format!("{}/{}", req.to_workspace, project_name),
// copy_purge_merge is only reached from the merge branch
// of handle_move_project; the destination project pre-existed.
merged_into_existing: true,
@@ -7615,10 +7813,10 @@ async fn copy_purge_merge(
// source is intact (mirrors `handle_purge_project`'s ordering). The
// previous version called `Wiki::purge_project` AFTER `writer.purge_project`,
// which ran admit AFTER the rows were gone — reject came too late.
- let label = format!("{}/{}", req.from_workspace, req.project);
+ let label = format!("{}/{}", req.from_workspace, project_name);
let purge_ctx = AdmissionContext {
workspace: req.from_workspace.clone(),
- project: req.project.clone(),
+ project: project_name.to_string(),
op: AdmissionOp::PurgeProject,
actor,
..Default::default()
@@ -7668,7 +7866,7 @@ async fn copy_purge_merge(
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,
+ req.to_workspace, project_name,
)
})),
));
@@ -7711,13 +7909,13 @@ async fn copy_purge_merge(
&state.wiki,
format!(
"move-project {}/{} -> {}/{}",
- req.from_workspace, req.project, req.to_workspace, req.project
+ req.from_workspace, project_name, req.to_workspace, project_name
),
);
let report = MoveProjectReport {
from: label,
- to: format!("{}/{}", req.to_workspace, req.project),
+ to: format!("{}/{}", req.to_workspace, project_name),
// copy_purge_merge is only reached from the merge branch.
merged_into_existing: true,
moved_via: "copy-purge",
@@ -7837,7 +8035,8 @@ async fn handle_merge_workspace(
for p in &projects {
let move_req = MoveProjectRequest {
from_workspace: req.from.clone(),
- project: p.project_name.clone(),
+ project: Some(p.project_name.clone()),
+ project_id: None,
to_workspace: req.to.clone(),
confirm: true,
force: req.force,
diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rs
index ffa442cb..7493268b 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs
@@ -3081,3 +3081,173 @@ async fn delete_workspace_refuses_invalid_namespace_before_db_or_notification()
"a refused operation must not notify observers"
);
}
+
+// ---------------------------------------------------------------------------
+// #1208: `project_id` as an alternative to `project`
+// ---------------------------------------------------------------------------
+
+/// `move-project` accepts `project_id` in place of `project`, targeting the
+/// exact row rather than whichever row a name lookup happens to resolve to.
+#[tokio::test]
+async fn move_project_accepts_project_id_instead_of_name() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "movable", None)
+ .await
+ .unwrap();
+
+ let resp = post(
+ state,
+ "/admin/move-project",
+ json!({
+ "from_workspace": "default",
+ "project_id": proj.to_string(),
+ "to_workspace": "elsewhere",
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "move by project_id must resolve the same target as move by name"
+ );
+
+ let dst_ws = store
+ .writer
+ .get_or_create_workspace("elsewhere")
+ .await
+ .unwrap();
+ assert!(
+ store
+ .reader
+ .find_project(dst_ws, "movable".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "the row named by project_id must land in the destination"
+ );
+}
+
+/// A malformed `project_id` is a 400, before any lookup or filesystem work.
+#[tokio::test]
+async fn move_project_rejects_a_malformed_project_id_with_400() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let resp = post(
+ state,
+ "/admin/move-project",
+ json!({
+ "from_workspace": "default",
+ "project_id": "not-a-uuid",
+ "to_workspace": "elsewhere",
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+}
+
+/// An unknown (or foreign-scope) `project_id` is a 404, so a stray id from
+/// another workspace can never drive a destructive move.
+#[tokio::test]
+async fn move_project_unknown_project_id_is_404() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let resp = post(
+ state,
+ "/admin/move-project",
+ json!({
+ "from_workspace": "default",
+ "project_id": "00000000-0000-0000-0000-0000000000ff",
+ "to_workspace": "elsewhere",
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+}
+
+/// `project` and `project_id` together are ambiguous and refused with 400.
+#[tokio::test]
+async fn move_project_refuses_both_project_and_project_id() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "movable", None)
+ .await
+ .unwrap();
+
+ let resp = post(
+ state,
+ "/admin/move-project",
+ json!({
+ "from_workspace": "default",
+ "project": "movable",
+ "project_id": proj.to_string(),
+ "to_workspace": "elsewhere",
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ assert!(
+ store
+ .reader
+ .find_project(ws, "movable".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "an ambiguous request must not move anything"
+ );
+}
+
+/// The existing name path still works when `project_id` is absent, so the
+/// wire format stays backward compatible with older CLI builds.
+#[tokio::test]
+async fn move_project_still_accepts_a_bare_project_name() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ store
+ .writer
+ .get_or_create_project(ws, "movable", None)
+ .await
+ .unwrap();
+
+ let resp = post(
+ state,
+ "/admin/move-project",
+ json!({
+ "from_workspace": "default",
+ "project": "movable",
+ "to_workspace": "elsewhere",
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+}
diff --git a/crates/ai-memory-mcp/tests/suite/admin_purge.rs b/crates/ai-memory-mcp/tests/suite/admin_purge.rs
index 289ec859..41c3ae43 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_purge.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_purge.rs
@@ -1800,3 +1800,363 @@ async fn purge_project_dry_run_conflicts_on_a_live_managed_run_without_force() {
"a live managed run must still 409 a preview without --force"
);
}
+
+// ---------------------------------------------------------------------------
+// #1208: `project_id` as an alternative to `project` / `from`
+// ---------------------------------------------------------------------------
+
+/// `purge-project` accepts `project_id` in place of `project`, so an operator
+/// can target a legacy twin row whose NAME collides with another project's
+/// `legacy_name` (the name lookup resolves to the wrong row in that case).
+#[tokio::test]
+async fn purge_project_accepts_project_id_instead_of_name() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let (ws, _keep, doomed) = seed_two_projects(&store, &state.wiki).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({
+ "workspace": "default",
+ "project_id": doomed.to_string(),
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "purge by project_id must resolve the same target as purge by name"
+ );
+
+ assert!(
+ store
+ .reader
+ .find_project(ws, "doomed".to_string())
+ .await
+ .unwrap()
+ .is_none(),
+ "the row named by project_id must be the one purged"
+ );
+}
+
+/// A `project_id` that is not a UUID is a client error (400), not a 404 or a
+/// 500: it can never match a row, so the request itself is malformed.
+#[tokio::test]
+async fn purge_project_rejects_a_malformed_project_id_with_400() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({
+ "workspace": "default",
+ "project_id": "not-a-uuid",
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+}
+
+/// A well-formed `project_id` with no matching row in this workspace is a 404.
+/// A foreign-scope id lands here too: the row is not visible from this
+/// workspace, so it must never be purged by a stray id.
+#[tokio::test]
+async fn purge_project_unknown_project_id_is_404() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({
+ "workspace": "default",
+ "project_id": "00000000-0000-0000-0000-0000000000ff",
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+}
+
+/// Sending BOTH `project` and `project_id` is ambiguous, so it is refused
+/// before any lookup runs rather than silently preferring one.
+#[tokio::test]
+async fn purge_project_refuses_both_project_and_project_id() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let (_ws, _keep, doomed) = seed_two_projects(&store, &state.wiki).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({
+ "workspace": "default",
+ "project": "doomed",
+ "project_id": doomed.to_string(),
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::BAD_REQUEST,
+ "project and project_id are mutually exclusive"
+ );
+
+ assert!(
+ store
+ .reader
+ .find_project(_ws, "doomed".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "an ambiguous request must not purge anything"
+ );
+}
+
+/// Sending NEITHER `project` nor `project_id` is also a 400: the old CLI
+/// always sent `project`, so a request missing both is a caller bug.
+#[tokio::test]
+async fn purge_project_refuses_neither_project_nor_project_id() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({ "workspace": "default", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+}
+
+/// The preview path (`dry_run: true`) must resolve `project_id` identically,
+/// so `--project-id` works for the default no-confirm preview too.
+#[tokio::test]
+async fn purge_project_preview_accepts_project_id() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let (_ws, _keep, doomed) = seed_two_projects(&store, &state.wiki).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({
+ "workspace": "default",
+ "project_id": doomed.to_string(),
+ "confirm": false,
+ "dry_run": true,
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "the preview branch must resolve project_id too"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// #1208 security boundary: a `project_id` is scoped to the named workspace
+// ---------------------------------------------------------------------------
+//
+// `docs/security-boundaries.md` row 9 (scope resolution fail-closed): an
+// operator holding an id must not be able to reach a row the workspace
+// coordinate does not name. These are the adversarial cases plus the
+// legitimate control, so a blanket deny cannot pass for a working guard.
+
+/// Seed the ambiguity this feature exists for, at the real store level: a
+/// project named `widget`, plus a second project carrying `widget` as its
+/// legacy (v2 basename) key, so a NAME lookup for `widget` answers with two
+/// holders and is refused. Returns `(the named row, the legacy twin)`.
+async fn seed_legacy_twin(store: &Store) -> (WorkspaceId, ProjectId, ProjectId) {
+ use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
+
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ // The row the NAME resolves to.
+ let named = store
+ .writer
+ .get_or_create_project(ws, "widget", None)
+ .await
+ .unwrap();
+ // A second row whose derived legacy key is also `widget`: captured from a
+ // repository whose path-style name would be `widget`, so the store records
+ // `widget` as its `legacy_name` while its current name differs.
+ let twin = store
+ .writer
+ .resolve_project_by_identity_for_capture(
+ ws,
+ RepositoryIdentity {
+ identity: "github.com/acme/widget".to_owned(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::Path,
+ "acme-widget",
+ Some("/work/widget".to_owned()),
+ None,
+ None,
+ )
+ .await
+ .unwrap()
+ .0;
+ assert_ne!(named, twin, "the twin must be a distinct row");
+ (ws, named, twin)
+}
+
+/// The `project` name is not an address once two rows answer to it: the
+/// lookup refuses instead of guessing, which is the pre-existing fail-closed
+/// behaviour this feature makes escapable rather than removes. (#1208)
+#[tokio::test]
+async fn purge_project_still_refuses_an_ambiguous_name_by_default() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let (ws, named, twin) = seed_legacy_twin(&store).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({ "workspace": "default", "project": "widget", "confirm": true }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::BAD_REQUEST,
+ "an ambiguous name must stay refused, never silently resolved"
+ );
+
+ // Nothing was purged: both holders are still there.
+ assert!(
+ store
+ .reader
+ .find_project(ws, "widget".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "the named row must survive a refused ambiguous purge"
+ );
+ assert!(
+ store
+ .reader
+ .project_name_by_id(ws, twin)
+ .await
+ .unwrap()
+ .is_some(),
+ "the twin must survive a refused ambiguous purge"
+ );
+ assert!(named != twin);
+}
+
+/// The id reaches the twin the name could not, and it purges THAT row only --
+/// the name-holder is left completely intact. This is the legitimate control
+/// for the boundary: without it, a blanket deny would look like a passing
+/// guard. (#1208)
+#[tokio::test]
+async fn purge_project_by_id_reaches_the_twin_and_leaves_the_name_holder_intact() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let (ws, named, twin) = seed_legacy_twin(&store).await;
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({
+ "workspace": "default",
+ "project_id": twin.to_string(),
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "the id must be able to name the row the ambiguous name could not"
+ );
+
+ assert!(
+ store
+ .reader
+ .project_name_by_id(ws, twin)
+ .await
+ .unwrap()
+ .is_none(),
+ "the row named by project_id is the one purged"
+ );
+ assert!(
+ store
+ .reader
+ .project_name_by_id(ws, named)
+ .await
+ .unwrap()
+ .is_some(),
+ "the sibling that owns the NAME must be untouched"
+ );
+ assert_eq!(
+ store
+ .reader
+ .project_name_by_id(ws, named)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("widget"),
+ "and it must still carry its own name"
+ );
+}
+
+/// An id that really exists, but in ANOTHER workspace, is a 404 -- the same
+/// answer as an id that does not exist. It must never resolve across the
+/// workspace the request named. (#1208)
+#[tokio::test]
+async fn purge_project_refuses_a_real_id_from_another_workspace() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let other_ws = store
+ .writer
+ .get_or_create_workspace("elsewhere")
+ .await
+ .unwrap();
+ let foreign = store
+ .writer
+ .get_or_create_project(other_ws, "secret", None)
+ .await
+ .unwrap();
+
+ let resp = post(
+ state,
+ "/admin/purge-project",
+ json!({
+ "workspace": "default",
+ "project_id": foreign.to_string(),
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::NOT_FOUND,
+ "a real id from another workspace must not resolve here"
+ );
+
+ assert!(
+ store
+ .reader
+ .project_name_by_id(other_ws, foreign)
+ .await
+ .unwrap()
+ .is_some(),
+ "the foreign row must be untouched"
+ );
+}
diff --git a/crates/ai-memory-mcp/tests/suite/admin_rename.rs b/crates/ai-memory-mcp/tests/suite/admin_rename.rs
index 6bf7c33c..7e3413a8 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_rename.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_rename.rs
@@ -505,3 +505,132 @@ async fn rename_project_after_purge_returns_404_not_silent_200() {
"rename of a vanished project must NOT silently return 200"
);
}
+
+// ---------------------------------------------------------------------------
+// #1208: `project_id` as an alternative to `from`
+// ---------------------------------------------------------------------------
+
+/// `rename-project` accepts `project_id` in place of `from`, so an operator
+/// can rename a legacy twin row whose name is shadowed by another project's
+/// `legacy_name`.
+#[tokio::test]
+async fn rename_project_accepts_project_id_instead_of_from() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ seed_page(&store, &state.wiki, "old-name").await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .reader
+ .find_project(ws, "old-name".to_string())
+ .await
+ .unwrap()
+ .expect("seeded project exists");
+
+ let resp = post(
+ state,
+ "/admin/rename-project",
+ json!({
+ "workspace": "default",
+ "project_id": proj.to_string(),
+ "to": "new-name",
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ assert!(
+ store
+ .reader
+ .find_project(ws, "new-name".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "the row named by project_id must be renamed"
+ );
+}
+
+/// A malformed `project_id` is a 400, before any lookup.
+#[tokio::test]
+async fn rename_project_rejects_a_malformed_project_id_with_400() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let resp = post(
+ state,
+ "/admin/rename-project",
+ json!({
+ "workspace": "default",
+ "project_id": "not-a-uuid",
+ "to": "new-name",
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+}
+
+/// An unknown (or foreign-scope) `project_id` is a 404.
+#[tokio::test]
+async fn rename_project_unknown_project_id_is_404() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let resp = post(
+ state,
+ "/admin/rename-project",
+ json!({
+ "workspace": "default",
+ "project_id": "00000000-0000-0000-0000-0000000000ff",
+ "to": "new-name",
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+}
+
+/// `from` and `project_id` together are ambiguous and refused with 400.
+#[tokio::test]
+async fn rename_project_refuses_both_from_and_project_id() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ seed_page(&store, &state.wiki, "old-name").await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .reader
+ .find_project(ws, "old-name".to_string())
+ .await
+ .unwrap()
+ .expect("seeded project exists");
+
+ let resp = post(
+ state,
+ "/admin/rename-project",
+ json!({
+ "workspace": "default",
+ "from": "old-name",
+ "project_id": proj.to_string(),
+ "to": "new-name",
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ assert!(
+ store
+ .reader
+ .find_project(ws, "old-name".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "an ambiguous request must not rename anything"
+ );
+}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 7c902338..2d81aa10 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -4613,6 +4613,86 @@ mod tests {
assert!(s.last_updated.is_some());
}
+ /// #1208: a project id is an address, so it must be exposed exactly where
+ /// the name is -- no wider. Boundary row 9's rule is that a restricted
+ /// project is hidden from a caller without a grant, and this pins that the
+ /// new id column inherits that rule rather than bypassing it. The filter is
+ /// on the row, so a restricted row is absent entirely; the control proves
+ /// the id IS returned once the caller may see the row, so a blanket deny
+ /// would not pass for a working guard.
+ #[tokio::test]
+ async fn list_projects_with_stats_hides_a_restricted_projects_id_from_an_ungranted_viewer() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let open = store
+ .writer
+ .get_or_create_project(ws, "open-project", None)
+ .await
+ .unwrap();
+ let secret = store
+ .writer
+ .get_or_create_project(ws, "secret-project", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(secret, crate::AccessMode::Restricted)
+ .await
+ .unwrap();
+
+ let outsider = ai_memory_core::UserId::new();
+
+ // Adversarial: the ungranted viewer sees neither the restricted
+ // project's name NOR its id -- the id must not be a side channel
+ // around the name-hiding rule.
+ let visible = store
+ .reader
+ .list_projects_with_stats(Some(outsider))
+ .await
+ .unwrap();
+ assert!(
+ visible.iter().any(|s| s.project_name == "open-project"),
+ "the open project (and its id) must still be listed: {visible:?}"
+ );
+ assert_eq!(
+ visible
+ .iter()
+ .filter(|s| s.project_id == secret.to_string())
+ .count(),
+ 0,
+ "a restricted project's id must not leak to an ungranted viewer: {visible:?}"
+ );
+ assert_eq!(
+ visible
+ .iter()
+ .filter(|s| s.project_name == "secret-project")
+ .count(),
+ 0,
+ "and neither may its name: {visible:?}"
+ );
+ assert_eq!(
+ visible
+ .iter()
+ .find(|s| s.project_name == "open-project")
+ .map(|s| s.project_id.as_str()),
+ Some(open.to_string().as_str()),
+ "the visible row still carries its own id: {visible:?}"
+ );
+
+ // Control: the operator (no viewer filter) sees both, ids included.
+ let all = store.reader.list_projects_with_stats(None).await.unwrap();
+ assert_eq!(all.len(), 2, "the operator surface lists both: {all:?}");
+ assert!(
+ all.iter().any(|s| s.project_id == secret.to_string()),
+ "the operator may see the restricted id: {all:?}"
+ );
+ }
+
#[tokio::test]
async fn list_pages_returns_latest_pages_for_project() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index bc024085..9b8a1752 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1451,8 +1451,15 @@ pub struct BriefPageBody {
/// Returned by [`ReaderPool::list_projects_with_stats`].
#[derive(Debug, Clone, Serialize)]
pub struct ProjectSummary {
+ /// Id of the workspace, as the stable half of the scope coordinate. (#1208)
+ pub workspace_id: String,
/// Name of the workspace.
pub workspace_name: String,
+ /// Id of the project, as the stable coordinate an operator can hand to an
+ /// id-targeted admin operation. Names are not stable -- a legacy twin row
+ /// can shadow another project's `legacy_name` -- so this is what makes a
+ /// `list-projects` row unambiguous. (#1208)
+ pub project_id: String,
/// Name of the project within the workspace.
pub project_name: String,
/// Number of `is_latest = 1` pages.
@@ -8106,7 +8113,9 @@ impl ReaderPool {
// project row, not only on the pages counted beside it.
let visible = readable_repository_predicate("p.id", viewer);
let mut stmt = conn.prepare(&format!(
- "SELECT w.name AS workspace_name, \
+ "SELECT w.id AS workspace_id, \
+ w.name AS workspace_name, \
+ p.id AS project_id, \
p.name AS project_name, \
COUNT(pg.id) AS page_count, \
MAX(pg.updated_at) AS last_updated_us \
@@ -8118,20 +8127,40 @@ impl ReaderPool {
ORDER BY last_updated_us DESC NULLS LAST"
))?;
let rows = stmt.query_map(params![workspace], |row| {
- let workspace_name: String = row.get(0)?;
- let project_name: String = row.get(1)?;
- let page_count: i64 = row.get(2)?;
- let last_updated_us: Option<i64> = row.get(3)?;
- Ok((workspace_name, project_name, page_count, last_updated_us))
+ let workspace_id: Vec<u8> = row.get(0)?;
+ let workspace_name: String = row.get(1)?;
+ let project_id: Vec<u8> = row.get(2)?;
+ let project_name: String = row.get(3)?;
+ let page_count: i64 = row.get(4)?;
+ let last_updated_us: Option<i64> = row.get(5)?;
+ Ok((
+ workspace_id,
+ workspace_name,
+ project_id,
+ project_name,
+ page_count,
+ last_updated_us,
+ ))
})?;
let mut out = Vec::new();
for r in rows {
- let (workspace_name, project_name, page_count, last_updated_us) = r?;
+ let (
+ workspace_id,
+ workspace_name,
+ project_id,
+ project_name,
+ page_count,
+ last_updated_us,
+ ) = r?;
+ let workspace_id = WorkspaceId::from_slice(&workspace_id)?;
+ let project_id = ProjectId::from_slice(&project_id)?;
let last_updated = last_updated_us
.and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
.map(|ts| ts.to_string());
out.push(ProjectSummary {
+ workspace_id: workspace_id.to_string(),
workspace_name,
+ project_id: project_id.to_string(),
project_name,
page_count: u64::try_from(page_count).unwrap_or(0),
last_updated,
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 3c7577c9..687a3c5f 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -59,7 +59,7 @@ means the boundary is not built yet.
| 8d | Messaging: an inferred scope never changes a queue; a read names it (#854) | `scope.rs` `ScopeSource::is_inferred`; `ai-memory-mcp/src/server.rs` `refuse_inferred_message_scope`, called by `memory_message_pop` and `memory_message_cancel` (mailbox scope) and `memory_message_send` (sender scope) before admission or any writer call, so a `shared_slot`/`startup_seed`/`default`/`default_after_mismatch` scope is refused with nothing claimed, cancelled, or delivered; `inferred_scope_hint` on every inferred `memory_message_list` (inbox and outbox, empty or not); the SessionStart notice (`ai-memory-hooks/src/router.rs` `render_inbox_notice`) and `memory_briefing` `scope` name the inbox from server-side names only | `agent_messages_scope.rs` `unscoped_pop_from_the_shared_slot_is_refused_and_claims_nothing`, `unscoped_cancel_from_the_shared_slot_is_refused_and_the_outbox_survives`, `unscoped_send_from_the_shared_slot_is_refused_and_explicit_sender_is_stamped` (each with the shared slot on another project; session-bound and explicit callers as controls; each fails with the guard removed), `unscoped_list_names_the_mailbox_it_read_even_when_not_empty`; `agent_messages_briefing.rs` `no_scope_pop_is_refused_and_the_briefing_names_the_inbox_to_pop`, `no_scope_inbox_list_that_misses_the_mail_names_the_inferred_scope`; router `session_start_notice_surfaces_pending_mail_without_consuming_it` (names the inbox, carries no message text) | STRONG |
| 8e | Messaging: admission is the same for MCP and admin sends (#756) | `ai-memory-mcp/src/admin.rs` `handle_send_message` runs `Wiki::authorize_operation(.., AdmissionOp::MessageSend, ..)` at the recipient scope before `insert_message` (a refusal is 403 and stores nothing) and calls `notify_operation_observers` only after a successful commit; skipping webhooks needs `Capability::SkipAdmissionChain` (`skip_webhooks_for_admin_request`); the MCP path is `server.rs` `memory_message_send` | `admin.rs` `admin_message_send_reject_leaves_inbox_empty` (a rejecting webhook gets 403 and an empty inbox; fails with the admission call removed), controls `admin_message_send_observer_sees_commit_without_blocking_response` and `admin_message_send_full_inbox_does_not_notify_observer` | STRONG |
| 8f | Messaging: the web mailbox shows a restricted sender's name and a card's count only to a reader of that repository; it never consumes mail | `ai-memory-store/src/reader.rs` `list_inbox_with_senders` (`readable_repository_predicate("sp.id", viewer)` on the sender join, so the name is `NULL` for an unreadable sender) and `pending_inbox_counts` (`readable_repository_predicate("p.id", viewer)`); `ai-memory-web/src/routes/project.rs` `mailbox` is `list`-only, no pop/cancel route exists, and `mailbox_scope` matches the URL's exact project name (as `list_pages` does), so an alias never shows another project's mail | `routes.rs` `web_mailbox_hides_restricted_sender_names_and_cards` (a granted reader of the recipient is shown "a project you cannot read", the restricted sender's name and card never reach the grid, alice as the control; fails with either predicate removed), `web_mailbox_lists_only_this_projects_inbox_and_never_consumes_it` (sender and bystander pages show nothing of the recipient's mail, a POST is 405 and the message is still pending, the body is HTML-escaped), `web_mailbox_does_not_follow_a_project_alias` (a legacy key that resolves to `acme-api` shows none of its mail on `/w/default/api`; `acme-api` itself is the control) | STRONG |
-| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; its message names each holder and the key it matched by, but a restricted holder only as "a restricted project", because the lookup runs before any caller is authorized and the project list hides restricted names from callers without a grant; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. A managed run whose `project` is the name its checkout's git remote derives (`PrepareManagedRunRequest.repository_identity`, accepted only through `accept_wire_identity` and only when `path_style_name` equals the requested name) resolves through `resolve_project_by_identity_for_capture` — the identity holder, else the cwd-prefix project with `$HOME` excluded, claimed or renamed only for a writer — and then `authorize_scope_for(Write)` on the writer connection, so an identity can neither redirect a differently named run nor open, claim, or create a project the caller may not write; Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, `a_slashed_label_reaches_only_a_project_the_caller_may_use` (a `workspace/project` label passed as the project is authorized as the pair it names and creates nothing when refused; granted control), `a_slashed_write_resolves_its_own_pair_and_never_creates`, `an_existing_slashed_project_wins_over_the_split`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `an_ambiguous_name_names_its_holders_but_not_a_restricted_one` (restricted holder unnamed; open holder named as the control), `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_by_remote_identity_claims_the_folder_named_project`, `managed_run_by_remote_identity_routes_past_an_identityless_twin` (name-only control is ambiguous), `managed_run_identity_never_redirects_another_project_name`, `managed_run_by_remote_identity_refuses_a_viewer_without_write` (outsider refused with no project created; granted member admitted as the control), `managed_run_identity_never_claims_a_restricted_legacy_project` (an outsider whose cwd sits in a restricted identity-less project is refused, the identity stays unrecorded and no twin appears; fails with either the writer's claim check or the route's write check removed; a granted member claims it as the control), `managed_run_identity_routing_stays_inside_the_requested_workspace`, `concurrent_identity_runs_on_a_legacy_project_converge_on_it` (invariant #16), `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG |
+| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`. The admin destructive project routes (`admin.rs` `resolve_target_for_admin`, used by `purge-project` / `rename-project` / `move-project`) accept a bare `project_id` as an alternative to the name: it is parsed to a UUID (400 on a malformed one), looked up **within the workspace the request named** via `ReaderPool::project_name_by_id` (404 when it names no row there, so a real id from another workspace is refused rather than resolved), and the two spellings are mutually exclusive (both or neither is a 400). `list-projects` carries the id in each row, and inherits the same row-level visibility filter as the name, so a restricted project leaks neither. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; its message names each holder and the key it matched by, but a restricted holder only as "a restricted project", because the lookup runs before any caller is authorized and the project list hides restricted names from callers without a grant; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. A managed run whose `project` is the name its checkout's git remote derives (`PrepareManagedRunRequest.repository_identity`, accepted only through `accept_wire_identity` and only when `path_style_name` equals the requested name) resolves through `resolve_project_by_identity_for_capture` — the identity holder, else the cwd-prefix project with `$HOME` excluded, claimed or renamed only for a writer — and then `authorize_scope_for(Write)` on the writer connection, so an identity can neither redirect a differently named run nor open, claim, or create a project the caller may not write; Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, `a_slashed_label_reaches_only_a_project_the_caller_may_use` (a `workspace/project` label passed as the project is authorized as the pair it names and creates nothing when refused; granted control), `a_slashed_write_resolves_its_own_pair_and_never_creates`, `an_existing_slashed_project_wins_over_the_split`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `an_ambiguous_name_names_its_holders_but_not_a_restricted_one` (restricted holder unnamed; open holder named as the control), `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; admin `admin_purge.rs` `purge_project_refuses_a_real_id_from_another_workspace` (a row that really exists in another workspace answers 404 from `default` and is left intact), `purge_project_still_refuses_an_ambiguous_name_by_default` (a name held by two rows -- one via its `legacy_name` -- stays a 400 and purges nothing), `purge_project_by_id_reaches_the_twin_and_leaves_the_name_holder_intact` (legitimate control: the id reaches the row the name could not, and the name-holder survives with its name), and store `list_projects_with_stats_hides_a_restricted_projects_id_from_an_ungranted_viewer` (the id is absent exactly where the name is, for an ungranted viewer, and present for the operator -- bite-checked with the visibility filter removed); `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_by_remote_identity_claims_the_folder_named_project`, `managed_run_by_remote_identity_routes_past_an_identityless_twin` (name-only control is ambiguous), `managed_run_identity_never_redirects_another_project_name`, `managed_run_by_remote_identity_refuses_a_viewer_without_write` (outsider refused with no project created; granted member admitted as the control), `managed_run_identity_never_claims_a_restricted_legacy_project` (an outsider whose cwd sits in a restricted identity-less project is refused, the identity stays unrecorded and no twin appears; fails with either the writer's claim check or the route's write check removed; a granted member claims it as the control), `managed_run_identity_routing_stays_inside_the_requested_workspace`, `concurrent_identity_runs_on_a_legacy_project_converge_on_it` (invariant #16), `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG |
| 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it | STRONG |
| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; the session's prompt `profile_candidates` (`source_ref = 'session:<sid>'`, a globally unique id) are deleted in whichever project the harvest filed them, matching the `observations` cascade they were harvested from; whole op in one transaction, and the tombstone it leaves is checked by `begin_session_row` and by the new-session arm of `admit_hook_session_event`; `move_project_workspace` re-stamps the `purged_sessions` tombstone with the rest of the project so it still matches after a move; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control; the `purged_sessions` tombstone holds against live hook ingest as well as `begin_session`: `ops.rs` `a_purged_session_is_not_recreated_by_hook_admission` (`admit_hook_session_event` refuses a purged session and writes nothing, with a sibling session and the same id in another project admitted as controls) and `router.rs` `async_processing_drops_events_of_a_purged_session` (the late delivery is a terminal `dropped_invalid`, not a failure the client retries) and `batch_drops_a_purged_session_then_commits_next_item` (the batch endpoint acknowledges it as `dropped_invalid` and commits the next item instead of stopping fail-fast); the user's own sentences the profile harvested from the session's prompts go with it: `ops.rs` `purge_session_deletes_the_profile_candidates_harvested_from_it` (including the candidate harvested from a prompt the session recorded in another project, whose observation the purge deletes through the cascade; a sibling session's candidates in both projects and a page candidate survive); `ops.rs` `a_purged_session_stays_purged_after_its_project_moves` (after `move-project`, `begin_session` for the purged id in the destination is refused with `SessionPurged`; a fresh session there is admitted as the control) | STRONG |
| 10c | Ledger reclaim is content-gated, not filename-gated (invariant #16) | `ai-memory-store/src/ops.rs` `reclaim_ledger_versions` — a candidate row must pass `ai_memory_core::log_ledger::body_opens_with_log_ledger` on its own `body`, and only `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned rows stay with `forget-sweep`; confirm gate in `admin.rs` `handle_reclaim_ledger_versions` | `reclaim_ledger_versions.rs` `a_prose_page_wearing_the_ledger_name_keeps_its_whole_version_chain`, `an_ordinary_page_chain_in_another_project_is_untouched`, `a_decay_tombstone_stays_with_the_sweep_that_owns_it`; `admin_reclaim_ledger_versions.rs` `deleting_without_confirm_is_refused_and_changes_nothing` (with dry-run and confirmed controls) | STRONG |