1use std::ffi::OsString;
18use std::ops::Range;
19use std::path::{Path, PathBuf};
20use std::time::Duration;
21
22#[cfg(windows)]
23use agentmux_common::win32::NoWindow;
24use agentmux_common::time::now_ms_u64 as now_ms;
25use anyhow::{Context, Result};
26
27use serde::{Deserialize, Serialize};
28
29pub const SHELL_PREFIX_ENV: &str = "CLAUDE_CODE_SHELL_PREFIX";
31pub const SESSION_ID_ENV: &str = "CLAUDE_CODE_SESSION_ID";
34const CALLS_DIR_OVERRIDE_ENV: &str = "AGENTMUX_BASHWRAP_CALLS_DIR";
36const RECORD_MAX_AGE: Duration = Duration::from_secs(3600);
39const SUBCOMMANDS: &[&str] = &["exec", "hook", "precompact", "sessionstart", "git-credential", "github-token", "github-owner-tag", "github-text-guard", "git-hook", "git-env", "help"];
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct CallRecord {
45 pub tool_use_id: String,
46 pub command: String,
47 #[serde(default)]
48 pub run_in_background: bool,
49 pub created_ms: u64,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub description: Option<String>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub agent_id: Option<String>,
59 #[serde(skip)]
64 pub agent_ambiguous: bool,
65}
66
67fn marker_path(dir: &Path, command: &str) -> PathBuf {
72 let hash = command.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
73 dir.join(format!("{hash:016x}.ambiguous"))
74}
75
76fn mark_ambiguous(dir: &Path, command: &str) {
77 let _ = std::fs::write(marker_path(dir, command), command.as_bytes());
78}
79
80fn marked_ambiguous(dir: &Path, command: &str) -> bool {
81 marker_path(dir, command).exists()
82}
83
84fn agents_differ(records: &[&(PathBuf, CallRecord)]) -> bool {
87 records.windows(2).any(|w| w[0].1.agent_id != w[1].1.agent_id)
88}
89
90const MAX_DESCRIPTION_CHARS: usize = 200;
92
93pub fn prefix_script(args: &[OsString]) -> Option<String> {
103 if args.len() != 2 {
104 return None;
105 }
106 let script = args[1].to_str()?;
107 let looks_like_cli_arg = script.starts_with('-') || SUBCOMMANDS.contains(&script);
108 (!looks_like_cli_arg && !script.trim().is_empty()).then(|| script.to_string())
109}
110
111pub fn prefix_active() -> bool {
114 std::env::var_os(SHELL_PREFIX_ENV)
115 .map(|v| is_bashwrap_path(Path::new(&v)))
116 .unwrap_or(false)
117}
118
119fn is_bashwrap_path(path: &Path) -> bool {
120 path.file_stem()
121 .and_then(|s| s.to_str())
122 .map(|s| s.eq_ignore_ascii_case("agentmux-bashwrap"))
123 .unwrap_or(false)
124}
125
126pub fn extract_command(script: &str) -> Option<(String, Range<usize>)> {
131 let at = script.find("&& eval '")? + "&& eval ".len();
133 let (command, end) = read_shell_word(script, at)?;
134 Some((command, at..end))
135}
136
137fn read_shell_word(s: &str, start: usize) -> Option<(String, usize)> {
141 let bytes = s.as_bytes();
142 let mut out = String::new();
143 let mut i = start;
144 while i < bytes.len() {
145 match bytes[i] {
146 b'\'' => {
147 let close = s[i + 1..].find('\'')? + i + 1;
148 out.push_str(&s[i + 1..close]);
149 i = close + 1;
150 }
151 b'"' => {
152 i += 1;
153 loop {
154 let c = *bytes.get(i)?;
155 if c == b'"' {
156 i += 1;
157 break;
158 }
159 if c == b'\\' && matches!(bytes.get(i + 1), Some(b'"' | b'\\' | b'$' | b'`')) {
160 out.push(bytes[i + 1] as char);
161 i += 2;
162 continue;
163 }
164 let ch = s[i..].chars().next()?;
165 out.push(ch);
166 i += ch.len_utf8();
167 }
168 }
169 b'\\' => {
170 let ch = s[i + 1..].chars().next()?;
171 out.push(ch);
172 i += 1 + ch.len_utf8();
173 }
174 c if c.is_ascii_whitespace() => break,
175 _ => {
176 let ch = s[i..].chars().next()?;
177 out.push(ch);
178 i += ch.len_utf8();
179 }
180 }
181 }
182 (i > start).then_some((out, i))
183}
184
185pub fn single_quote(s: &str) -> String {
187 format!("'{}'", s.replace('\'', "'\"'\"'"))
188}
189
190pub fn replace_command(script: &str, range: Range<usize>, command: &str) -> String {
192 format!("{}{}{}", &script[..range.start], single_quote(command), &script[range.end..])
193}
194
195fn calls_root() -> Option<PathBuf> {
196 if let Some(over) = std::env::var_os(CALLS_DIR_OVERRIDE_ENV).filter(|v| !v.is_empty()) {
197 return Some(PathBuf::from(over));
198 }
199 Some(dirs::home_dir()?.join(".agentmux").join("state").join("bashwrap-calls"))
200}
201
202fn session_dir(session_id: &str) -> Option<PathBuf> {
203 Some(calls_root()?.join(sanitize(session_id)))
204}
205
206fn sanitize(raw: &str) -> String {
207 raw.chars()
208 .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
209 .collect()
210}
211
212pub fn register(session_id: &str, record: &CallRecord) -> std::io::Result<()> {
216 let dir = session_dir(session_id)
217 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no home directory"))?;
218 let name = format!("{}.json", sanitize(&record.tool_use_id));
219 let tmp = dir.join(format!(".{name}.{}", std::process::id()));
220 let bytes = serde_json::to_vec(record)?;
221 let write = || -> std::io::Result<()> {
222 std::fs::create_dir_all(&dir)?;
223 std::fs::write(&tmp, &bytes)?;
224 std::fs::rename(&tmp, dir.join(&name))
225 };
226 write().or_else(|e| if e.kind() == std::io::ErrorKind::NotFound { write() } else { Err(e) })?;
229 let records = read_records(&dir);
232 let same: Vec<&(PathBuf, CallRecord)> = records.iter().filter(|(_, r)| r.command == record.command).collect();
233 if agents_differ(&same) {
234 mark_ambiguous(&dir, &record.command);
235 }
236 if let Some(root) = calls_root() {
237 sweep_other_sessions(&root, &dir);
238 }
239 Ok(())
240}
241
242fn sweep_other_sessions(root: &Path, keep: &Path) {
247 let Ok(entries) = std::fs::read_dir(root) else { return };
248 for entry in entries.flatten() {
249 let path = entry.path();
250 if path == keep || !path.is_dir() {
251 continue;
252 }
253 if read_records(&path).is_empty() {
254 let _ = std::fs::remove_dir(&path);
256 }
257 }
258}
259
260pub fn claim(session_id: &str, command: &str) -> Option<CallRecord> {
269 let dir = session_dir(session_id)?;
270 let mut records = read_records(&dir);
271 records.sort_by_key(|(_, r)| std::cmp::Reverse(r.created_ms));
272 let matching: Vec<&(PathBuf, CallRecord)> =
273 records.iter().filter(|(_, r)| r.command == command).collect();
274 if agents_differ(&matching) {
277 mark_ambiguous(&dir, command);
278 }
279 let candidates: Vec<&(PathBuf, CallRecord)> = if !matching.is_empty() {
280 matching
281 } else if records.len() == 1 {
282 records.iter().collect()
283 } else {
284 Vec::new()
285 };
286 let mut claimed_record = None;
287 for (path, record) in candidates {
288 let claimed = path.with_extension(format!("claimed.{}", std::process::id()));
289 if std::fs::rename(path, &claimed).is_ok() {
290 let _ = std::fs::remove_file(&claimed);
291 let ambiguous = marked_ambiguous(&dir, &record.command);
294 claimed_record = Some(CallRecord { agent_ambiguous: ambiguous, ..record.clone() });
295 break;
296 }
297 }
298 if let Some(r) = claimed_record.as_ref().filter(|r| r.agent_ambiguous) {
300 if !read_records(&dir).iter().any(|(_, w)| w.command == r.command) {
301 let _ = std::fs::remove_file(marker_path(&dir, &r.command));
302 }
303 }
304 let _ = std::fs::remove_dir(&dir);
307 claimed_record
308}
309
310fn read_records(dir: &Path) -> Vec<(PathBuf, CallRecord)> {
312 let Ok(entries) = std::fs::read_dir(dir) else {
313 return Vec::new();
314 };
315 let cutoff = now_ms().saturating_sub(RECORD_MAX_AGE.as_millis() as u64);
316 let mut out = Vec::new();
317 let mut markers = Vec::new();
318 for entry in entries.flatten() {
319 let path = entry.path();
320 let ext = path.extension().and_then(|e| e.to_str());
321 if ext == Some("ambiguous") {
322 markers.push(path);
323 continue;
324 }
325 let is_record = ext == Some("json") && !path.file_name().and_then(|n| n.to_str()).unwrap_or("").starts_with('.');
326 if !is_record {
327 continue;
328 }
329 match std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::<CallRecord>(&b).ok()) {
330 Some(record) if record.created_ms >= cutoff => out.push((path, record)),
331 _ => {
332 let _ = std::fs::remove_file(&path);
333 }
334 }
335 }
336 for marker in markers {
339 let command = std::fs::read_to_string(&marker).unwrap_or_default();
340 if !out.iter().any(|(_, r)| r.command == command) {
341 let _ = std::fs::remove_file(&marker);
342 }
343 }
344 out
345}
346
347pub async fn run(script: String) -> Result<i32> {
355 let Some((command, range)) = extract_command(&script) else {
360 tracing::info!(target: "bashwrap", "prefix: not a Bash call; running it as it is");
361 return run_passthrough(&script);
362 };
363 let session = std::env::var(SESSION_ID_ENV).ok().filter(|s| !s.is_empty());
364 let record = session.as_deref().and_then(|s| claim(s, &command));
365 let Some(record) = record else {
366 tracing::info!(target: "bashwrap", session = ?session, "prefix: no call to link; running the script as plain bash");
367 return run_plain(&script);
368 };
369 let script = match crate::hook::tee_redirect_rewrite(&command) {
372 Some(teed) => replace_command(&script, range, &teed),
373 None => script,
374 };
375 let report = record.description.clone().map(|d| tokio::spawn(report_call(record.tool_use_id.clone(), d)));
377 let args = crate::bash_wrap::Args {
378 tool_id: record.tool_use_id,
379 b64_cmd: String::new(),
380 block_id: None,
381 declared_background: record.run_in_background,
382 agent: if record.agent_ambiguous { None } else { record.agent_id },
383 agent_unknown: record.agent_ambiguous,
384 };
385 if record.agent_ambiguous {
386 println!(
388 "[bashwrap] another agent ran this same command at the same moment, so which agent it belongs to can't be \
389 told: it runs in the folder Claude Code gave it, and no agent's saved folder is used or changed"
390 );
391 }
392 let result = crate::bash_wrap::run_command(args, script).await;
393 if let Some(task) = report {
394 let _ = tokio::time::timeout(Duration::from_secs(6), task).await;
396 }
397 result
398}
399
400async fn report_call(tool_id: String, description: String) {
405 let Some(client) = crate::mps_client::WpsClient::from_env() else { return };
406 let block_id = std::env::var("AGENTMUX_BLOCKID").ok().filter(|b| !b.is_empty());
407 let description: String = description.chars().take(MAX_DESCRIPTION_CHARS).collect();
408 let msg = agentmux_common::client_events::ToolChunk::Call { tool_id: tool_id.clone(), pid: std::process::id(), description, timestamp: now_ms() };
409 if let Err(e) = client.publish_chunk(block_id.as_deref(), &msg).await {
410 tracing::warn!(target: "bashwrap", tool_id, error = %e, "call report failed");
411 }
412}
413
414fn run_passthrough(script: &str) -> Result<i32> {
424 let script = script.trim();
425 if cfg!(windows) {
426 if let Some(words) = windows_path_words(script) {
427 let args: Vec<&str> = words[1..].iter().map(String::as_str).collect();
428 return run_program(&words[0], &args);
429 }
430 }
431 if !script.contains(char::is_whitespace) {
432 return run_program(script, &[]);
433 }
434 run_plain(script)
435}
436
437fn windows_path_words(line: &str) -> Option<Vec<String>> {
445 let words = quoted_words(line).unwrap_or_else(|| line.split_whitespace().map(str::to_owned).collect());
446 words.first().is_some_and(|program| program.contains('\\')).then_some(words)
447}
448
449fn quoted_words(line: &str) -> Option<Vec<String>> {
451 let mut words = Vec::new();
452 let mut word = String::new();
453 let mut in_word = false;
454 let mut rest = line;
455 while let Some(c) = rest.chars().next() {
456 rest = &rest[c.len_utf8()..];
457 match c {
458 '\'' | '"' => {
459 in_word = true;
460 loop {
461 let close = rest.find(c)?;
462 word.push_str(&rest[..close]);
463 rest = &rest[close + 1..];
464 match rest.strip_prefix("\\''") {
466 Some(after) if c == '\'' => {
467 word.push('\'');
468 rest = after;
469 }
470 _ => break,
471 }
472 }
473 }
474 c if c.is_whitespace() => {
475 if in_word {
476 words.push(std::mem::take(&mut word));
477 in_word = false;
478 }
479 }
480 c => {
481 in_word = true;
482 word.push(c);
483 }
484 }
485 }
486 if in_word {
487 words.push(word);
488 }
489 Some(words)
490}
491
492#[cfg(unix)]
495fn run_program(program: &str, args: &[&str]) -> Result<i32> {
496 use std::os::unix::process::CommandExt;
497 let err = std::process::Command::new(program).args(args).exec();
498 eprintln!("agentmux-bashwrap: cannot run {program}: {err}");
499 Ok(127)
500}
501
502#[cfg(windows)]
508fn run_program(program: &str, args: &[&str]) -> Result<i32> {
509 let resolved = which::which(program).unwrap_or_else(|_| PathBuf::from(program));
510 let mut cmd = std::process::Command::new(resolved);
511 cmd.args(args);
512 cmd.no_window();
514 match cmd.status() {
515 Ok(status) => Ok(status.code().unwrap_or(1)),
516 Err(e) => {
517 eprintln!("agentmux-bashwrap: cannot run {program}: {e}");
518 Ok(127)
519 }
520 }
521}
522
523fn run_plain(script: &str) -> Result<i32> {
525 let bash = crate::bash_wrap::locate_bash()?;
526 let mut cmd = std::process::Command::new(&bash);
527 cmd.arg("-c").arg(script);
528 #[cfg(windows)]
531 cmd.no_window();
532 let status = cmd.status().with_context(|| format!("running {}", bash.display()))?;
533 Ok(status.code().unwrap_or(1))
534}
535
536pub fn new_record(tool_use_id: &str, command: &str, run_in_background: bool) -> CallRecord {
538 CallRecord {
539 tool_use_id: tool_use_id.to_string(),
540 command: command.to_string(),
541 run_in_background,
542 created_ms: now_ms(),
543 description: None,
544 agent_id: None,
545 agent_ambiguous: false,
546 }
547}
548
549#[cfg(test)]
550mod tests {
551 use super::*;
552
553 const CLI_SCRIPT: &str = r#"source /c/Users/u/AppData/Local/Temp/config/shell-snapshots/snapshot-bash-1.sh 2>/dev/null || true && export TEMP='C:\Users\u\AppData\Local\Temp' TMP='C:\Users\u\AppData\Local\Temp' && { shopt -u extglob || setopt NO_EXTENDED_GLOB NO_BARE_GLOB_QUAL; } >/dev/null 2>&1 || true && { \builtin unalias -- 'unsetenv'; \builtin unset -f -- 'unsetenv'; } >/dev/null 2>&1 || true && eval 'echo '"'"'it'"'"''"'"'s'"'"' "q" && echo two > out.txt; cat out.txt' < /dev/null && pwd -P >| /c/Users/u/AppData/Local/Temp/claude-941e-cwd"#;
556
557 fn os(args: &[&str]) -> Vec<OsString> {
558 args.iter().map(OsString::from).collect()
559 }
560
561 #[test]
562 fn a_lone_script_argument_is_a_prefix_call() {
563 assert_eq!(prefix_script(&os(&["bw", CLI_SCRIPT])).as_deref(), Some(CLI_SCRIPT));
564 }
565
566 #[test]
567 fn subcommands_flags_and_other_shapes_are_not() {
568 for args in [
569 vec!["bw", "hook"],
570 vec!["bw", "exec"],
571 vec!["bw", "--version"],
572 vec!["bw", "--help"],
573 vec!["bw"],
574 vec!["bw", "exec", "--tool-id=x"],
575 vec!["bw", " "],
576 ] {
577 assert_eq!(prefix_script(&os(&args)), None, "{args:?}");
578 }
579 }
580
581 #[test]
584 fn hooks_and_mcp_servers_are_prefix_calls_too() {
585 for script in ["agentmux-mcp", r"C:\tools\server.exe", "npx -y @scope/server", "agentmux-bashwrap hook"] {
586 assert_eq!(prefix_script(&os(&["bw", script])).as_deref(), Some(script));
587 }
588 }
589
590 #[test]
594 fn a_script_without_the_clis_eval_never_claims_a_call() {
595 with_calls_dir(|| {
596 register("s", &new_record("toolu_1", "cargo build", false)).unwrap();
597 std::env::set_var(SESSION_ID_ENV, "s");
598 let rt = tokio::runtime::Runtime::new().unwrap();
599 let code = rt.block_on(run("agentmux-no-such-program-4f1c".to_string())).unwrap();
600 std::env::remove_var(SESSION_ID_ENV);
601 assert_eq!(code, 127, "a program that can't be started exits like a shell's");
602 assert_eq!(claim("s", "cargo build").unwrap().tool_use_id, "toolu_1", "the call is still waiting");
603 });
604 }
605
606 #[cfg(windows)]
609 #[test]
610 fn a_cmd_shim_on_path_starts_as_a_lone_word() {
611 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
612 let dir = std::env::temp_dir().join(format!("bashwrap-shim-test-{}-{}", std::process::id(), now_ms()));
613 std::fs::create_dir_all(&dir).unwrap();
614 std::fs::write(dir.join("bw-shim-test.cmd"), "@exit /b 9\r\n").unwrap();
615 let old_path = std::env::var_os("PATH").unwrap_or_default();
616 let mut paths = vec![dir.clone()];
617 paths.extend(std::env::split_paths(&old_path));
618 std::env::set_var("PATH", std::env::join_paths(paths).unwrap());
619 let code = run_program("bw-shim-test", &[]);
620 std::env::set_var("PATH", &old_path);
621 let _ = std::fs::remove_dir_all(&dir);
622 assert_eq!(code.unwrap(), 9);
623 }
624
625 #[cfg(windows)]
629 #[test]
630 fn a_windows_path_with_arguments_starts_without_bash() {
631 let dir = std::env::temp_dir().join(format!("bashwrap-winpath-test-{}-{}", std::process::id(), now_ms()));
632 if dir.to_string_lossy().contains(char::is_whitespace) {
633 return; }
635 std::fs::create_dir_all(&dir).unwrap();
636 let script = dir.join("server.cmd");
637 std::fs::write(&script, "@exit /b %1\r\n").unwrap();
638 let line = format!("{} 5", script.display());
639 let code = run_passthrough(&line);
640 let _ = std::fs::remove_dir_all(&dir);
641 assert_eq!(code.unwrap(), 5, "its argument reached it");
642 }
643
644 #[cfg(windows)]
647 #[test]
648 fn a_quoted_windows_path_starts_and_its_arguments_reach_it() {
649 let dir = std::env::temp_dir().join(format!("bashwrap quoted path test-{}-{}", std::process::id(), now_ms()));
650 std::fs::create_dir_all(&dir).unwrap();
651 let script = dir.join("server.cmd");
652 std::fs::write(&script, "@exit /b %1\r\n").unwrap();
653 let alone = run_passthrough(&format!("'{}'", script.display()));
654 let with_an_argument = run_passthrough(&format!("'{}' 7", script.display()));
655 let _ = std::fs::remove_dir_all(&dir);
656 assert_eq!(alone.unwrap(), 0, "the quoted path alone is the program");
657 assert_eq!(with_an_argument.unwrap(), 7, "its argument reached it");
658 }
659
660 #[test]
661 fn a_windows_path_line_is_read_word_by_word_with_its_quotes_taken_off() {
662 let words = |line: &str| windows_path_words(line);
663 let own = |list: &[&str]| Some(list.iter().map(|w| (*w).to_owned()).collect::<Vec<_>>());
664 assert_eq!(words(r"'C:\tools\my server.exe' --port 1"), own(&[r"C:\tools\my server.exe", "--port", "1"]));
666 assert_eq!(words(r"'C:\tools\server.exe'"), own(&[r"C:\tools\server.exe"]));
667 assert_eq!(words(r"C:\tools\server.exe --port 1"), own(&[r"C:\tools\server.exe", "--port", "1"]));
669 assert_eq!(words(r#"'C:\a\it'\''s.exe' "two words" ''"#), own(&[r"C:\a\it's.exe", "two words", ""]));
671 assert_eq!(words(r"C:\tools\server.exe it's"), own(&[r"C:\tools\server.exe", "it's"]));
673 assert_eq!(words("node 'C:\\x\\server.js'"), None);
675 assert_eq!(words("agentmux-mcp"), None);
676 assert_eq!(words(""), None);
677 }
678
679 #[test]
680 fn takes_the_command_out_of_the_clis_script() {
681 let (command, range) = extract_command(CLI_SCRIPT).unwrap();
682 assert_eq!(command, r#"echo 'it''s' "q" && echo two > out.txt; cat out.txt"#);
683 assert!(CLI_SCRIPT[range.end..].starts_with(" < /dev/null && pwd -P"));
684 assert!(CLI_SCRIPT[..range.start].ends_with("&& eval "));
685 }
686
687 #[test]
688 fn putting_the_command_back_round_trips() {
689 let (command, range) = extract_command(CLI_SCRIPT).unwrap();
690 assert_eq!(replace_command(CLI_SCRIPT, range.clone(), &command), CLI_SCRIPT);
691 let rewritten = replace_command(CLI_SCRIPT, range, "echo 'a' | tee out.txt");
692 assert_eq!(extract_command(&rewritten).unwrap().0, "echo 'a' | tee out.txt");
693 }
694
695 #[test]
696 fn multi_line_and_unicode_commands_survive() {
697 let cmd = "for f in *; do\n echo \"$f\" — ✓ 'x'\ndone";
698 let script = format!("source s.sh || true && eval {} < /dev/null && pwd -P >| f", single_quote(cmd));
699 assert_eq!(extract_command(&script).unwrap().0, cmd);
700 }
701
702 #[test]
703 fn a_script_without_the_clis_eval_has_no_command() {
704 assert_eq!(extract_command("echo hi && ls"), None);
705 assert_eq!(extract_command("x && eval 'unterminated"), None);
706 }
707
708 #[test]
709 fn only_a_path_to_agentmux_bashwrap_turns_the_prefix_on() {
710 assert!(is_bashwrap_path(Path::new("C:/Program Files/AgentMux/tools/bin/agentmux-bashwrap.exe")));
711 assert!(is_bashwrap_path(Path::new("/usr/local/bin/agentmux-bashwrap")));
712 assert!(!is_bashwrap_path(Path::new("/usr/local/bin/logger.sh")));
713 assert!(!is_bashwrap_path(Path::new("")));
714 }
715
716 fn with_calls_dir<T>(f: impl FnOnce() -> T) -> T {
717 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
718 let dir = std::env::temp_dir().join(format!("bashwrap-calls-test-{}-{}", std::process::id(), now_ms()));
719 std::env::set_var(CALLS_DIR_OVERRIDE_ENV, &dir);
720 let out = f();
721 std::env::remove_var(CALLS_DIR_OVERRIDE_ENV);
722 let _ = std::fs::remove_dir_all(&dir);
723 out
724 }
725
726 #[test]
727 fn a_claim_takes_the_matching_record_once() {
728 with_calls_dir(|| {
729 register("s1", &new_record("toolu_a", "cargo build", false)).unwrap();
730 register("s1", &new_record("toolu_b", "npm test", true)).unwrap();
731 register("s1", &new_record("toolu_c", "ls", false)).unwrap();
732 let got = claim("s1", "npm test").unwrap();
733 assert_eq!((got.tool_use_id.as_str(), got.run_in_background), ("toolu_b", true));
734 assert_eq!(claim("s1", "npm test"), None, "claimed once: two others left, neither matches");
735 assert_eq!(claim("s1", "cargo build").unwrap().tool_use_id, "toolu_a");
736 assert_eq!(claim("s1", "ls ").unwrap().tool_use_id, "toolu_c");
739 });
740 }
741
742 #[test]
745 fn the_newest_record_for_a_command_is_claimed_first() {
746 with_calls_dir(|| {
747 let mut denied = new_record("toolu_denied", "make", false);
748 denied.created_ms -= 10_000;
749 register("s", &denied).unwrap();
750 register("s", &new_record("toolu_retry", "make", true)).unwrap();
751 let got = claim("s", "make").unwrap();
752 assert_eq!((got.tool_use_id.as_str(), got.run_in_background), ("toolu_retry", true));
753 });
754 }
755
756 #[test]
757 fn without_a_match_only_a_lone_record_is_claimed() {
758 with_calls_dir(|| {
759 register("s", &new_record("toolu_1", "a", false)).unwrap();
760 assert_eq!(claim("s", "no match").unwrap().tool_use_id, "toolu_1");
761 register("s", &new_record("toolu_2", "b", false)).unwrap();
762 register("s", &new_record("toolu_3", "c", false)).unwrap();
763 assert_eq!(claim("s", "zzz"), None, "two candidates: ambiguous");
764 assert_eq!(claim("other-session", "b"), None, "another session's records are never claimed");
765 });
766 }
767
768 fn by(id: &str, command: &str, agent: Option<&str>) -> CallRecord {
769 CallRecord { agent_id: agent.map(str::to_string), ..new_record(id, command, false) }
770 }
771
772 #[test]
777 fn two_agents_identical_commands_are_claimed_as_ambiguous() {
778 with_calls_dir(|| {
779 register("s", &by("toolu_a", "git status", Some("sub-a"))).unwrap();
780 register("s", &by("toolu_b", "git status", Some("sub-b"))).unwrap();
781 let first = claim("s", "git status").unwrap();
782 let second = claim("s", "git status").unwrap();
783 assert!(first.agent_ambiguous && second.agent_ambiguous);
784 assert!(!marker_path(&session_dir("s").unwrap(), "git status").exists(), "gone with the last record");
785 register("s", &by("toolu_c", "git status", Some("sub-a"))).unwrap();
787 assert!(!claim("s", "git status").unwrap().agent_ambiguous);
788 });
789 }
790
791 #[test]
796 fn a_marker_lasts_as_long_as_its_command_waits() {
797 with_calls_dir(|| {
798 register("s", &by("toolu_a", "git status", Some("sub-a"))).unwrap();
799 register("s", &by("toolu_b", "git status", Some("sub-b"))).unwrap();
800 let dir = session_dir("s").unwrap();
801 let marker = marker_path(&dir, "git status");
802 assert!(claim("s", "git status").unwrap().agent_ambiguous);
803 let old = std::time::SystemTime::now() - Duration::from_secs(30 * 60);
804 std::fs::File::options().write(true).open(&marker).unwrap().set_modified(old).unwrap();
805 read_records(&dir);
806 assert!(marker.exists(), "the other call still waits");
807 assert!(claim("s", "git status").unwrap().agent_ambiguous, "and is still told");
808 mark_ambiguous(&dir, "ls");
810 register("s", &by("toolu_c", "pwd", None)).unwrap();
811 read_records(&dir);
812 assert!(!marker_path(&dir, "ls").exists());
813 assert!(claim("s", "pwd").is_some());
814 assert!(std::fs::remove_dir(&dir).is_ok() || !dir.exists(), "nothing keeps the directory");
815 });
816 }
817
818 #[test]
821 fn a_tidied_command_still_finds_its_records_marker() {
822 with_calls_dir(|| {
823 register("s", &by("toolu_a", "git status", Some("sub-a"))).unwrap();
824 register("s", &by("toolu_b", "git status", Some("sub-b"))).unwrap();
825 assert!(claim("s", "git status").unwrap().agent_ambiguous);
826 assert!(claim("s", "git status ").unwrap().agent_ambiguous, "the remaining record is still unsure");
827 assert!(!marker_path(&session_dir("s").unwrap(), "git status").exists());
828 });
829 }
830
831 #[test]
832 fn one_agents_parallel_calls_and_different_commands_are_not_ambiguous() {
833 with_calls_dir(|| {
834 register("s", &by("t1", "cargo test", Some("sub-a"))).unwrap();
835 register("s", &by("t2", "cargo test", Some("sub-a"))).unwrap();
836 register("s", &by("t3", "ls", Some("sub-b"))).unwrap();
837 assert!(!claim("s", "cargo test").unwrap().agent_ambiguous);
838 assert!(!claim("s", "cargo test").unwrap().agent_ambiguous);
839 assert!(!claim("s", "ls").unwrap().agent_ambiguous);
840 });
841 }
842
843 #[test]
844 fn a_session_directory_goes_once_its_last_call_is_claimed() {
845 with_calls_dir(|| {
846 register("s", &new_record("toolu_1", "a", false)).unwrap();
847 register("s", &new_record("toolu_2", "b", false)).unwrap();
848 let dir = session_dir("s").unwrap();
849 claim("s", "a").unwrap();
850 assert!(dir.is_dir(), "a call still waits in it");
851 claim("s", "b").unwrap();
852 assert!(!dir.exists());
853 register("s", &new_record("toolu_3", "c", false)).unwrap();
855 assert_eq!(claim("s", "c").unwrap().tool_use_id, "toolu_3");
856 });
857 }
858
859 #[test]
860 fn a_new_record_sweeps_other_sessions_left_behind() {
861 with_calls_dir(|| {
862 let mut denied = new_record("toolu_old", "x", false);
864 denied.created_ms -= RECORD_MAX_AGE.as_millis() as u64 + 1;
865 register("ended", &denied).unwrap();
866 std::fs::create_dir_all(session_dir("empty").unwrap()).unwrap();
868 register("live", &new_record("toolu_live", "y", false)).unwrap();
870 register("current", &new_record("toolu_now", "z", false)).unwrap();
871 assert!(!session_dir("ended").unwrap().exists());
872 assert!(!session_dir("empty").unwrap().exists());
873 assert_eq!(claim("live", "y").unwrap().tool_use_id, "toolu_live");
874 assert_eq!(claim("current", "z").unwrap().tool_use_id, "toolu_now");
875 });
876 }
877
878 #[test]
879 fn stale_records_are_dropped() {
880 with_calls_dir(|| {
881 let mut old = new_record("toolu_old", "x", false);
882 old.created_ms -= RECORD_MAX_AGE.as_millis() as u64 + 1;
883 register("s", &old).unwrap();
884 assert_eq!(claim("s", "x"), None);
885 assert!(read_records(&session_dir("s").unwrap()).is_empty());
886 });
887 }
888}