diff --git a/docs/reference.md b/docs/reference.md index 75ab677..539052d 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -64,7 +64,8 @@ Names match `[a-z0-9_-]{1,64}`. | Codex | `codex-` | | OpenCode | `opencode-<16 hex of SHA-256(session)>` | -`` is the first 20 characters of the working directory name. After +`` is the first 20 characters of the name of the directory where the +session started. A `cd` of the agent does not change the mailbox. After `/clear` in Claude Code, the session changes, so the mailbox changes too. Recipient aliases: `codex` is the most recent Codex session. `all` is the diff --git a/src/hooks.rs b/src/hooks.rs index 9217076..c5018ba 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -179,8 +179,24 @@ fn text_field<'a>(payload: &'a Value, name: &str) -> &'a str { .unwrap_or_default() } +/// Returns the directory that names the mailbox of a Claude Code session. +/// +/// `project_dir` is `CLAUDE_PROJECT_DIR`: the directory where the session started. It does not +/// change. The `cwd` of a hook follows each `cd` of the agent, so a name made from it changes +/// during the session, and the shim then listens to another mailbox than the one of the hooks. +/// `cwd` is the fallback for a Claude Code that does not set the variable. +#[must_use] +pub fn mailbox_directory<'a>(project_dir: Option<&'a str>, cwd: &'a str) -> &'a str { + project_dir + .map(str::trim) + .filter(|dir| !dir.is_empty()) + .unwrap_or(cwd) +} + /// Runs one Claude Code hook, and returns its output, or `None` when it has nothing to say. /// +/// `project_dir` is the value of `CLAUDE_PROJECT_DIR`, see [`mailbox_directory`]. +/// /// - `SessionStart` binds the mailbox, and returns the identity and the protocol. /// - `UserPromptSubmit` runs a team command. /// - `PostToolUse` tells a working session about its unread mail, at most every two minutes. @@ -190,12 +206,14 @@ pub async fn claude_hook( payload: &Value, state: &MailcheckState, files: Option<&ClientDirs>, + project_dir: Option<&str>, ) -> Option { let session = text_field(payload, "session_id"); if session.is_empty() { return None; } - let mailbox = claude_mailbox(text_field(payload, "cwd"), session); + let directory = mailbox_directory(project_dir, text_field(payload, "cwd")); + let mailbox = claude_mailbox(directory, session); match text_field(payload, "hook_event_name") { "SessionStart" => { let mut output = claude_session_start(client, &mailbox, session).await; diff --git a/src/hooks_tests.rs b/src/hooks_tests.rs index 71dafeb..e1d4f1e 100644 --- a/src/hooks_tests.rs +++ b/src/hooks_tests.rs @@ -76,6 +76,7 @@ async fn hook( &claude(event, session, extra), &MailcheckState::always(), None, + None, ) .await } @@ -158,6 +159,7 @@ async fn check_mail_reminders( &claude("PostToolUse", WORKER_SESSION, &json!({})), &state, None, + None, ) .await .unwrap(); @@ -167,6 +169,7 @@ async fn check_mail_reminders( &claude("PostToolUse", LEAD_SESSION, &json!({})), &state, None, + None, ) .await .unwrap(); @@ -180,6 +183,7 @@ async fn check_mail_reminders( &claude("PostToolUse", LEAD_SESSION, &json!({})), &state, None, + None, ) .await; assert_eq!(none, None); @@ -195,6 +199,7 @@ async fn a_wrong_token_is_refused_and_blocks_the_command() { &claude("SessionStart", LEAD_SESSION, &json!({})), &state, None, + None, ) .await .unwrap(); @@ -208,6 +213,7 @@ async fn a_wrong_token_is_refused_and_blocks_the_command() { ), &state, None, + None, ) .await .unwrap(); @@ -253,6 +259,7 @@ async fn hooks_fail_open_when_the_daemon_is_down() { &claude("SessionStart", LEAD_SESSION, &json!({})), &MailcheckState::always(), None, + None, ) .await .unwrap(); @@ -301,7 +308,7 @@ async fn a_changed_command_file_is_refused_and_reported() { let state = MailcheckState::always(); let files = installed_files("poison"); let start = claude("SessionStart", LEAD_SESSION, &json!({})); - let clean = claude_hook(&daemon, &start, &state, Some(&files)) + let clean = claude_hook(&daemon, &start, &state, Some(&files), None) .await .unwrap(); assert!(clean.get("systemMessage").is_none(), "{clean}"); @@ -314,7 +321,7 @@ async fn a_changed_command_file_is_refused_and_reported() { ) .unwrap(); - let warned = claude_hook(&daemon, &start, &state, Some(&files)) + let warned = claude_hook(&daemon, &start, &state, Some(&files), None) .await .unwrap(); assert!( @@ -335,7 +342,7 @@ async fn a_changed_command_file_is_refused_and_reported() { LEAD_SESSION, &json!({"prompt": "/lead x"}), ); - let refused = claude_hook(&daemon, &prompt, &state, Some(&files)) + let refused = claude_hook(&daemon, &prompt, &state, Some(&files), None) .await .unwrap(); assert_eq!(refused["decision"], "block"); @@ -358,7 +365,7 @@ async fn a_changed_command_file_is_refused_and_reported() { LEAD_SESSION, &json!({"prompt": "/join x"}), ); - let joined = claude_hook(&daemon, &join, &state, Some(&files)) + let joined = claude_hook(&daemon, &join, &state, Some(&files), None) .await .unwrap(); assert!( @@ -388,3 +395,53 @@ async fn codex_sessions_are_warned_about_a_changed_plugin() { "{out}" ); } + +#[test] +fn the_project_directory_names_the_mailbox() { + assert_eq!( + mailbox_directory(Some("/home/dev"), "/home/dev/notes"), + "/home/dev" + ); + assert_eq!( + mailbox_directory(None, "/home/dev/notes"), + "/home/dev/notes", + "a Claude Code without the variable" + ); + assert_eq!( + mailbox_directory(Some(" "), "/home/dev/notes"), + "/home/dev/notes" + ); +} + +/// The `cwd` of a hook follows each `cd` of the agent. The mailbox must keep its name: the shim +/// listens to the mailbox of the start, and a team command for another name makes a lead that +/// receives no mail. +#[tokio::test] +async fn a_changed_working_directory_keeps_the_mailbox() { + let (base, bridge) = serve().await; + let daemon = daemon_client(&base, CLAUDE_CLIENT); + let state = MailcheckState::always(); + let project = Some("/work/My Repo"); + let mailbox = claude_mailbox("/work/My Repo", LEAD_SESSION); + let moved = claude_mailbox("/work/My Repo/notes", LEAD_SESSION); + assert_ne!(mailbox, moved); + + let start = claude("SessionStart", LEAD_SESSION, &json!({})); + claude_hook(&daemon, &start, &state, None, project) + .await + .unwrap(); + let lead = claude( + "UserPromptSubmit", + LEAD_SESSION, + &json!({"prompt": "/lead x", "cwd": "/work/My Repo/notes"}), + ); + let lead = claude_hook(&daemon, &lead, &state, None, project) + .await + .unwrap(); + assert!( + context_of(&lead).contains(&format!("`{mailbox}` is now the lead of team `x`")), + "{lead}" + ); + assert!(bridge.membership(&mailbox).unwrap().is_some()); + assert_eq!(bridge.membership(&moved).unwrap(), None); +} diff --git a/src/main.rs b/src/main.rs index 422decb..d53ecd1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -123,6 +123,7 @@ async fn hook(client: HookClient) -> Result<(), String> { &payload, &MailcheckState::from_env(&env()), files.as_ref(), + env().get("CLAUDE_PROJECT_DIR").map(String::as_str), ) .await } diff --git a/src/shim.rs b/src/shim.rs index 7531b9f..b87a2ab 100644 --- a/src/shim.rs +++ b/src/shim.rs @@ -25,7 +25,7 @@ use serde_json::{Map, Value, json}; use crate::client::Client; use crate::config::EnvMap; -use crate::hooks::claude_mailbox; +use crate::hooks::{claude_mailbox, mailbox_directory}; /// The time of one long poll. The daemon limits a long poll to 300 s. const POLL_SECONDS: u64 = 290; @@ -48,6 +48,9 @@ pub struct ClaudeRegistry { file: PathBuf, pid: u32, first_session: String, + /// `CLAUDE_PROJECT_DIR`: the directory where the session started. The hooks name the mailbox + /// from it, so the shim does the same, see [`mailbox_directory`]. + project_dir: Option, /// The project directory, for a process that keeps no registry file (`claude -p`). first_cwd: Option, /// `startedAt` and `procStart` of the process, pinned at the first valid read: a later file @@ -85,21 +88,22 @@ impl ClaudeRegistry { .map(|home| PathBuf::from(home).join(".claude")) }) .ok_or("no HOME and no CLAUDE_CONFIG_DIR")?; + let project_dir = env + .get("CLAUDE_PROJECT_DIR") + .filter(|dir| !dir.trim().is_empty()) + .cloned(); Ok(Self { file: config_dir .join("sessions") .join(format!("{parent_pid}.json")), pid: parent_pid, first_session, - first_cwd: env - .get("CLAUDE_PROJECT_DIR") - .filter(|dir| !dir.is_empty()) - .cloned() - .or_else(|| { - std::env::current_dir() - .ok() - .map(|dir| dir.display().to_string()) - }), + project_dir: project_dir.clone(), + first_cwd: project_dir.or_else(|| { + std::env::current_dir() + .ok() + .map(|dir| dir.display().to_string()) + }), pinned: Mutex::new(None), }) } @@ -159,7 +163,7 @@ impl ClaudeRegistry { } Some(Identity { session: session.to_owned(), - mailbox: claude_mailbox(cwd, session), + mailbox: claude_mailbox(mailbox_directory(self.project_dir.as_deref(), cwd), session), }) } } diff --git a/src/shim_tests.rs b/src/shim_tests.rs index 57b6224..a4d52a7 100644 --- a/src/shim_tests.rs +++ b/src/shim_tests.rs @@ -112,7 +112,9 @@ async fn team(base: &str) { for session in [LEAD_SESSION, WORKER_SESSION] { let start = json!({"hook_event_name": "SessionStart", "session_id": session, "cwd": "/work/repo"}); - claude_hook(&daemon, &start, &state, None).await.unwrap(); + claude_hook(&daemon, &start, &state, None, None) + .await + .unwrap(); } let lead = identity(LEAD_SESSION).mailbox; let worker = identity(WORKER_SESSION).mailbox; @@ -378,3 +380,15 @@ async fn the_codex_shim_signs_the_session_that_codex_names() { .await; assert!(anonymous.get("error").is_some(), "{anonymous}"); } + +/// The shim and the hooks must give one session the same mailbox. The hooks name it from +/// `CLAUDE_PROJECT_DIR`, so the shim does not use another directory of the registry file. +#[test] +fn the_registry_names_the_mailbox_from_the_project_directory() { + let dir = registry_dir("project"); + let registry = registry(&dir, 4444, LEAD_SESSION); + let row = json!({"pid": 4444, "sessionId": LEAD_SESSION, "cwd": "/work/repo/notes", + "startedAt": 100, "procStart": "77"}); + std::fs::write(dir.join("sessions/4444.json"), row.to_string()).unwrap(); + assert_eq!(registry.current(), Some(identity(LEAD_SESSION))); +}