Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.
Rust agent-to-agentai-agentsclaude-codecodexcoding-agentscursorgrokirohmcpmcp-servermulti-agentpeer-to-peerreason
After /clear, Claude Code's MCP server serves the new conversation (#106)
Lars Talianb7d10b6839a2
diff --git a/DESIGN.md b/DESIGN.mdindex 4a27e88..2cea9dd 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -281,7 +281,15 @@ Agent kind comes from MCP `clientInfo.name` plus env (`CLAUDECODE`, `CODEX_*`, `**Passive discovery.** Claude Code writes every live session to `~/.claude/sessions/<pid>.json` (name, cwd,busy/idle). The daemon reads these, so Claude sessions show up with live busy/idle status even without our-MCP server loaded.+MCP server loaded. Our MCP server reads the conversation it serves from there too, from the entry of the Claude Code+process it runs under: the nearest of its ancestors, else `CLAUDE_PID`, whose entry names the conversation it was+started in (`CLAUDE_CODE_SESSION_ID`), followed from then on. After `/clear` the same process is in a new conversation,+which the server then serves, and the one before ends. With no such entry (a headless Claude run from an interactive+one's shell has none, and the entry above it is the other conversation's), it goes by `CLAUDE_CODE_SESSION_ID` and+registers no process, so nothing ends it but its own server. The daemon's scan ends it as soon as the registry names the new one, by the process the server registered+it under, so mail for it waits for it instead of going into the new conversation before the server's next call. Any MCP+server that serves one session at a time (not Codex's, opencode's or Cursor's) ends its session when it registers or+takes up another, also one the registry scan or its hooks already registered.## Getting messages into agentsdiff --git a/src/agent.rs b/src/agent.rsindex 3b52ce9..cc4216a 100644--- a/src/agent.rs+++ b/src/agent.rs@@ -82,10 +82,17 @@ pub fn multiplexed(agent: &str) -> bool {}/// The session id an agent exports to its MCP servers, if any. `REASON_NETWORK_SESSION` is set by our own pi extension.+/// Claude Code's is read from its session registry first: `/clear` starts a new conversation in the same process, and+/// the variable it gave us at start still names the old one.pub fn env_session_id(agent: &str) -> Option<String> {if let Some(id) = crate::paths::env_var("SESSION").ok().filter(|s| !s.is_empty()) {return Some(id);}+ if agent == CLAUDE_CODE+ && let Some(id) = claude_pid().and_then(|pid| registry_session_id(&paths::claude_sessions(), pid))+ {+ return Some(id);+ }let var = match agent {CLAUDE_CODE => "CLAUDE_CODE_SESSION_ID","copilot" => "COPILOT_AGENT_SESSION_ID",@@ -200,6 +207,94 @@ pub fn agent_pid() -> u32 {std::env::var("CLAUDE_PID").ok().and_then(|s| s.parse().ok()).unwrap_or_else(util::parent_pid)}+/// The Claude Code process we run under, if any: the nearest of our ancestors (a shell or a launcher can sit between),+/// else `CLAUDE_PID`, whose entry in Claude Code's session registry names the conversation Claude Code started us in+/// (`CLAUDE_CODE_SESSION_ID`). Another's isn't ours: a headless Claude run from an interactive one's shell has no entry+/// of its own, and the entry above it is the other conversation's. Kept once found, and its entry followed from then+/// on (after `/clear` it names the new conversation). Not found, it is looked for again after a while (Claude Code may+/// not have written its entry yet), not on every call: each look can run `ps` for each ancestor.+pub fn claude_pid() -> Option<u32> {+ static PID: std::sync::OnceLock<u32> = std::sync::OnceLock::new();+ static MISSED: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);+ if let Some(pid) = PID.get() {+ return Some(*pid);+ }+ if MISSED.lock().unwrap().is_some_and(|t| t.elapsed() < LOOK_AGAIN) {+ return None;+ }+ let dir = paths::claude_sessions();+ let found = find_claude(+ util::parent_pid(),+ std::env::var("CLAUDE_CODE_SESSION_ID").ok().as_deref(),+ std::env::var("CLAUDE_PID").ok().and_then(|s| s.parse().ok()),+ |p| registry_session_id(&dir, p),+ parent_of,+ );+ match found {+ Some(pid) => {+ let _ = PID.set(pid);+ }+ None => *MISSED.lock().unwrap() = Some(std::time::Instant::now()),+ }+ found+}++/// How long `claude_pid` goes by not having found the Claude process before it looks again.+const LOOK_AGAIN: std::time::Duration = std::time::Duration::from_secs(30);++/// The Claude Code process in conversation `given`: the nearest of `start` and its ancestors, else `claude_pid`, whose+/// registry entry (`entry`) names it. None without a conversation to match.+fn find_claude(+ start: u32,+ given: Option<&str>,+ claude_pid: Option<u32>,+ entry: impl Fn(u32) -> Option<String>,+ parent: impl Fn(u32) -> Option<u32>,+) -> Option<u32> {+ let given = given.filter(|g| !g.is_empty())?;+ let ours = |p: u32| entry(p).as_deref() == Some(given);+ registry_ancestor(start, ours, parent).or_else(|| claude_pid.filter(|p| ours(*p)))+}++/// The nearest of `pid` and its ancestors (a few levels up) that `has_entry`.+fn registry_ancestor(+ mut pid: u32,+ has_entry: impl Fn(u32) -> bool,+ parent: impl Fn(u32) -> Option<u32>,+) -> Option<u32> {+ for _ in 0..5 {+ if has_entry(pid) {+ return Some(pid);+ }+ match parent(pid) {+ Some(p) if p > 1 && p != pid => pid = p,+ _ => return None,+ }+ }+ None+}++/// A process's parent: from `/proc` on Linux, else as `ps` (or Windows) says.+fn parent_of(pid: u32) -> Option<u32> {+ #[cfg(target_os = "linux")]+ return stat_parent(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?);+ #[cfg(not(target_os = "linux"))]+ return util::process(pid).map(|(parent, _)| parent);+}++/// The parent pid in a `/proc/<pid>/stat` line: `<pid> (<name>) <state> <ppid> …`, where the name can hold spaces and+/// parentheses of its own.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn stat_parent(stat: &str) -> Option<u32> {+ stat.rsplit_once(')')?.1.split_whitespace().nth(1)?.parse().ok()+}++/// The conversation Claude Code process `pid` is in now, from its registry entry.+fn registry_session_id(dir: &Path, pid: u32) -> Option<String> {+ let s: Value = serde_json::from_str(&std::fs::read_to_string(dir.join(format!("{pid}.json"))).ok()?).ok()?;+ s["sessionId"].as_str().filter(|id| !id.is_empty()).map(str::to_string)+}+/// The inbox socket of the Claude Code session that spawned us. Posting a `user` frame there puts the text in/// the conversation between tool calls, or starts a turn if the session is idle.#[derive(Debug, Clone)]@@ -214,7 +309,7 @@ pub fn claude_socket() -> Option<ClaudeSocket> {return Some(ClaudeSocket { path: path.into(), token });}// Not exported to this process: fall back to the session's registry entry.- let pid = agent_pid();+ let pid = claude_pid().unwrap_or_else(agent_pid);let file = paths::claude_sessions().join(format!("{pid}.json"));let s: Value = serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()?;let path = s["messagingSocketPath"].as_str()?;@@ -264,6 +359,65 @@ mod tests {assert_eq!(from_client_name("example-client"), None);}+ #[test]+ fn claude_codes_registry_names_the_conversation_its_process_is_in_now() {+ let dir = std::env::temp_dir().join(format!("reason-network-claude-{}", ulid::Ulid::generate()));+ std::fs::create_dir_all(&dir).unwrap();+ // After `/clear`, the same process is in a new conversation.+ std::fs::write(dir.join("4242.json"), r#"{"pid":4242,"sessionId":"after-clear","kind":"interactive"}"#)+ .unwrap();+ std::fs::write(dir.join("4343.json"), r#"{"pid":4343,"sessionId":""}"#).unwrap();+ assert_eq!(registry_session_id(&dir, 4242).as_deref(), Some("after-clear"));+ assert_eq!(registry_session_id(&dir, 4343), None);+ assert_eq!(registry_session_id(&dir, 4444), None);+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn the_claude_process_is_the_nearest_ancestor_with_a_registry_entry() {+ // 900 (us) ← 800 (a shell) ← 700 (Claude Code, with an entry) ← 600 (another Claude Code, with one) ← 1.+ let parent = |p: u32| match p {+ 900 => Some(800),+ 800 => Some(700),+ 700 => Some(600),+ 600 => Some(1),+ _ => None,+ };+ assert_eq!(registry_ancestor(900, |p| p == 700 || p == 600, parent), Some(700));+ assert_eq!(registry_ancestor(900, |p| p == 600, parent), Some(600));+ assert_eq!(registry_ancestor(900, |_| false, parent), None);+ // Not past init, nor round a loop.+ assert_eq!(registry_ancestor(900, |p| p == 1, parent), None);+ assert_eq!(registry_ancestor(5, |_| false, |_| Some(5)), None);+ }++ #[test]+ fn the_claude_process_is_the_one_whose_entry_names_our_conversation() {+ // 900 (us) ← 800 (a headless Claude, no entry) ← 700 (an interactive Claude, in `outer`) ← 1.+ let parent = |p: u32| match p {+ 900 => Some(800),+ 800 => Some(700),+ 700 => Some(1),+ _ => None,+ };+ let entry = |p: u32| (p == 700).then(|| "outer".to_string());+ // The headless Claude's server, started in `inner`: not the interactive one's, by walking up or by CLAUDE_PID.+ assert_eq!(find_claude(900, Some("inner"), None, entry, parent), None);+ assert_eq!(find_claude(900, Some("inner"), Some(700), entry, parent), None);+ // The interactive one's own server.+ assert_eq!(find_claude(900, Some("outer"), None, entry, parent), Some(700));+ assert_eq!(find_claude(5, Some("outer"), Some(700), entry, |_| None), Some(700));+ // Nothing to match by.+ assert_eq!(find_claude(900, None, Some(700), entry, parent), None);+ }++ #[test]+ fn a_parent_is_read_from_proc_stat() {+ assert_eq!(stat_parent("4242 (claude) S 4100 4242 4100 0 -1 4194560"), Some(4100));+ assert_eq!(stat_parent("4242 (node (my) ) app) R 77 1 1"), Some(77));+ assert_eq!(stat_parent("garbage"), None);+ }+#[test]fn names() {let git = GitInfo { root: Some("/Users/alex/src/API".into()), ..Default::default() };diff --git a/src/client.rs b/src/client.rsindex f30d0bf..13a788a 100644--- a/src/client.rs+++ b/src/client.rs@@ -60,7 +60,7 @@ impl Link {pub async fn register(self: &Arc<Self>, reg: SessionReg) -> Result<Registered> {let r = self.call(Request::Register { session: reg.clone() }).await?;- self.regs.lock().unwrap().insert(reg.key.clone(), reg);+ remember(&mut self.regs.lock().unwrap(), reg);Ok(r)}@@ -246,8 +246,39 @@ fn detach(cmd: &mut Command) -> std::io::Result<std::process::Child> {cmd.creation_flags(flags | CREATE_BREAKAWAY_FROM_JOB).spawn().or_else(|_| cmd.creation_flags(flags).spawn())}+/// Remembers a registration, to make again after a reconnect. An agent with an MCP server per session is in one+/// conversation at a time: a new one (Claude Code's `/clear`) replaces the one before, which must not come back.+fn remember(regs: &mut HashMap<String, SessionReg>, reg: SessionReg) {+ if !crate::agent::multiplexed(®.agent) {+ regs.retain(|_, r| r.agent != reg.agent);+ }+ regs.insert(reg.key.clone(), reg);+}+#[cfg(test)]mod tests {+ #[test]+ fn a_reconnect_registers_only_the_conversation_a_server_is_in_now() {+ let reg = |key: &str, agent: &str| crate::proto::SessionReg {+ key: key.into(),+ agent: agent.into(),+ cwd: "/".into(),+ agent_session_id: None,+ pid: None,+ tier: crate::proto::Tier::Pull,+ name: None,+ };+ let mut regs = super::HashMap::new();+ super::remember(&mut regs, reg("claude-code:before-clear", "claude-code"));+ super::remember(&mut regs, reg("claude-code:after-clear", "claude-code"));+ // A shared server (Codex's) serves several at once.+ super::remember(&mut regs, reg("codex:1", "codex"));+ super::remember(&mut regs, reg("codex:2", "codex"));+ let mut keys: Vec<&String> = regs.keys().collect();+ keys.sort();+ assert_eq!(keys, ["claude-code:after-clear", "codex:1", "codex:2"]);+ }+#[test]fn a_daemon_runs_only_while_it_holds_the_lock() {let dir = std::env::temp_dir().join(format!("reason-network-lock-{}", std::process::id()));diff --git a/src/daemon/ask.rs b/src/daemon/ask.rsindex 4cdcd02..41d17d2 100644--- a/src/daemon/ask.rs+++ b/src/daemon/ask.rs@@ -245,7 +245,7 @@ impl Daemon {let Ok(said) = self.said(answer) else { return };let mut g = self.inner.lock().unwrap();let Some(to) = g.live.get(key).map(|l| self.addr(&l.name)) else {- return log(&format!("{key} had gone before {} answered its question", self.person));+ return log(&format!("a session had gone before {} answered its question", self.person));};let mut msg = Message {id: Ulid::generate().to_string(),diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex bf45414..b09e07c 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -70,29 +70,8 @@ impl Daemon {if claude::wired() {let now = util::now_ms();for c in &claude {- let Some(id) = &c.session_id else { continue };- let key = format!("{}:{id}", agent::CLAUDE_CODE);- if !self.inner.lock().unwrap().live.contains_key(&key) {- let cwd = c.cwd.clone().unwrap_or_else(|| "/".into());- let git = gits.get(&cwd).cloned().unwrap_or_default();- let named = matches!(c.name_source.as_deref(), Some("user" | "peer" | "hook" | "auto"));- let reg = SessionReg {- key: key.clone(),- agent: agent::CLAUDE_CODE.into(),- cwd,- agent_session_id: Some(id.clone()),- pid: Some(c.pid),- tier: Tier::Push,- name: if named { c.label() } else { None },- };- if let Err(e) = self.register(None, reg, git) {- super::log(&format!("adding Claude session {id}: {e:#}"));- }- }- // Seen alive just now (it goes when its process does).- if let Some(l) = self.inner.lock().unwrap().live.get_mut(&key) {- l.last_hook = Some(now);- }+ let git = c.cwd.as_ref().and_then(|cwd| gits.get(cwd)).cloned().unwrap_or_default();+ self.claude_seen(c, git, now);}}// A Claude Code session someone renamed goes by that name here too.@@ -173,6 +152,43 @@ impl Daemon {Ok(rows)}+ /// A live Claude Code session in Claude Code's own registry: on the team, and the conversation its process is in.+ fn claude_seen(self: &Arc<Self>, c: &ClaudeSession, git: GitInfo, now: i64) {+ let Some(id) = &c.session_id else { return };+ let key = format!("{}:{id}", agent::CLAUDE_CODE);+ // Its process is in this conversation now: after `/clear`, the one it was in has ended, though its MCP server+ // (which the registration names by this process) hasn't said so; until then mail for it would go to this one.+ {+ let mut g = self.inner.lock().unwrap();+ let before: Vec<String> = g+ .live+ .iter()+ .filter(|(k, l)| l.reg.agent == agent::CLAUDE_CODE && l.reg.pid == Some(c.pid) && **k != key)+ .map(|(k, _)| k.clone())+ .collect();+ self.moved_on(&mut g, before, now);+ }+ if !self.inner.lock().unwrap().live.contains_key(&key) {+ let named = matches!(c.name_source.as_deref(), Some("user" | "peer" | "hook" | "auto"));+ let reg = SessionReg {+ key: key.clone(),+ agent: agent::CLAUDE_CODE.into(),+ cwd: c.cwd.clone().unwrap_or_else(|| "/".into()),+ agent_session_id: Some(id.clone()),+ pid: Some(c.pid),+ tier: Tier::Push,+ name: if named { c.label() } else { None },+ };+ if let Err(e) = self.register(None, reg, git) {+ super::log(&format!("adding the Claude session of process {}: {e:#}", c.pid));+ }+ }+ // Seen alive just now (it goes when its process does).+ if let Some(l) = self.inner.lock().unwrap().live.get_mut(&key) {+ l.last_hook = Some(now);+ }+ }+fn row(&self, name: &str, agent: &str, cwd: &str, git: Option<&GitInfo>) -> SessionInfo {SessionInfo {address: self.addr(name),@@ -479,6 +495,82 @@ fn claude_match(c: &ClaudeSession, reg: &SessionReg) -> bool {mod tests {use super::*;+ #[tokio::test]+ async fn after_clear_the_registry_ends_the_cleared_conversation_before_any_tool_call() {+ let d = Arc::new(super::super::test_daemon(crate::config::Config::default()));+ // A live process, standing in for Claude Code's.+ let pid = std::process::id();+ let reg = |key: &str, agent: &str, cwd: &str, conn: u64| {+ let reg = SessionReg {+ key: key.into(),+ agent: agent.into(),+ cwd: cwd.into(),+ agent_session_id: None,+ pid: Some(pid),+ tier: Tier::Push,+ name: None,+ };+ d.register(Some(conn), reg, GitInfo::default()).unwrap().name+ };+ // A Claude Code session, registered by its MCP server under its process; and another agent run from it.+ assert_eq!(reg("claude-code:before", agent::CLAUDE_CODE, "/work/api", 1), "api-claude");+ reg("codex:1", "codex", "/work/web", 2);+ // `/clear`: Claude Code's registry names the new conversation; its MCP server hasn't made a call since.+ let entry: ClaudeSession = serde_json::from_value(serde_json::json!({+ "pid": pid, "sessionId": "after", "cwd": "/work/api", "kind": "interactive"+ }))+ .unwrap();+ d.claude_seen(&entry, GitInfo::default(), util::now_ms());+ let mut live: Vec<String> = d.inner.lock().unwrap().live.keys().cloned().collect();+ live.sort();+ // Another agent's session from that process stays.+ assert_eq!(live, ["claude-code:after", "codex:1"]);+ // Mail for the cleared conversation waits for it; the new one, api-claude-2, gets none of it.+ let res = d+ .send("codex:1".into(), "api-claude", "for the old one", None, true, false, None, Vec::new())+ .await+ .unwrap();+ assert_eq!(res.recipients[0].state, "queued");+ assert!(+ res.recipients[0].note.ends_with("it reaches that session when it's back"),+ "{}",+ res.recipients[0].note+ );+ let g = d.inner.lock().unwrap();+ assert_eq!(g.live["claude-code:after"].name, "api-claude-2");+ assert_eq!(g.store.unread_count(&d.addr("api-claude-2")).unwrap(), 0);+ }++ #[tokio::test]+ async fn a_headless_claude_run_from_an_interactive_ones_shell_is_a_session_of_its_own() {+ let d = Arc::new(super::super::test_daemon(crate::config::Config::default()));+ // The interactive Claude, in `outer`, in Claude Code's registry.+ let pid = std::process::id();+ let entry: ClaudeSession = serde_json::from_value(serde_json::json!({+ "pid": pid, "sessionId": "outer", "cwd": "/work/api", "kind": "interactive"+ }))+ .unwrap();+ d.claude_seen(&entry, GitInfo::default(), util::now_ms());+ // A headless Claude it ran, in `inner`, with no entry: its MCP server registers it with no process.+ let reg = SessionReg {+ key: "claude-code:inner".into(),+ agent: agent::CLAUDE_CODE.into(),+ cwd: "/work/api".into(),+ agent_session_id: Some("inner".into()),+ pid: None,+ tier: Tier::Pull,+ name: None,+ };+ assert_eq!(d.register(Some(1), reg, GitInfo::default()).unwrap().name, "api-claude-2");+ // The scan, again and again, leaves it alone.+ for _ in 0..3 {+ d.claude_seen(&entry, GitInfo::default(), util::now_ms());+ }+ let mut live: Vec<String> = d.inner.lock().unwrap().live.keys().cloned().collect();+ live.sort();+ assert_eq!(live, ["claude-code:inner", "claude-code:outer"]);+ }+#[test]fn each_machine_answers_for_its_own_terminal() {let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex 64c2e97..d57e47c 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -408,8 +408,8 @@ impl Daemon {Ok(Ok(())) => {let _ = g.store.mark_read(&ids, util::now_ms());}- Ok(Err(e)) => log(&format!("delivering to Claude session {key}: {e}")),- Err(e) => log(&format!("delivering to Claude session {key}: {e}")),+ Ok(Err(e)) => log(&format!("delivering to Claude session {}: {e}", this.logged(&g, &key))),+ Err(e) => log(&format!("delivering to Claude session {}: {e}", this.logged(&g, &key))),}});}@@ -468,9 +468,10 @@ impl Daemon {}// Reason has no hooks to fall back on: its sync pushes again, backing off (15 s doubling to 30 min).Err(why) if bin == "reason" => {+ let who = this.logged(&g, &key);if let Some(l) = g.live.get_mut(&key) {if l.retry.is_none() {- log(&format!("{bin} delivery to {key} failed ({why}); retrying with backoff"));+ log(&format!("{bin} delivery to {who} failed ({why}); retrying with backoff"));}let wait =l.retry.map_or(Duration::from_secs(15), |(_, w)| (w * 2).min(Duration::from_secs(1800)));@@ -478,7 +479,7 @@ impl Daemon {}}Err(why) => {- log(&format!("{bin} delivery to {key} failed ({why}); falling back to hooks"));+ log(&format!("{bin} delivery to {} failed ({why}); falling back to hooks", this.logged(&g, &key)));// Hooks (or check_inbox) show it instead; tell senders the truth from now on.if let Some(l) = g.live.get_mut(&key) {l.push_failed = true;diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex b387b74..41503f6 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -230,6 +230,11 @@ impl Daemon {format!("{}/{name}", self.person)}+ /// A session, as the log names it: by its address. Its key carries its agent's session id, which stays out of it.+ fn logged(&self, g: &Inner, key: &str) -> String {+ g.live.get(key).map_or_else(|| "a session that has gone".into(), |l| self.addr(&l.name))+ }+fn net(&self) -> Option<Arc<Net>> {self.net.read().unwrap().clone()}diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rsindex f923759..7b3e12a 100644--- a/src/daemon/sessions.rs+++ b/src/daemon/sessions.rs@@ -68,6 +68,18 @@ impl Daemon {if g.off.contains_key(&key) {bail!(OFF_HERE);}+ // An agent with an MCP server per session is in one conversation at a time: the one its server registers now+ // ends any other it served (Claude Code's `/clear`, which runs no new server). Also when the new one is known+ // already, from its hooks or Claude Code's registry.+ if conn.is_some() && !agent::multiplexed(®.agent) {+ let before: Vec<String> = g+ .live+ .iter()+ .filter(|(k, l)| l.conn == conn && l.reg.agent == reg.agent && **k != key)+ .map(|(k, _)| k.clone())+ .collect();+ self.moved_on(g, before, now);+ }if let Some(l) = g.live.get_mut(&key) {// Known already (e.g. from a hook, now the MCP server connects, or a reconnect).if conn.is_some() {@@ -114,7 +126,7 @@ impl Daemon {let address = self.addr(&name);let pending: Vec<Message> = g.pending(&address)?;let wake: Vec<Message> = pending.iter().filter(|m| m.wake).cloned().collect();- log(&format!("session {address} ({key}) registered"));+ log(&format!("session {address} registered"));Ok((Registered { name, address, unread: pending.len() as u32 }, (key, wake)))}@@ -165,7 +177,19 @@ impl Daemon {l.attached = true;let r = remembered(l, util::now_ms());if let Err(e) = g.store.upsert_session(&r, &self.person) {- log(&format!("remembering {key}: {e:#}"));+ log(&format!("remembering {}: {e:#}", self.addr(&r.name)));+ }+ }+ }++ /// Ends sessions whose agent is in another conversation now: they are offline from here on, their names kept for+ /// them. (The log names them by address: agents' session ids stay out of it.)+ pub(super) fn moved_on(&self, g: &mut Inner, keys: Vec<String>, now: i64) {+ for k in keys {+ if let Some(l) = g.live.remove(&k) {+ let _ = g.store.touch_session(&l.name, now);+ log(&format!("session {} ended: its agent went on to another conversation", self.addr(&l.name)));+ self.presence_changed();}}}@@ -177,7 +201,7 @@ impl Daemon {&& r.key != key&& r.kept(){- log(&format!("{} lapsed: {key} takes the name", self.addr(name)));+ log(&format!("{} lapsed: a new session takes the name", self.addr(name)));g.store.forget_session(&r, &self.person)?;}Ok(())@@ -283,7 +307,7 @@ impl Daemon {&& let Some(l) = g.live.remove(&key){let _ = g.store.touch_session(&l.name, now);- log(&format!("session {} ({key}) ended", self.addr(&l.name)));+ log(&format!("session {} ended", self.addr(&l.name)));self.presence_changed();}return Ok(HookReply::default());@@ -401,7 +425,7 @@ impl Daemon {}if let Some(l) = g.live.remove(&key) {let _ = g.store.touch_session(&l.name, now);- log(&format!("session {} ({key}) left", self.addr(&l.name)));+ log(&format!("session {} left", self.addr(&l.name)));self.presence_changed();}}@@ -580,8 +604,15 @@ mod tests {}}+ /// Registers a session through an MCP server of its own, as Claude Code runs one per session.fn join(d: &Daemon, reg: SessionReg) -> Registered {- d.register_quiet(Some(1), reg, GitInfo::default()).unwrap().0+ let conn = conn_of(®.key);+ d.register_quiet(Some(conn), reg, GitInfo::default()).unwrap().0+ }++ /// The connection of the MCP server `join` registers a session through.+ fn conn_of(key: &str) -> u64 {+ key.bytes().fold(7, |h: u64, b| h.wrapping_mul(31).wrapping_add(b.into()))}/// Takes a session here offline, last seen `ago` before now.@@ -672,7 +703,7 @@ mod tests {// Its MCP server registered it; then it ends.assert_eq!(join(&d, claude("a")).name, "api-claude");d.hook(call("a")).await.unwrap();- d.drop_conn(1);+ d.drop_conn(conn_of("claude-code:a"));d.hook(HookCall { event: "end".into(), ..call("a") }).await.unwrap();mail(&d, "m1", "api-claude");assert_eq!(d.hook(call("b")).await.unwrap().address, Some(d.addr("api-claude-2")));@@ -1205,6 +1236,53 @@ mod tests {assert!(g.store.session_by_key("codex:1").unwrap().is_none());}+ #[test]+ fn a_new_conversation_from_the_same_mcp_server_ends_the_one_before() {+ let d = super::super::test_daemon(Default::default());+ let reg = |key: &str, agent: &str| SessionReg {+ key: key.into(),+ agent: agent.into(),+ cwd: "/work/api".into(),+ agent_session_id: None,+ pid: None,+ tier: Tier::Pull,+ name: None,+ };+ // Claude Code's `/clear`: its MCP server now registers the new conversation.+ assert_eq!(+ d.register_quiet(Some(1), reg("claude-code:a", "claude-code"), GitInfo::default()).unwrap().0.name,+ "api-claude"+ );+ d.register_quiet(Some(2), reg("claude-code:other", "claude-code"), GitInfo::default()).unwrap();+ let (r, _) = d.register_quiet(Some(1), reg("claude-code:b", "claude-code"), GitInfo::default()).unwrap();+ // The cleared conversation keeps its name: `/resume` can bring it back.+ assert_eq!(r.name, "api-claude-3");+ assert!(d.inner.lock().unwrap().store.session_by_name("api-claude").unwrap().unwrap().kept());+ let live = |d: &Daemon| {+ let mut k: Vec<String> = d.inner.lock().unwrap().live.keys().cloned().collect();+ k.sort();+ k+ };+ assert_eq!(live(&d), ["claude-code:b", "claude-code:other"]);+ // The registry scan can register the new conversation before the server's next call does: its call then still+ // ends the one before.+ d.register_quiet(+ None,+ SessionReg { tier: Tier::Push, ..reg("claude-code:c", "claude-code") },+ GitInfo::default(),+ )+ .unwrap();+ d.register_quiet(Some(1), reg("claude-code:c", "claude-code"), GitInfo::default()).unwrap();+ assert_eq!(live(&d), ["claude-code:c", "claude-code:other"]);+ let g = d.inner.lock().unwrap();+ assert_eq!(g.live["claude-code:c"].conn, Some(1));+ drop(g);+ // One shared MCP server serves many sessions at once.+ d.register_quiet(Some(3), reg("codex:1", "codex"), GitInfo::default()).unwrap();+ d.register_quiet(Some(3), reg("codex:2", "codex"), GitInfo::default()).unwrap();+ assert_eq!(live(&d), ["claude-code:c", "claude-code:other", "codex:1", "codex:2"]);+ }+#[tokio::test]async fn a_session_its_hooks_put_in_a_folder_that_is_off_never_gets_a_key() {let cfg = crate::config::Config {diff --git a/src/mcp.rs b/src/mcp.rsindex 44cf457..7bd5cfc 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -320,7 +320,9 @@ impl ReasonNetworkMcp {agent: agent.to_string(),cwd: agent::cwd(),agent_session_id: id,- pid: Some(agent::agent_pid()),+ // Claude Code's own process, as its registry names it: the daemon's scan of the registry matches it. None+ // when that isn't known: any other process (a parent's) would get this session ended as that one moves on.+ pid: if agent == agent::CLAUDE_CODE { agent::claude_pid() } else { Some(agent::agent_pid()) },tier,name: None,};diff --git a/tests/e2e/hooks.py b/tests/e2e/hooks.pyindex 72ac6da..53325c8 100644--- a/tests/e2e/hooks.py+++ b/tests/e2e/hooks.py@@ -254,6 +254,66 @@ got_back = json.dumps(reply(cx, 4))check("…and the message is there at the next check_inbox", "after the wait was cancelled" in got_back, got_back)cx.kill()+# Claude Code's `/clear`: the same process (and MCP server) goes on in a new conversation, which its registry names; the+# variable the server started with still names the old one.+clear_dir = os.path.join(D, "clear-proj")+os.makedirs(clear_dir)+claude_proc = subprocess.Popen(["sleep", "120"])+entry = os.path.join(CLAUDE, "sessions", f"{claude_proc.pid}.json")+def in_conversation(sid):+ with open(entry, "w") as f:+ json.dump({"pid": claude_proc.pid, "sessionId": sid, "cwd": clear_dir, "kind": "interactive"}, f)+in_conversation("before-clear")+cc_env = dict(env, CLAUDE_PID=str(claude_proc.pid), CLAUDE_CODE_SESSION_ID="before-clear")+cc = subprocess.Popen([BIN, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=cc_env, cwd=clear_dir, text=True)+rpc(cc, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "claude-code", "version": "1"}}})+reply(cc, 1)+rpc(cc, {"jsonrpc": "2.0", "method": "notifications/initialized"})+rpc(cc, {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_team", "arguments": {}}})+reply(cc, 2)+in_conversation("after-clear")+# Before the server makes another call (it may make none for a while), the daemon's scan of the registry finds the new+# conversation, and ends the one before: mail for that waits for it rather than going into this window.+until_out = ""+for _ in range(20):+ until_out = run("who", "clear-proj")+ if "clear-proj-claude-2" in until_out:+ break+ time.sleep(0.5)+check("after /clear, Claude Code's registry puts the new conversation on at once, and only it",+ "clear-proj-claude-2" in until_out and until_out.count("clear-proj-claude") == 1, until_out)+log = open(os.path.join(env["REASON_NETWORK_HOME"], "daemon.log")).read()+check("…ending the cleared one", "alex/clear-proj-claude ended: its agent went on to another conversation" in log, log[-1500:])+out = run("send", "clear-proj-claude", "for the cleared conversation")+check("…whose mail waits for it", "queued" in out and "it reaches that session when it's back" in out, out)+rpc(cc, {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "list_team", "arguments": {}}})+got3 = json.dumps(reply(cc, 3))+check("its MCP server's next call is the new conversation's, without that mail", "for the cleared conversation" not in got3, got3)+out = run("who", "clear-proj")+check("…so one session shows for it", out.count("clear-proj-claude") == 1, out)+# A shell Claude Code starts in the new conversation (the cleared one keeps its name, for /resume).+shell_env = dict(cc_env, CLAUDECODE="1", CLAUDE_CODE_SESSION_ID="after-clear")+out = subprocess.run([BIN, "status"], env=shell_env, capture_output=True, text=True, timeout=30).stdout+check("…and a shell it starts now is that conversation", "You are alex/clear-proj-claude-2." in out, out)+# A headless Claude run from that session's shell: no registry entry of its own, its server started in `inner`. The+# entry above it is the other conversation's, so it is a session of its own, which the scan leaves alone.+hc = subprocess.Popen([BIN, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,+ env=dict(cc_env, CLAUDE_CODE_SESSION_ID="inner"), cwd=clear_dir, text=True)+rpc(hc, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "claude-code", "version": "1"}}})+reply(hc, 1)+rpc(hc, {"jsonrpc": "2.0", "method": "notifications/initialized"})+rpc(hc, {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_team", "arguments": {}}})+reply(hc, 2)+time.sleep(5)+out = run("who", "clear-proj")+log = open(os.path.join(env["REASON_NETWORK_HOME"], "daemon.log")).read()+check("a headless Claude run from it is a session of its own, not its parent's conversation",+ "clear-proj-claude-3" in out and "clear-proj-claude-2" in out and "clear-proj-claude-3 ended" not in log+ and "session alex/clear-proj-claude-3 registered" in log, out + log[-800:])+hc.kill()+cc.kill()+claude_proc.kill()+# An agent's MCP server outlives daemon restarts without collecting zombies or storming restarts.mcp = subprocess.Popen([BIN, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)time.sleep(4)