Skip to content

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

Rust

fix(store): reuse the coordinate a capture name already resolves to

AkitaOnRails9d92f20b60d4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 199dc2a8..378a4a43 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,14 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
+- A capture whose `.ai-memory.toml` names a promoted project's old name (its
+ v2 basename, now the project's `legacy_name`) no longer creates a second,
+ empty project under that name. The read path already resolved the old name
+ to the promoted project, so the twin made every later lookup of that name
+ fail as ambiguous until it was purged — and the next capture from the same
+ checkout created it again. The capture path now reuses the project the read
+ path resolves, and refuses an already-ambiguous name instead of adding a
+ third row (#1657).
- `ai-memory workstream-search` now labels a historical tool call or tool
result as completed evidence, as the managed-workstream docs describe. Its
text output used the event's role, which every transcript adapter sets to
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index fd6bb77c..e6477bf4 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -6936,28 +6936,60 @@ pub(crate) mod tests {
assert_eq!(again, a, "one repository, one project, whatever the folder");
// A client that sends no repository identity falls back to the folder
- // name. Here that name is already occupied by repository A, so it
- // resolves there without inventing another project.
+ // name. Both repositories above were promoted away from `api`, so that
+ // name is now the legacy key of two projects: no row answers to it
+ // outright, and the capture path refuses rather than minting a third
+ // one under it — which is what used to leave `api` unresolvable for
+ // every read (#1657).
let plain = tmp.path().join("plain").join("api");
std::fs::create_dir_all(&plain).unwrap();
- let by_name =
- capture_with_identity(&state, &plain, &SessionId::new().to_string(), None).await;
- let plain_name = state
- .reader
- .project_name_by_id(state.workspace_id, by_name)
- .await
- .unwrap();
- assert_eq!(plain_name.as_deref(), Some("api"));
- assert_ne!(by_name, a, "canonical path naming leaves `api` available");
+ let session = SessionId::new().to_string();
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": session,
+ "cwd": plain.to_string_lossy(),
+ "prompt": "hello",
+ }),
+ );
+ let ambiguous = process_authorized(
+ &state,
+ env,
+ None,
+ ai_memory_core::AuthLevel::User,
+ Vec::new(),
+ None,
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ format!("{ambiguous:?}").contains("ambiguous"),
+ "an identity-less capture under a twice-claimed legacy key must refuse: {ambiguous:?}"
+ );
+
+ // A manifest identity is ignored on the wire, so a capture under a name
+ // no project answers to still routes by folder name.
+ let solo = tmp.path().join("solo").join("solo");
+ std::fs::create_dir_all(&solo).unwrap();
let declared = capture_with_identity(
&state,
- &plain,
+ &solo,
&SessionId::new().to_string(),
- Some(("github.com/orgc/api", "manifest")),
+ Some(("github.com/orgc/solo", "manifest")),
)
.await;
assert_eq!(
- declared, by_name,
+ state
+ .reader
+ .project_name_by_id(state.workspace_id, declared)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("solo"),
"a manifest identity is ignored on the wire and routes by folder name"
);
}
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index fe887919..9108895f 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -4803,11 +4803,19 @@ mod tests {
)
.await
.unwrap();
- // The twin an earlier name-only run created under the derived name.
- store
- .writer
- .get_or_create_project(workspace_id, "victorcesc-unknown-system", None)
- .await
+ // The twin an earlier name-only run created under the derived name,
+ // inserted directly: the capture path under test no longer mints it, so
+ // this has to stand in for the row an older release left behind.
+ rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at) \
+ VALUES (?1, ?2, 'victorcesc-unknown-system', 0)",
+ rusqlite::params![
+ ai_memory_core::ProjectId::new().as_bytes().to_vec(),
+ workspace_id.as_bytes().to_vec()
+ ],
+ )
.unwrap();
// By name alone the derived name names both projects.
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index a6ed3ab5..c1edb3a1 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -455,35 +455,56 @@ pub fn get_or_create_project_as(
let id = if let Some(bytes) = existing {
ai_memory_core::ProjectId::from_slice(&bytes)?
} else {
- also_in = project_name_in_other_workspaces(&tx, workspace_id, name)?;
- let id = ai_memory_core::ProjectId::new();
- tx.execute(
- "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
- VALUES (?1, ?2, ?3, ?4, ?5)",
- params![
- id.as_bytes(),
- workspace_id.as_bytes(),
- name,
- repo_path.as_deref(),
- Timestamp::now().as_microsecond()
- ],
- )?;
- // `open` and no creator are the column defaults, so the insert above
- // is the one upstream always ran; only what differs needs a write.
- if initial_access_mode(name, new_project_mode) == crate::AccessMode::Restricted {
- tx.execute(
- "UPDATE projects SET access_mode = 'restricted' WHERE id = ?1",
- params![id.as_bytes()],
- )?;
- }
- if let Some(creator) = creator {
- tx.execute(
- "UPDATE projects SET created_by = ?1 WHERE id = ?2",
- params![creator.as_bytes(), id.as_bytes()],
- )?;
+ // A name that a promoted project still answers to (its `legacy_name`
+ // or `canonical_name`) is not a new project. Inserting a row under it
+ // splits one project in two — the capture lands in an empty twin while
+ // every read keeps resolving the promoted project — and the name then
+ // resolves ambiguously for both paths until someone purges the twin
+ // (#1657). Reuse the row the read path already picks, and let the
+ // authorization choke point decide whether the caller may write there;
+ // an ambiguous name is an error, never another twin. The exact-name
+ // lookup above still runs first, so a name that is only a name behaves
+ // exactly as before.
+ let coordinate = if crate::project_coordinates::supports_coordinates(&tx)? {
+ crate::project_coordinates::resolve(&tx, *workspace_id, name)?
+ } else {
+ None
+ };
+ match coordinate {
+ Some(coordinate) => coordinate.id,
+ None => {
+ also_in = project_name_in_other_workspaces(&tx, workspace_id, name)?;
+ let id = ai_memory_core::ProjectId::new();
+ tx.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ params![
+ id.as_bytes(),
+ workspace_id.as_bytes(),
+ name,
+ repo_path.as_deref(),
+ Timestamp::now().as_microsecond()
+ ],
+ )?;
+ // `open` and no creator are the column defaults, so the insert
+ // above is the one upstream always ran; only what differs needs
+ // a write.
+ if initial_access_mode(name, new_project_mode) == crate::AccessMode::Restricted {
+ tx.execute(
+ "UPDATE projects SET access_mode = 'restricted' WHERE id = ?1",
+ params![id.as_bytes()],
+ )?;
+ }
+ if let Some(creator) = creator {
+ tx.execute(
+ "UPDATE projects SET created_by = ?1 WHERE id = ?2",
+ params![creator.as_bytes(), id.as_bytes()],
+ )?;
+ }
+ created = true;
+ id
+ }
}
- created = true;
- id
};
tx.commit()?;
if scheduler_state_table_exists(conn)? {
diff --git a/crates/ai-memory-store/src/project_coordinates.rs b/crates/ai-memory-store/src/project_coordinates.rs
index 9da2a7b4..9a2d97d4 100644
--- a/crates/ai-memory-store/src/project_coordinates.rs
+++ b/crates/ai-memory-store/src/project_coordinates.rs
@@ -174,6 +174,19 @@ pub(crate) fn matches(
.collect()
}
+/// Whether this connection's schema carries the derived coordinate keys
+/// (`canonical_name`/`legacy_name`, V76).
+///
+/// Every project-coordinate query indexes those columns, so it cannot run
+/// against a store an in-flight migration has not reached yet — which is what
+/// the migration fixtures do when they build a project row on the old schema.
+/// The lookup falls back to a plain insert there, exactly as it always did.
+pub(crate) fn supports_coordinates(conn: &Connection) -> StoreResult<bool> {
+ Ok(conn
+ .prepare_cached("SELECT 1 FROM pragma_table_info('projects') WHERE name = 'legacy_name'")?
+ .exists([])?)
+}
+
pub(crate) fn resolve(
conn: &Connection,
workspace_id: WorkspaceId,
diff --git a/crates/ai-memory-store/tests/suite/identity_resolution.rs b/crates/ai-memory-store/tests/suite/identity_resolution.rs
index 86068aca..f6157010 100644
--- a/crates/ai-memory-store/tests/suite/identity_resolution.rs
+++ b/crates/ai-memory-store/tests/suite/identity_resolution.rs
@@ -1431,10 +1431,17 @@ async fn canonical_target_conflict_rolls_back_the_promotion() {
let legacy = resolve(&store, ws, &remote("github.com/acme/api"), "api", None)
.await
.0;
- let conflict = store
- .writer
- .get_or_create_project(ws, "acme-api", None)
- .await
+ // A plain row under the canonical name, as an install that ran before the
+ // capture path stopped minting twins would already hold. Creating it
+ // through the writer would now bind it to the identity row above, which is
+ // the fix under test, not the state this test is about.
+ let conflict = ProjectId::new();
+ rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at) VALUES (?1, ?2, 'acme-api', 0)",
+ rusqlite::params![conflict.as_bytes().to_vec(), ws.as_bytes().to_vec()],
+ )
.unwrap();
let error =
create_explicit_scope_guarded(&store.reader, &store.writer, "default", "acme-api", None)
@@ -1727,3 +1734,148 @@ async fn reads_of_a_path_named_project_stay_no_create() {
);
}
}
+
+/// A capture whose marker names a promoted project's legacy key lands in that
+/// project instead of minting a twin (#1657).
+///
+/// The read path already resolves the legacy key — `lookup_existing_scope`
+/// answers the promoted row — so the capture path creating a second row under
+/// the same name left the name ambiguous for both, and every later explicit
+/// call failed with `ProjectNameAmbiguous` until the twin was purged. The
+/// capture path now reuses the row the read path picks.
+#[tokio::test]
+async fn a_capture_naming_a_promoted_projects_legacy_key_reuses_it() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let owner = user(&store, "promotion-owner").await;
+ let project = resolve(
+ &store,
+ ws,
+ &remote("github.com/acme/api"),
+ "api",
+ Some(owner),
+ )
+ .await
+ .0;
+ let promoted = create_explicit_scope_guarded(
+ &store.reader,
+ &store.writer,
+ "default",
+ "acme-api",
+ Some(owner),
+ )
+ .await
+ .unwrap();
+ assert_eq!(promoted.scope.project_id, project);
+ assert_eq!(row(&store, project).0, "acme-api");
+
+ // What the router's marker branch calls, with the marker's `project` key.
+ let (id, created) = store
+ .writer
+ .get_or_create_project_as(ws, "api", None, Some(owner))
+ .await
+ .unwrap();
+
+ assert_eq!(id, project, "the capture must not mint a second project");
+ assert!(!created, "nothing was created");
+ assert_eq!(
+ lookup_existing_scope(&store.reader, "default", "api")
+ .await
+ .unwrap()
+ .project_id,
+ project,
+ "the name still resolves, which a twin would have made ambiguous"
+ );
+ let count: i64 = rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row("SELECT COUNT(*) FROM projects", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(count, 1, "one project, not a twin");
+}
+
+/// A capture under a name that is genuinely new still creates the project, so
+/// the legacy-key fallback does not turn capture into a read-only path.
+#[tokio::test]
+async fn a_capture_of_a_new_name_still_creates_its_project() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let owner = user(&store, "new-project-owner").await;
+
+ let (id, created) = store
+ .writer
+ .get_or_create_project_as(ws, "brand-new", None, Some(owner))
+ .await
+ .unwrap();
+
+ assert!(created);
+ assert_eq!(row(&store, id).0, "brand-new");
+ let creator: Option<Vec<u8>> = rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT created_by FROM projects WHERE id = ?1",
+ [id.as_bytes().to_vec()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(
+ creator.as_deref(),
+ Some(owner.as_bytes().as_slice()),
+ "a created project must still record its creator"
+ );
+}
+
+/// Control: when a row already carries the exact name, the capture still
+/// lands there and creates nothing. The legacy-key fallback runs only after
+/// the exact-name lookup misses, so a name that is only a name keeps its old
+/// behaviour — here a twin left behind by the pre-fix code, which the operator
+/// purges by id; the fallback must not turn three rows into four.
+#[tokio::test]
+async fn a_capture_of_an_existing_exact_name_still_lands_there() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let owner = user(&store, "ambiguous-owner").await;
+ let project = resolve(
+ &store,
+ ws,
+ &remote("github.com/acme/widget"),
+ "widget",
+ Some(owner),
+ )
+ .await
+ .0;
+ create_explicit_scope_guarded(
+ &store.reader,
+ &store.writer,
+ "default",
+ "acme-widget",
+ Some(owner),
+ )
+ .await
+ .unwrap();
+ assert_eq!(row(&store, project).0, "acme-widget");
+ let twin = ProjectId::new();
+ rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at) VALUES (?1, ?2, 'widget', 0)",
+ rusqlite::params![twin.as_bytes().to_vec(), ws.as_bytes().to_vec()],
+ )
+ .unwrap();
+
+ let (id, created) = store
+ .writer
+ .get_or_create_project_as(ws, "widget", None, Some(owner))
+ .await
+ .unwrap();
+
+ assert_eq!(id, twin, "the exact-name row still answers to its own name");
+ assert!(!created);
+ let count: i64 = rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row("SELECT COUNT(*) FROM projects", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(count, 2, "no third row");
+}
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 5febef38..ae475285 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -82,7 +82,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), 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 |
+| 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`; `ops.rs` `get_or_create_project_as` — the capture and managed-run creator path — consults the same coordinate lookup before inserting, so a name a promoted project still answers to (its `legacy_name` or `canonical_name`) reuses that row, an ambiguous name is refused, and no twin is minted under a key the read path already resolves (the lookup is skipped only while the schema predates V76, via `project_coordinates::supports_coordinates`). 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`, `identity_resolution.rs` `a_capture_naming_a_promoted_projects_legacy_key_reuses_it` (a capture naming the promoted project's legacy key lands in it, creates nothing and leaves the name resolvable), `a_capture_of_an_existing_exact_name_still_lands_there`, `a_capture_of_a_new_name_still_creates_its_project` (controls: the fallback runs only after the exact-name miss and still records the creator), hooks `two_api_checkouts_with_different_remotes_get_two_projects` (an identity-less capture under a key two projects claim refuses and creates nothing; a fresh folder-named capture still creates its project as the control), `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; `uninstall.rs` `purge_guard_refuses_a_live_sibling_before_stopping_the_service` — `uninstall --purge-data` checks for siblings (the `setup` service's own pid excepted) before it stops that service, and `purge_guard_rechecks_after_stopping_the_service` refuses when the stopped service is still alive; `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 |