Skip to main content

agentmux_srv_core/backend/
tool_store.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Tool store: ensures CLI tools (jq, rg, etc.) are available to agent
5//! subprocesses. Reads a bundled catalog JSON, checks system/bundled/managed
6//! install paths, and can download + verify tools on demand.
7
8#[cfg(windows)]
9use agentmux_common::win32::NoWindow;
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15
16// Embedded catalog — path is relative to THIS FILE's location.
17// File: crates/srv-core/src/backend/tool_store.rs
18// Catalog: crates/srv-core/src/config/tool-catalog.json
19const CATALOG_JSON: &str = include_str!("../config/tool-catalog.json");
20
21// ---- Catalog structs ----
22
23#[derive(Debug, Clone, Deserialize)]
24pub struct ToolCatalog {
25    pub tools: Vec<ToolSpec>,
26}
27
28#[derive(Debug, Clone, Deserialize)]
29pub struct ToolSpec {
30    pub id: String,
31    pub display: String,
32    pub description: String,
33    pub tier: u8,
34    pub version: String,
35    pub check_cmd: String,
36    /// Flag (e.g. `"--version"`) to pass to the binary to get its version string.
37    /// If absent, version probing is skipped and the catalog version is reported.
38    #[serde(default)]
39    pub version_arg: Option<String>,
40    pub platforms: HashMap<String, PlatformSpec>,
41}
42
43#[derive(Debug, Clone, Deserialize)]
44pub struct PlatformSpec {
45    pub url: String,
46    pub sha256: String,
47    /// "none" | "zip" | "tar_gz"
48    pub extract: String,
49    /// Final filename placed in the bin/ directory.
50    pub bin: String,
51    /// Path of the target file inside the archive (zip/tar_gz only).
52    pub bin_in_archive: Option<String>,
53}
54
55// ---- Status types ----
56
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
58#[ts(export, export_to = "../../../frontend/types/rpc/")]
59#[serde(rename_all = "snake_case")]
60pub enum ToolStatus {
61    InstalledSystem,
62    InstalledBundled,
63    InstalledManaged,
64    Missing,
65    Unavailable,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
69#[ts(export, export_to = "../../../frontend/types/rpc/")]
70pub struct ToolStatusEntry {
71    pub id: String,
72    pub display: String,
73    pub description: String,
74    pub tier: u8,
75    pub status: ToolStatus,
76    pub version: Option<String>,
77    pub path: Option<String>,
78}
79
80// ---- Directory helpers ----
81
82/// Returns the bundled tools bin dir: `<exe_dir>/tools/bin/`.
83///
84/// In development (binary lives under `target/debug/` or `target/release/`)
85/// we return `None` so dev builds don't accidentally depend on a non-existent
86/// bundled dir.
87pub fn bundled_tools_dir() -> Option<PathBuf> {
88    let exe = std::env::current_exe().ok()?;
89    let exe_dir = exe.parent()?;
90
91    // Skip if we're running from a Cargo target directory.
92    let exe_str = exe_dir.to_string_lossy();
93    if exe_str.contains("target/debug")
94        || exe_str.contains("target/release")
95        || exe_str.contains("target\\debug")
96        || exe_str.contains("target\\release")
97    {
98        return None;
99    }
100
101    let bundled = bundled_dir_in(exe_dir);
102    // A Store (MSIX) install can't run its tools from inside the package, so
103    // they run from a copy (see `packaged_tools`); anything else is unchanged.
104    Some(crate::backend::packaged_tools::runnable(bundled))
105}
106
107/// The tools folder of an install whose server program is in `exe_dir`: `tools/bin` below it (the desktop app), or the
108/// folder itself when that has no `tools/bin` and holds the helpers beside the server (the server package keeps
109/// `bin/agentmux-bashwrap` next to `bin/agentmux-srv`).
110fn bundled_dir_in(exe_dir: &Path) -> PathBuf {
111    let tools = exe_dir.join("tools").join("bin");
112    let wrapper = if cfg!(windows) { "agentmux-bashwrap.exe" } else { "agentmux-bashwrap" };
113    if !tools.exists() && exe_dir.join(wrapper).is_file() {
114        return exe_dir.to_path_buf();
115    }
116    tools
117}
118
119/// Returns `~/.agentmux/tools/bin/`.
120pub fn user_tools_dir() -> Option<PathBuf> {
121    let home = dirs::home_dir()?;
122    Some(home.join(".agentmux").join("tools").join("bin"))
123}
124
125/// Where the user tools dir goes relative to the existing PATH. The bundled
126/// dir always goes first: it is app-owned and version-locked, and a stale
127/// system copy shadowing it is the exit-130 trap
128/// (RETRO_BASHWRAP_STALE_BUNDLE_2026_06_13.md).
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum UserToolsPrecedence {
131    /// Before the existing PATH. Agent CLIs: in `task dev` there is no
132    /// bundled dir and the wrapper lives in the user dir, so a system copy
133    /// must not win.
134    BeforeExisting,
135    /// After the existing PATH. Interactive shells: the user's own system
136    /// PATH wins for tools they installed via /tools.
137    AfterExisting,
138}
139
140/// `existing` with the given tool dirs added (bundled first, user per
141/// `user_precedence`). `None` when neither dir is given, so the caller can
142/// leave PATH untouched.
143pub fn compose_tools_path(
144    existing: &str,
145    bundled: Option<&std::path::Path>,
146    user: Option<&std::path::Path>,
147    user_precedence: UserToolsPrecedence,
148) -> Option<String> {
149    if bundled.is_none() && user.is_none() {
150        return None;
151    }
152    let mut parts: Vec<String> = Vec::new();
153    if let Some(d) = bundled {
154        parts.push(d.to_string_lossy().into_owned());
155    }
156    if let (Some(d), UserToolsPrecedence::BeforeExisting) = (user, user_precedence) {
157        parts.push(d.to_string_lossy().into_owned());
158    }
159    if !existing.is_empty() {
160        parts.push(existing.to_string());
161    }
162    if let (Some(d), UserToolsPrecedence::AfterExisting) = (user, user_precedence) {
163        parts.push(d.to_string_lossy().into_owned());
164    }
165    let sep = if cfg!(windows) { ";" } else { ":" };
166    Some(parts.join(sep))
167}
168
169/// [`compose_tools_path`] over the tool dirs that exist on this machine.
170pub fn tools_path(existing: &str, user_precedence: UserToolsPrecedence) -> Option<String> {
171    let bundled = bundled_tools_dir().filter(|d| d.exists());
172    let user = user_tools_dir().filter(|d| d.exists());
173    compose_tools_path(existing, bundled.as_deref(), user.as_deref(), user_precedence)
174}
175
176/// Puts the tool dirs ahead of the PATH in `env_vars` (else the process's own) for an agent's
177/// process: the bundled dir, then the user dir, so the build-slot shims in the user dir
178/// (`agentmux_common::build_slot`) and the app's own tools beat anything on the system PATH.
179/// Every agent spawn calls this: a spawn that skips it never reaches the shims.
180pub fn prepend_agent_tools_path(env_vars: &mut HashMap<String, String>) {
181    let bundled = bundled_tools_dir().filter(|d| d.exists());
182    let user = user_tools_dir().filter(|d| d.exists());
183    prepend_tools_path_with(env_vars, bundled.as_deref(), user.as_deref());
184}
185
186fn prepend_tools_path_with(env_vars: &mut HashMap<String, String>, bundled: Option<&std::path::Path>, user: Option<&std::path::Path>) {
187    let existing = env_vars.get("PATH").cloned().or_else(|| std::env::var("PATH").ok()).unwrap_or_default();
188    if let Some(path) = compose_tools_path(&existing, bundled, user, UserToolsPrecedence::BeforeExisting) {
189        env_vars.insert("PATH".to_string(), path);
190    }
191}
192
193/// The `agentmux-bashwrap` agents' Bash commands run through: the bundled
194/// copy, else the user tools dir's (where `task dev` puts it), in the order
195/// [`tools_path`] puts them on PATH. An absolute path, so a stale copy
196/// elsewhere on PATH can never be the one that runs
197/// (RETRO_BASHWRAP_STALE_BUNDLE_2026_06_13.md).
198pub fn bashwrap_path() -> Option<PathBuf> {
199    use crate::backend::agent_tools::{find_in_tool_dirs, ToolDir};
200    find_in_tool_dirs("agentmux-bashwrap", &[ToolDir::Bundled, ToolDir::User])
201}
202
203/// Returns `~/.agentmux/tools/downloads/`.
204fn downloads_dir() -> Option<PathBuf> {
205    let home = dirs::home_dir()?;
206    Some(home.join(".agentmux").join("tools").join("downloads"))
207}
208
209// ---- Catalog ----
210
211/// Load and parse the embedded catalog.
212pub fn load_catalog() -> Result<ToolCatalog, String> {
213    serde_json::from_str(CATALOG_JSON).map_err(|e| format!("parse tool-catalog.json: {e}"))
214}
215
216// ---- Platform detection ----
217
218/// Returns the platform key for the current compile target.
219pub fn current_platform() -> Result<&'static str, String> {
220    // Use std::env::consts at runtime so this compiles on every platform
221    // without unreachable-expression warnings.
222    match (std::env::consts::OS, std::env::consts::ARCH) {
223        ("windows", "x86_64") => Ok("windows-x64"),
224        ("macos", "aarch64") => Ok("macos-arm64"),
225        ("macos", "x86_64") => Ok("macos-x64"),
226        ("linux", "x86_64") => Ok("linux-x64"),
227        ("linux", "aarch64") => Ok("linux-arm64"),
228        (os, arch) => Err(format!("unsupported platform: os={os} arch={arch}")),
229    }
230}
231
232// ---- System PATH probe ----
233
234/// Returns true if `name` can be found on the system PATH.
235fn probe_system_path(name: &str) -> bool {
236    #[cfg(windows)]
237    {
238        std::process::Command::new("where")
239            .arg(name)
240            .no_window()
241            .output()
242            .map(|o| o.status.success())
243            .unwrap_or(false)
244    }
245    #[cfg(not(windows))]
246    {
247        std::process::Command::new("which")
248            .arg(name)
249            .output()
250            .map(|o| o.status.success())
251            .unwrap_or(false)
252    }
253}
254
255/// Returns the system PATH location of `name`, or None.
256fn system_path_of(name: &str) -> Option<String> {
257    #[cfg(windows)]
258    let output = {
259        std::process::Command::new("where")
260            .arg(name)
261            .no_window()
262            .output()
263            .ok()?
264    };
265    #[cfg(not(windows))]
266    let output = std::process::Command::new("which").arg(name).output().ok()?;
267
268    if output.status.success() {
269        let path = String::from_utf8_lossy(&output.stdout)
270            .lines()
271            .next()
272            .unwrap_or("")
273            .trim()
274            .to_string();
275        if !path.is_empty() {
276            return Some(path);
277        }
278    }
279    None
280}
281
282/// Run `cmd --version-arg` and extract the first version-looking token.
283/// Returns `Some(version_string)` on success, `None` if the command fails or
284/// the output contains no recognisable version token.
285pub fn probe_version(cmd: &str, version_arg: &Option<String>) -> Option<String> {
286    probe_version_with_env(cmd, version_arg, &[])
287}
288
289/// [`probe_version`] with extra environment for the child, for a CLI that must not start its own
290/// update on a probe.
291pub(crate) fn probe_version_with_env(cmd: &str, version_arg: &Option<String>, env: &[(&str, &str)]) -> Option<String> {
292    probe_version_inner(cmd, version_arg, env, false)
293}
294
295/// [`probe_version_with_env`] for "does this program run": a non-zero exit gives `None`, so an
296/// error message that happens to contain a number (macOS runs a file that is not a program through
297/// `sh`, which prints its path and 127) is never read as a version.
298pub(crate) fn probe_version_when_it_runs(cmd: &str, version_arg: &Option<String>, env: &[(&str, &str)]) -> Option<String> {
299    probe_version_inner(cmd, version_arg, env, true)
300}
301
302fn probe_version_inner(cmd: &str, version_arg: &Option<String>, env: &[(&str, &str)], must_succeed: bool) -> Option<String> {
303    let arg = version_arg.as_deref()?;
304    let mut command = std::process::Command::new(cmd);
305    // `cmd` is a third-party binary, so it gets the strict policy for the same
306    // reason `open_browser` does (invariant I7) — short-lived and output-parsed
307    // is a weaker argument than "does not need our identity at all".
308    crate::backend::pane_env::sanitize_external_std_command(&mut command);
309    command.arg(arg);
310    command.envs(env.iter().copied());
311    #[cfg(windows)]
312    {
313        command.no_window();
314    }
315    let output = command.output().ok()?;
316    if must_succeed && !output.status.success() {
317        return None;
318    }
319    // Some tools write version to stderr (e.g. older jq), try both.
320    let text = if !output.stdout.is_empty() {
321        String::from_utf8_lossy(&output.stdout).into_owned()
322    } else {
323        String::from_utf8_lossy(&output.stderr).into_owned()
324    };
325    // Extract first token that looks like a semver number.
326    for word in text.split_whitespace() {
327        let candidate = word.trim_matches(|c: char| !c.is_ascii_digit() && c != '.');
328        if candidate.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false)
329            && candidate.contains('.')
330        {
331            return Some(candidate.to_string());
332        }
333    }
334    None
335}
336
337// ---- Status query ----
338
339/// Get the install status of every tool in the catalog.
340///
341/// Priority: system PATH > bundled dir > user-managed dir.
342pub fn get_tool_statuses() -> Vec<ToolStatusEntry> {
343    let catalog = match load_catalog() {
344        Ok(c) => c,
345        Err(e) => {
346            tracing::error!(error = %e, "failed to load tool catalog");
347            return Vec::new();
348        }
349    };
350
351    let platform = current_platform().ok();
352
353    catalog
354        .tools
355        .iter()
356        .map(|spec| {
357            // Check platform availability first so we can return Unavailable early.
358            let platform_key = match &platform {
359                Some(k) => *k,
360                None => {
361                    return ToolStatusEntry {
362                        id: spec.id.clone(),
363                        display: spec.display.clone(),
364                        description: spec.description.clone(),
365                        tier: spec.tier,
366                        status: ToolStatus::Unavailable,
367                        version: None,
368                        path: None,
369                    };
370                }
371            };
372
373            if !spec.platforms.contains_key(platform_key) {
374                return ToolStatusEntry {
375                    id: spec.id.clone(),
376                    display: spec.display.clone(),
377                    description: spec.description.clone(),
378                    tier: spec.tier,
379                    status: ToolStatus::Unavailable,
380                    version: None,
381                    path: None,
382                };
383            }
384
385            let bin_name = &spec.platforms[platform_key].bin;
386
387            // 1. System PATH wins.
388            if probe_system_path(&spec.check_cmd) {
389                let path = system_path_of(&spec.check_cmd);
390                // Probe the actual installed version rather than assuming the catalog version.
391                let version = probe_version(&spec.check_cmd, &spec.version_arg);
392                return ToolStatusEntry {
393                    id: spec.id.clone(),
394                    display: spec.display.clone(),
395                    description: spec.description.clone(),
396                    tier: spec.tier,
397                    status: ToolStatus::InstalledSystem,
398                    version,
399                    path,
400                };
401            }
402
403            // 2. Bundled dir.
404            if let Some(bundled) = bundled_tools_dir() {
405                let p = bundled.join(bin_name);
406                if p.exists() {
407                    return ToolStatusEntry {
408                        id: spec.id.clone(),
409                        display: spec.display.clone(),
410                        description: spec.description.clone(),
411                        tier: spec.tier,
412                        status: ToolStatus::InstalledBundled,
413                        version: Some(spec.version.clone()),
414                        path: Some(p.to_string_lossy().into_owned()),
415                    };
416                }
417            }
418
419            // 3. User-managed store.
420            if let Some(user_bin) = user_tools_dir() {
421                let p = user_bin.join(bin_name);
422                if p.exists() {
423                    return ToolStatusEntry {
424                        id: spec.id.clone(),
425                        display: spec.display.clone(),
426                        description: spec.description.clone(),
427                        tier: spec.tier,
428                        status: ToolStatus::InstalledManaged,
429                        version: Some(spec.version.clone()),
430                        path: Some(p.to_string_lossy().into_owned()),
431                    };
432                }
433            }
434
435            // 4. Not found.
436            ToolStatusEntry {
437                id: spec.id.clone(),
438                display: spec.display.clone(),
439                description: spec.description.clone(),
440                tier: spec.tier,
441                status: ToolStatus::Missing,
442                version: None,
443                path: None,
444            }
445        })
446        .collect()
447}
448
449// ---- Installation ----
450
451/// Download, verify, and install a single tool by ID into the user-managed
452/// store (`~/.agentmux/tools/bin/`).
453///
454/// Returns the installed binary path on success.
455pub async fn install_tool(id: &str, http_client: &reqwest::Client) -> Result<String, String> {
456    let catalog = load_catalog()?;
457    let spec = catalog
458        .tools
459        .iter()
460        .find(|t| t.id == id)
461        .ok_or_else(|| format!("tool '{id}' not found in catalog"))?;
462
463    let platform_key = current_platform()?;
464    let platform_spec = spec
465        .platforms
466        .get(platform_key)
467        .ok_or_else(|| format!("tool '{id}' has no entry for platform '{platform_key}'"))?;
468
469    // Ensure directories exist.
470    let dl_dir = downloads_dir().ok_or("cannot determine downloads dir")?;
471    let bin_dir = user_tools_dir().ok_or("cannot determine user tools dir")?;
472    std::fs::create_dir_all(&dl_dir)
473        .map_err(|e| format!("create downloads dir: {e}"))?;
474    std::fs::create_dir_all(&bin_dir)
475        .map_err(|e| format!("create bin dir: {e}"))?;
476
477    // Download to a temp file.
478    let dl_path = dl_dir.join(format!("{id}-download"));
479    tracing::info!(tool = %id, url = %platform_spec.url, dest = %dl_path.display(), "downloading tool");
480
481    {
482        let bytes = http_client
483            .get(&platform_spec.url)
484            .send()
485            .await
486            .map_err(|e| format!("download '{id}': {e}"))?
487            .error_for_status()
488            .map_err(|e| format!("download '{id}' HTTP error: {e}"))?
489            .bytes()
490            .await
491            .map_err(|e| format!("read download body '{id}': {e}"))?;
492
493        std::fs::write(&dl_path, &bytes)
494            .map_err(|e| format!("write download file: {e}"))?;
495    }
496
497    // Verify SHA-256.
498    {
499        let data = std::fs::read(&dl_path)
500            .map_err(|e| format!("read downloaded file for hash: {e}"))?;
501        let mut hasher = Sha256::new();
502        hasher.update(&data);
503        let digest = hex::encode(hasher.finalize());
504        if digest != platform_spec.sha256 {
505            let _ = std::fs::remove_file(&dl_path);
506            return Err(format!(
507                "SHA-256 mismatch for '{id}': expected={} got={digest}",
508                platform_spec.sha256,
509            ));
510        }
511        tracing::debug!(tool = %id, "SHA-256 verified");
512    }
513
514    // Extract / copy into bin dir.
515    let dest_path = bin_dir.join(&platform_spec.bin);
516
517    match platform_spec.extract.as_str() {
518        "none" => {
519            std::fs::copy(&dl_path, &dest_path)
520                .map_err(|e| format!("copy '{id}' to bin: {e}"))?;
521        }
522        "zip" => {
523            let archive_in = platform_spec
524                .bin_in_archive
525                .as_deref()
526                .ok_or_else(|| format!("tool '{id}': extract=zip but bin_in_archive is missing"))?;
527
528            let zip_data = std::fs::read(&dl_path)
529                .map_err(|e| format!("read zip file: {e}"))?;
530            let cursor = std::io::Cursor::new(zip_data);
531            let mut archive = zip::ZipArchive::new(cursor)
532                .map_err(|e| format!("open zip archive: {e}"))?;
533
534            let mut entry = archive
535                .by_name(archive_in)
536                .map_err(|e| format!("zip entry '{archive_in}': {e}"))?;
537
538            let mut out = std::fs::File::create(&dest_path)
539                .map_err(|e| format!("create dest file: {e}"))?;
540            std::io::copy(&mut entry, &mut out)
541                .map_err(|e| format!("extract zip entry: {e}"))?;
542        }
543        "tar_gz" => {
544            let archive_in = platform_spec
545                .bin_in_archive
546                .as_deref()
547                .ok_or_else(|| format!("tool '{id}': extract=tar_gz but bin_in_archive is missing"))?;
548
549            let gz_file = std::fs::File::open(&dl_path)
550                .map_err(|e| format!("open tar.gz: {e}"))?;
551            let gz_decoder = flate2::read::GzDecoder::new(gz_file);
552            let mut archive = tar::Archive::new(gz_decoder);
553
554            let mut found = false;
555            for entry in archive.entries().map_err(|e| format!("tar entries: {e}"))? {
556                let mut entry = entry.map_err(|e| format!("tar entry: {e}"))?;
557                let path = entry.path().map_err(|e| format!("tar entry path: {e}"))?;
558                if path.to_string_lossy() == archive_in {
559                    entry
560                        .unpack(&dest_path)
561                        .map_err(|e| format!("unpack tar entry: {e}"))?;
562                    found = true;
563                    break;
564                }
565            }
566            if !found {
567                return Err(format!(
568                    "tar archive does not contain expected entry '{archive_in}'"
569                ));
570            }
571        }
572        other => {
573            return Err(format!("unknown extract mode '{other}' for tool '{id}'"));
574        }
575    }
576
577    // Set executable bit on Unix.
578    #[cfg(unix)]
579    {
580        use std::os::unix::fs::PermissionsExt as _;
581        let mut perms = std::fs::metadata(&dest_path)
582            .map_err(|e| format!("stat installed binary: {e}"))?
583            .permissions();
584        let mode = perms.mode();
585        perms.set_mode(mode | 0o111);
586        std::fs::set_permissions(&dest_path, perms)
587            .map_err(|e| format!("set executable bit: {e}"))?;
588    }
589
590    // Clean up download.
591    let _ = std::fs::remove_file(&dl_path);
592
593    let dest_str = dest_path.to_string_lossy().into_owned();
594    tracing::info!(tool = %id, path = %dest_str, "tool installed successfully");
595    Ok(dest_str)
596}
597
598#[cfg(test)]
599mod tool_status_wire_tests {
600    use super::*;
601    use serde_json::json;
602
603    // `version` and `path` are plain Options with NO skip_serializing_if, so
604    // the keys are ALWAYS present and carry null when unknown. The
605    // hand-written declaration marked both optional (`version?`), i.e. "the
606    // key may be absent" -- which it never is. The generated binding says
607    // `string | null`, and this pins which of the two is true.
608    #[test]
609    fn a_tool_entry_always_carries_version_and_path() {
610        let v = serde_json::to_value(ToolStatusEntry {
611            id: "rg".to_string(),
612            display: "ripgrep".to_string(),
613            description: "search".to_string(),
614            tier: 1,
615            status: ToolStatus::Missing,
616            version: None,
617            path: None,
618        })
619        .expect("serializable");
620        let obj = v.as_object().expect("object");
621        assert!(obj.contains_key("version") && obj.contains_key("path"));
622        assert_eq!(v["version"], json!(null));
623        assert_eq!(v["path"], json!(null));
624    }
625
626    // ToolStatus is a closed set the frontend branches on; it is
627    // `rename_all = "snake_case"` and generates as a string union. Pin the
628    // wire spellings so the union cannot drift from them.
629    #[test]
630    fn tool_status_serializes_to_the_expected_snake_case_tags() {
631        for (variant, tag) in [
632            (ToolStatus::InstalledSystem, "installed_system"),
633            (ToolStatus::InstalledBundled, "installed_bundled"),
634            (ToolStatus::InstalledManaged, "installed_managed"),
635            (ToolStatus::Missing, "missing"),
636            (ToolStatus::Unavailable, "unavailable"),
637        ] {
638            assert_eq!(serde_json::to_value(variant).unwrap(), json!(tag));
639        }
640    }
641}
642
643#[cfg(test)]
644mod tools_path_tests {
645    use super::{compose_tools_path, prepend_tools_path_with, UserToolsPrecedence};
646    use std::path::Path;
647
648    const SEP: &str = if cfg!(windows) { ";" } else { ":" };
649
650    fn join(parts: &[&str]) -> String {
651        parts.join(SEP)
652    }
653
654    #[test]
655    fn bundled_always_leads_and_user_follows_the_requested_precedence() {
656        let (b, u) = (Path::new("B"), Path::new("U"));
657        assert_eq!(
658            compose_tools_path("SYS", Some(b), Some(u), UserToolsPrecedence::BeforeExisting),
659            Some(join(&["B", "U", "SYS"]))
660        );
661        assert_eq!(
662            compose_tools_path("SYS", Some(b), Some(u), UserToolsPrecedence::AfterExisting),
663            Some(join(&["B", "SYS", "U"]))
664        );
665    }
666
667    #[test]
668    fn no_tool_dirs_leaves_path_untouched() {
669        assert_eq!(compose_tools_path("SYS", None, None, UserToolsPrecedence::BeforeExisting), None);
670    }
671
672    #[test]
673    fn an_agents_own_path_gets_the_tool_dirs_in_front_and_none_means_no_change() {
674        let sep = if cfg!(windows) { ";" } else { ":" };
675        let mut env = std::collections::HashMap::from([("PATH".to_string(), "SYS".to_string())]);
676        prepend_tools_path_with(&mut env, Some(Path::new("B")), Some(Path::new("U")));
677        assert_eq!(env["PATH"], format!("B{sep}U{sep}SYS"), "the user dir (build-slot shims) is ahead of the system PATH");
678        let mut untouched = std::collections::HashMap::from([("PATH".to_string(), "SYS".to_string())]);
679        prepend_tools_path_with(&mut untouched, None, None);
680        assert_eq!(untouched["PATH"], "SYS");
681        let mut none = std::collections::HashMap::new();
682        prepend_tools_path_with(&mut none, None, Some(Path::new("U")));
683        assert!(none["PATH"].starts_with(&format!("U{sep}")) || none["PATH"] == "U", "no PATH in the env: the process's own follows the user dir");
684    }
685
686    #[test]
687    fn an_empty_inherited_path_adds_no_empty_entry() {
688        // An empty PATH entry means "the current directory" on Unix.
689        assert_eq!(
690            compose_tools_path("", None, Some(Path::new("U")), UserToolsPrecedence::BeforeExisting),
691            Some("U".to_string())
692        );
693        assert_eq!(
694            compose_tools_path("", Some(Path::new("B")), None, UserToolsPrecedence::AfterExisting),
695            Some("B".to_string())
696        );
697    }
698}
699
700#[cfg(test)]
701mod bundled_dir_tests {
702    use super::bundled_dir_in;
703
704    fn wrapper() -> &'static str {
705        if cfg!(windows) { "agentmux-bashwrap.exe" } else { "agentmux-bashwrap" }
706    }
707
708    #[test]
709    fn the_desktop_keeps_its_tools_below_the_server() {
710        let dir = tempfile::tempdir().unwrap();
711        std::fs::create_dir_all(dir.path().join("tools").join("bin")).unwrap();
712        std::fs::write(dir.path().join(wrapper()), b"x").unwrap();
713        assert_eq!(bundled_dir_in(dir.path()), dir.path().join("tools").join("bin"), "tools/bin wins where it exists");
714    }
715
716    #[test]
717    fn the_server_package_keeps_its_helpers_beside_the_server() {
718        let dir = tempfile::tempdir().unwrap();
719        std::fs::write(dir.path().join(wrapper()), b"x").unwrap();
720        assert_eq!(bundled_dir_in(dir.path()), dir.path());
721    }
722
723    #[test]
724    fn a_folder_with_neither_is_still_the_tools_folder_that_is_missing() {
725        let dir = tempfile::tempdir().unwrap();
726        assert_eq!(bundled_dir_in(dir.path()), dir.path().join("tools").join("bin"));
727    }
728}