Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): keep session-start context when a resumed session's claim is refused
AkitaOnRailsf085a52ec58a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 63f67d4a..78d51745 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,13 @@ version in [`docs/changelog/`](docs/changelog/):relay and wiki sync companions take the same `rustls-webpki` bump.### Fixed+- A resumed session that had already ended (`claude --resume` after a clean+ exit, for example) now still gets its session-start context. An ended+ session may not take a handoff, and that refused claim used to fail the whole+ session-start fetch whenever any handoff was open, so the session started+ with no profile digest, brief or inbox notice at all. The refusal now costs+ only the claim, and the handoff stays open.+- `mcp-bridge` and the `setup` self-check no longer send requests to theserver through `HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`, as the hooksalready did. A sandbox such as ai-jail exports a proxy with an emptydiff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 918f1d94..a4699f50 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1807,7 +1807,7 @@ async fn fetch_and_accept_handoff_at(None};let acceptance = if handoff.is_some() || managed.is_some() {- state+ match state.writer.accept_startup_context(handoff@@ -1826,7 +1826,19 @@ async fn fetch_and_accept_handoff_at(receiving_session,busy_since,)- .await?+ .await+ {+ Ok(acceptance) => acceptance,+ // A refused claim (a resumed session that already ended may not+ // take a baton, #840) claims nothing, since the transaction rolled+ // back. Like a refused admission chain it costs only the claim: the+ // handoff stays open and the rest of the on-start context is still+ // delivered, instead of the whole response coming back empty.+ Err(e) => {+ warn!(error = %e, "startup claim refused; delivering the rest of the session-start context");+ ai_memory_store::StartupContextAcceptance::default()+ }+ }} else {ai_memory_store::StartupContextAcceptance::default()};@@ -5318,6 +5330,52 @@ pub(crate) mod tests {);}+ /// A resumed session that had already ended may not take a baton+ /// (#840), but the refused claim must cost only the claim. Before, the+ /// refusal failed the whole fetch, so `claude --resume` of a session that+ /// had exited cleanly started with no on-start context at all (no profile+ /// digest, brief or inbox notice) whenever any baton was open.+ #[tokio::test]+ async fn a_resumed_ended_session_still_gets_its_session_start_context() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let resumed = "claude-ended-then-resumed";+ for event in ["session-start", "user-prompt", "session-end"] {+ process(+ &state,+ HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({ "session_id": resumed, "prompt": "pair the controller" }),+ ),+ None,+ Vec::new(),+ )+ .await+ .unwrap();+ }+ assert!(open_handoff_exists(&state).await, "the end left a baton");+ seed_inbox(&state, 1).await;++ let mut query = session_start_query(&tmp.path().to_string_lossy());+ query.session_id = Some(resumed.into());+ let body = fetch_and_accept_handoff(&state, query, None, Vec::new(), None)+ .await+ .unwrap()+ .unwrap_or_default();+ assert!(+ body.contains("1 cross-project message waiting"),+ "the rest of the on-start context must still arrive: {body:?}"+ );+ assert!(+ open_handoff_exists(&state).await,+ "the refused claim must leave the baton open"+ );+ }+/// With an empty inbox, the on-start block emits no inbox notice at all —/// `render_inbox_notice(0)` returns `None`, so nothing is appended.#[tokio::test]diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex d7cd6370..566ff922 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -42,7 +42,7 @@ means the boundary is not built yet.| 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; 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 || 3h | Cross-project `GET /admin/search` (no `workspace`/`project`, the `ai-memory search --global` path, #1253) is root-only on a multi-user server | `ai-memory-mcp/src/admin.rs` `handle_search` runs the no-scope branch through `ReaderPool::search_pages_with_meta` as `OPERATOR` (every project, each hit tagged with its workspace and project); the route sits in the operational router under `require_root_for_multiuser_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`), so a DB user or proxy-asserted user never reaches the unfiltered read. A partial scope is still a 400, never a silent global fallback. `ai-memory-cli/src/commands/search.rs` sends no scope only when `--global` is passed, and clap rejects `--global` with `--workspace`/`--project` | MCP `admin_status_search.rs` `global_search_never_reaches_a_non_root_caller` (a restricted project the user holds no grant on, for both a DB-user deployment and a trusted-proxy deployment with no `users` rows: user 403 and anonymous 401 with neither the sentinel path nor the query term in the body; root control 200 with both projects' hits), `global_search_tags_each_hit_with_its_workspace_and_project`, `search_rejects_partial_scope_instead_of_global_fallback`; the shared `admin.rs` all-admin 403/401 route matrix includes `/admin/search`; CLI `cli.rs` `search_global_parses_and_conflicts_with_an_explicit_scope` | STRONG. Bite check: with the gate's operator test forced off (`authorize(Capability::Admin, false)`) the refusal test fails on the DB-user case (200 instead of 403) |-| 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 |+| 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); router `a_resumed_ended_session_still_gets_its_session_start_context` (the session-start caller, `fetch_and_accept_handoff_at`, treats a refused claim as no claim: the ended claude-code receiver still gets the rest of its on-start context, and the baton stays open) | 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 |