Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(web): show CLI commands on /web/pending to a Basic-auth browser
Felipe Neves Ricardoe0007df6846f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0a8c0725..2fd4acbe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,13 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]### Fixed+- Fixed `/web/pending` offering Approve and Reject buttons that always failed+ with `401: unknown error` on a server with a bearer token and no password+ sign-in. The browser reaches `/web` there with the root token over HTTP+ Basic, which only admits reads. The page now says so, points to password+ sign-in, and shows each proposal's `ai-memory pending-writes approve` /+ `reject` command instead; a decision that fails for another reason now shows+ the server's message even when it is plain text. (#1288)- Fixed Windows capture dropping the body of file and shell tool eventsthe client had kept. With `[capture] ignore_paths` active, serverre-inspection compiled a POSIX never-match sentinel and treated thediff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rsindex 23c92f32..c26bd000 100644--- a/crates/ai-memory-core/src/actor.rs+++ b/crates/ai-memory-core/src/actor.rs@@ -106,6 +106,14 @@ pub struct ActorContext {#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct AuthorizedViewer(pub crate::UserId);+/// Marks a request that authenticated with the legacy browser credential: the+/// root bearer sent as HTTP Basic, or an `ai_memory_auth` cookie an older build+/// set. That path exists only until human auth is set up and admits GET only,+/// so a page served through it can tell the viewer that a change it would post+/// cannot succeed, instead of offering a control that always fails.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct LegacyBrowserAuth;+impl AuthorizedViewer {/// The user id inside.#[must_use]diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 10f2e966..634ece03 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -56,9 +56,9 @@ pub use active_project::{DEFAULT_PER_KEY_TTL, MidSessionRouting, ReadPointer,};pub use actor::{- ActorContext, AuthLevel, AuthorizedViewer, AuthzError, Capability, IdentityKey, OwnerFilter,- SKIP_ADMISSION_CHAIN_HEADER, owner_identity, owner_stamp, parse_skip_admission_chain,- skip_admission_chain_for,+ ActorContext, AuthLevel, AuthorizedViewer, AuthzError, Capability, IdentityKey,+ LegacyBrowserAuth, OwnerFilter, SKIP_ADMISSION_CHAIN_HEADER, owner_identity, owner_stamp,+ parse_skip_admission_chain, skip_admission_chain_for,};pub use agent_backup::{AGENT_BACKUP_SCHEMA_VERSION, AgentAssetKind, AgentAssetScope, AgentBackupEntry,diff --git a/crates/ai-memory-mcp/src/human_auth.rs b/crates/ai-memory-mcp/src/human_auth.rsindex 27ddb5f0..74d251f3 100644--- a/crates/ai-memory-mcp/src/human_auth.rs+++ b/crates/ai-memory-mcp/src/human_auth.rs@@ -1088,6 +1088,8 @@ pub async fn require_dual_auth(match crate::auth::authenticate_token(&state, &mut req, &provided, false).await {Ok(crate::auth::BearerAuth::Authenticated) => {req.extensions_mut().insert(state.clone());+ req.extensions_mut()+ .insert(ai_memory_core::LegacyBrowserAuth);return next.run(req).await;}Err(response) => return response,@@ -1603,6 +1605,74 @@ mod tests {);}+ /// Only the legacy browser path is marked read-only, so `/web/pending`+ /// can hide controls that would post and fail. The marker never widens+ /// that path: a Basic POST is still refused. Control: the root bearer is+ /// not marked, because a POST with it succeeds.+ #[tokio::test]+ async fn only_a_legacy_browser_credential_is_marked_read_only() {+ async fn echo_marker(+ marker: Option<axum::Extension<ai_memory_core::LegacyBrowserAuth>>,+ ) -> &'static str {+ if marker.is_some() {+ "legacy"+ } else {+ "unmarked"+ }+ }+ let (_tmp, state, _writer) = legacy_transition_fixture().await;+ let router = axum::Router::new()+ .route("/probe", axum::routing::get(echo_marker).post(echo_marker))+ .route_layer(axum::middleware::from_fn_with_state(+ state,+ require_dual_auth,+ ));+ let send = |method: Method, header: (&'static str, String)| {+ let router = router.clone();+ async move {+ let response = router+ .oneshot(+ axum::http::Request::builder()+ .method(method)+ .uri("/probe")+ .header(header.0, header.1)+ .body(axum::body::Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let status = response.status();+ let body = axum::body::to_bytes(response.into_body(), 4096)+ .await+ .unwrap();+ (status, String::from_utf8(body.to_vec()).unwrap())+ }+ };++ let basic = ("authorization", legacy_basic("legacy-root-token"));+ let cookie = ("cookie", format!("{LEGACY_AUTH_COOKIE}=legacy-root-token"));+ let bearer = ("authorization", "Bearer legacy-root-token".to_owned());++ assert_eq!(+ send(Method::GET, basic.clone()).await,+ (StatusCode::OK, "legacy".into())+ );+ assert_eq!(+ send(Method::GET, cookie).await,+ (StatusCode::OK, "legacy".into())+ );+ assert_eq!(+ send(Method::GET, bearer.clone()).await,+ (StatusCode::OK, "unmarked".into())+ );+ assert_eq!(+ send(Method::POST, bearer).await,+ (StatusCode::OK, "unmarked".into())+ );+ let (status, _) = send(Method::POST, basic).await;+ assert_eq!(status, StatusCode::UNAUTHORIZED, "Basic stays GET-only");+ }+#[tokio::test]async fn legacy_browser_credentials_stop_when_human_bootstrap_completes() {let (_tmp, state, writer) = legacy_transition_fixture().await;diff --git a/crates/ai-memory-web/src/routes/pending.rs b/crates/ai-memory-web/src/routes/pending.rsindex ab87e1a5..e1e48acd 100644--- a/crates/ai-memory-web/src/routes/pending.rs+++ b/crates/ai-memory-web/src/routes/pending.rs@@ -8,7 +8,7 @@use std::sync::Arc;-use ai_memory_core::AuthLevel;+use ai_memory_core::{AuthLevel, LegacyBrowserAuth};use ai_memory_store::{PendingAutoImproveReview, PendingAutoImproveScope};use askama::Template;use axum::Extension;@@ -53,6 +53,7 @@ pub(crate) struct PendingQuery {pub(crate) async fn handler(State(state): State<Arc<WebState>>,level: Option<Extension<AuthLevel>>,+ legacy: Option<Extension<LegacyBrowserAuth>>,Query(query): Query<PendingQuery>,) -> Response {if let Err(response) = super::require_admin(&state, level).await {@@ -123,6 +124,7 @@ pub(crate) async fn handler(project_count: scopes.len(),truncated,limit: PENDING_REVIEW_LIMIT,+ read_only: legacy.is_some(),},StatusCode::OK,)diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rsindex 86792798..bb2b569d 100644--- a/crates/ai-memory-web/src/templates.rs+++ b/crates/ai-memory-web/src/templates.rs@@ -755,6 +755,9 @@ pub(crate) struct PendingView {pub truncated: bool,/// The read cap, shown when `truncated`.pub limit: usize,+ /// The browser signed in with the legacy Basic credential, which admits+ /// GET only: the decision buttons give way to the CLI commands.+ pub read_only: bool,}// ---------------------------------------------------------------------------diff --git a/crates/ai-memory-web/templates/pending.html b/crates/ai-memory-web/templates/pending.htmlindex 1da2f0d5..46019ebf 100644--- a/crates/ai-memory-web/templates/pending.html+++ b/crates/ai-memory-web/templates/pending.html@@ -35,6 +35,14 @@{% if truncated %}· only the oldest {{ limit }} of this selection are listed; pick a project, or use <code>ai-memory pending-writes list</code>{% endif %}</p>+{% if read_only %}+<p class="mb-4 rounded-md bg-amber-50 dark:bg-amber-950 px-3 py-2 text-sm text-amber-800 dark:text-amber-300">+ This browser signed in with the root token, which can only read pages. To approve or reject here, set up password sign-in+ (<code>AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD</code>, see "Human password bootstrap and recovery" in <code>docs/install.md</code>).+ Until then, use the command shown under each proposal.+</p>+{% endif %}+<p id="pending-status" class="mb-4 hidden rounded-md px-3 py-2 text-sm" role="status" aria-live="polite"></p>{% if rows.is_empty() %}@@ -89,6 +97,10 @@<pre class="max-h-96 overflow-auto whitespace-pre-wrap break-words rounded-md bg-slate-50 dark:bg-slate-900 p-3 text-sm text-slate-700 dark:text-slate-300">{{ row.body_markdown }}</pre></div><p class="text-xs text-slate-500 dark:text-slate-400 font-mono break-all">id {{ row.id }}</p>+ {% if read_only %}+ <pre class="whitespace-pre-wrap break-all rounded-md bg-slate-50 dark:bg-slate-900 p-3 text-xs text-slate-700 dark:text-slate-300">ai-memory pending-writes approve {{ row.id }} --workspace {{ row.workspace }} --project {{ row.project }}+ai-memory pending-writes reject {{ row.id }} --workspace {{ row.workspace }} --project {{ row.project }} --reason "..."</pre>+ {% else %}<div class="flex flex-wrap items-center gap-2"><button type="button" data-action="approve"class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50">Approve</button>@@ -97,6 +109,7 @@<input type="text" name="reason" maxlength="500" placeholder="Reject reason (optional)" aria-label="Reject reason"class="flex-1 min-w-0 max-w-md rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-500 dark:placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"></div>+ {% endif %}</div></details></li>@@ -146,7 +159,10 @@},body: JSON.stringify(action === "reject" ? { reason: reason.value.trim() } : {})}).then(function (resp) {- return resp.json().catch(function () { return {}; }).then(function (json) {+ // An auth refusal can answer in plain text, not JSON: keep that text.+ return resp.text().then(function (text) {+ var json = {};+ try { json = JSON.parse(text); } catch (e) { json = { error: text.trim() }; }if (resp.ok) {item.remove();count.textContent = String(document.querySelectorAll(".pending-item").length);diff --git a/crates/ai-memory-web/tests/suite/pending.rs b/crates/ai-memory-web/tests/suite/pending.rsindex dcb23c96..63e34820 100644--- a/crates/ai-memory-web/tests/suite/pending.rs+++ b/crates/ai-memory-web/tests/suite/pending.rs@@ -315,6 +315,55 @@ async fn pending_page_lists_every_projects_queue_for_root() {assert!(body.contains("\"/admin/pending-writes/\""));}+/// A browser signed in through the legacy Basic credential can read the page+/// but never post a decision (`require_dual_auth` keeps that path GET-only),+/// so the page replaces the buttons with the CLI commands and says how to+/// enable password sign-in. Control: a root request without the marker keeps+/// the buttons.+#[tokio::test]+async fn pending_page_offers_cli_commands_instead_of_buttons_to_a_basic_browser() {+ let f = fixture().await;+ let (_, _, id) = stage(+ &f.store,+ "alpha",+ "notes/a.md",+ "Alpha",+ AutoImproveProposalOperation::Create,+ )+ .await;+ let legacy = app(&f, AuthLevel::Root).layer(axum::middleware::from_fn(+ |mut req: Request<Body>, next: axum::middleware::Next| async move {+ req.extensions_mut()+ .insert(ai_memory_core::LegacyBrowserAuth);+ next.run(req).await+ },+ ));++ let (status, _, body) = get(legacy, "/pending", true).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(body.contains(&format!("data-id=\"{id}\"")), "{body}");+ assert!(!body.contains("data-action=\"approve\""), "{body}");+ assert!(!body.contains("data-action=\"reject\""), "{body}");+ assert!(+ body.contains("AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD"),+ "{body}"+ );+ assert!(+ body.contains(&format!(+ "ai-memory pending-writes approve {id} --workspace default --project alpha"+ )),+ "{body}"+ );++ let (status, _, body) = get(app(&f, AuthLevel::Root), "/pending", true).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(body.contains("data-action=\"approve\""), "{body}");+ assert!(+ !body.contains("AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD"),+ "{body}"+ );+}+#[tokio::test]async fn pending_page_follows_the_admin_gate_on_a_single_operator_server() {// No users and no trusted proxy: `/admin` admits the anonymousdiff --git a/docs/auto-improvement-loop.md b/docs/auto-improvement-loop.mdindex e624d867..465ef1be 100644--- a/docs/auto-improvement-loop.md+++ b/docs/auto-improvement-loop.md@@ -469,7 +469,7 @@ them by default through the wiki mutation path. With `require_approval = true`,| `ai-memory pending-writes diff <id>` | Show markdown diff. || `ai-memory pending-writes approve <id>` | Apply through the normal wiki mutation path. || `ai-memory pending-writes reject <id>` | Discard proposal with audit trail. |-| `GET {web_slug}/pending` | Root-only browser page. It lists pending proposals across all projects, with a project filter and a sort. Approve and reject post to the `/admin/pending-writes/{id}/approve\|reject` routes with the session cookie and the CSRF header. |+| `GET {web_slug}/pending` | Root-only browser page. It lists pending proposals across all projects, with a project filter and a sort. Approve and reject post to the `/admin/pending-writes/{id}/approve\|reject` routes with the session cookie and the CSRF header. A browser signed in with the root bearer through HTTP Basic, before password sign-in is set up, can only read: the page shows each proposal's `pending-writes` commands instead of the buttons. |Pending proposals should be visible as markdown under `_pending/auto-improve/`so humans can review them in the wiki/Obsidian workflow. SQLite can still holddiff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex 3b7a1473..f4d297db 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -50,7 +50,9 @@ position). Both follow the same per-project read rule as the page view.The builtin wiki also serves the root-only `GET {web_slug}/pending` page. Itlists pending auto-improvement proposals and posts approve and reject to theexisting `/admin/pending-writes/*` routes. A signed-in non-root user gets a-403 page, not the change-password redirect. The root-only+403 page, not the change-password redirect. A browser on the GET-only legacy+Basic credential sees each proposal's `ai-memory pending-writes` commands in+place of the buttons, since its posts would be refused. The root-only`GET {web_slug}/health` page follows the same gate: hook counters (accepted,shed, 429), writer queue, the spool and recovery journal under the server'sdata directory, the consolidation queue, embedder and provider state, and thediff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 16fb0bdf..f577bcbf 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -38,7 +38,7 @@ means the boundary is not built yet.| 3d | `GET /admin/metrics` is root-only on a multi-user server and content-free | `ai-memory-mcp/src/admin.rs` mounts `/admin/metrics` inside the operational router under `require_root_for_multiuser_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`); `ai-memory-mcp/src/metrics.rs` `render_prometheus` writes only counts and durations under compile-time metric names and the closed label set `result` / `outcome` / `kind` / `le`; `McpMetrics::record_tool_call` takes only a read/write bit (no client name); `ai-memory-core/src/latency.rs` `LatencyHistogram` holds bucket counts and a sum, nothing keyed on a request; scope is never a label | mcp `integration::admin_metrics` `metrics_count_queries_and_hooks_without_leaking_any_content` (secret-shaped strings planted in a `memory_query` query, a `/hook` prompt and the project name never appear in the scrape, nor do the session id, workspace name or root token; every label key is from the closed set; control: the query and hook histograms, the accepted-hook counter and the read tool-call counter move by exactly what was sent), `metrics_are_root_only_on_a_multi_user_server` (production `require_dual_auth` with a real DB-user key: anonymous 401, DB user 403, unknown bearer 401, root control 200); `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` include the route, `multiuser_operational_admin_routes_allow_root` admits root | STRONG. Bite checks: with the route mounted outside the gate the three refusal tests fail; with the query, the project name or the hook body rendered as a label value the leak test fails on each || 3e | The web health panel is root-only on a multi-user server, read-only and content-free | `ai-memory-web/src/routes/mod.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, shared with `/web/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect) gates `GET {web_slug}/health`, a GET-only route; `routes/health.rs` renders only counters, timestamps and configured provider/model labels, `provider_line` leaves out `last_error_message` (it can quote a response body), and the process side comes through `health::HealthProbe` as counts (`ServeHealthProbe` in `ai-memory-cli/src/commands/serve.rs` drops the journal's error text); the response is `Cache-Control: private, no-store` | `ai-memory-web` `tests/suite/health.rs` — `health_page_refuses_anonymous_once_operators_are_distinguished` (401, login redirect on navigation, no counters or fix lines), `health_page_refuses_a_db_user_and_admits_root` (403 "Root access required", no redirect, no counters; root control 200), `health_page_follows_the_admin_gate_on_a_single_operator_server` (control), `health_page_carries_no_secret_material` (secret-shaped strings planted in a failed LLM call's and a failed embed's provider error body, a page body, a page title and the project name never appear), `health_page_has_no_write_route` (POST/PUT/DELETE 405), plus a fixture per rendered check (`health_page_renders_each_failing_check_with_its_fix_line`, `health_page_renders_pending_spool_and_journal_checks`, `health_page_reports_a_healthy_server_as_passing`, and `src/health.rs` unit tests for every check id) | STRONG. Bite checks: with the `require_admin` call removed from the handler, the anonymous and DB-user tests fail; with `last_error_message` appended to the provider line, the planted-secret test fails || 3f | The 1.x token-management surface stays removed, and tokens it issued stay ordinary API keys (3.0) | `ai-memory-mcp/src/admin.rs` mounts only `GET /admin/users` on that path and no `/admin/users/{name}/expire`, `/revive` or `/rotate-token` route; `ai-memory-store` migration `V79__drop_legacy_user_token_columns.sql` drops `users.token_hash` / `token_expired_at` and the V55 mirror triggers, with a guard that aborts the migration if the `users` rebuild would lose any resolving reference to a user (credentials, sessions, grants, authors); authentication reads only `api_credentials` (`api_credentials.rs` `find_active_user_by_token_hash`, `revoked_at` and `expires_at` honored) | `admin.rs` `removed_legacy_token_routes_are_gone_for_every_tier` (production `require_dual_auth`; each removed route as root: 405 on `POST /admin/users`, 404 on the rest; as a DB user and as a legacy-token holder: 403 on `POST /admin/users`, 404 on the rest; anonymous 401; afterwards no user was created, no credential revoked, and the legacy token still authenticates), `legacy_user_token_is_managed_as_an_api_key` (an unprefixed legacy token authenticates as a non-root user, an expired one is 401, `api-key list` shows it as `legacy-user-token`, rotate retires the old secret, revoke refuses the new one); `ai-memory-store` `api_credentials.rs` `v79_upgrade_keeps_legacy_tokens_as_api_keys` (a V78 database seeded the 2.x way with active, expired and rotated tokens plus a web session: after V79 the active and rotated tokens authenticate, the expired and superseded ones do not, all three list as `legacy-user-token`, rotate/revoke work, the session survives, no FK violation) and `v79_rolls_back_rather_than_cascade_delete_credentials` (run with foreign keys on, V79 aborts and leaves the V78 schema and the token intact); `ai-memory-cli` `removed_user_token_commands_no_longer_parse` | STRONG. Bite checks: with a stub `POST /admin/users/{name}/expire` route mounted the route test fails; without V79 the upgrade test and the schema pin fail; without the guard the rollback test fails |-| 3g | A Basic browser sign-in on a server without human accounts never persists the root bearer in a cookie | `ai-memory-mcp/src/human_auth.rs` `require_dual_auth` accepts Basic (or an `ai_memory_auth` cookie an older build set) for GET only before human auth exists and sets no cookie on success; the browser resends Basic itself; `expire_legacy_cookie_mw` retires a leftover cookie once human auth is active | `human_auth.rs` `a_basic_sign_in_mints_no_cookie_holding_the_root_bearer` (no `Set-Cookie` carries the token, no `ai_memory_auth` is set; control: the Basic GET is served and the bearer still authenticates; bite-checked against the old cookie minting), `legacy_browser_credentials_stop_when_human_bootstrap_completes` (Basic and a leftover cookie both stop at bootstrap) | STRONG |+| 3g | A Basic browser sign-in on a server without human accounts never persists the root bearer in a cookie | `ai-memory-mcp/src/human_auth.rs` `require_dual_auth` accepts Basic (or an `ai_memory_auth` cookie an older build set) for GET only before human auth exists and sets no cookie on success; the browser resends Basic itself; `expire_legacy_cookie_mw` retires a leftover cookie once human auth is active; a request admitted this way carries `ai_memory_core::LegacyBrowserAuth`, which `/web/pending` reads to show CLI commands instead of decision buttons that would post and fail | `human_auth.rs` `a_basic_sign_in_mints_no_cookie_holding_the_root_bearer` (no `Set-Cookie` carries the token, no `ai_memory_auth` is set; control: the Basic GET is served and the bearer still authenticates; bite-checked against the old cookie minting), `legacy_browser_credentials_stop_when_human_bootstrap_completes` (Basic and a leftover cookie both stop at bootstrap), `only_a_legacy_browser_credential_is_marked_read_only` (Basic and the leftover cookie are marked, a Basic POST is still 401; control: the root bearer is unmarked and its POST is served; bite-checked by removing the insertion); `ai-memory-web` `pending_page_offers_cli_commands_instead_of_buttons_to_a_basic_browser` (bite-checked) | STRONG || 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS; the receiver-session check, which requires the receiving session to exist in the claim's own workspace, project and agent kind and refuses with `InvalidState` before the handoff row is touched; an ended receiver is final EXCEPT for the agents where `AgentKind::reuses_session_id_after_end()` holds — Grok and Kimi Code, whose harnesses reuse the native session id across SessionEnd→resume, so accepting reopens `ended_at` only after the claim-once guard) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff`; `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (receivers from a sibling project, another workspace, a different agent kind, and a nonexistent session are each refused as `InvalidState` with the handoff left open and every `accepted_*` column NULL; the matching receiver claims it; the same receiver retrying and a second matching session get `false` with the first claim intact; fails with the `project_id` or `agent_kind` predicate, or the missing-session refusal, removed. The `workspace_id` predicate is redundant defence in depth: project ids are globally unique, so the cross-workspace receiver is already caught by `project_id`); `multi_session.rs` `accept_reopens_an_ended_receiver_session_but_keeps_claim_once` (Grok reopen + no-steal) and `accept_reopens_an_ended_kimi_receiver_but_keeps_every_guard` (Kimi Code resume claims and reopens `ended_at`; adversarial controls: an ended claude-code receiver stays refused, a kimi-code receiver in another project stays refused, and the already-claimed guard still refuses the resumed kimi session a second baton) | STRONG || 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG || 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865) | STRONG |