Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(run): attach to a linked Claude session still running in the background
Éverton Toffanetto35cc1c36f0ba
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0229db6..06ff8d5a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0provider. (#1026)### Fixed+- 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.+ (#1052)- Fixed interrupted launchers blocking an immediate managed-workstream restartby adding explicit `ai-memory run --force-unlock` recovery. The serveratomically expires and replaces only a lease attributed to the samediff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 80be0fda..f72459ab 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -16,14 +16,14 @@ 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, 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, omp_profile_flag,- omp_profile_flag_env, parse_jail_toggles, store_override_vars, usable_ai_jail_here,- wait_for_transcript_flush,+ build_launch_plan, build_launch_plan_with_env, claude_live_background_attach_id,+ claude_session_ran_in_background, 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, 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 tokio::process::Command;@@ -50,6 +50,8 @@ const HELD_LEASE_EXPIRY_SLACK: Duration = Duration::from_secs(1);const IMPORT_BATCH_EVENTS: usize = 400;const IMPORT_BATCH_BYTES: usize = 1024 * 1024;const ADOPTION_CANDIDATE_LIMIT: usize = 8;+/// Bound on `claude agents --json`, which only reads the daemon's session list.+const CLAUDE_AGENTS_TIMEOUT: Duration = Duration::from_secs(10);const AUTO_HARNESSES: [ManagedHarness; 9] = [ManagedHarness::Claude,ManagedHarness::Codex,@@ -333,6 +335,11 @@ pub(super) async fn run_from_with_wiring(&repository.cwd,&run_env,));+ 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 {eprintln!("ai-memory: linked {} session {} is missing from its native store; starting fresh and repointing workstream '{}' after the new session is established",@@ -513,6 +520,30 @@ pub(super) async fn run_from_with_wiring(.context("linking the managed native session; the agent was not started"));}+ // Claude refuses `--resume` on a background session that is still running+ // and points at `claude attach`, so open it that way instead. An attached+ // terminal starts no native session of its own: SessionStart never fires+ // in it, and native flags have nothing to apply to.+ let attached_background = if harness == ManagedHarness::Claude+ && plan.mode == LaunchMode::Session+ && resumes_linked_session+ && let Some(native_session_id) = plan.expected_session_id.as_deref()+ {+ claude_background_attach_id(&plan, &home, &repository.cwd, &run_env, native_session_id)+ .await+ } else {+ None+ };+ if let Some(attach_id) = &attached_background {+ eprintln!(+ "ai-memory: Claude session {} is still running in the background; attaching to it (`claude attach {attach_id}`). Native arguments and the workstream context packet do not reach an attached session",+ plan.expected_session_id+ .as_deref()+ .map(display_session_id)+ .unwrap_or_default()+ );+ plan.args = vec![OsString::from("attach"), OsString::from(attach_id)];+ }let crush_context = if harness == ManagedHarness::Crush && plan.mode == LaunchMode::Session {let source = crush_context_source(&home, &repository.cwd, launch_env);@@ -725,6 +756,7 @@ pub(super) async fn run_from_with_wiring(if plan.mode == LaunchMode::Session&& prepared.sync_through > prepared.sync_after&& !server_status.is_some_and(|status| status.context_delivered)+ && attached_background.is_none(){eprintln!("ai-memory: this harness did not acknowledge its managed context packet; refresh its ai-memory hooks before the next run"@@ -1821,6 +1853,44 @@ fn executable_available(program: &OsStr) -> bool {/// to spawn with "program not found". Resolving to the concrete file keeps the/// availability check and the launch agreeing on one answer, and lets the/// launch use a path that works.+/// The `claude attach` id for a linked Claude session that is still running in+/// the background, or `None` to keep the native `--resume`. The transcript is+/// checked first so a foreground session never costs a `claude agents` call;+/// any failure of that call (an older Claude, a wrapper executable, a timeout)+/// also keeps the resume.+async fn claude_background_attach_id(+ plan: &LaunchPlan,+ home: &Path,+ cwd: &Path,+ env: &[(String, String)],+ native_session_id: &str,+) -> Option<String> {+ let background =+ claude_session_ran_in_background(home, cwd, plan.session_dir.as_deref(), native_session_id)+ .unwrap_or(false);+ if !background {+ return None;+ }+ let program = resolve_program(&plan.program).unwrap_or_else(|| plan.program.clone().into());+ let mut command = Command::new(&program);+ command+ .args(["agents", "--json", "--cwd"])+ .arg(cwd)+ .current_dir(cwd)+ .envs(env.iter().map(|(key, value)| (key, value)))+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .kill_on_drop(true);+ let output = tokio::time::timeout(CLAUDE_AGENTS_TIMEOUT, command.output())+ .await+ .ok()?+ .ok()?;+ if !output.status.success() {+ return None;+ }+ claude_live_background_attach_id(&output.stdout, native_session_id, cwd)+}+pub(super) fn resolve_program(program: &OsStr) -> Option<std::path::PathBuf> {let path = Path::new(program);if path.components().count() > 1 {@@ -4116,6 +4186,82 @@ mod tests {);}+ #[cfg(unix)]+ #[tokio::test]+ async fn a_live_claude_background_session_is_attached_to_not_resumed() {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ std::fs::create_dir_all(&cwd).unwrap();+ let project = temp+ .path()+ .join(".claude/projects")+ .join(cwd.to_string_lossy().replace('/', "-"));+ std::fs::create_dir_all(&project).unwrap();+ let full = "94e41265-4001-431c-828e-1c54953e596b";+ let calls = temp.path().join("calls");+ let listing = temp.path().join("agents.json");+ let script = temp.path().join("claude");+ std::fs::write(+ &script,+ "#!/bin/sh\necho \"$*\" >> \"$FAKE_CALLS\"\ncat \"$FAKE_AGENTS\"\n",+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ let env = vec![+ ("FAKE_CALLS".to_string(), calls.display().to_string()),+ ("FAKE_AGENTS".to_string(), listing.display().to_string()),+ ];+ std::fs::write(+ &listing,+ serde_json::json!([{+ "id": "94e41265", "sessionId": full, "kind": "background",+ "status": "idle", "cwd": cwd,+ }])+ .to_string(),+ )+ .unwrap();+ let mut plan = build_launch_plan(+ ManagedHarness::Claude,+ Some(script.clone().into()),+ Vec::new(),+ Some(full),+ )+ .unwrap();+ plan.session_dir = None;+ let attach = || claude_background_attach_id(&plan, temp.path(), &cwd, &env, full);+ let transcript = |kind: Option<&str>| {+ let mut record = serde_json::json!({"type": "user", "sessionId": full, "cwd": cwd});+ if let Some(kind) = kind {+ record["sessionKind"] = serde_json::json!(kind);+ }+ std::fs::write(project.join(format!("{full}.jsonl")), format!("{record}\n")).unwrap();+ };++ // A foreground session keeps its resume without asking Claude at all.+ transcript(None);+ assert_eq!(attach().await, None);+ assert!(+ !calls.exists(),+ "claude agents ran for a foreground session"+ );++ transcript(Some("bg"));+ assert_eq!(attach().await.as_deref(), Some("94e41265"));+ assert_eq!(+ std::fs::read_to_string(&calls).unwrap().trim(),+ format!("agents --json --cwd {}", cwd.display())+ );++ // Stopped (no longer listed), or a listing Claude could not produce:+ // the native resume stays.+ std::fs::write(&listing, "[]").unwrap();+ assert_eq!(attach().await, None);+ std::fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();+ assert_eq!(attach().await, None);+ }+#[cfg(unix)]#[tokio::test]async fn run_env_reaches_the_spawned_child_and_overrides_env_file() {diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rsindex 32b804ff..16321ca5 100644--- a/crates/ai-memory-workstream/src/lib.rs+++ b/crates/ai-memory-workstream/src/lib.rs@@ -22,7 +22,8 @@ pub use jail::{};pub use repository::{RepositoryIdentity, inspect_repository};pub use transcript::{- AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, discover_native_session,+ AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate,+ 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,wait_for_transcript_flush,diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 498a3d0d..ebac0f7e 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -209,6 +209,77 @@ pub async fn discover_native_session(Ok(None)}+/// Whether a Claude transcript was written by a Claude Code background session+/// (one the Claude Code daemon hosts), whose records carry+/// `"sessionKind": "bg"`. Foreground transcripts never carry the field, so this+/// keeps the launcher from asking Claude about live sessions on every resume.+pub fn claude_session_ran_in_background(+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ native_session_id: &str,+) -> Result<bool> {+ let Some(path) = locate_session_file(+ ManagedHarness::Claude,+ home,+ cwd,+ session_dir,+ native_session_id,+ )?+ else {+ return Ok(false);+ };+ let reader = BufReader::new(File::open(&path)?);+ for line in reader.lines() {+ let line = line?;+ if !line.contains("\"sessionKind\"") {+ continue;+ }+ let Ok(value) = serde_json::from_str::<Value>(&line) else {+ continue;+ };+ if value.get("sessionKind").and_then(Value::as_str) == Some("bg")+ && value.get("sessionId").and_then(Value::as_str) == Some(native_session_id)+ {+ return Ok(true);+ }+ }+ Ok(false)+}++/// The id `claude attach` takes for `native_session_id` when `claude agents+/// --json` lists it as a live background session in this checkout.+///+/// Claude Code refuses `--resume` on a background session that is still+/// running and points at `claude attach <id>`, whose `<id>` is the short id+/// the listing prints, not the full session id. Anything unexpected in the+/// listing yields `None`, so the launcher keeps its native resume.+pub fn claude_live_background_attach_id(+ agents_json: &[u8],+ native_session_id: &str,+ cwd: &Path,+) -> Option<String> {+ let sessions: Vec<Value> = serde_json::from_slice(agents_json).ok()?;+ sessions.iter().find_map(|session| {+ let attach_id = session.get("id").and_then(Value::as_str)?;+ let matches = session.get("sessionId").and_then(Value::as_str) == Some(native_session_id)+ && session.get("kind").and_then(Value::as_str) == Some("background")+ && session+ .get("cwd")+ .and_then(Value::as_str)+ .is_some_and(|recorded| same_path(Path::new(recorded), cwd));+ (matches+ && attach_id+ .chars()+ .next()+ .is_some_and(|first| first.is_ascii_alphanumeric())+ && attach_id+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-'))+ .then(|| attach_id.to_string())+ })+}+/// List newest native sessions whose recorded working directory matches the/// current checkout. Native stores are opened read-only and unrelated paths are/// excluded before candidates reach the launcher prompt.@@ -4310,6 +4381,87 @@ mod tests {assert_eq!(found.as_deref(), Some(path.as_path()));}+ #[test]+ fn claude_session_ran_in_background_needs_its_own_bg_record() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ fs::create_dir_all(&cwd).unwrap();+ let project = temp+ .path()+ .join(".claude/projects")+ .join(cwd.to_string_lossy().replace('/', "-"));+ fs::create_dir_all(&project).unwrap();+ let write = |id: &str, records: &[Value]| {+ let body = records+ .iter()+ .map(|record| format!("{record}\n"))+ .collect::<String>();+ fs::write(project.join(format!("{id}.jsonl")), body).unwrap();+ };+ let ran = |id: &str| claude_session_ran_in_background(temp.path(), &cwd, None, id).unwrap();++ write(+ "fg",+ &[json!({"type": "user", "sessionId": "fg", "cwd": cwd})],+ );+ assert!(!ran("fg"));+ // A foreground transcript can quote another session's bg record (a+ // pasted log, a tool result); only its own sessionId counts.+ write(+ "quoting",+ &[+ json!({"type": "user", "sessionId": "quoting", "cwd": cwd,+ "message": {"content": "{\"sessionKind\":\"bg\",\"sessionId\":\"other\"}"}}),+ json!({"type": "user", "sessionId": "other", "sessionKind": "bg", "cwd": cwd}),+ ],+ );+ assert!(!ran("quoting"));+ write(+ "bg",+ &[+ json!({"type": "mode", "sessionId": "bg"}),+ json!({"type": "user", "sessionId": "bg", "sessionKind": "bg", "cwd": cwd}),+ ],+ );+ assert!(ran("bg"));+ assert!(!ran("missing"));+ }++ #[test]+ fn claude_live_background_attach_id_matches_only_a_live_background_session_here() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let other = temp.path().join("other");+ fs::create_dir_all(&cwd).unwrap();+ fs::create_dir_all(&other).unwrap();+ let listing = |entries: Value| serde_json::to_vec(&entries).unwrap();+ let entry = |id: &str, session: &str, kind: &str, cwd: &Path| json!({"id": id, "sessionId": session, "kind": kind, "status": "idle", "cwd": cwd});+ let full = "94e41265-4001-431c-828e-1c54953e596b";++ let live = listing(json!([+ entry("aaaa1111", "another-session", "background", &cwd),+ entry("94e41265", full, "background", &cwd),+ ]));+ assert_eq!(+ claude_live_background_attach_id(&live, full, &cwd).as_deref(),+ Some("94e41265")+ );+ for refused in [+ // The same session listed as an interactive one, or from another+ // checkout, is not attached to from here.+ listing(json!([entry("94e41265", full, "interactive", &cwd)])),+ listing(json!([entry("94e41265", full, "background", &other)])),+ // An id that could smuggle an option or path into argv.+ listing(json!([entry("--help", full, "background", &cwd)])),+ listing(json!([entry("../x", full, "background", &cwd)])),+ listing(json!([])),+ b"not json".to_vec(),+ listing(json!({"sessions": []})),+ ] {+ assert_eq!(claude_live_background_attach_id(&refused, full, &cwd), None);+ }+ }+#[test]fn claude_adapter_excludes_thinking_and_keeps_tools() {let value = json!({"type":"assistant","uuid":"record","timestamp":"2026-01-01T00:00:00Z","message":{"role":"assistant","content":[diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 9b42d59d..075498df 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -419,6 +419,19 @@ Codex's `resume`, or Antigravity's `--conversation` / `--continue` wins.ai-memory links the selected native session and resets an unrelated adaptercursor rather than assuming it belongs to the old session.+When the linked Claude session is a Claude Code background session that is+still running in the daemon, Claude refuses `--resume <id>` when another flag+comes with it (seen with `--model`, `--effort` and+`--dangerously-skip-permissions` on Claude Code 2.1.287; a bare `--resume`+attaches) and points at `claude attach <id>`. Only when the+transcript shows the session ran in the background (`sessionKind: "bg"`)+does ai-memory ask `claude agents --json --cwd <checkout>`. When that lists the+session as a live background one in this checkout, it launches+`claude attach <id>` with the listing's short id instead. An attached terminal+starts no native session of its own: native arguments are not passed, and the+workstream context packet is not delivered (SessionStart does not fire). A+failed or unexpected listing keeps the native resume. (#1052)+Crush has no hooks to link its session: a fresh Crush launch claims the one top-level sessioncreated while it ran (its title and sub-agent sessions do not count), andimports nothing, with a warning, when another launch on the same store created