Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: supersede stale automatic handoffs
AkitaOnRailseb9745019a61
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 91523e04..66a497ac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- Automatic handoff selection now prefers the newest cwd-eligible session over+ a stale, more-specific ancestor. A new automatic handoff expires prior open+ automatic handoffs from the exact cwd, and accepting the winner atomically+ expires older eligible automatic handoffs. Manual and sibling-directory+ handoffs remain open, preventing stale delivery and inflated pending counts.+ (#293)- OpenAI-compatible providers now send each structured operation's JSON Schemathrough `response_format=json_schema` by default, so local models cannotreplace consolidation JSON with prose or omit required fields. Explicitdiff --git a/README.md b/README.mdindex a9e34b54..4c2dbc69 100644--- a/README.md+++ b/README.md@@ -673,7 +673,11 @@ observation generation advances; the persisted generation watermark makesduplicate SessionEnd delivery and system clock skew converge without repeatedprovider work. The end watermark and automatic handoff commit atomically, andan interrupted keyed replay finishes the wiki commit, queue insert, and key-completion without duplicating that handoff.+completion without duplicating that handoff. On the next SessionStart, the+newest cwd-eligible automatic handoff wins; accepting it expires older eligible+automatic handoffs without consuming manual or sibling-directory work. A new+automatic handoff also expires prior open automatic handoffs from its exact+cwd, so repeated SessionEnds cannot accumulate there before a receiver starts.Recommended defaults:diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex b2ef9ab2..30bdfc40 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1020,9 +1020,10 @@ pub struct HandoffQuery {/// Identifier of the agent fetching the handoff. Used to mark the/// handoff as accepted-by; defaults to `Other` if unrecognised.pub agent: Option<String>,- /// Optional cwd filter. When provided, only handoffs whose stored- /// cwd matches this string are returned. Note: the cwd string is- /// not canonicalized; symlinked paths must match byte-for-byte.+ /// Optional receiving cwd. Automatic handoffs whose stored cwd is this+ /// directory or a path-boundary ancestor are eligible; manual handoffs are+ /// project-wide. Paths are string-normalized, not filesystem-canonicalized,+ /// so symlink aliases remain distinct.pub cwd: Option<String>,/// Workspace override (mirror of `HookQuery.workspace`). Lets the/// `session-start` hook fetch the handoff for the same `(workspace,@@ -1136,6 +1137,7 @@ async fn fetch_and_accept_handoff(agent,None,managed.as_ref().map(|managed| managed.run_id),+ query.cwd.clone(),).await?} else {@@ -5939,6 +5941,92 @@ mod tests {);}+ #[tokio::test]+ async fn session_start_passes_receiving_cwd_to_auto_handoff_cleanup() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;++ async fn insert_auto(+ state: &HookState,+ cwd: &str,+ summary: &str,+ ) -> ai_memory_core::HandoffId {+ let session_id = SessionId::new();+ state+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ agent_kind: AgentKind::ClaudeCode,+ cwd: Some(cwd.into()),+ })+ .await+ .unwrap();+ state+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ from_session_id: Some(session_id),+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: Some(cwd.into()),+ summary: summary.into(),+ open_questions: Vec::new(),+ next_steps: Vec::new(),+ files_touched: Vec::new(),+ })+ .await+ .unwrap()+ }++ let stale = insert_auto(&state, "/repo/api", "STALE-SPECIFIC").await;+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ let newest = insert_auto(&state, "/repo", "NEWEST-PARENT").await;+ let rendered = fetch_and_accept_handoff(+ &state,+ HandoffQuery {+ agent: Some("codex".into()),+ cwd: Some("/repo/api/src".into()),+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ project_strategy: None,+ briefing: None,+ briefing_budget: None,+ managed_run: None,+ session_id: None,+ },+ None,+ )+ .await+ .unwrap()+ .unwrap();++ assert!(rendered.contains("NEWEST-PARENT"));+ assert!(!rendered.contains("STALE-SPECIFIC"));+ assert_eq!(+ state+ .reader+ .handoff_by_id(stale)+ .await+ .unwrap()+ .unwrap()+ .state,+ ai_memory_core::HandoffState::Expired+ );+ assert_eq!(+ state+ .reader+ .handoff_by_id(newest)+ .await+ .unwrap()+ .unwrap()+ .state,+ ai_memory_core::HandoffState::Accepted+ );+ }+#[tokio::test]async fn managed_session_start_delivers_ledger_and_pending_handoff() {use ai_memory_core::{NewWorkstreamEvent, WorkstreamEventKind};diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 1467755b..337fb708 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -597,7 +597,8 @@ struct HandoffBeginArgs {#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]struct HandoffAcceptArgs {- /// Restrict the search to handoffs created for a specific cwd.+ /// Set the receiving cwd so automatic handoffs from that directory or a+ /// path-boundary ancestor are eligible./// **Omit unless the user explicitly asks about a handoff from a/// *different* directory** — by default this scopes to the current/// project (the SessionStart hook usually pre-fetches it into context).@@ -2217,16 +2218,17 @@ impl AiMemoryServer {&aps_actor,).await?;+ let receiving_cwd = args.cwd;let handoff = self.reader- .latest_open_handoff(ws, proj, args.cwd)+ .latest_open_handoff(ws, proj, receiving_cwd.clone()).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;match handoff {None => ok_json(&serde_json::json!({ "handoff": null })),Some(h) => {self.writer- .accept_handoff(h.id, AgentKind::Other, None)+ .accept_handoff(h.id, AgentKind::Other, None, receiving_cwd).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;ok_json(&serde_json::json!({ "handoff": h }))diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 7a4e9204..09432615 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -124,9 +124,10 @@ impl Store {mod tests {use super::*;use ai_memory_core::{- ActorContext, AgentKind, LinkTarget, ManagedRunId, NewHandoff, NewObservation, NewPage,- NewSession, NewWorkstreamEvent, ObservationId, ObservationKind, PageId, PagePath,- ProjectId, Sanitized, Sanitizer, SessionId, Tier, UserId, WorkspaceId, WorkstreamEventKind,+ ActorContext, AgentKind, HandoffId, HandoffState, LinkTarget, ManagedRunId, NewHandoff,+ NewObservation, NewPage, NewSession, NewWorkstreamEvent, ObservationId, ObservationKind,+ PageId, PagePath, ProjectId, Sanitized, Sanitizer, SessionId, Tier, UserId, WorkspaceId,+ WorkstreamEventKind,};use rusqlite::{Connection, params};use sha2::{Digest, Sha256};@@ -4803,6 +4804,7 @@ mod tests {AgentKind::Codex,None,Some(run.run_id),+ None,).await.unwrap();@@ -4830,6 +4832,7 @@ mod tests {AgentKind::Codex,None,Some(run.run_id),+ None,).await.unwrap();@@ -4848,6 +4851,71 @@ mod tests {Some(second_handoff),"a failed managed claim must roll back the handoff transition");++ async fn insert_auto_handoff(+ store: &Store,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ cwd: &str,+ ) -> HandoffId {+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id,+ project_id,+ agent_kind: AgentKind::ClaudeCode,+ cwd: Some(cwd.into()),+ })+ .await+ .unwrap();+ store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id,+ project_id,+ from_session_id: Some(session_id),+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: Some(cwd.into()),+ summary: cwd.into(),+ open_questions: Vec::new(),+ next_steps: Vec::new(),+ files_touched: Vec::new(),+ })+ .await+ .unwrap()+ }++ let stale_auto = insert_auto_handoff(&store, ws, proj, "/repo/api").await;+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ let selected_auto = insert_auto_handoff(&store, ws, proj, "/repo").await;+ let rejected_auto = store+ .writer+ .accept_startup_context(+ Some(selected_auto),+ AgentKind::Codex,+ None,+ Some(run.run_id),+ Some("/repo/api/src".into()),+ )+ .await+ .unwrap();+ assert_eq!(rejected_auto, StartupContextAcceptance::default());+ for handoff_id in [stale_auto, selected_auto] {+ assert_eq!(+ store+ .reader+ .handoff_by_id(handoff_id)+ .await+ .unwrap()+ .unwrap()+ .state,+ HandoffState::Open,+ "a rejected managed claim must not accept or expire automatic handoffs"+ );+ }}#[tokio::test]diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 5e0a4992..146a576e 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -1257,6 +1257,30 @@ fn insert_handoff_row(conn: &Transaction<'_>, h: &NewHandoff) -> StoreResult<Han});let from_agent = h.from_agent.as_str();let to_agent = h.to_agent.map(AgentKind::as_str);+ // A newer automatic handoff from the exact same cwd is the only one that+ // can ever win there, even before a SessionStart occurs. Bound abandoned+ // same-directory sessions without touching deliberate manual handoffs or+ // independent parent/sibling cwd scopes.+ if from_session.is_some() {+ let expired = conn.execute(+ "UPDATE handoffs SET state = 'expired' \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND state = 'open' AND from_session_id IS NOT NULL \+ AND (cwd = ?3 OR (cwd IS NULL AND ?3 IS NULL))",+ params![h.workspace_id.as_bytes(), h.project_id.as_bytes(), cwd],+ )?;+ if expired > 0 {+ audit(+ conn,+ "expire_superseded_handoffs",+ Some(h.workspace_id.as_bytes()),+ Some(h.project_id.as_bytes()),+ None,+ None,+ now,+ )?;+ }+ }// Insert + audit atomically. Handoffs are keyed by agent/session, not a DB// user, so the audit author is NULL — the row records the lifecycle event// (op + workspace/project + time), not an operator identity.@@ -1324,9 +1348,16 @@ pub fn accept_handoff(handoff_id: &HandoffId,accepting_agent: AgentKind,accepting_session: Option<&SessionId>,+ receiving_cwd: Option<&str>,) -> StoreResult<()> {let tx = conn.transaction()?;- accept_handoff_in_transaction(&tx, handoff_id, accepting_agent, accepting_session)?;+ accept_handoff_in_transaction(+ &tx,+ handoff_id,+ accepting_agent,+ accepting_session,+ receiving_cwd,+ )?;tx.commit()?;Ok(())}@@ -1336,10 +1367,30 @@ pub(crate) fn accept_handoff_in_transaction(handoff_id: &HandoffId,accepting_agent: AgentKind,accepting_session: Option<&SessionId>,+ receiving_cwd: Option<&str>,) -> StoreResult<bool> {let now = Timestamp::now().as_microsecond();let agent = accepting_agent.as_str();let session: Option<&[u8]> = accepting_session.map(|s| &s.as_bytes()[..]);+ let metadata = tx+ .query_row(+ "SELECT workspace_id, project_id, from_session_id IS NOT NULL, cwd, created_at \+ FROM handoffs WHERE id = ?1 AND state = 'open'",+ params![handoff_id.as_bytes()],+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, Vec<u8>>(1)?,+ row.get::<_, bool>(2)?,+ row.get::<_, Option<String>>(3)?,+ row.get::<_, i64>(4)?,+ ))+ },+ )+ .optional()?;+ let Some((workspace_id, project_id, automatic, cwd, created_at)) = metadata else {+ return Ok(false);+ };let (ws, proj) = handoff_scope(tx, handoff_id)?;let changed = tx.execute("UPDATE handoffs SET state = 'accepted', accepted_by = ?1, accepted_at = ?2, \@@ -1358,10 +1409,92 @@ pub(crate) fn accept_handoff_in_transaction(None,now,)?;+ if automatic {+ let expired = expire_superseded_auto_handoffs(+ tx,+ handoff_id,+ &workspace_id,+ &project_id,+ cwd.as_deref(),+ created_at,+ receiving_cwd,+ )?;+ if expired > 0 {+ audit(+ tx,+ "expire_superseded_handoffs",+ ws.as_ref(),+ proj.as_ref(),+ None,+ None,+ now,+ )?;+ }+ }}Ok(changed > 0)}+/// Expire older automatic handoffs that were eligible for the same receiving+/// cwd as the accepted handoff. Manual and sibling-directory handoffs are+/// deliberately excluded.+fn expire_superseded_auto_handoffs(+ tx: &Transaction<'_>,+ accepted_id: &HandoffId,+ workspace_id: &[u8],+ project_id: &[u8],+ accepted_cwd: Option<&str>,+ accepted_created_at: i64,+ receiving_cwd: Option<&str>,+) -> StoreResult<usize> {+ let receiving_cwd = receiving_cwd.or(accepted_cwd);+ let accepted_key = crate::reader::handoff_selection_key(+ false,+ accepted_created_at,+ accepted_cwd,+ *accepted_id,+ );+ let mut stmt = tx.prepare(+ "SELECT id, cwd, created_at FROM handoffs \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND state = 'open' AND from_session_id IS NOT NULL",+ )?;+ let rows = stmt.query_map(params![workspace_id, project_id], |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, Option<String>>(1)?,+ row.get::<_, i64>(2)?,+ ))+ })?;+ let mut ids = Vec::new();+ for row in rows {+ let (id_bytes, cwd, created_at) = row?;+ let id = HandoffId::from_slice(&id_bytes)?;+ if crate::reader::auto_handoff_matches_cwd(cwd.as_deref(), receiving_cwd)+ && crate::reader::handoff_selection_key(false, created_at, cwd.as_deref(), id)+ < accepted_key+ {+ ids.push(id_bytes);+ }+ }+ drop(stmt);++ let mut expired = 0;+ for chunk in ids.chunks(500) {+ let placeholders = std::iter::repeat_n("?", chunk.len())+ .collect::<Vec<_>>()+ .join(", ");+ expired += tx.execute(+ &format!(+ "UPDATE handoffs SET state = 'expired' \+ WHERE state = 'open' AND id IN ({placeholders})"+ ),+ rusqlite::params_from_iter(chunk.iter().map(Vec::as_slice)),+ )?;+ }+ Ok(expired)+}+/// Mark an open handoff expired so it will no longer be consumed.pub fn cancel_handoff(conn: &mut Connection, handoff_id: &HandoffId) -> StoreResult<bool> {let now = Timestamp::now().as_microsecond();@@ -2708,7 +2841,7 @@ mod tests {assert_eq!(state, "open");assert!(accepted_by.is_none());- accept_handoff(&mut conn, &id, AgentKind::Codex, None).unwrap();+ accept_handoff(&mut conn, &id, AgentKind::Codex, None, None).unwrap();let (state, accepted_by): (String, Option<String>) = conn.query_row("SELECT state, accepted_by FROM handoffs WHERE id = ?1",@@ -2723,10 +2856,60 @@ mod tests {// either succeed silently or fail clearly, never corrupt// the row. (Current impl is a no-op UPDATE with a state// guard.)- let second = accept_handoff(&mut conn, &id, AgentKind::Codex, None);+ let second = accept_handoff(&mut conn, &id, AgentKind::Codex, None, None);assert!(second.is_ok(), "double-accept must not error");}+ #[test]+ fn failed_auto_handoff_insert_rolls_back_same_cwd_expiration() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let first_session = SessionId::new();+ begin_session(+ &mut conn,+ &NewSession {+ id: first_session,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::ClaudeCode,+ cwd: Some("/repo".into()),+ },+ )+ .unwrap();+ let handoff = |session_id| NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: Some(session_id),+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: Some("/repo".into()),+ summary: "continue".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ };+ let first = insert_handoff(&mut conn, &handoff(first_session)).unwrap();++ let error = insert_handoff(&mut conn, &handoff(SessionId::new()))+ .expect_err("a missing source session must violate the foreign key");+ assert!(matches!(error, StoreError::Sqlite(_)));+ let state: String = conn+ .query_row(+ "SELECT state FROM handoffs WHERE id = ?1",+ params![first.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(+ state, "open",+ "the failed transaction must restore the prior handoff"+ );+ assert_eq!(+ audit_row_for(&conn, "expire_superseded_handoffs").0,+ 0,+ "the rolled-back expiration must leave no audit row"+ );+ }+/// The handoff lifecycle (insert / accept / cancel) writes audit rows,/// scoped to the handoff's workspace/project, with a NULL author (handoffs/// are agent/session-keyed, not owned by a DB user).@@ -2746,7 +2929,7 @@ mod tests {files_touched: vec![],};let id = insert_handoff(&mut conn, &new()).unwrap();- accept_handoff(&mut conn, &id, AgentKind::Codex, None).unwrap();+ accept_handoff(&mut conn, &id, AgentKind::Codex, None, None).unwrap();let id2 = insert_handoff(&mut conn, &new()).unwrap();assert!(cancel_handoff(&mut conn, &id2).unwrap());@@ -2762,7 +2945,7 @@ mod tests {);// Idempotent misses stay out of the trail: a double-accept and a// cancel of an already-accepted handoff change no row, audit nothing.- accept_handoff(&mut conn, &id, AgentKind::Codex, None).unwrap();+ accept_handoff(&mut conn, &id, AgentKind::Codex, None, None).unwrap();assert!(!cancel_handoff(&mut conn, &id).unwrap());assert_eq!(audit_row_for(&conn, "accept_handoff").0,diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 8ed08601..86377d3c 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -2267,8 +2267,8 @@ impl ReaderPool {/// ancestor-or-equal of `cwd_filter` (path-boundary, the prior art's/// check rather than exact equality: a handoff left in `/repo` reaches a/// session in `/repo/api`, but never `/repo-other`). Among candidates a- /// manual handoff wins over an auto one, then the most specific cwd, then- /// the most recent — so an explicit "where we left off" baton+ /// manual handoff wins over an auto one, then the most recent, with cwd+ /// specificity only breaking timestamp ties — so an explicit "where we left off" baton/// deterministically beats the heuristic SessionEnd handoff, regardless of/// whether the model passed a cwd. With `cwd_filter == None` every open/// handoff is a candidate (project-wide read, e.g. the web overview). The@@ -5015,7 +5015,7 @@ fn telemetry_count_from_row(/// Normalize a cwd for comparison: treat Windows backslashes as path/// separators and trim trailing separators while keeping a bare root as `/`./// Pure and string-only; it does not touch the filesystem.-fn normalize_cwd(p: &str) -> std::borrow::Cow<'_, str> {+pub(crate) fn normalize_cwd(p: &str) -> std::borrow::Cow<'_, str> {let replaced = if p.contains('\\') {std::borrow::Cow::Owned(p.replace('\\', "/"))} else {@@ -5036,7 +5036,7 @@ fn normalize_cwd(p: &str) -> std::borrow::Cow<'_, str> {/// `/repo/api` but neither `/repo-other` nor `/repository`. Inputs are/// normalized first. Pure; no SQL `LIKE`, so `%`/`_` in a path cannot act/// as wildcards.-fn cwd_within(ancestor: &str, descendant: &str) -> bool {+pub(crate) fn cwd_within(ancestor: &str, descendant: &str) -> bool {let a = normalize_cwd(ancestor);let d = normalize_cwd(descendant);if a == d {@@ -5060,7 +5060,17 @@ fn is_handoff_candidate(h: &Handoff, cwd_filter: Option<&str>) -> bool {if h.from_session_id.is_none() {return true;}- match (cwd_filter, h.cwd.as_deref()) {+ auto_handoff_matches_cwd(h.cwd.as_deref(), cwd_filter)+}++/// Whether an automatic handoff is eligible for a session starting in+/// `cwd_filter`. Shared with the acceptance path so selection and supersession+/// apply exactly the same path-boundary rule.+pub(crate) fn auto_handoff_matches_cwd(+ handoff_cwd: Option<&str>,+ cwd_filter: Option<&str>,+) -> bool {+ match (cwd_filter, handoff_cwd) {// Project-wide read: every open handoff is a candidate.(None, _) => true,// No stored cwd: treat as project-wide.@@ -5070,33 +5080,50 @@ fn is_handoff_candidate(h: &Handoff, cwd_filter: Option<&str>) -> bool {}}-fn handoff_selection_key(h: &Handoff) -> (bool, usize, Timestamp) {- let manual = h.from_session_id.is_none();- // cwd specificity discriminates only AUTO handoffs (most specific subdir- // wins). For manual handoffs it must be neutral so the NEWEST manual wins,- // not whichever happens to carry the longest cwd. Normalize before counting- // so legacy `/repo/` rows do not outrank equivalent `/repo` rows.+pub(crate) fn handoff_selection_key(+ manual: bool,+ created_at_micros: i64,+ cwd: Option<&str>,+ id: HandoffId,+) -> (bool, i64, usize, [u8; 16]) {+ // Cwd specificity discriminates only equal-time AUTO handoffs. For manual+ // handoffs it must be neutral so the newest manual wins, not whichever+ // happens to carry the longest cwd. Normalize before counting so legacy+ // `/repo/` rows do not outrank equivalent `/repo` rows.let auto_specificity = if manual {0} else {- h.cwd.as_deref().map_or(0, |cwd| normalize_cwd(cwd).len())+ cwd.map_or(0, |cwd| normalize_cwd(cwd).len())};(- manual, // manual beats auto- auto_specificity, // most specific auto cwd- h.created_at, // newest+ manual, // manual beats auto+ created_at_micros, // newest+ auto_specificity, // most specific equal-time auto cwd+ *id.as_bytes(), // deterministic final tie-break)}fn prefer_handoff(a: &Handoff, b: &Handoff) -> std::cmp::Ordering {- handoff_selection_key(a).cmp(&handoff_selection_key(b))+ handoff_selection_key(+ a.from_session_id.is_none(),+ a.created_at.as_microsecond(),+ a.cwd.as_deref(),+ a.id,+ )+ .cmp(&handoff_selection_key(+ b.from_session_id.is_none(),+ b.created_at.as_microsecond(),+ b.cwd.as_deref(),+ b.id,+ ))}/// Pick the handoff to deliver from a project's open handoffs.////// See [`ReaderPool::latest_open_handoff`] for the full contract: manual handoffs/// are project-wide, auto handoffs are filtered by cwd path-boundary, and a-/// manual handoff always beats an auto one, then most specific cwd, then newest.+/// manual handoff always beats an auto one, then newest, with cwd specificity+/// only breaking timestamp ties.#[cfg(test)]fn select_open_handoff(candidates: Vec<Handoff>, cwd_filter: Option<&str>) -> Option<Handoff> {candidates@@ -5434,7 +5461,8 @@ mod tests {use crate::Store;use ai_memory_core::{- AgentKind, Handoff, HandoffId, HandoffState, NewHandoff, ProjectId, SessionId, WorkspaceId,+ AgentKind, Handoff, HandoffId, HandoffState, NewHandoff, NewSession, ProjectId, SessionId,+ WorkspaceId,};#[test]@@ -5592,12 +5620,12 @@ mod tests {}#[test]- fn handoff_most_specific_ancestor_wins() {+ fn handoff_newer_parent_beats_stale_specific_ancestor() {let c = vec![handoff("a", Some("/a"), false, 2),handoff("ab", Some("/a/b"), false, 1),];- assert_eq!(pick(c, Some("/a/b/c")), "ab");+ assert_eq!(pick(c, Some("/a/b/c")), "a");}#[test]@@ -5697,6 +5725,148 @@ mod tests {assert_eq!(handoff.summary, "right project");}+ #[tokio::test]+ async fn accepting_newest_auto_expires_only_older_matching_autos() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "repo", Some("/repo".into()))+ .await+ .unwrap();++ async fn insert_auto(+ store: &Store,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ cwd: &str,+ summary: &str,+ ) -> HandoffId {+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id,+ project_id,+ agent_kind: AgentKind::ClaudeCode,+ cwd: Some(cwd.into()),+ })+ .await+ .unwrap();+ store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id,+ project_id,+ from_session_id: Some(session_id),+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: Some(cwd.into()),+ summary: summary.into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ })+ .await+ .unwrap()+ }++ let superseded_same_cwd =+ insert_auto(&store, ws, proj, "/repo/api", "older same cwd").await;+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ let stale_specific = insert_auto(&store, ws, proj, "/repo/api", "stale specific").await;+ assert_eq!(+ store+ .reader+ .handoff_by_id(superseded_same_cwd)+ .await+ .unwrap()+ .unwrap()+ .state,+ HandoffState::Expired,+ "a newer auto from the exact cwd must bound pre-accept accumulation"+ );+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ let newest_parent = insert_auto(&store, ws, proj, "/repo", "newest parent").await;+ let sibling = insert_auto(&store, ws, proj, "/repo/web", "sibling").await;++ let selected = store+ .reader+ .latest_open_handoff(ws, proj, Some("/repo/api/src".into()))+ .await+ .unwrap()+ .unwrap();+ assert_eq!(selected.id, newest_parent, "newest eligible auto must win");++ // A manual handoff appearing between selection and acceptance must not+ // be swept by automatic-handoff cleanup.+ let manual = store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: None,+ from_agent: AgentKind::Codex,+ to_agent: None,+ cwd: None,+ summary: "manual".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ })+ .await+ .unwrap();+ store+ .writer+ .accept_handoff(+ selected.id,+ AgentKind::Codex,+ None,+ Some("/repo/api/src".into()),+ )+ .await+ .unwrap();++ assert_eq!(+ store+ .reader+ .handoff_by_id(stale_specific)+ .await+ .unwrap()+ .unwrap()+ .state,+ HandoffState::Expired+ );+ assert_eq!(+ store+ .reader+ .handoff_by_id(newest_parent)+ .await+ .unwrap()+ .unwrap()+ .state,+ HandoffState::Accepted+ );+ for untouched in [sibling, manual] {+ assert_eq!(+ store+ .reader+ .handoff_by_id(untouched)+ .await+ .unwrap()+ .unwrap()+ .state,+ HandoffState::Open+ );+ }+ }+/// A stored `repo_path` equal to the operator's `$HOME` must never be/// prefix-matched: such a row would be a catch-all parent for every/// project beneath the home directory. A normal nested repo underdiff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 724294b8..0e3397fe 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -158,6 +158,7 @@ pub(crate) enum WriteCmd {handoff_id: HandoffId,accepting_agent: AgentKind,accepting_session: Option<SessionId>,+ receiving_cwd: Option<String>,reply: oneshot::Sender<StoreResult<()>>,},CancelHandoff {@@ -347,6 +348,7 @@ pub(crate) enum WriteCmd {accepting_agent: AgentKind,accepting_session: Option<SessionId>,managed_run_id: Option<ManagedRunId>,+ receiving_cwd: Option<String>,reply: oneshot::Sender<StoreResult<StartupContextAcceptance>>,},FinishWorkstreamRun {@@ -737,12 +739,14 @@ impl WriterHandle {handoff_id: HandoffId,accepting_agent: AgentKind,accepting_session: Option<SessionId>,+ receiving_cwd: Option<String>,) -> StoreResult<()> {let (tx, rx) = oneshot::channel();self.send(WriteCmd::AcceptHandoff {handoff_id,accepting_agent,accepting_session,+ receiving_cwd,reply: tx,}).await?;@@ -1358,6 +1362,7 @@ impl WriterHandle {accepting_agent: AgentKind,accepting_session: Option<SessionId>,managed_run_id: Option<ManagedRunId>,+ receiving_cwd: Option<String>,) -> StoreResult<StartupContextAcceptance> {let (tx, rx) = oneshot::channel();self.send(WriteCmd::AcceptStartupContext {@@ -1365,6 +1370,7 @@ impl WriterHandle {accepting_agent,accepting_session,managed_run_id,+ receiving_cwd,reply: tx,}).await?;@@ -1596,6 +1602,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {handoff_id,accepting_agent,accepting_session,+ receiving_cwd,reply,} => {let result = ops::accept_handoff(@@ -1603,6 +1610,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {&handoff_id,accepting_agent,accepting_session.as_ref(),+ receiving_cwd.as_deref(),);send_or_warn(reply, result, "accept_handoff");}@@ -1860,6 +1868,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {accepting_agent,accepting_session,managed_run_id,+ receiving_cwd,reply,} => {let result = (|| {@@ -1879,6 +1888,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {&handoff_id,accepting_agent,accepting_session.as_ref(),+ receiving_cwd.as_deref(),)?,None => false,};diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 91c893bf..7f379324 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -146,7 +146,12 @@ transcript 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.+complete startup response has been assembled. Manual handoffs take precedence;+otherwise the newest cwd-eligible automatic handoff is delivered, and that+same transaction expires older eligible automatic handoffs while preserving+manual and sibling-directory work. Insertion also expires prior open automatic+handoffs from the exact cwd, bounding repeated SessionEnds before any receiver+starts.ai-memory opens native stores read-only. Raw sanitized JSONL segments areimmutable, while SQLite supplies monotonic sequences, FTS, nativesource/delivery cursors, and idempotent retry state. A full-ledgerdiff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex 1d9fec16..987e2f7c 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -191,7 +191,7 @@ struct Handoff {}```-MCP tools `memory_handoff_begin` (writes a handoff row tagged `state=open`), `memory_handoff_accept` (acknowledges, returns the handoff content, marks `accepted_by`), and `memory_handoff_cancel` (marks an exact open handoff id expired when it was created by mistake). The user can stop Claude Code, start Codex, and Codex's session-start hook fetches the open handoff for the cwd. The cwd is matched by path-boundary (the prior art's check), not exact equality: a handoff left in `/repo` is delivered to a session in `/repo/api`, but never to `/repo-other`. A manual `memory_handoff_begin` handoff is stored with no cwd and so is project-wide, and is preferred over the auto SessionEnd handoff (then the most specific cwd, then the most recent) so an explicit "where we left off" baton is never shadowed by the heuristic one.+MCP tools `memory_handoff_begin` (writes a handoff row tagged `state=open`), `memory_handoff_accept` (acknowledges, returns the handoff content, marks `accepted_by`), and `memory_handoff_cancel` (marks an exact open handoff id expired when it was created by mistake). The user can stop Claude Code, start Codex, and Codex's session-start hook fetches the open handoff for the cwd. The cwd is matched by path-boundary (the prior art's check), not exact equality: a handoff left in `/repo` is delivered to a session in `/repo/api`, but never to `/repo-other`. A manual `memory_handoff_begin` handoff is stored with no cwd and so is project-wide, and is preferred over the auto SessionEnd handoff so an explicit "where we left off" baton is never shadowed by the heuristic one. Among cwd-eligible automatic handoffs the newest wins, with cwd specificity only breaking timestamp ties, so stale subdirectory context cannot shadow a newer parent-session handoff. Creating an automatic handoff expires prior open automatic handoffs from the exact cwd. Accepting one atomically expires older automatic candidates eligible for that receiving cwd; manual and sibling-directory handoffs remain open.agentmemory has this informally (`/handoff` skill); we make it explicit from day one because every research report flagged cross-agent as the v0.1 weak spot.diff --git a/docs/usage.md b/docs/usage.mdindex bff62841..e53128d4 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -17,7 +17,13 @@ general prompt/output DLP filter.You normally do not create handoffs by hand. With lifecycle hooksinstalled, session-end capture writes the handoff and the next-session-start hook fetches it.+session-start hook fetches it. Manual handoffs are project-wide and take+precedence over automatic SessionEnd handoffs. Among automatic handoffs that+match the receiving directory by path boundary, the newest is delivered;+creating a new automatic handoff expires prior open automatic handoffs from+that exact directory, and acceptance expires older matching automatic+handoffs without disturbing manual handoffs or pending work from sibling+directories.```text$ claude