Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: recheck managed runs before idle session end
AkitaOnRails25f4ffd21ac3
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 2715484d..870d870a 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -4,7 +4,7 @@//! the writer thread would violate the single-writer invariant (see//! [`crate::writer`]).-use std::collections::BTreeSet;+use std::collections::{BTreeSet, HashSet};use ai_memory_core::{AgentKind, EntityId, HandoffAcceptance, HandoffId, IdentityKey, LinkTarget, MessageClaim,@@ -3336,7 +3336,10 @@ pub struct IdleEndCandidate {/// ordinary version. The lifecycle-only end applies the same scope/open/// guards before any mutation and re-checks substantiveness atomically,/// reporting `Lost` instead of downgrading substantive work to a boundary--/// only end.+/// only end. Immediately before the batch, the writer actor also snapshots+/// active managed-run session links. Since every managed-run link and idle+/// stamp is serialized through that actor, no link can land between this+/// decisive snapshot and the guarded writes.////// `ended_at` is the tick's clock (`now_us`), and/// `ended_observation_count` is counted in the same transaction as the@@ -3390,10 +3393,27 @@ fn idle_end_sessions_inner(mut pre_stamp: Option<&mut dyn FnMut(&mut Connection)>,) -> StoreResult<Vec<IdleEndResult>> {let mut results = Vec::with_capacity(candidates.len());+ // The production command holds the sole writer actor for the entire+ // batch, so one snapshot is decisive and avoids one query per candidate.+ // The test seam deliberately mutates between candidates and therefore+ // refreshes after each injected effect.+ let active_sessions = if pre_stamp.is_none() {+ Some(active_managed_run_sessions(conn)?)+ } else {+ None+ };for candidate in candidates {if let Some(hook) = pre_stamp.as_mut() {hook(conn);}+ let managed_run_active = match &active_sessions {+ Some(active) => active.contains(&candidate.session_id),+ None => active_managed_run_sessions(conn)?.contains(&candidate.session_id),+ };+ if managed_run_active {+ results.push(IdleEndResult::Lost);+ continue;+ }let result = match &candidate.action {IdleEndAction::Substantive {expected_page_id,@@ -3535,6 +3555,20 @@ fn idle_end_sessions_inner(Ok(results)}+fn active_managed_run_sessions(conn: &Connection) -> StoreResult<HashSet<SessionId>> {+ let mut stmt = conn.prepare(+ "SELECT native_session_id FROM managed_runs \+ WHERE state = 'active' AND native_session_id IS NOT NULL",+ )?;+ let mut rows = stmt.query([])?;+ let mut sessions = HashSet::new();+ while let Some(row) = rows.next()? {+ let native_session_id: String = row.get(0)?;+ sessions.insert(SessionId::from_native(&native_session_id));+ }+ Ok(sessions)+}+/// Mark a keyed hook event complete after its downstream effects finish.////// This transition is idempotent so two resumed processors can converge on thediff --git a/crates/ai-memory-store/tests/suite/idle_session_end.rs b/crates/ai-memory-store/tests/suite/idle_session_end.rsindex 263f8240..b27685ea 100644--- a/crates/ai-memory-store/tests/suite/idle_session_end.rs+++ b/crates/ai-memory-store/tests/suite/idle_session_end.rs@@ -12,7 +12,8 @@ use ai_memory_core::{Tier, WorkspaceId,};use ai_memory_store::{- AuditLogFilter, IdleEndAction, IdleEndCandidate, IdleEndResult, SessionEndDisposition, Store,+ AuditLogFilter, IdleEndAction, IdleEndCandidate, IdleEndResult, PrepareWorkstreamRun,+ SessionEndDisposition, Store, WorkstreamSelection,};const HOUR_US: i64 = 3_600_000_000;@@ -51,6 +52,18 @@ async fn begin(actor: Option<String>,) -> SessionId {let id = SessionId::new();+ begin_with_id(store, ws, proj, id, at_us, actor).await;+ id+}++async fn begin_with_id(+ store: &Store,+ ws: WorkspaceId,+ proj: ProjectId,+ id: SessionId,+ at_us: i64,+ actor: Option<String>,+) {store.writer.begin_session(NewSession {@@ -61,7 +74,6 @@ async fn begin(}).await.unwrap();- id}fn observation(@@ -1215,6 +1227,149 @@ async fn idle_end_pre_stamp_real_session_end_in_window_loses_the_cas() {);}+#[tokio::test]+async fn idle_end_writer_recheck_refuses_runs_linked_after_selection() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let now = jiff::Timestamp::now().as_microsecond();+ let watermark = now - 5 * HOUR_US;++ let substantive_native = "native-substantive-race";+ let substantive_sid = SessionId::from_native(substantive_native);+ begin_with_id(&store, ws, proj, substantive_sid, watermark - HOUR_US, None).await;+ insert(+ &store,+ observation(+ substantive_sid,+ ws,+ proj,+ ObservationKind::UserPrompt,+ watermark,+ "idle prompt",+ ),+ )+ .await;+ let page = session_page(&store, ws, proj, substantive_sid).await;++ let lifecycle_native = "native-lifecycle-race";+ let lifecycle_sid = SessionId::from_native(lifecycle_native);+ begin_with_id(&store, ws, proj, lifecycle_sid, watermark - HOUR_US, None).await;+ insert(+ &store,+ observation(+ lifecycle_sid,+ ws,+ proj,+ ObservationKind::Stop,+ watermark,+ "turn finished",+ ),+ )+ .await;++ let prepare = |name: &str| PrepareWorkstreamRun {+ workspace_id: ws,+ project_id: proj,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::New(name.into()),+ lease_owner: format!("launcher-{name}"),+ };+ let substantive_run = store+ .writer+ .prepare_workstream_run(prepare("substantive-race"))+ .await+ .unwrap();+ let lifecycle_run = store+ .writer+ .prepare_workstream_run(prepare("lifecycle-race"))+ .await+ .unwrap();++ // Both runs are active but unlinked when the reader would select these+ // sessions. Link each one in the last writer-side seam before its stamp.+ // The decisive recheck must reject both action arms.+ let mut links = std::collections::VecDeque::from([+ (substantive_run.run_id, substantive_native),+ (lifecycle_run.run_id, lifecycle_native),+ ]);+ let results = store+ .writer+ .end_idle_sessions_pre_stamp(+ vec![+ substantive(substantive_sid, ws, proj, page, 1, now, watermark),+ lifecycle_only(lifecycle_sid, ws, proj, now, watermark),+ ],+ true,+ Box::new(move |conn| {+ let (run_id, native_session_id) = links.pop_front().unwrap();+ conn.execute(+ "UPDATE managed_runs SET native_session_id = ?1 \+ WHERE id = ?2 AND state = 'active'",+ rusqlite::params![native_session_id, run_id.as_bytes()],+ )+ .unwrap();+ }),+ )+ .await+ .unwrap();++ assert_eq!(results, vec![IdleEndResult::Lost, IdleEndResult::Lost]);+ for session_id in [substantive_sid, lifecycle_sid] {+ assert_eq!(+ store+ .reader+ .session_end_disposition(session_id, ws, proj, AgentKind::Codex)+ .await+ .unwrap(),+ SessionEndDisposition::Open,+ "an active managed run keeps its session open"+ );+ }+ assert!(+ store+ .reader+ .list_audit_events(idle_audit_filter())+ .await+ .unwrap()+ .is_empty(),+ "the refused stamps write no audit rows"+ );+ let claim_at = now + 1;+ assert!(+ store+ .writer+ .claim_session_consolidation(claim_at, claim_at - 1)+ .await+ .unwrap()+ .is_none(),+ "the refused substantive stamp enqueues no consolidation job"+ );+ assert!(+ store+ .reader+ .page_versions(+ ws,+ proj,+ PagePath::new(format!("sessions/{lifecycle_sid}.md"))+ .unwrap()+ .to_string(),+ 10,+ 0,+ )+ .await+ .unwrap()+ .versions+ .is_empty(),+ "the refused lifecycle-only stamp creates no page"+ );+}+#[tokio::test]async fn idle_end_consolidation_enqueue_failure_rolls_back_and_retries() {let tmp = tempfile::tempdir().unwrap();diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 33790f6d..b3d8f581 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -139,6 +139,19 @@ Claude-shaped `Read` path is dropped, a public-path control is kept, and thesame body under an unknown agent stays unclassified. Removing Bob from eitherguard makes the corresponding adversarial test fail. Coverage: **STRONG**.+Boundary **4k** also has a writer-side managed-run race guard. After the+reader-side exclusion and immediately before the idle-end batch,+`ops.rs` `active_managed_run_sessions` derives every active run's native+session id in one batch snapshot and refuses a match. Managed-run+links and idle stamps share the single writer actor, so no link can interleave+after that decisive snapshot.+`idle_session_end.rs`+`idle_end_writer_recheck_refuses_runs_linked_after_selection` links active+runs in the pre-stamp seam for both substantive and lifecycle-only candidates;+both remain open, with no idle audit or consolidation job, while an unrelated+session is not blanket-refused by the existing positive controls. Removing the+writer-side recheck ends both sessions. Coverage: **STRONG**.+## Keeping this current (the standing protocol)1. **Touch a guard, add/extend its adversarial test.** Any change to code in the