Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(handoff): complete offer-mode safeguards
AkitaOnRailsb1a89d78f3d5
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 52489c14..5717ba4a 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -3762,6 +3762,9 @@ mod tests {[auth]secure_cookie = true+ [handoff]+ claim_on_session_start = false+[maintenance]enabled = falselint_interval_secs = 3600@@ -3816,6 +3819,7 @@ mod tests {assert_eq!(cfg.contradiction_band_min, 0.5);assert_eq!(cfg.contradiction_band_max, 0.8);assert!(cfg.auth.secure_cookie);+ assert!(!cfg.handoff.claim_on_session_start);assert!(!cfg.maintenance.enabled);assert_eq!(cfg.maintenance.lint_interval_secs, 3600);assert!(cfg.auto_improve.scheduler.enabled);@@ -3853,6 +3857,11 @@ mod tests {assert_eq!(cfg.auto_improve.pending_path, "_pending/review-bot");}+ #[test]+ fn handoff_claim_on_session_start_defaults_to_true() {+ assert!(Config::default().handoff.claim_on_session_start);+ }+#[test]fn gemini_embedding_provider_uses_google_defaults() {let mut cfg = Config {diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 7c4cd165..8674e226 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -11917,6 +11917,29 @@ mod tests {open_handoff_exists(&state).await,"offer mode must never claim the handoff on its own",);++ let accepted = state+ .writer+ .accept_handoff(ai_memory_core::HandoffAcceptance {+ handoff_id,+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ accepting_agent: AgentKind::Codex,+ accepting_session: None,+ accepting_user: None,+ owner_filter: ai_memory_core::OwnerFilter::Unattributed,+ receiving_cwd: None,+ })+ .await+ .unwrap();+ assert!(+ accepted,+ "an explicit exact-id accept must still claim the offered baton",+ );+ assert!(+ !open_handoff_exists(&state).await,+ "the explicit accept control must consume the offered baton",+ );}/// A listener that accepts connections and never replies, so a webhookdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex f272094a..0306b689 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -192,9 +192,13 @@ imports the native transcript tail and a Git checkpoint when the child exits.Every injected packet starts with a versioned origin marker. The Claudetranscript normalizer excludes a marked packet if Claude persists and reads itback, preventing delivered history from recursively re-entering the ledger.-An explicitly pending handoff is delivered before the managed event range;-their single-use delivery claims share one writer transaction after the-complete startup response has been assembled. Manual handoffs take precedence;+An explicitly pending handoff is considered before the managed event range.+By default their single-use delivery claims share one writer transaction after+the complete startup response has been assembled. With server-wide+`[handoff].claim_on_session_start = false`, SessionStart instead emits a+metadata-only notice naming the exact handoff id and leaves the row open for+an explicit `memory_handoff_accept`; the managed event range is still claimed.+Manual handoffs take precedence;otherwise the newest cwd-eligible automatic handoff is delivered, and thatsame transaction expires older eligible automatic handoffs while preservingmanual and sibling-directory work. Insertion also expires prior open automatic@@ -770,6 +774,9 @@ dedup_cold_clusters = false # A3 opt-in: cluster near-duplicate cold[slots] # optional shared-server injection boundaryper_user = false # shared + own slots in agent context+[handoff] # optional server-wide delivery policy+claim_on_session_start = true # false offers metadata; explicit accept claims+[consolidation] # LLM consolidation prompt sizingmax_input_tokens = 100000 # approximate whole-input target; min 6000# a flat chars-per-token heuristic, so itdiff --git a/docs/design-handoff-offer-not-claim.md b/docs/design-handoff-offer-not-claim.mdindex 406936d1..d79f5f30 100644--- a/docs/design-handoff-offer-not-claim.md+++ b/docs/design-handoff-offer-not-claim.md@@ -1,7 +1,8 @@# Design proposal: offer, don't claim, at session start (#959)-**Status: accepted design (maintainer review folded in, 2026-10-01) — not implemented.** The maintainer marked #959-design-first: it touches the single-claim contract (invariant #16 — a handoff+**Status: accepted design (maintainer review folded in, 2026-10-01). Option 1+is implemented on `release/2.6`; options 2 and 3 remain follow-up work.** The+maintainer marked #959 design-first: it touches the single-claim contract (invariant #16 — a handoffis claimed exactly once by two independent `state='open'` guards) in severalplaces at once, so this is the design pass requested before any code lands.@@ -29,7 +30,7 @@ over a directory-matched automatic one — working as documented, just not asexpected), but the remaining ask stood: the automatic claim at session starthas no opt-out, and `to_agent` is stored but never used to target delivery.-## Current model (what exists today)+## Baseline before implementation- **Claim site**: `fetch_and_accept_handoff_at` in `crates/ai-memory-hooks/src/router.rs`(~line 1355). Every `SessionStart` (and every `opencode run` /@@ -101,10 +102,10 @@ siblings in `crates/ai-memory-cli/src/config.rs`):claim_on_session_start = true # default: unchanged behavior```-**Where the switch lives.** A server-wide `[handoff]` key applies to every-operator on a shared server. Prefer (or additionally offer) a per-project-`.ai-memory.toml` marker key, so one team's repository can opt into offer mode-without changing another's. Settle this before implementation.+**Where the switch lives.** The initial implementation uses a server-wide+`[handoff]` key, which applies to every operator on a shared server. A+per-project `.ai-memory.toml` override remains a possible follow-up for teams+that need different behavior per repository.When `true` (default — **no behavior change for existing installs**),`fetch_and_accept_handoff_at` claims exactly as it does today.@@ -244,4 +245,4 @@ interact).harness.- Regression: existing handoff-selection and owner-filter tests in`reader.rs` continue to pass unchanged (this proposal adds a filter stage,- it does not alter the ones already there).\ No newline at end of file+ it does not alter the ones already there).diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex eb80f53b..2065ee11 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -34,6 +34,7 @@ boundary not yet built.| 4e | A live session's baton stays its own until the session is quiet | `ai-memory-store/src/ops.rs` - `expire_same_cwd_auto_handoffs` spares batons of other open sessions; `accept_handoff_in_transaction(.., busy_since)` re-checks inside the claim that the source is not an open session with observations after the cutoff, and its sweep `expire_superseded_auto_handoffs(.., busy_since)` spares a busy open session's baton (every open session's when `None`, the explicit MCP accept); `reader.rs` `startup_handoff` selects with the same cutoff; `ai-memory-hooks/src/router.rs` `LIVE_BATON_QUIET_PERIOD` | `multi_session.rs` `parallel_live_sessions_keep_their_own_checkpoint_batons`, `startup_claim_rechecks_the_source_and_sweeps_only_quiet_open_batons`; `router.rs` `opencode_parallel_live_batons_are_owned_and_wait_for_quiet` - each fails with its guard removed | STRONG || 4f | Finalize-on-exit closes only a session the run provably owns (invariant #16) | `ai-memory-cli/src/commands/run.rs` `finalize_hookless_session` runs only for `harness.lacks_session_end_hook()` harnesses (Command Code, Kiro v2/v3, Antigravity); `own_native_session` returns a session only when it is named, chosen before the spawn, or linked under this run's own id in this checkout — a merely *discovered* native session (possibly a concurrent launch's) is never finalized | `run.rs` `a_session_linked_during_the_run_wins_over_discovery` — `own_native_session` returns `None` for the unlinked and other-checkout (`nested`) cases, so a foreign/concurrent session is refused; the named/linked control is finalized (#944) | STRONG || 4g | `memory_handoff_accept` `status` never points a caller at another session's baton | `ai-memory-store/src/reader.rs` `handoff_claimed_by_live_session` — the caller-supplied session id (header or native `_meta`, routing-only per row 6b) selects which claim to check, but the answer is bounded by the resolved `(workspace_id, project_id)`, the authenticated `handoff_owner_sql` owner filter, `state='accepted'`, and a still-open receiving session; `ai-memory-mcp/src/server.rs` `unclaimed_handoff` reports `consumed_by_hook` only on that match (and, for a requested `handoff_id`, only when it is the matched row), `none_pending` otherwise | `handoff_ownership.rs` `a_session_start_claim_is_confirmed_only_to_its_own_live_session` (forged session id under another operator, unattributed reader, foreign project, sibling session and ended session all empty; owner and root controls see the claim); `ai-memory-mcp` `tests/suite/handoff_identity.rs` `consumed_by_hook_is_reported_only_to_the_session_that_claimed_it` (over the production transport: a colleague forwarding the session id, the owner from another session, and a request with no session id all get `none_pending`; the claiming session gets `consumed_by_hook`) | STRONG |+| 4h | Offer-mode SessionStart never consumes or injects handoff-controlled text | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` branches on the startup configuration before admission/claim and `render_handoff_notice` emits only typed metadata (`HandoffId`, `AgentKind`, computed age); the normal writer CAS remains the only later claim path | `router.rs` `handoff_notice_is_metadata_only_and_never_carries_the_summary` plants hostile summary/questions/steps/files; `offer_mode_leaves_the_baton_open_and_notice_omits_the_summary` exercises the production hook route, asserts the row remains open, then proves the legitimate exact-id writer claim still consumes it (#1030) | STRONG || 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project | STRONG || 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs` | STRONG || 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`) | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed` | STRONG |diff --git a/docs/usage.md b/docs/usage.mdindex 3f5d57f3..5069b213 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -101,7 +101,8 @@ uncalled can). Pick it up explicitly:```This is server-wide — every operator on the server gets the same behavior.-The default (`true`) is unchanged for every existing install.+Restart the server after changing `config.toml`; configuration is loaded once+at startup. The default (`true`) is unchanged for every existing install.## Compaction recovery