Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(handoffs): let a resumed kimi-code session claim its handoff
AkitaOnRails3de2f38d66b4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 19ff988c..6f198792 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -59,6 +59,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0unknown or foreign-scope id, and `500` only for unexpected internalerrors. New tests in `admin::tests` cover the unknown, foreign-scope,and unparsable cases for both `approve` and `reject`. (#1205)+- Fixed Kimi Code sessions resumed after `SessionEnd` never receiving an+ open handoff. Kimi Code reuses its native session id when a session is+ resumed, so the receiver row already had `ended_at` set when the resumed+ session asked for its handoff, and `accept_handoff` refused the claim with+ "an ended session cannot accept a handoff" — an error the `/handoff` route+ swallows as an empty 200, leaving the handoff open forever.+ `AgentKind::reuses_session_id_after_end()` now covers Kimi Code alongside+ Grok, so accepting reopens the ended receiver row. Every surrounding guard+ is unchanged: an ended session of any other agent is still final, a+ receiver in another project is still refused, and the claim-once guard+ still stops the resumed session from taking a second baton. Covered by an+ adversarial integration test in `multi_session.rs` and a unit test on the+ predicate itself.## [2.6.3] - 2026-10-09diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 0f081fa1..db04b72a 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -477,14 +477,17 @@ impl AgentKind {////// Grok does: the same session id comes back after an end, so an already-/// ended receiver row is a live restart, not a corpse, and- /// `accept_handoff` reopens it. For every other agent an ended session is+ /// `accept_handoff` reopens it. Kimi Code does too: a resumed session+ /// reuses the native session id after `SessionEnd` (same shape as Grok;+ /// observed in production 2026-10). For every other agent an ended+ /// session is/// final — a late/out-of-order startup fetch must not rebind it to a new/// handoff, so accepting into an ended session stays an error (this is what/// keeps a lifecycle-only receiver from reclaiming after it released and/// ended).#[must_use]pub fn reuses_session_id_after_end(self) -> bool {- matches!(self, Self::Grok)+ matches!(self, Self::Grok | Self::KimiCode)}}@@ -599,6 +602,12 @@ mod tests {// source), so the handoff is delivered on UserPromptSubmit instead.assert!(!AgentKind::KimiCode.session_start_injects_handoff());assert!(AgentKind::KimiCode.user_prompt_injects_handoff());+ // A resumed session reuses the native id after SessionEnd (observed+ // in production 2026-10), the same shape as Grok's restart.+ assert!(AgentKind::KimiCode.reuses_session_id_after_end());+ assert!(AgentKind::Grok.reuses_session_id_after_end());+ assert!(!AgentKind::ClaudeCode.reuses_session_id_after_end());+ assert!(!AgentKind::Codex.reuses_session_id_after_end());}#[test]diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 290b657e..2c23bd31 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -907,6 +907,147 @@ async fn accept_reopens_an_ended_receiver_session_but_keeps_claim_once() {);}+/// Kimi Code reuses its native session id when a session is resumed after+/// SessionEnd (observed in production 2026-10: one kimi session row carried a+/// SessionEnd and then fresh session-start/user-prompt observations under the+/// same id), so it needs the same reopen exemption as Grok — without weakening+/// any guard around it: other agents stay final-after-end, a receiver in a+/// different project is still refused, and claim-once still binds the resumed+/// session.+#[tokio::test]+async fn accept_reopens_an_ended_kimi_receiver_but_keeps_every_guard() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ let new_handoff = |summary: &str| NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ from_session_id: None,+ summary: summary.into(),+ next_steps: Vec::new(),+ open_questions: Vec::new(),+ files_touched: Vec::new(),+ cwd: None,+ owner_user: None,+ };+ let accept = |id, agent: AgentKind, session: SessionId, ws, proj| HandoffAcceptance {+ handoff_id: id,+ workspace_id: ws,+ project_id: proj,+ accepting_agent: agent,+ accepting_session: Some(session),+ accepting_user: None,+ owner_filter: OwnerFilter::Any,+ receiving_cwd: None,+ };++ // Adversarial control: an ended Claude Code session is still final — the+ // reuse exemption must not leak to agents that never reuse ids.+ let claude = open_session(&store, ws, proj, AgentKind::ClaudeCode).await;+ store.writer.end_session(claude, None).await.unwrap();+ let claude_baton = store+ .writer+ .insert_handoff(new_handoff("claude control"))+ .await+ .unwrap();+ let err = store+ .writer+ .accept_handoff(accept(+ claude_baton,+ AgentKind::ClaudeCode,+ claude,+ ws,+ proj,+ ))+ .await+ .unwrap_err();+ assert!(+ matches!(err, StoreError::InvalidState(_)),+ "an ended claude-code session must still be refused: {err}"+ );++ // The resumed kimi-code session: ended at SessionEnd, then the same+ // native id comes back on resume and must be able to take the baton.+ let kimi = open_session(&store, ws, proj, AgentKind::KimiCode).await;+ store.writer.end_session(kimi, None).await.unwrap();++ let id = store+ .writer+ .insert_handoff(new_handoff("resume after restart"))+ .await+ .unwrap();+ let claimed = store+ .writer+ .accept_handoff(accept(id, AgentKind::KimiCode, kimi, ws, proj))+ .await+ .unwrap();+ assert!(+ claimed,+ "a resumed kimi-code session must be able to accept the handoff"+ );++ // The receiver row was reopened (ended_at cleared), not left a corpse.+ let kimi_bytes = kimi.as_bytes().to_vec();+ let ended_at: Option<i64> = store+ .reader+ .with_conn(move |conn| {+ Ok(conn.query_row(+ "SELECT ended_at FROM sessions WHERE id = ?1",+ rusqlite::params![kimi_bytes],+ |r| r.get(0),+ )?)+ })+ .await+ .unwrap();+ assert!(+ ended_at.is_none(),+ "accepting a handoff must reopen the ended kimi-code receiver session"+ );++ // Claim-once still binds kimi: the same resumed session must not take a+ // second baton.+ let second = store+ .writer+ .insert_handoff(new_handoff("a second baton"))+ .await+ .unwrap();+ let claimed_again = store+ .writer+ .accept_handoff(accept(second, AgentKind::KimiCode, kimi, ws, proj))+ .await+ .unwrap();+ assert!(+ !claimed_again,+ "a kimi-code session that already claimed a handoff must not claim another"+ );++ // Adversarial control: a kimi-code session living in a DIFFERENT project+ // must not claim this project's baton (scope isolation).+ let other_proj = store+ .writer+ .get_or_create_project(ws, "other-app".to_string(), None)+ .await+ .unwrap();+ let foreign = open_session(&store, ws, other_proj, AgentKind::KimiCode).await;+ let third = store+ .writer+ .insert_handoff(new_handoff("foreign attempt"))+ .await+ .unwrap();+ let err = store+ .writer+ .accept_handoff(accept(third, AgentKind::KimiCode, foreign, ws, proj))+ .await+ .unwrap_err();+ assert!(+ matches!(err, StoreError::InvalidState(_)),+ "a kimi-code session from another project must be refused: {err}"+ );+}+/// Parallel live sessions in one directory each own a turn-checkpoint baton./// One session's checkpoint, and a receiver claiming it, must leave the other/// live session's baton open: before this held, every completed turn retireddiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 9f49220e..07aea70c 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -34,7 +34,7 @@ means the boundary is not built yet.| 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-workstream/src/repository.rs` `inspect_repository_fingerprints` shares the launch identity derivation without checkpoint scans; `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; the explicit `--all` walk (`candidates_across_checkouts`) lists each linked checkout through its own fingerprint-scoped request and applies `--workspace` before any request; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`, `resume_all_walks_every_linked_checkout_and_honours_the_workspace_filter` (a foreign workspace filter sends no request; the default picker still ignores the registry); `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links); `repository.rs` `reports_origin_push_url_and_linked_worktree` verifies lightweight/full fingerprint parity and distinct worktree keys; CLI `resume_yolo_displays_picker_without_scanning_git_status` verifies listing skips status scans | STRONG || 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP; `serve.rs` mounts API-only and web+API protected routers behind `require_dual_auth` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control); `serve.rs` `api_only_mode_keeps_data_authenticated_and_web_absent` (anonymous API read refused, authenticated control admitted, browser route absent; #986) | STRONG || 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed); `ai-memory-mcp` `admin.rs` `pending_write_approve_foreign_scope_returns_404` and `pending_write_reject_foreign_scope_returns_404` — an id staged in workspace `alpha` requested through an existing `default` scope is 404 (never approved or rejected across the boundary), with the in-scope reject as the legitimate control (each proven to fail with 500 with the `pending_detail` guard removed, #1205) | 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) | `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`) | 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 || 4d | Native session rebind / drifted-end is owner+agent+cwd CAS | `ai-memory-store/src/ops.rs` — `session.moved` rebind gated on `agent==OpenCode` + `ended_at IS NULL` + lexical `normalize_cwd(stored)==normalize_cwd(from)`; `expire_same_cwd_auto_handoffs` AND-gated on `owner_user IS ?4 AND id IS NOT ?5` and on the source not being another still-open session (row 4e, #883); drifted `SessionEnd` ends only same owner+agent+cwd | `ops.rs` `native_move_rebinds_live_session_only_from_its_current_cwd`, `native_move_rejects_foreign_owner_and_ignores_completed_replay`, `drifted_session_end_ends_only_the_same_actor_agent_and_cwd` (#865) | STRONG |