Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge branch 'main' into release/2.6
AkitaOnRailsc3ec7abca829
diff --cc CHANGELOG.mdindex badd5706,e148247b..c1a164eb--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -271,6 -128,55 +271,65 @@@ and this project adheres to [Semantic Vsubagent under its parent's session id, so a subagent's events no longermark that session as a subagent: the parent's Stop, SessionEnd, summary andhandoff are kept. (#1041, #1048)++- Fixed the generated OpenCode 2 plugin ending every tracked session when++ OpenCode unloads it on idle-location eviction. Unload is not shutdown: the++ host and its sessions stay alive, so each eviction froze a live session++ (`SessionStart` cannot reopen an ended OpenCode session), fabricated a++ spurious summary page and open handoff, and made the next baton fetch fail++ with `invalid state: an ended session cannot accept a handoff`. Plugin++ unload no longer posts `session-end`; deletion (`session.deleted`) remains++ the end signal and a completed root turn already publishes its continuation++ checkpoint and baton. Regenerate the plugin with++ `ai-memory install-hooks --agent opencode2 --apply`. (#1074)+ - Corrected the `[auto_scope]` default in doc comments (`Config`,+ `AutoScopeSettings`, the `ActiveProjectMode` module docs, `serve`) and the+ README docs index: they still named `single` as the default or called+ `per_actor` opt-in, but the default has been `per_actor` since v1.39. (#1065)+ - Fixed `gemini-3.8-flash` consolidation and lint spending hidden thinking+ tokens on strict-JSON calls. The Gemini provider now sends+ `thinkingBudget = 0` to 3.8 Flash as it already did for 2.5 and 3.5 Flash+ (verified live: 0 thought tokens, about half the latency); 3.8 Flash-Lite+ keeps the field omitted until verified. (#1077)+ - Fixed the secret scrubber missing Gemini authorization keys. AI Studio has+ issued `AQ.Ab…` keys instead of `AIza…` since 2026-05-28, so a bare new key+ reached capture unredacted; it is now redacted as `google_api_key`. (#1077)+ - Fixed the OpenCode provider sending every Go/Zen model through Chat+ Completions. It now selects the published wire API per supported model:+ Responses, Anthropic Messages, or OpenAI-compatible Chat Completions.+ Claude Sonnet 5.5 and the legacy Sonnet 4 ID also use Messages.+ Its default model is now `mimo-v2.6-flash`, matching the default Go catalogue;+ Claude models require an explicit Zen base URL. Configured base URLs remain+ authoritative, with no automatic switching between Go and Zen billing.+ MiniMax M3/M2.7 and Qwen3.8 Max use Messages on Go and Chat Completions on+ Zen; Go's Muse Contributor IDs use Responses. Changing the base URL also+ reselects the transport while preserving configured headers, reasoning,+ and timeout.+ (#1080)+ - Fixed `[[_global:path]]` resolving against the source page's workspace+ instead of the reserved `_global` project in the default workspace. A+ page outside `default` can now graph-link to standing global pages, and+ `/web` points at the same home. Sibling `[[project:path]]` and explicit+ `[[workspace/project:path]]` are unchanged. Legacy rows that stored the+ project-only form with a NULL workspace resolve when the reserved page+ is next written. (#1042)+ - Fixed `ai-memory run claude` / `continue` exiting with Claude's "That session+ is running in the background" error when the linked session is a Claude Code+ background session that is still running and the launch carries any native+ flag. The launcher now confirms the session is live in this checkout with+ `claude agents --json` (only for a transcript recorded in the background) and+ opens it with `claude attach <id>`; any failure keeps the native resume.+ Documented the observed attach-hook behavior, early-exit import boundary and+ fallback validation limits.+ (#1052)++ ### Security+ - Fixed GHSA-7qj3-7wqw-m5w6: in multi-user mode a database user without a+ write grant on the reserved global preferences scope (`default/_global`)+ could write it, and its pages are unioned into every user's queries,+ including restricted projects. Writing it now needs root or an explicit+ `write` grant on `_global`, whichever way the scope is named; creating it+ grants nothing, reads stay open, and installs without database users are+ unchanged. Reported by @Josehbr.### Docs- Corrected the Codex support matrix to describe managed-run recovery from adiff --cc crates/ai-memory-cli/src/commands/run.rsindex 34bbc5f1,2ce1574b..b2a6dccc--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@@ -16,18 -16,17 +16,19 @@@ use ai_memory_workstream::JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode, LaunchPlan,LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,- build_launch_plan, build_launch_plan_with_env, claude_attached_background_session, clean_path,+ build_launch_plan, build_launch_plan_with_env, claude_attached_background_session,+ claude_live_background_attach_id, claude_session_ran_in_background, clean_path,crush_global_config_path, discover_native_session, export_transcript,- has_native_session_selector, inside_ai_jail_here, inspect_repository, jail_checklist,- jail_toggle, kiro_explicit_session_id, kiro_harness_from_source_cursor,- kiro_selects_non_default_engine, kiro_selects_v2_engine, kiro_selects_v3_engine,- kiro_v3_resume_uses_default_store, list_native_sessions, marked_choices, native_session_exists,- native_session_in_checkout, native_store_root, omp_profile_flag, omp_profile_flag_env,- parse_jail_toggles, store_override_vars, usable_ai_jail_here, wait_for_transcript_flush,+ has_native_session_selector, inside_ai_jail_here, inspect_repository,+ is_interactive_session_invocation, jail_checklist, jail_toggle, kiro_explicit_session_id,+ kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,+ kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,+ marked_choices, native_session_exists, native_session_in_checkout, native_store_root,+ omp_profile_flag, omp_profile_flag_env, parse_jail_toggles, store_override_vars,+ usable_ai_jail_here, wait_for_transcript_flush,};use anyhow::{Context as _, Result, anyhow};+use clap::ValueEnum as _;use tokio::process::Command;use tokio_util::sync::CancellationToken;@@@ -538,7 -336,11 +541,12 @@@ async fn run_once_with_wiring&repository.cwd,&run_env,));+ let interactive_session = is_interactive_session_invocation(harness, &native_args);+ let resumes_linked_session = !force_fresh+ && orphaned_session.is_none()+ && prepared.native_session_id.is_some()+ && plan.expected_session_id == prepared.native_session_id+ && !has_native_session_selector(harness, &native_args);if let Some(orphaned_session) = orphaned_session {let recorded = super::project_registry::recorded_session_store(config,diff --cc crates/ai-memory-mcp/src/server.rsindex 5b21b619,f7c6a0eb..e51f35be--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@@ -12668,6 -12055,234 +12673,235 @@@ mod tests.expect("a writer may delete");}+ /// Two users and a restricted project, for the global-scope write gate:+ /// `joao` writes `acme-app`, `maria` holds nothing anywhere.+ async fn global_gate_fixture(+ tmp: &TempDir,+ ) -> (+ Store,+ AiMemoryServer,+ ai_memory_core::UserId,+ ai_memory_core::UserId,+ ) {+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let acme = store+ .writer+ .get_or_create_project(ws, "acme-app", None)+ .await+ .unwrap();+ store+ .writer+ .set_access_mode(acme, ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ let mut users = Vec::new();+ for name in ["joao", "maria"] {+ users.push(+ store+ .writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ ai_memory_core::UserRole::User,+ None,+ false,+ )+ .await+ .unwrap(),+ );+ }+ grant_writer(store.db_path(), users[0], acme);+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, acme)+ .with_wiki(wiki);+ (store, server, users[0], users[1])+ }++ fn parts_as_user(user: ai_memory_core::UserId) -> axum::http::request::Parts {+ let mut parts = test_parts_default();+ parts.extensions.insert(AuthLevel::User);+ parts.extensions.insert(user);+ parts+ .extensions+ .insert(ai_memory_core::AuthorizedViewer(user));+ parts+ }++ fn global_page(+ path: &str,+ scope: Option<&str>,+ workspace: Option<&str>,+ project: Option<&str>,+ ) -> WritePageArgs {+ WritePageArgs {+ path: path.into(),+ body: "# Preferences\n\nglobalverify marker.".into(),+ title: None,+ tier: Some("semantic".into()),+ tags: vec![],+ pinned: false,+ project: project.map(str::to_owned),+ workspace: workspace.map(str::to_owned),+ scope: scope.map(str::to_owned),+ expires_at: None,++ metadata: Default::default(),+ }+ }++ /// GHSA-7qj3-7wqw-m5w6: the reserved global scope is unioned into every+ /// user's reads, so a database user without a write grant on it must not+ /// write it — through `scope: "global"` or by naming `default/_global` —+ /// nor delete from it. Having created `_global` first grants nothing.+ #[tokio::test]+ async fn a_user_without_a_global_grant_cannot_change_the_global_scope() {+ let tmp = TempDir::new().unwrap();+ let (store, server, _joao, maria) = global_gate_fixture(&tmp).await;++ for (label, args) in [+ (+ "scope: global",+ global_page("preferences.md", Some("global"), None, None),+ ),+ (+ "explicit default/_global",+ global_page("preferences.md", None, Some("default"), Some("_global")),+ ),+ ] {+ let err = server+ .memory_write_page(Parameters(args), OptionalParts(parts_as_user(maria)))+ .await+ .expect_err(label);+ assert!(+ err.message.contains("not authorized for _global"),+ "{label}: {}",+ err.message+ );+ }+ // Maria's refused write created `_global` and recorded her as its+ // creator; that must not have made her a writer.+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();+ let creator: Option<Vec<u8>> = conn+ .query_row(+ "SELECT created_by FROM projects WHERE name = '_global'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(creator.as_deref(), Some(maria.as_bytes().as_slice()));+ server+ .memory_write_page(+ Parameters(global_page("preferences.md", Some("global"), None, None)),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect_err("the creator of _global is not its writer");++ // Root (no viewer) writes a real global page; maria cannot delete it.+ server+ .memory_write_page(+ Parameters(global_page("preferences.md", Some("global"), None, None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .expect("root writes the global scope");+ server+ .memory_delete_page(+ Parameters(DeletePageArgs {+ path: "preferences.md".into(),+ project: Some("_global".into()),+ workspace: Some("default".into()),+ }),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect_err("maria holds no write grant on _global");+ server+ .memory_read_page(+ Parameters(ReadPageArgs {+ include_related: false,+ related_depth: None,+ path: Some("preferences.md".into()),+ query: None,+ project: Some("_global".into()),+ workspace: Some("default".into()),+ }),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect("the refused delete left the page, and reads stay open");+ }++ /// The legitimate half of GHSA-7qj3: a write grant on `_global` admits+ /// both spellings, and every user still reads the global page through the+ /// union on their own restricted project.+ #[tokio::test]+ async fn a_global_write_grant_admits_writes_and_the_union_stays_readable() {+ let tmp = TempDir::new().unwrap();+ let (store, server, joao, maria) = global_gate_fixture(&tmp).await;+ let global = ai_memory_store::create_global_scope(&store.writer)+ .await+ .unwrap();+ grant_writer(store.db_path(), maria, global.project_id);++ server+ .memory_write_page(+ Parameters(global_page("preferences.md", Some("global"), None, None)),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect("a write grant on _global admits scope: global");+ server+ .memory_write_page(+ Parameters(global_page(+ "style.md",+ None,+ Some("default"),+ Some("_global"),+ )),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect("a write grant on _global admits default/_global");++ let result = server+ .memory_query(+ Parameters(QueryArgs {+ query: "globalverify".into(),+ limit: Some(5),+ project: Some("acme-app".into()),+ scopes: Vec::new(),+ workspace: Some("default".into()),+ global: None,+ include_expired: None,+ include_superseded: None,+ pin_first: None,+ explain: None,+ as_of: None,+ answer: None,+ reasoning: None,+ }),+ OptionalParts(parts_as_user(joao)),+ )+ .await+ .expect("joao reads his restricted project");+ let value = tool_json(&result);+ let paths: Vec<&str> = value["global_scope_hits"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|hit| hit["path"].as_str())+ .collect();+ assert!(paths.contains(&"preferences.md"), "{value}");+ }+/// The finding that started #708, as a test.////// Two `role=user` accounts on upstream 2.1.1: alice writes a page into herdiff --cc crates/ai-memory-workstream/src/lib.rsindex e2b9bc2c,a2c395a3..51a14add--- a/crates/ai-memory-workstream/src/lib.rs+++ b/crates/ai-memory-workstream/src/lib.rs@@@ -23,8 -23,9 +23,9 @@@ pub use jail::pub use repository::{RepositoryIdentity, inspect_repository};pub use transcript::{AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate,- claude_attached_background_session, discover_native_session, export_transcript,+ claude_attached_background_session, claude_live_background_attach_id,+ claude_session_ran_in_background, discover_native_session, export_transcript,kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,- native_session_exists, native_session_in_checkout, native_store_root,+ native_memory_dir, native_session_exists, native_session_in_checkout, native_store_root,wait_for_transcript_flush,};diff --cc docs/security-boundaries.mdindex ec4cf477,cc0618be..c736e3d3--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@@ -22,10 -22,11 +22,11 @@@ boundary not yet built| # | Boundary | Enforcing code | Adversarial test(s) | Coverage ||---|----------|----------------|---------------------|----------|-| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs` | STRONG |+| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can) | STRONG || 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG |+ | 1c | Reserved `_global` scope is read-open, write-gated (GHSA-7qj3-7wqw-m5w6) | `ai-memory-store/src/project_authz.rs` `ProjectAuthz::authorize` (a write to `default/_global` needs root or a `write` grant in either access mode; creator ignored) fed by `resolve_project_authz`/`read_project_row` (`reserved_global`, grant read for the global scope regardless of mode); `ai-memory-mcp/src/server.rs` `memory_write_page` resolves `scope: "global"` through `write_target_ids_with_actor` like an explicit `default/_global` | `project_authz.rs` `the_global_scope_admits_writes_only_from_root_or_a_write_grant`; `server.rs` `a_user_without_a_global_grant_cannot_change_the_global_scope` (both spellings and delete refused for an ungranted user and for `_global`'s creator; page survives; reads stay open), `a_global_write_grant_admits_writes_and_the_union_stays_readable` (legitimate control: write grant admits both spellings, another user's restricted-project query still unions the page); bite-checked with the authz rule removed and with the raw `create_global_scope` path restored | STRONG || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | 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` | `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` | 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) | STRONG || 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff` | 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 |