Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(handoff,hooks): add create_on_session_end to opt out of automatic batons (#1043)
Vinícius Andradece25fa286db3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 762d7fbb..a7347247 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0harness, or a non-interactive launch silently consuming a baton meant fora specific session. Server-wide for now; a per-project override is left fora follow-up change. (#1030)+- Added `[handoff].create_on_session_end` (default `true` - unchanged+ behavior). When set to `false`, unmanaged session ends write the session+ summary page and enqueue consolidation as usual, but skip creating an+ automatic open handoff for the next session. Explicit handoffs created via+ `memory_handoff_begin` and managed workstream runs remain unaffected.+ Server-wide: applies to every operator on this server. (#1043)- Added a default-quit prompt after a successful interactive managed run so theoperator can re-run the current harness or switch to another installedharness in the same workstream. Utility, failed, interrupted,diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 09b17755..aa521392 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1356,6 +1356,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {session_consolidation_notify,capture_assistant_enabled: config.capture_assistant,claim_handoff_on_session_start: config.handoff.claim_on_session_start,+ create_handoff_on_session_end: config.handoff.create_on_session_end,per_user_slots: config.slots.per_user,subagent_sessions: std::sync::Arc::new(tokio::sync::Mutex::new(ai_memory_hooks::SubagentSessionSet::default(),diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 84b78cc6..4efe7e3a 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -1111,7 +1111,7 @@ impl Default for ConsolidationSettings {}}-/// `[handoff]` session-start handoff delivery settings (design: #959).+/// `[handoff]` session handoff delivery and creation settings.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(default)]pub struct HandoffSettings {@@ -1134,12 +1134,23 @@ pub struct HandoffSettings {/// Server-wide: applies to every operator on this server. A per-project/// override is intentionally left for a follow-up change.pub claim_on_session_start: bool,+ /// When `true` (default — unchanged behavior), ending an unmanaged session+ /// creates an automatic open handoff for the next session.+ ///+ /// When `false`, `SessionEnd` writes the session summary page and+ /// enqueues consolidation as usual, but does not create an automatic+ /// handoff (#1043). Explicit handoffs created via `memory_handoff_begin`+ /// and managed runs are unaffected.+ ///+ /// Server-wide: applies to every operator on this server.+ pub create_on_session_end: bool,}impl Default for HandoffSettings {fn default() -> Self {Self {claim_on_session_start: true,+ create_on_session_end: true,}}}@@ -3835,6 +3846,7 @@ mod tests {[handoff]claim_on_session_start = false+ create_on_session_end = false[maintenance]enabled = false@@ -3891,6 +3903,7 @@ mod tests {assert_eq!(cfg.contradiction_band_max, 0.8);assert!(cfg.auth.secure_cookie);assert!(!cfg.handoff.claim_on_session_start);+ assert!(!cfg.handoff.create_on_session_end);assert!(!cfg.maintenance.enabled);assert_eq!(cfg.maintenance.lint_interval_secs, 3600);assert!(cfg.auto_improve.scheduler.enabled);@@ -3933,6 +3946,11 @@ mod tests {assert!(Config::default().handoff.claim_on_session_start);}+ #[test]+ fn handoff_create_on_session_end_defaults_to_true() {+ assert!(Config::default().handoff.create_on_session_end);+ }+#[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 8674e226..039feec0 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -507,6 +507,10 @@ pub struct HookState {/// handoff; it renders a non-consuming notice instead and leaves the/// claim to an explicit `memory_handoff_accept` (design: #959).pub claim_handoff_on_session_start: bool,+ /// `[handoff].create_on_session_end` (default `true` — unchanged+ /// behavior). When `false`, `SessionEnd` writes the summary page and+ /// consolidates as usual, but skips automatic handoff creation (#1043).+ pub create_handoff_on_session_end: bool,/// Scoped session keys known to be subagents (seeded by `SubagentStart` / any/// marker-bearing event). For a project that opted into/// `drop_subagent_captures` (via its `.ai-memory.toml`, forwarded as the@@ -3491,7 +3495,9 @@ async fn process_authorized(// Other harnesses are not gated: Claude Code also sets `agent_type` on// a top-level `--agent` session, which still owns its baton.let child_session = env.agent == AgentKind::OpenCode && body_is_subagent(&env.raw);- let handoff = (!managed && !child_session).then(|| {+ let should_create_handoff =+ !managed && !child_session && (turn_checkpoint || state.create_handoff_on_session_end);+ let handoff = should_create_handoff.then(|| {build_auto_handoff(page_ws,page_proj,@@ -3625,6 +3631,12 @@ async fn process_authorized(managed_run = ?managed_run,"managed or child session ended; summary page written without legacy handoff",);+ } else if !state.create_handoff_on_session_end {+ info!(+ session = %session_id,+ page = %new_page.path,+ "session ended; summary page written without a handoff (create_on_session_end disabled)",+ );} else {// Only reachable through the admission refusal above, which// already warned with the reason; without this arm the refusal@@ -4993,6 +5005,7 @@ mod tests {session_consolidation_notify: None,capture_assistant_enabled: false,claim_handoff_on_session_start: true,+ create_handoff_on_session_end: true,subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),ingest_rate: Arc::new(tokio::sync::Mutex::new(IngestRateLimiter::disabled())),home_dir: None,@@ -11038,6 +11051,121 @@ mod tests {);}+ #[tokio::test]+ async fn session_end_with_create_on_session_end_disabled_writes_summary_page_without_handoff() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.create_handoff_on_session_end = false;+ let state = Arc::new(state);++ let session = SessionId::new();+ for event in ["session-start", "user-prompt", "session-end"] {+ let envelope = HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ cwd: Some(tmp.path().to_string_lossy().into_owned()),+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": session.to_string(),+ "cwd": tmp.path(),+ }),+ );+ process(&state, envelope, None, Vec::new()).await.unwrap();+ }++ // Summary page was written to the wiki.+ let pages = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap();+ assert!(+ pages+ .iter()+ .any(|p| p.path.as_str().starts_with("sessions/")),+ "SessionEnd must still write the session summary page when create_on_session_end is false"+ );++ // Session was ended in the database.+ let disposition = state+ .reader+ .session_end_disposition(+ session,+ state.workspace_id,+ state.project_id,+ AgentKind::ClaudeCode,+ )+ .await+ .unwrap();+ assert_eq!(+ disposition,+ ai_memory_store::SessionEndDisposition::AlreadyEnded,+ "session row must be marked ended"+ );++ // No open handoff was created.+ assert!(+ state+ .reader+ .latest_open_handoff(+ state.workspace_id,+ state.project_id,+ None,+ ai_memory_core::OwnerFilter::Any+ )+ .await+ .unwrap()+ .is_none(),+ "create_on_session_end = false must not create an automatic handoff"+ );+ }++ #[tokio::test]+ async fn session_end_with_create_on_session_end_enabled_creates_handoff() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ assert!(state.create_handoff_on_session_end, "default is true");+ let state = Arc::new(state);++ let session = SessionId::new();+ for event in ["session-start", "user-prompt", "session-end"] {+ let envelope = HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ cwd: Some(tmp.path().to_string_lossy().into_owned()),+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": session.to_string(),+ "cwd": tmp.path(),+ }),+ );+ process(&state, envelope, None, Vec::new()).await.unwrap();+ }++ assert!(+ state+ .reader+ .latest_open_handoff(+ state.workspace_id,+ state.project_id,+ None,+ ai_memory_core::OwnerFilter::Any+ )+ .await+ .unwrap()+ .is_some(),+ "default create_on_session_end = true must create an automatic handoff"+ );+ }+/// `GET /handoff` is the session-start delivery path, and it filters by the/// human the request names. An ingress that forwards an OIDC issuer/subject/// pair names one — the auth layer resolves it to `AuthLevel::User` — sodiff --git a/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rsindex 9eea2e18..8c5275f7 100644--- a/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rs+++ b/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rs@@ -177,6 +177,7 @@ impl MultiUserHarness {session_consolidation_notify: None,capture_assistant_enabled: false,claim_handoff_on_session_start: true,+ create_handoff_on_session_end: true,per_user_slots: false,mid_session_routing: ai_memory_core::MidSessionRouting::default(),subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),diff --git a/crates/ai-memory-mcp/tests/suite/stress_autoscope.rs b/crates/ai-memory-mcp/tests/suite/stress_autoscope.rsindex aa856f54..31a2baf2 100644--- a/crates/ai-memory-mcp/tests/suite/stress_autoscope.rs+++ b/crates/ai-memory-mcp/tests/suite/stress_autoscope.rs@@ -165,6 +165,7 @@ impl Harness {session_consolidation_notify: None,capture_assistant_enabled: false,claim_handoff_on_session_start: true,+ create_handoff_on_session_end: true,per_user_slots: false,mid_session_routing: ai_memory_core::MidSessionRouting::default(),subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 645ddcb8..231bde92 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -198,7 +198,9 @@ the complete startup response has been assembled. With server-wide`[handoff].claim_on_session_start = false`, SessionStart instead emits ametadata-only notice naming the exact handoff id and leaves the row open foran explicit `memory_handoff_accept`; the managed event range is still claimed.-Manual handoffs take precedence;+With server-wide `[handoff].create_on_session_end = false`, session end writes+the summary page and enqueues consolidation but skips creating an automatic+baton (#1043). 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@@ -811,8 +813,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+[handoff] # optional server-wide handoff policyclaim_on_session_start = true # false offers metadata; explicit accept claims+create_on_session_end = true # false stops automatic handoff creation at session end[consolidation] # LLM consolidation prompt sizingmax_input_tokens = 100000 # approximate whole-input target; min 6000diff --git a/docs/usage.md b/docs/usage.mdindex 5069b213..2c39dffd 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -104,6 +104,17 @@ This is server-wide — every operator on the server gets the same behavior.Restart the server after changing `config.toml`; configuration is loaded onceat startup. The default (`true`) is unchanged for every existing install.+### Opting out of automatic handoff creation at session end++By default, every unmanaged session end creates an open handoff for the next session. In a single-operator setup where consecutive sessions are part of the same continuous workflow or where batons are undesirable, automatic creation can be disabled while preserving the session summary page and consolidation:++```toml+[handoff]+create_on_session_end = false+```++When set to `false`, `SessionEnd` writes `sessions/<id>.md` and queues consolidation as usual, but skips creating an open handoff row (#1043). Explicit batons created with `memory_handoff_begin` and managed workstream runs remain unaffected. Like `claim_on_session_start`, this setting is server-wide.+## Compaction recoveryWhen Claude Code or Codex compact their working context, the