Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(admin): rekey checkout links by the resolved name; refuse foreign ids in rename and move
AkitaOnRails4c545ce44859
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0be3d2ca..c6325f2c 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1546,8 +1546,8 @@ pub struct PurgeProjectArgs {/// 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+ /// collides with another project's `legacy_name` is refused by name, so+ /// only the id reaches it. Find it in the/// `list-projects` output. Mutually exclusive with `--project`.#[arg(long)]pub project_id: Option<String>,@@ -1644,8 +1644,8 @@ pub struct RenameProjectArgs {/// 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+ /// collides with another project's `legacy_name` is refused by name, so+ /// only the id reaches it. Find it in the/// `list-projects` output. Mutually exclusive with `--from`.#[arg(long)]pub project_id: Option<String>,@@ -1669,8 +1669,8 @@ pub struct MoveProjectArgs {/// 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+ /// collides with another project's `legacy_name` is refused by name, so+ /// only the id reaches it. Find it in the/// `list-projects` output. Mutually exclusive with `--project`.#[arg(long)]pub project_id: Option<String>,diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rsindex e99918a7..96beefc1 100644--- a/crates/ai-memory-cli/src/commands/move_project.rs+++ b/crates/ai-memory-cli/src/commands/move_project.rs@@ -53,15 +53,10 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {(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"),+ let (target_flag, requested) = match (&project, &project_id) {+ (Some(project), _) => (format!("--project {project}"), project.clone()),+ (None, Some(id)) => (format!("--project-id {id}"), id.clone()),+ (None, None) => bail!("one of --project or --project-id is required"),};if !args.confirm {@@ -100,6 +95,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {.await?;let pages = report["pages_copied"].as_u64().unwrap_or(0);+ let target_label = moved_project_name(&report, requested);let purged = report["source_purged"].as_bool().unwrap_or(false);let moved_via = report["moved_via"].as_str().unwrap_or("");let skipped_count = report["pages_skipped"].as_array().map_or(0, |s| s.len());@@ -166,3 +162,27 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {}Ok(())}++/// The moved project's name as the server resolved it. The report's `from` is+/// `<workspace>/<project>`, and it is the only way to learn the name behind+/// `--project-id`; the client-local checkout link is keyed by that name.+fn moved_project_name(report: &serde_json::Value, requested: String) -> String {+ report["from"]+ .as_str()+ .and_then(|label| label.rsplit_once('/'))+ .map_or(requested, |(_, name)| name.to_owned())+}++#[cfg(test)]+mod tests {+ use super::moved_project_name;++ #[test]+ fn a_move_by_id_rekeys_the_link_under_the_resolved_name() {+ let report = serde_json::json!({ "from": "default/api", "to": "team/api" });+ let id = "0193e7a1-0000-7000-8000-000000000001".to_owned();+ assert_eq!(moved_project_name(&report, id.clone()), "api");+ // A report without the label keeps what the operator asked for.+ assert_eq!(moved_project_name(&serde_json::json!({}), id.clone()), id);+ }+}diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rsindex 3536eb1a..c3333c0f 100644--- a/crates/ai-memory-cli/src/commands/rename_project.rs+++ b/crates/ai-memory-cli/src/commands/rename_project.rs@@ -1,6 +1,6 @@//! `ai-memory rename-project` — thin HTTP client for project rename.-use anyhow::Result;+use anyhow::{Context, Result};use crate::cli::RenameProjectArgs;use crate::config::Config;@@ -35,15 +35,10 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {(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 requested = from+ .clone()+ .or_else(|| project_id.clone())+ .context("one of --from or --project-id is required")?;let body = serde_json::json!({"workspace": workspace,"from": from,@@ -52,16 +47,12 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {});let summary: serde_json::Value = post_json(&endpoint, "/admin/rename-project", &body).await?;let pages = summary["pages"].as_u64().unwrap_or(0);+ let old_name = renamed_from(&summary, requested);if let Some(warning) = summary["manifest_warning"].as_str() {eprintln!("ai-memory: warning: {warning}");}if let Err(error) = super::project_registry::rekey_scope(- config,- &endpoint,- &workspace,- &target_label,- &workspace,- &args.to,+ config, &endpoint, &workspace, &old_name, &workspace, &args.to,) {eprintln!("ai-memory: project renamed, but the client-local checkout link could not be updated ({error:#})"@@ -69,7 +60,27 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {}println!("Renamed {}/{} → {}/{} ({} pages now under the new name).",- workspace, target_label, workspace, args.to, pages+ workspace, old_name, workspace, args.to, pages);Ok(())}++/// The renamed project's old name as the server resolved it, the only way to+/// learn the name behind `--project-id`; the client-local checkout link is+/// keyed by that name.+fn renamed_from(summary: &serde_json::Value, requested: String) -> String {+ summary["from"].as_str().map_or(requested, str::to_owned)+}++#[cfg(test)]+mod tests {+ use super::renamed_from;++ #[test]+ fn a_rename_by_id_rekeys_the_link_under_the_resolved_name() {+ let id = "0193e7a1-0000-7000-8000-000000000001".to_owned();+ let summary = serde_json::json!({ "from": "api", "to": "api-v2" });+ assert_eq!(renamed_from(&summary, id.clone()), "api");+ assert_eq!(renamed_from(&serde_json::json!({}), id.clone()), id);+ }+}diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rsindex 771252f9..4bfbb67b 100644--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs@@ -3187,6 +3187,69 @@ async fn move_project_unknown_project_id_is_404() {assert_eq!(resp.status(), StatusCode::NOT_FOUND);}+/// An id that really exists, but in ANOTHER workspace, is a 404 and moves+/// nothing. Control: the same id moves when the request names its own+/// workspace as the source. (#1208)+#[tokio::test]+async fn move_project_refuses_a_real_id_from_another_workspace() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ 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.clone(),+ "/admin/move-project",+ json!({+ "from_workspace": "default",+ "project_id": foreign.to_string(),+ "to_workspace": "target",+ "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 project stays where it was"+ );++ let resp = post(+ state,+ "/admin/move-project",+ json!({+ "from_workspace": "elsewhere",+ "project_id": foreign.to_string(),+ "to_workspace": "target",+ "confirm": true,+ }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK, "control: its own workspace");+}+/// `project` and `project_id` together are ambiguous and refused with 400.#[tokio::test]async fn move_project_refuses_both_project_and_project_id() {diff --git a/crates/ai-memory-mcp/tests/suite/admin_rename.rs b/crates/ai-memory-mcp/tests/suite/admin_rename.rsindex 3aef8396..24f04121 100644--- a/crates/ai-memory-mcp/tests/suite/admin_rename.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_rename.rs@@ -595,6 +595,68 @@ async fn rename_project_unknown_project_id_is_404() {assert_eq!(resp.status(), StatusCode::NOT_FOUND);}+/// An id that really exists, but in ANOTHER workspace, is a 404 and leaves+/// that project's name alone. Control: the same id renames when the request+/// names its own workspace. (#1208)+#[tokio::test]+async fn rename_project_refuses_a_real_id_from_another_workspace() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ 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.clone(),+ "/admin/rename-project",+ json!({+ "workspace": "default",+ "project_id": foreign.to_string(),+ "to": "hijacked",+ }),+ )+ .await;+ assert_eq!(+ resp.status(),+ StatusCode::NOT_FOUND,+ "a real id from another workspace must not resolve here"+ );+ assert_eq!(+ store+ .reader+ .project_name_by_id(other_ws, foreign)+ .await+ .unwrap()+ .as_deref(),+ Some("secret"),+ "the foreign project keeps its name"+ );++ let resp = post(+ state,+ "/admin/rename-project",+ json!({+ "workspace": "elsewhere",+ "project_id": foreign.to_string(),+ "to": "renamed",+ }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK, "control: its own workspace");+}+/// `from` and `project_id` together are ambiguous and refused with 400.#[tokio::test]async fn rename_project_refuses_both_from_and_project_id() {diff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex 246fae6a..1db81f7b 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -160,7 +160,9 @@ GET /api/v1/projects?workspace=NAME # projects in one workspace```json[{+ "workspace_id": "0193e7a1-0000-7000-8000-00000000000a","workspace_name": "default",+ "project_id": "0193e7a1-0000-7000-8000-00000000000b","project_name": "ai-memory","page_count": 138,"last_updated": "2026-05-28T14:02:11.123Z"@@ -168,6 +170,11 @@ GET /api/v1/projects?workspace=NAME # projects in one workspace]```+`project_id` is the stable address of a project: names can collide (a legacy+twin row can carry another project's old name), and the admin project+operations accept the id where the name is ambiguous. A restricted project's+row, id included, is hidden from a caller without a grant.+### 4.3 Pages (list)```httpdiff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 2ebcc5f3..ca27c7a0 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -26,6 +26,16 @@ on a homelab box where mistakes are harder to undo.| `reset --confirm` | ❌ **stop the server first** | yes, all data | no | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). || `reindex` | ❌ **stop the server first** | no wiki wipe; requires a clean DB | only with prior DB backup | Rebuilds pages/links/FTS from `wiki/` using `_meta.md` manifests. Refuses if SQLite already has rows so stale DB-only state cannot survive silently. |+`purge-project`, `rename-project` and `move-project` also take `--project-id+<uuid>` instead of the name (`project_id` on the admin endpoints), for a project+whose name is ambiguous: an empty legacy twin row left by an older migration+can carry another project's old name, and the name lookup refuses it.+`list-projects` prints each project's id. The id is looked up inside the+workspace the command names. Sending both the name and the id, or neither, is+a `400`, so is a malformed UUID, and an id that names no project in that+workspace is a `404`. `--confirm`, the preview and every other guard behave+the same as with a name.+State-touching commands route through the HTTP admin API except `reset`,`restore`, and `reindex`, which are direct-disk lifecycle operations thatfundamentally cannot run while another process holds the SQLite WAL writer. Seediff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 1ccdc2fc..112e7bdf 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -62,7 +62,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`. 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 |+| 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), admin_rename/admin_move `rename_project_refuses_a_real_id_from_another_workspace` / `move_project_refuses_a_real_id_from_another_workspace` (the same for rename and move, the foreign project keeps its name and workspace, with the same id accepted from its own workspace as the control), `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 |