Skip to content

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

Rust

fix(web): keep the project mailbox on the page's own project

Peterson Salme1929563e6090
diff --git a/Cargo.lock b/Cargo.lock
index 6dbf9eee..bfe669d4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -282,6 +282,7 @@ dependencies = [
"base64 0.22.1",
"jiff",
"pulldown-cmark",
+ "rusqlite",
"serde",
"serde_json",
"sha2",
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 64567abb..31914903 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -6233,26 +6233,25 @@ impl ReaderPool {
let limit = limit.clamp(1, 200);
self.with_conn(move |conn| {
let sender_visible = readable_repository_predicate("sp.id", viewer);
- let columns = crate::ops::MESSAGE_COLUMNS
- .split(',')
- .map(|column| format!("m.{}", column.trim()))
- .collect::<Vec<_>>()
- .join(", ");
+ let columns = crate::ops::MESSAGE_COLUMNS;
+ // The sender names follow the message columns.
+ let sender_at = columns.split(',').count();
let mut stmt = conn.prepare(&format!(
- "SELECT {columns}, sw.name, sp.name \
- FROM agent_messages m \
+ "SELECT m.*, sw.name, sp.name \
+ FROM (SELECT {columns} FROM agent_messages \
+ WHERE to_workspace_id = ?1 AND to_project_id = ?2 AND state = 'pending' \
+ ORDER BY created_at ASC LIMIT {limit}) m \
LEFT JOIN projects sp ON sp.id = m.from_project_id \
AND sp.workspace_id = m.from_workspace_id{sender_visible} \
LEFT JOIN workspaces sw ON sw.id = sp.workspace_id \
- WHERE m.to_workspace_id = ?1 AND m.to_project_id = ?2 AND m.state = 'pending' \
- ORDER BY m.created_at ASC LIMIT {limit}"
+ ORDER BY m.created_at ASC"
))?;
let rows = stmt.query_map(
params![workspace_id.as_bytes(), project_id.as_bytes()],
|row| {
let message = crate::ops::row_to_agent_message(row)?;
- let workspace: Option<String> = row.get(12)?;
- let project: Option<String> = row.get(13)?;
+ let workspace: Option<String> = row.get(sender_at)?;
+ let project: Option<String> = row.get(sender_at + 1)?;
Ok((message, workspace.zip(project)))
},
)?;
diff --git a/crates/ai-memory-web/Cargo.toml b/crates/ai-memory-web/Cargo.toml
index 2c00906b..90978bc7 100644
--- a/crates/ai-memory-web/Cargo.toml
+++ b/crates/ai-memory-web/Cargo.toml
@@ -34,6 +34,7 @@ anyhow.workspace = true
sha2.workspace = true
[dev-dependencies]
+rusqlite.workspace = true
tempfile.workspace = true
tower.workspace = true
diff --git a/crates/ai-memory-web/src/routes/index.rs b/crates/ai-memory-web/src/routes/index.rs
index d901c101..453ba335 100644
--- a/crates/ai-memory-web/src/routes/index.rs
+++ b/crates/ai-memory-web/src/routes/index.rs
@@ -26,21 +26,19 @@ pub(crate) async fn handler(
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
) -> Result<Html<String>, StatusCode> {
let viewer_id = viewer.map(|axum::Extension(viewer)| viewer.user());
- let summaries = state
- .reader
- .list_projects_with_stats(viewer_id)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
-
- // One grouped query for every card; the badge shows only where mail waits.
- let pending: HashMap<(String, String), u64> = state
- .reader
- .pending_inbox_counts(viewer_id)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
- .into_iter()
- .map(|c| ((c.workspace_name, c.project_name), c.pending))
- .collect();
+ let (summaries, counts) = tokio::try_join!(
+ state.reader.list_projects_with_stats(viewer_id),
+ // One grouped query for every card; the badge shows only where mail waits.
+ state.reader.pending_inbox_counts(viewer_id),
+ )
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let mut pending: HashMap<String, HashMap<String, u64>> = HashMap::new();
+ for c in counts {
+ pending
+ .entry(c.workspace_name)
+ .or_default()
+ .insert(c.project_name, c.pending);
+ }
let projects: Vec<ProjectCard> = summaries
.into_iter()
@@ -48,7 +46,8 @@ pub(crate) async fn handler(
let last_updated_relative = s.last_updated.as_deref().map(humanize).unwrap_or_default();
let href = project_href(&s.workspace_name, &s.project_name);
let pending_inbox = pending
- .get(&(s.workspace_name.clone(), s.project_name.clone()))
+ .get(&s.workspace_name)
+ .and_then(|projects| projects.get(&s.project_name))
.copied()
.unwrap_or(0);
ProjectCard {
@@ -71,6 +70,7 @@ pub(crate) async fn handler(
with_mail.sort_by(|a, b| {
b.pending_inbox
.cmp(&a.pending_inbox)
+ .then_with(|| a.workspace.cmp(&b.workspace))
.then_with(|| a.project.cmp(&b.project))
});
let mail_total: u64 = with_mail.iter().map(|card| card.pending_inbox).sum();
diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rs
index 22029b9d..b352ee0c 100644
--- a/crates/ai-memory-web/src/routes/mod.rs
+++ b/crates/ai-memory-web/src/routes/mod.rs
@@ -23,16 +23,17 @@ mod statics;
/// first — the page views and the project listing. Those went straight from a
/// URL to the page body, so the guard never saw them.
///
-/// No viewer — an install with no database users, or root — returns `Ok`
-/// without a lookup, so these routes behave exactly as they did before.
+/// No viewer — an install with no database users, or root — returns
+/// `Ok(None)` without a lookup, so these routes behave exactly as they did
+/// before. Otherwise returns the scope the check resolved.
pub(crate) async fn authorize_read(
state: &WebState,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
workspace: &str,
project: &str,
-) -> Result<(), ai_memory_store::ScopeResolutionError> {
+) -> Result<Option<ai_memory_store::ResolvedScope>, ai_memory_store::ScopeResolutionError> {
let Some(axum::Extension(viewer)) = viewer else {
- return Ok(());
+ return Ok(None);
};
ai_memory_store::lookup_existing_scope_guarded(
&state.reader,
@@ -42,7 +43,7 @@ pub(crate) async fn authorize_read(
ai_memory_store::ProjectAccess::Read,
)
.await
- .map(|_| ())
+ .map(Some)
}
/// Build the read-only wiki page router (no static assets — those are public).
diff --git a/crates/ai-memory-web/src/routes/project.rs b/crates/ai-memory-web/src/routes/project.rs
index 7caf7026..36014171 100644
--- a/crates/ai-memory-web/src/routes/project.rs
+++ b/crates/ai-memory-web/src/routes/project.rs
@@ -8,6 +8,8 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{Html, IntoResponse, Response};
+use ai_memory_store::ResolvedScope;
+
use crate::state::WebState;
use crate::templates::{
Folder, MailboxRow, PageRow, ProjectView, humanize, page_href, project_href,
@@ -26,10 +28,11 @@ pub(crate) async fn handler(
Path((workspace, project)): Path<(String, String)>,
) -> Response {
let viewer_id = viewer.as_ref().map(|axum::Extension(viewer)| viewer.user());
- if let Err(refusal) = super::authorize_read(&state, viewer, &workspace, &project).await {
- return super::page::refusal_response(&refusal);
- }
- render(&state, workspace, project, viewer_id)
+ let authorized = match super::authorize_read(&state, viewer, &workspace, &project).await {
+ Ok(authorized) => authorized,
+ Err(refusal) => return super::page::refusal_response(&refusal),
+ };
+ render(&state, workspace, project, viewer_id, authorized)
.await
.into_response()
}
@@ -39,12 +42,18 @@ async fn render(
workspace: String,
project: String,
viewer: Option<ai_memory_core::UserId>,
+ authorized: Option<ResolvedScope>,
) -> Result<Html<String>, StatusCode> {
- let pages = state
- .reader
- .list_pages(&workspace, &project)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let (pages, (mailbox, mailbox_total)) = tokio::try_join!(
+ async {
+ state
+ .reader
+ .list_pages(&workspace, &project)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+ },
+ mailbox(state, &workspace, &project, viewer, authorized),
+ )?;
// Build sidebar folder trees (group by first path segment), split
// into knowledge and machinery. A store accumulates far more
@@ -112,8 +121,6 @@ async fn render(
})
.collect();
- let (mailbox, mailbox_total) = mailbox(state, &workspace, &project, viewer).await?;
-
let mailbox_capped = mailbox_total > mailbox.len() as u64;
let html = ProjectView {
workspace,
@@ -142,21 +149,24 @@ async fn mailbox(
workspace: &str,
project: &str,
viewer: Option<ai_memory_core::UserId>,
+ authorized: Option<ResolvedScope>,
) -> Result<(Vec<MailboxRow>, u64), StatusCode> {
- let scope = ai_memory_store::lookup_existing_scope(&state.reader, workspace, project)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
- let entries = state
- .reader
- .list_inbox_with_senders(scope.workspace_id, scope.project_id, viewer, MAILBOX_LIMIT)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
- let total = state
- .reader
- .pending_message_count(scope.workspace_id, scope.project_id)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
- .max(entries.len() as u64);
+ let Some(scope) = mailbox_scope(state, workspace, project, authorized).await? else {
+ return Ok((Vec::new(), 0));
+ };
+ let (entries, total) = tokio::try_join!(
+ state.reader.list_inbox_with_senders(
+ scope.workspace_id,
+ scope.project_id,
+ viewer,
+ MAILBOX_LIMIT
+ ),
+ state
+ .reader
+ .pending_message_count(scope.workspace_id, scope.project_id),
+ )
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let total = total.max(entries.len() as u64);
let rows = entries
.into_iter()
.map(|entry| {
@@ -183,14 +193,49 @@ async fn mailbox(
Ok((rows, total))
}
+/// The project whose pages this page lists, or `None` when there is none.
+///
+/// Matches the exact name, as `list_pages` does, so an alias that resolves to
+/// another project cannot put that project's mail beside these pages. A URL
+/// that names no project renders an empty mailbox, as it renders no pages.
+async fn mailbox_scope(
+ state: &WebState,
+ workspace: &str,
+ project: &str,
+ authorized: Option<ResolvedScope>,
+) -> Result<Option<ResolvedScope>, StatusCode> {
+ let workspace_id = match authorized {
+ Some(scope) => scope.workspace_id,
+ None => match ai_memory_store::lookup_existing_workspace(&state.reader, workspace).await {
+ Ok(workspace_id) => workspace_id,
+ Err(error) if error.is_not_found() => return Ok(None),
+ Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
+ },
+ };
+ let project_id = state
+ .reader
+ .find_project(workspace_id, project.to_owned())
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ Ok(project_id.map(|project_id| ResolvedScope {
+ workspace_id,
+ project_id,
+ }))
+}
+
/// First [`SNIPPET_CHARS`] characters of `body` on one line.
fn snippet(body: &str) -> String {
- let flat = body.split_whitespace().collect::<Vec<_>>().join(" ");
- if flat.chars().count() <= SNIPPET_CHARS {
- return flat;
+ // Lazy, so a large body is read only up to the cut.
+ let mut flat = body
+ .split_whitespace()
+ .flat_map(|word| std::iter::once(' ').chain(word.chars()))
+ .skip(1);
+ let cut: String = flat.by_ref().take(SNIPPET_CHARS).collect();
+ if flat.next().is_some() {
+ format!("{cut}…")
+ } else {
+ cut
}
- let cut: String = flat.chars().take(SNIPPET_CHARS).collect();
- format!("{cut}…")
}
/// Machinery rather than knowledge: hidden from Recent Activity and
diff --git a/crates/ai-memory-web/templates/project.html b/crates/ai-memory-web/templates/project.html
index 525eddbc..d2ccc1b7 100644
--- a/crates/ai-memory-web/templates/project.html
+++ b/crates/ai-memory-web/templates/project.html
@@ -93,7 +93,7 @@
{% endfor %}
</ul>
<p class="mt-2 text-xs text-slate-400 dark:text-slate-500">
- {% if mailbox_capped %}Showing the oldest {{ mailbox.len() }} of {{ mailbox_total }}; <code class="font-mono">ai-memory message list</code> shows the rest. {% endif %}An agent in this project reads them with <code class="font-mono">memory_message_pop</code>.
+ {% if mailbox_capped %}Showing the oldest {{ mailbox.len() }} of {{ mailbox_total }}; <code class="font-mono">ai-memory message list --workspace {{ workspace }} --project {{ project }} --limit 200</code> lists up to 200. {% endif %}An agent in this project reads them with <code class="font-mono">memory_message_pop</code>.
</p>
{% endif %}
</section>
diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rs
index 321a3e0f..980c5920 100644
--- a/crates/ai-memory-web/tests/suite/routes.rs
+++ b/crates/ai-memory-web/tests/suite/routes.rs
@@ -4366,4 +4366,77 @@ async fn web_mailbox_says_how_many_pending_messages_it_does_not_list() {
assert!(body.contains("request 1"), "oldest first: {body}");
assert!(body.contains("request 5"), "{body}");
assert!(!body.contains("request 6"), "capped at five: {body}");
+ assert!(
+ body.contains("ai-memory message list --workspace default --project recipient --limit 200"),
+ "the hint names this project's inbox: {body}"
+ );
+}
+
+/// With no auth, a project URL that names nothing renders the empty page
+/// (200) as before the mailbox existed, not a 500.
+#[tokio::test]
+async fn web_project_page_without_a_project_renders_an_empty_mailbox() {
+ let (_tmp, store, wiki) = setup().await;
+ store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let web = router(store.reader.clone(), wiki.clone());
+
+ for uri in ["/w/default/typo-project", "/w/no-such-workspace/api"] {
+ let (status, body) = get_text(&web, uri, None).await;
+ assert_eq!(status, StatusCode::OK, "{uri}: {body}");
+ assert!(
+ body.contains("No pending messages for this project."),
+ "{uri}: {body}"
+ );
+ }
+}
+
+/// The mailbox matches the URL's exact project name, as the page list does,
+/// so a legacy alias never shows another project's mail beside no pages.
+#[tokio::test]
+async fn web_mailbox_does_not_follow_a_project_alias() {
+ let (tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let sender = store
+ .writer
+ .get_or_create_project(ws, "sender", None)
+ .await
+ .unwrap();
+ let acme = store
+ .writer
+ .get_or_create_project(ws, "acme-api", None)
+ .await
+ .unwrap();
+ send_mail(&store, (ws, sender), (ws, acme), "Aliased mail", "body").await;
+ rusqlite::Connection::open(tmp.path().join("db").join(ai_memory_store::DB_FILENAME))
+ .unwrap()
+ .execute(
+ "UPDATE projects SET legacy_name = 'api' WHERE id = ?1",
+ [acme.as_bytes().to_vec()],
+ )
+ .unwrap();
+ // Control: the alias does resolve, so the test bites without the fix.
+ let resolved = ai_memory_store::lookup_existing_scope(&store.reader, "default", "api")
+ .await
+ .unwrap();
+ assert_eq!(resolved.project_id, acme);
+
+ let web = router(store.reader.clone(), wiki.clone());
+ let (status, body) = get_text(&web, "/w/default/api", None).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(!body.contains("Aliased mail"), "{body}");
+ assert!(
+ body.contains("No pending messages for this project."),
+ "{body}"
+ );
+
+ let (_, body) = get_text(&web, "/w/default/acme-api", None).await;
+ assert!(body.contains("Aliased mail"), "{body}");
}
diff --git a/docs/agent-messaging.md b/docs/agent-messaging.md
index 0328e409..1ded499c 100644
--- a/docs/agent-messaging.md
+++ b/docs/agent-messaging.md
@@ -138,8 +138,10 @@ none. The home page adds a one-line summary of the total with links to the
projects holding mail. The project page has a Mailbox section above Recent
Activity listing up to five pending messages, oldest first, with the subject,
the sender, a 160-character snippet and the age; when more are pending it says
-"5 of N" and points at `ai-memory message list`, and when none are waiting it
-says so. The section never pops or cancels: consuming a message stays an agent
+"5 of N" and gives the `ai-memory message list --workspace W --project P
+--limit 200` command for that project (the CLI lists at most 200 at a time),
+and when none are waiting it says so. A URL that names no project shows an
+empty mailbox, as it shows no pages. The section never pops or cancels: consuming a message stays an agent
action (`memory_message_pop`), so the claim-once queue is not reachable from a
browser. Only the inbox is shown; sent mail is still `memory_message_list`
with `box=outbox`.
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index e64dd206..ed460a0a 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -58,7 +58,7 @@ means the boundary is not built yet.
| 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG |
| 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 | `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) | 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 |
| 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 |