Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

Merge main into attach fix and verify early-exit fallback

Everton Toffanettoa1dd3d10d881
diff --cc CHANGELOG.md
index 06ff8d5a,ca172515..bfeeb1e4
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -12,13 -12,18 +12,25 @@@ and this project adheres to [Semantic V
provider. (#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 watcher reindexing racing with writes and batches to the same page by
+ sharing their per-page mutex from disk read through SQLite upsert. Both
+ mutation guards are released before embedding; external editors remain
+ outside this coordination. (#1059)
+ - Fixed a managed Claude Code run losing its conversation after `/resume` on a
+ Claude Code background session. The run used to finish on the foreground
+ session it started with, which held none of the conversation, so the next
+ `ai-memory run claude` or `continue` resumed it and Claude opened an empty
+ session. A Claude run now finishes on the background session its own
+ session attached to in this checkout, found from that transcript's
+ `sessionKind: "bg"` records; another launch's background session is never
+ taken. (#1050)
- Fixed interrupted launchers blocking an immediate managed-workstream restart
by adding explicit `ai-memory run --force-unlock` recovery. The server
atomically expires and replaces only a lease attributed to the same
diff --cc crates/ai-memory-cli/src/commands/run.rs
index f72459ab,06282eba..423e1de5
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@@ -16,14 -16,14 +16,15 @@@ 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, 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,
- build_launch_plan, build_launch_plan_with_env, claude_attached_background_session, clean_path,
++ build_launch_plan, build_launch_plan_with_env, claude_attached_background_session,
++ claude_live_background_attach_id, claude_session_ran_in_background, clean_path,
+ 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,
+ native_session_in_checkout, native_store_root, 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;
@@@ -335,12 -333,23 +336,28 @@@ pub(super) async fn run_from_with_wirin
&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 {
+ let recorded = super::project_registry::recorded_session_store(
+ config,
+ &endpoint,
+ harness.as_str(),
+ &orphaned_session,
+ )
+ .unwrap_or_else(|error| {
+ eprintln!(
+ "ai-memory: could not read the client-local session store record ({error:#}); treating the linked session as deleted"
+ );
+ None
+ });
+ let current = effective_store(harness, &home, &repository.cwd, plan.session_dir.as_deref());
+ if let Some(error) = store_mismatch_error(harness, &orphaned_session, recorded, &current) {
+ acquired_try!(Err(error));
+ }
eprintln!(
"ai-memory: linked {} session {} is missing from its native store; starting fresh and repointing workstream '{}' after the new session is established",
harness.as_str(),
@@@ -519,31 -539,8 +547,32 @@@
.await
.context("linking the managed native session; the agent was not started")
);
+ remember_session_store(config, &endpoint, harness, native_session_id, &linked_store);
}
+ // 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);
@@@ -1842,55 -2020,17 +2053,55 @@@ fn executable_available(program: &OsStr
resolve_program(program).is_some()
}
- /// Resolve `program` to a concrete path the OS can actually start, or `None`
- /// when nothing launchable matches.
- ///
- /// The bare name is not enough on Windows. An npm-style install drops three
- /// files next to each other — `opencode`, `opencode.cmd`, `opencode.ps1` — and
- /// only the ones carrying a `PATHEXT` extension are launchable: `CreateProcess`
- /// refuses the extension-less shell script, which exists for Git Bash. Probing
- /// for mere existence therefore reported harnesses as present that then failed
- /// 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)
+}
+
+ /// Resolve `program` to a concrete path the OS can actually start, or `None`
+ /// when nothing launchable matches.
+ ///
+ /// The bare name is not enough on Windows. An npm-style install drops three
+ /// files next to each other — `opencode`, `opencode.cmd`, `opencode.ps1` — and
+ /// only the ones carrying a `PATHEXT` extension are launchable: `CreateProcess`
+ /// refuses the extension-less shell script, which exists for Git Bash. Probing
+ /// for mere existence therefore reported harnesses as present that then failed
+ /// 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.
pub(super) fn resolve_program(program: &OsStr) -> Option<std::path::PathBuf> {
let path = Path::new(program);
if path.components().count() > 1 {
@@@ -4939,6 -5319,6 +5466,129 @@@ mod tests
(address, server)
}
++ /// Synthetic launcher evidence only: this does not assert which hooks a
++ /// real Claude daemon emits. An early child exit must still finish the
++ /// linked background session; an unavailable agents command keeps resume.
++ #[cfg(unix)]
++ #[tokio::test]
++ async fn background_attach_early_exit_and_unavailable_agents_finish_linked_session() {
++ use crate::commands::run_autowire::WireOverrides;
++ use std::os::unix::fs::PermissionsExt as _;
++
++ const SESSION: &str = "94e41265-4001-431c-828e-1c54953e596b";
++ for available in [true, false] {
++ let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
++ let links = requests.clone();
++ let finishes = requests.clone();
++ let app = Router::new()
++ .route(
++ "/workstream/runs",
++ post(|| async {
++ axum::Json(PrepareManagedRunResponse {
++ workstream_id: WorkstreamId::new(),
++ workstream_name: "default".into(),
++ run_id: ManagedRunId::new(),
++ resolved_agent: None,
++ native_session_id: Some(SESSION.into()),
++ source_cursor: None,
++ sync_after: 0,
++ sync_through: 0,
++ may_adopt_existing_session: false,
++ })
++ }),
++ )
++ .route(
++ "/workstream/runs/{run_id}/link",
++ post(move |axum::Json(body): axum::Json<serde_json::Value>| {
++ let links = links.clone();
++ async move {
++ links.lock().unwrap().push(("link", body));
++ StatusCode::NO_CONTENT
++ }
++ }),
++ )
++ .route(
++ "/workstream/runs/{run_id}/finish",
++ post(move |axum::Json(body): axum::Json<serde_json::Value>| {
++ let finishes = finishes.clone();
++ async move {
++ finishes.lock().unwrap().push(("finish", body));
++ axum::Json(FinishManagedRunResponse {
++ imported_events: 0,
++ latest_sequence: 0,
++ })
++ }
++ }),
++ );
++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
++ let address = listener.local_addr().unwrap();
++ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
++ let home = tempfile::tempdir().unwrap();
++ let data = tempfile::tempdir().unwrap();
++ let repo = tempfile::tempdir().unwrap();
++ let cwd = repo.path().canonicalize().unwrap();
++ let project = home
++ .path()
++ .join(".claude/projects")
++ .join(cwd.to_string_lossy().replace('/', "-"));
++ std::fs::create_dir_all(&project).unwrap();
++ let record = serde_json::json!({"type": "user", "sessionId": SESSION, "sessionKind": "bg", "cwd": cwd});
++ std::fs::write(
++ project.join(format!("{SESSION}.jsonl")),
++ format!("{record}\n"),
++ )
++ .unwrap();
++ let calls = data.path().join("calls");
++ let listing = data.path().join("agents.json");
++ std::fs::write(&listing, serde_json::json!([{"id": "94e41265", "sessionId": SESSION, "kind": "background", "cwd": cwd}]).to_string()).unwrap();
++ let script = data.path().join("fake-claude");
++ std::fs::write(&script, format!(
++ "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$FAKE_CALLS\"\nif [ \"$1\" = agents ]; then\n {}\nfi\nexit 23\n",
++ if available { "cat \"$FAKE_AGENTS\"; exit 0" } else { "exit 1" }
++ )).unwrap();
++ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
++ let config = launch_config(home.path(), data.path(), address);
++ let mut args = run_args(
++ RunHarnessChoice::Claude,
++ script,
++ vec![
++ ("FAKE_CALLS".into(), calls.display().to_string()),
++ ("FAKE_AGENTS".into(), listing.display().to_string()),
++ ],
++ &["--model", "test-model"],
++ );
++ args.no_autowire = true;
++ args.no_jail = true;
++ let exit = run_from_with_wiring(&config, args, &cwd, &WireOverrides::default())
++ .await
++ .unwrap();
++ assert_eq!(exit, 23, "early child exit is preserved");
++ let calls = std::fs::read_to_string(calls).unwrap();
++ let calls: Vec<_> = calls.lines().collect();
++ assert_eq!(calls.len(), 2);
++ assert_eq!(calls[0], format!("agents --json --cwd {}", cwd.display()));
++ if available {
++ assert_eq!(
++ calls[1], "attach 94e41265",
++ "native flags do not reach attach"
++ );
++ } else {
++ assert!(calls[1].contains(&format!("--resume {SESSION}")));
++ assert!(calls[1].contains("--model test-model"));
++ }
++ let requests = requests.lock().unwrap();
++ assert_eq!(requests.len(), 2);
++ assert_eq!(requests[0].0, "link");
++ assert_eq!(requests[1].0, "finish");
++ for (_, request) in requests.iter() {
++ assert_eq!(request["native_session_id"], SESSION);
++ }
++ assert_eq!(requests[1].1["exit_code"], 23);
++ assert_eq!(requests[1].1["complete"], true);
++ server.abort();
++ }
++ }
++
#[cfg(unix)]
fn capture_env_script(dir: &Path, variable: &str) -> (PathBuf, PathBuf) {
use std::os::unix::fs::PermissionsExt as _;
diff --cc crates/ai-memory-workstream/src/lib.rs
index 16321ca5,3cb4fad8..a2c395a3
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@@ -23,8 -23,8 +23,9 @@@ pub use jail::
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
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,
- claude_attached_background_session, discover_native_session, export_transcript,
++ claude_attached_background_session, 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, native_store_root,
wait_for_transcript_flush,
};
diff --cc crates/ai-memory-workstream/src/transcript.rs
index ebac0f7e,64373cd6..f73d6767
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@@ -209,77 -209,79 +209,150 @@@ 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())
+ })
+}
+
+ /// Find the Claude Code background session that `native_session_id` attached
+ /// to during this run, if any.
+ ///
+ /// `/resume` on a background session (one hosted by the Claude Code daemon)
+ /// does not continue the foreground session: the conversation keeps going in
+ /// the background session's own transcript, whose records carry
+ /// `"sessionKind": "bg"` and name the attached foreground session in
+ /// `session_id`. The daemon's hooks never see this run's id, so without this
+ /// the workstream stays on the foreground session and the next launch resumes
+ /// a transcript with no conversation in it.
+ ///
+ /// Only transcripts written since `started_at` are read, the newest first,
+ /// and a record must also match this checkout. Transcripts without those
+ /// fields (older Claude Code builds) never match.
+ pub fn claude_attached_background_session(
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+ started_at: SystemTime,
+ ) -> Result<Option<String>> {
+ if !valid_native_session_id(native_session_id) {
+ return Ok(None);
+ }
+ let mut candidates = collect_session_files(ManagedHarness::Claude, home, session_dir)?;
+ candidates.sort_by(|left, right| {
+ modified(right)
+ .cmp(&modified(left))
+ .then_with(|| left.cmp(right))
+ });
+ let attached_marker = format!("\"session_id\":\"{native_session_id}\"");
+ for path in candidates.into_iter().take(512) {
+ if modified(&path).is_some_and(|time| time + Duration::from_secs(2) < started_at) {
+ break;
+ }
+ if path
+ .file_stem()
+ .is_some_and(|stem| stem == std::ffi::OsStr::new(native_session_id))
+ {
+ continue;
+ }
+ let reader = BufReader::new(File::open(&path)?);
+ for line in reader.lines() {
+ let line = line?;
+ if !line.contains(&attached_marker) {
+ continue;
+ }
+ let Ok(value) = serde_json::from_str::<Value>(&line) else {
+ continue;
+ };
+ let background = value.get("sessionKind").and_then(Value::as_str) == Some("bg");
+ let attached =
+ value.get("session_id").and_then(Value::as_str) == Some(native_session_id);
+ let in_checkout = value
+ .get("cwd")
+ .and_then(Value::as_str)
+ .is_some_and(|recorded| same_path(Path::new(recorded), cwd));
+ let Some(session) = value.get("sessionId").and_then(Value::as_str) else {
+ continue;
+ };
+ if background
+ && attached
+ && in_checkout
+ && session != native_session_id
+ && valid_native_session_id(session)
+ {
+ return Ok(Some(session.to_string()));
+ }
+ }
+ }
+ Ok(None)
+ }
+
/// 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.
@@@ -4381,87 -4393,84 +4464,165 @@@ 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_attached_background_session_follows_only_this_checkouts_bg_records() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let other = temp.path().join("other");
+ let project = temp.path().join(".claude/projects/-repo");
+ fs::create_dir_all(&cwd).unwrap();
+ fs::create_dir_all(&other).unwrap();
+ fs::create_dir_all(&project).unwrap();
+ let started_at = SystemTime::now() - Duration::from_secs(60);
+ let write = |name: &str, records: &[Value]| {
+ let path = project.join(format!("{name}.jsonl"));
+ let body = records
+ .iter()
+ .map(|record| format!("{record}\n"))
+ .collect::<String>();
+ fs::write(&path, body).unwrap();
+ path
+ };
+ let record = |session: &str, attached: &str, kind: Option<&str>, cwd: &Path| {
+ let mut value = json!({
+ "type": "user",
+ "sessionId": session,
+ "session_id": attached,
+ "cwd": cwd,
+ });
+ if let Some(kind) = kind {
+ value["sessionKind"] = json!(kind);
+ }
+ value
+ };
+ let find = |id: &str| {
+ claude_attached_background_session(temp.path(), &cwd, None, id, started_at).unwrap()
+ };
+
+ // The foreground transcript names itself; it is never the answer.
+ write("fg", &[record("fg", "fg", None, &cwd)]);
+ assert_eq!(find("fg"), None);
+
+ // Without `sessionKind: bg`, or from another checkout, a record that
+ // names the foreground session is not a background continuation.
+ write("plain", &[record("plain", "fg", None, &cwd)]);
+ write(
+ "elsewhere",
+ &[record("elsewhere", "fg", Some("bg"), &other)],
+ );
+ assert_eq!(find("fg"), None);
+
+ // A concurrent launch in this checkout attached its own foreground
+ // session to a background one; that conversation is not this run's.
+ write(
+ "concurrent",
+ &[record("concurrent", "other-fg", Some("bg"), &cwd)],
+ );
+ assert_eq!(find("fg"), None);
+ assert_eq!(find("other-fg").as_deref(), Some("concurrent"));
+
+ // A transcript last written before the run started is not read.
+ let stale = write("stale", &[record("stale", "fg", Some("bg"), &cwd)]);
+ File::options()
+ .write(true)
+ .open(&stale)
+ .unwrap()
+ .set_modified(started_at - Duration::from_secs(60))
+ .unwrap();
+ assert_eq!(find("fg"), None);
+
+ write(
+ "bg",
+ &[
+ record("bg", "earlier-client", Some("bg"), &cwd),
+ record("bg", "fg", Some("bg"), &cwd),
+ ],
+ );
+ assert_eq!(find("fg").as_deref(), Some("bg"));
+ assert_eq!(find("unrelated"), 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 --cc docs/managed-workstreams.md
index 075498df,572188f3..fb6bab98
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@@ -419,19 -419,17 +419,30 @@@ Codex's `resume`, or Antigravity's `--c
ai-memory links the selected native session and resets an unrelated adapter
cursor 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)
+
+ Claude Code background sessions run inside the Claude Code daemon, not in the
+ process `ai-memory run` spawned, so their hooks never carry the run's id. When a
+ managed Claude session attaches to one (`/resume` on a session shown as
+ "running in the background"), the conversation goes on in the background
+ session's transcript. At the end of the run, ai-memory looks for a transcript
+ written during the run whose `sessionKind: "bg"` records name the run's own
+ session as the attached client and this checkout as `cwd`, and finishes the run
+ on that background session, so the next launch resumes it instead of the empty
+ foreground session. A background session attached by another launch is never
+ taken. (#1050)
+
Crush has no hooks to link its session: a fresh Crush launch claims the one top-level session
created while it ran (its title and sub-agent sessions do not count), and
imports nothing, with a warning, when another launch on the same store created