Skip to main content

agentmux_bashwrap/
shim_functions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Makes the build-slot shims win in the shells this wrapper starts.
5//!
6//! Every Bash call of an agent runs under this process, and bash imports functions from its
7//! environment, so exporting `cargo`, `task`, `npm`, `npx` and `docker` as functions that call the
8//! shims (`agentmux_common::build_slot::shim_function_env`) puts the slot in front of those
9//! tools however the shell's profile ordered the PATH. Without it, a `cargo.exe` in `~/bin`
10//! (ahead of the shims' directory in the CLI's shell snapshot) is found first and the slot is
11//! skipped: docs/specs/SPEC_BUILD_SLOT_ENFORCEMENT_2026_10_20.md ยง4.
12
13/// Sets the functions in this process's environment, which the bash it starts inherits.
14pub(crate) fn export() {
15    for (name, body) in agentmux_common::build_slot::shim_function_env_for_current_user() {
16        std::env::set_var(name, body);
17    }
18}
19
20
21
22#[cfg(test)]
23mod tests {
24    use agentmux_common::win32::NoWindow;
25
26    /// The `gh` function runs plain `gh` without the switch, and with the broker's token (or none)
27    /// with it. A fake `agentmux-bashwrap` and `gh` on PATH stand in for the real ones.
28    #[test]
29    fn the_gh_function_uses_the_brokers_token_or_none() {
30        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
31        let Ok(bash) = crate::bash_wrap::locate_bash() else { return };
32        let dir = std::env::temp_dir().join(format!("amx-gh-fn-{}", std::process::id()));
33        std::fs::create_dir_all(&dir).unwrap();
34        let script = |name: &str, body: &str| {
35            let p = dir.join(name);
36            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
37            #[cfg(unix)]
38            {
39                use std::os::unix::fs::PermissionsExt;
40                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
41            }
42        };
43        script("gh", "echo \"gh GH_TOKEN=[$GH_TOKEN] GITHUB_TOKEN=[$GITHUB_TOKEN] args=$*\"");
44        let run = |broker: &str, bashwrap_prints: &str, inherited: &str| {
45            // The text guard passes the arguments through and says ok; the token helper prints `bashwrap_prints`.
46            script(
47                "agentmux-bashwrap",
48                &format!("case \"$1\" in github-text-guard) shift; shift; for a in \"$@\"; do printf '%s\\0' \"$a\"; done; printf 'ok\\0';; github-token) printf '%s' '{bashwrap_prints}';; esac"),
49            );
50            let path = std::env::join_paths(std::iter::once(dir.clone()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()))).unwrap();
51            let mut cmd = std::process::Command::new(&bash);
52            cmd.args(["-c", "gh pr list"])
53                .env(agentmux_common::github_broker_shim::GH_FUNCTION_NAME, agentmux_common::github_broker_shim::GH_FUNCTION_BODY)
54                .env("PATH", path)
55                .env("AGENTMUX_GITHUB_BROKER", broker)
56                .env("GH_TOKEN", inherited);
57            cmd.no_window();
58            let out = cmd.output().unwrap();
59            String::from_utf8_lossy(&out.stdout).trim().to_string()
60        };
61        // No switch: plain gh, with whatever the environment has.
62        assert_eq!(run("", "ghs_X", "mine"), "gh GH_TOKEN=[mine] GITHUB_TOKEN=[] args=pr list");
63        // The switch and a token: that token, for both names.
64        assert_eq!(run("1", "ghs_X", "mine"), "gh GH_TOKEN=[ghs_X] GITHUB_TOKEN=[ghs_X] args=pr list");
65        // The switch and no token: none, not the one the environment carried.
66        assert_eq!(run("1", "", "mine"), "gh GH_TOKEN=[] GITHUB_TOKEN=[] args=pr list");
67        let _ = std::fs::remove_dir_all(&dir);
68    }
69
70    /// In a container, a command the `github-container` step does not handle (it answers 3) goes on to `gh` even in a
71    /// script run with `set -e`; one it handled (0) or refused (1) stops there with that answer.
72    #[test]
73    fn a_container_step_that_does_not_handle_a_command_lets_it_run_even_under_errexit() {
74        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
75        let Ok(bash) = crate::bash_wrap::locate_bash() else { return };
76        let dir = std::env::temp_dir().join(format!("amx-gh-container-fn-{}", std::process::id()));
77        std::fs::create_dir_all(&dir).unwrap();
78        let script = |name: &str, body: &str| {
79            let p = dir.join(name);
80            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
81            #[cfg(unix)]
82            {
83                use std::os::unix::fs::PermissionsExt;
84                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
85            }
86        };
87        script("gh", "echo \"gh args=$*\"");
88        script(
89            "agentmux-bashwrap",
90            "case \"$1\" in github-container) echo container-step; exit \"$FAKE_CONTAINER_EXIT\";; github-text-guard) shift; shift; for a in \"$@\"; do printf '%s\\0' \"$a\"; done; printf 'ok\\0';; github-token) printf 'ghs_X';; esac",
91        );
92        let posix_dir = {
93            let d = dir.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
94            match d.split_once(':') {
95                Some((drive, rest)) if drive.len() == 1 => format!("/{}{rest}", drive.to_ascii_lowercase()),
96                _ => d,
97            }
98        };
99        let run = |exit: &str| {
100            let mut cmd = std::process::Command::new(&bash);
101            cmd.args(["-c", &format!("set -e; PATH='{posix_dir}':\"$PATH\"; gh api repos/o/r/pulls; echo after")])
102                .env(agentmux_common::github_broker_shim::GH_FUNCTION_NAME, agentmux_common::github_broker_shim::GH_FUNCTION_BODY)
103                .env("AGENTMUX_GITHUB_BROKER", "1")
104                .env("AGENTMUX_IN_CONTAINER", "1")
105                .env("FAKE_CONTAINER_EXIT", exit);
106            cmd.no_window();
107            let out = cmd.output().unwrap();
108            (String::from_utf8_lossy(&out.stdout).replace('\r', ""), out.status.code())
109        };
110        let (out, code) = run("3");
111        assert!(out.contains("gh args=api repos/o/r/pulls") && out.contains("after"), "{out:?} {code:?}");
112        let (out, code) = run("0");
113        assert!(out.contains("container-step") && !out.contains("gh args="), "{out:?} {code:?}");
114        let (out, code) = run("1");
115        assert!(!out.contains("gh args=") && !out.contains("after"), "{out:?} {code:?}");
116        let _ = std::fs::remove_dir_all(&dir);
117    }
118
119    /// A repository flag in front of the command word (`gh -R o/r pr merge 7`) does not hide the command from the container
120    /// step or from the text check: both read the command word after it.
121    #[test]
122    fn a_repository_flag_in_front_of_the_command_still_reaches_the_container_step_and_the_text_check() {
123        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
124        let Ok(bash) = crate::bash_wrap::locate_bash() else { return };
125        let dir = std::env::temp_dir().join(format!("amx-gh-lead-repo-fn-{}", std::process::id()));
126        std::fs::create_dir_all(&dir).unwrap();
127        let script = |name: &str, body: &str| {
128            let p = dir.join(name);
129            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
130            #[cfg(unix)]
131            {
132                use std::os::unix::fs::PermissionsExt;
133                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
134            }
135        };
136        script("gh", "echo \"gh args=$*\"");
137        // The container step handles every command it is asked about; the text check refuses a body it is shown.
138        script(
139            "agentmux-bashwrap",
140            "case \"$1\" in github-container) echo container-step; exit 0;; github-text-guard) shift; shift; case \"$*\" in *SECRET*) echo text-refused >&2; printf 'refused\\0'; exit 1;; esac; for a in \"$@\"; do printf '%s\\0' \"$a\"; done; printf 'ok\\0';; github-token) printf 'ghs_X';; esac",
141        );
142        let posix_dir = {
143            let d = dir.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
144            match d.split_once(':') {
145                Some((drive, rest)) if drive.len() == 1 => format!("/{}{rest}", drive.to_ascii_lowercase()),
146                _ => d,
147            }
148        };
149        let run = |command: &str| {
150            let mut cmd = std::process::Command::new(&bash);
151            cmd.args(["-c", &format!("PATH='{posix_dir}':\"$PATH\"; {command}")])
152                .env(agentmux_common::github_broker_shim::GH_FUNCTION_NAME, agentmux_common::github_broker_shim::GH_FUNCTION_BODY)
153                .env("AGENTMUX_GITHUB_BROKER", "1")
154                .env("AGENTMUX_IN_CONTAINER", "1");
155            cmd.no_window();
156            let out = cmd.output().unwrap();
157            (String::from_utf8_lossy(&out.stdout).replace('\r', ""), out.status.code())
158        };
159        for lead in ["-R o/r", "--repo o/r", "--repo=o/r", "-Ro/r"] {
160            let (out, _) = run(&format!("gh {lead} pr merge 7 --squash"));
161            assert!(out.contains("container-step") && !out.contains("gh args="), "{lead}: {out:?}");
162            let (out, _) = run(&format!("gh {lead} release create v1"));
163            assert!(out.contains("container-step"), "{lead}: {out:?}");
164            // The text check sees the body whichever way the repository is named.
165            let (out, code) = run(&format!("gh {lead} issue create --body SECRET"));
166            assert!(!out.contains("gh args=") && code != Some(0), "{lead}: {out:?} {code:?}");
167            // A command the container step does not take runs as before.
168            let (out, _) = run(&format!("gh {lead} pr list"));
169            assert!(!out.contains("container-step") && out.contains("gh args="), "{lead}: {out:?}");
170        }
171        let _ = std::fs::remove_dir_all(&dir);
172    }
173
174    /// The `git` function asks `git-env` before a push or a commit: a refusal stops git, what it
175    /// prints becomes the command's environment, and every other git command is plain `git`. The
176    /// `gh` function gives `gh pr create` the arguments `github-owner-tag` prints.
177    #[test]
178    fn the_git_function_follows_git_env_and_the_gh_function_takes_the_owner_tag_arguments() {
179        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
180        let Ok(bash) = crate::bash_wrap::locate_bash() else { return };
181        let dir = std::env::temp_dir().join(format!("amx-git-fn-{}", std::process::id()));
182        std::fs::create_dir_all(&dir).unwrap();
183        let script = |name: &str, body: &str| {
184            let p = dir.join(name);
185            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
186            #[cfg(unix)]
187            {
188                use std::os::unix::fs::PermissionsExt;
189                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
190            }
191        };
192        script("git", "echo \"git AUTHOR=[$GIT_AUTHOR_NAME] OWNER=[$AGENTMUX_OWNER_GITHUB_ID] args=$*\"");
193        script("gh", "echo \"gh args=$*\"");
194        // What the real helper prints: the refusal, the environment lines, the arguments with a NUL after each.
195        script(
196            "agentmux-bashwrap",
197            r#"case "$1" in
198git-env)
199  if [ -n "$FAKE_REFUSE" ]; then echo 'agentmux: refused' >&2; exit 1; fi
200  if [ -n "$FAKE_ENV" ]; then printf 'GIT_AUTHOR_NAME=muxagent[bot]\nAGENTMUX_OWNER_GITHUB_ID=42\n'; fi;;
201github-owner-tag)
202  shift; shift
203  for a in "$@"; do printf '%s\0' "$a"; done
204  printf '%s\0' --tagged;;
205github-text-guard)
206  shift; shift
207  # The real helper decides which commands send text; this one refuses those with a body or `api`.
208  case "$*" in
209  *--body*|api\ *)
210    if [ "$FAKE_TEXT" = refuse ]; then echo 'agentmux: text refused' >&2; printf 'refused\0'; exit 1; fi
211    if [ "$FAKE_TEXT" = silent ]; then exit 0; fi;;
212  esac
213  for a in "$@"; do printf '%s\0' "$a"; done
214  if [ "$FAKE_TEXT" = rewrite ]; then printf '%s\0' --rewritten; fi
215  printf 'ok\0';;
216github-token) printf 'ghs_X';;
217esac"#,
218        );
219        let path = std::env::join_paths(std::iter::once(dir.clone()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()))).unwrap();
220        // The stand-ins go first on the shell's own PATH: on Windows a bash started with a PATH of
221        // Windows paths puts Git's `mingw64/bin` (the real `git`) ahead of it.
222        let posix_dir = {
223            let d = dir.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
224            match d.split_once(':') {
225                Some((drive, rest)) if drive.len() == 1 => format!("/{}{rest}", drive.to_ascii_lowercase()),
226                _ => d,
227            }
228        };
229        let run = |command: &str, broker: &str, refuse: &str, env: &str| {
230            let mut cmd = std::process::Command::new(&bash);
231            cmd.args(["-c", &format!("PATH='{posix_dir}':\"$PATH\"; {command}")])
232                .env(agentmux_common::github_broker_shim::GIT_FUNCTION_NAME, agentmux_common::github_broker_shim::GIT_FUNCTION_BODY)
233                .env(agentmux_common::github_broker_shim::GH_FUNCTION_NAME, agentmux_common::github_broker_shim::GH_FUNCTION_BODY)
234                .env("PATH", &path)
235                .env("AGENTMUX_GITHUB_BROKER", broker)
236                .env("FAKE_REFUSE", refuse)
237                .env("FAKE_ENV", env)
238                // This test may itself run under an agent's git setup.
239                .env_remove("GIT_AUTHOR_NAME")
240                .env_remove("AGENTMUX_OWNER_GITHUB_ID");
241            cmd.no_window();
242            let out = cmd.output().unwrap();
243            // Shown when an assertion below fails.
244            eprintln!("`{command}` (broker {broker:?}) exited {:?}, stderr: {}", out.status.code(), String::from_utf8_lossy(&out.stderr));
245            (String::from_utf8_lossy(&out.stdout).trim().to_string(), out.status.code())
246        };
247        // A commit with the switch runs with what git-env printed.
248        assert_eq!(run("git commit -m 'a b'", "1", "", "1").0, "git AUTHOR=[muxagent[bot]] OWNER=[42] args=commit -m a b");
249        // git-env printing nothing leaves the commit as it is.
250        assert_eq!(run("git commit -m x", "1", "", "").0, "git AUTHOR=[] OWNER=[] args=commit -m x");
251        // A refusal stops git, and its status is the command's.
252        assert_eq!(run("git push --no-verify", "1", "1", ""), (String::new(), Some(1)));
253        // Other git commands, and every command without the switch, are plain git.
254        assert_eq!(run("git status", "1", "1", "1").0, "git AUTHOR=[] OWNER=[] args=status");
255        assert_eq!(run("git commit -m x", "", "1", "1").0, "git AUTHOR=[] OWNER=[] args=commit -m x");
256        // `gh pr create` runs with the arguments the owner-tag helper gave; `gh pr list` with its own.
257        assert_eq!(run("gh pr create --body x", "1", "", "").0, "gh args=pr create --body x --tagged");
258        assert_eq!(run("gh pr list", "1", "", "").0, "gh args=pr list");
259        // What a gh command sends goes through the text guard first: a refusal stops gh (nothing
260        // runs, its status is the command's), arguments the guard rewrote (a stdin body handed on as
261        // a file) are the ones gh gets, and a guard that says nothing means the text was not checked.
262        assert_eq!(run("FAKE_TEXT=refuse gh pr comment 3 --body x", "1", "", ""), (String::new(), Some(1)));
263        assert_eq!(run("FAKE_TEXT=refuse gh api repos/o/r/issues", "1", "", ""), (String::new(), Some(1)));
264        assert_eq!(run("FAKE_TEXT=rewrite gh issue comment 3 --body x", "1", "", "").0, "gh args=issue comment 3 --body x --rewritten");
265        // pr create gets the rewritten arguments and then the owner tag.
266        assert_eq!(run("FAKE_TEXT=rewrite gh pr create --body x", "1", "", "").0, "gh args=pr create --body x --rewritten --tagged");
267        let (said, code) = run("FAKE_TEXT=silent gh pr comment 3 --body x", "1", "", "");
268        assert_eq!((said.as_str(), code), ("", Some(1)));
269        // An empty argument and one with a newline arrive whole.
270        assert_eq!(run("gh issue comment 3 --body '' --title $'a
271b'", "1", "", "").0, "gh args=issue comment 3 --body  --title a
272b");
273        // Commands that send no text, and every command without the switch, skip the guard.
274        assert_eq!(run("FAKE_TEXT=refuse gh pr view 3", "1", "", "").0, "gh args=pr view 3");
275        assert_eq!(run("FAKE_TEXT=refuse gh repo view", "1", "", "").0, "gh args=repo view");
276        assert_eq!(run("FAKE_TEXT=refuse gh pr comment 3 --body x", "", "", "").0, "gh args=pr comment 3 --body x");
277        // `gh auth status` says how gh is signed in, not "not logged in"; without the switch it is plain gh.
278        let (said, code) = run("gh auth status", "1", "", "");
279        assert!(said.starts_with("github.com") && said.contains("per repository") && !said.contains("gh args="), "{said}");
280        assert_eq!(code, Some(0));
281        assert_eq!(run("gh auth status", "", "", "").0, "gh args=auth status");
282        // With flags it is gh's own output, which a caller may parse.
283        assert_eq!(run("gh auth status --json hosts", "1", "", "").0, "gh args=auth status --json hosts");
284        let _ = std::fs::remove_dir_all(&dir);
285    }
286
287    /// A variable set with `std::env::set_var` under the name bash uses for exported functions
288    /// reaches a bash started afterwards as a function (the mechanism `export` relies on).
289    #[test]
290    fn an_exported_function_variable_reaches_a_child_bash() {
291        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
292        let Ok(bash) = crate::bash_wrap::locate_bash() else { return };
293        std::env::set_var("BASH_FUNC_agentmux_probe%%", "() {  echo from-function \"$@\"\n}");
294        let mut cmd = std::process::Command::new(bash);
295        cmd.args(["-c", "agentmux_probe a b"]);
296        cmd.no_window();
297        let out = cmd.output().unwrap();
298        std::env::remove_var("BASH_FUNC_agentmux_probe%%");
299        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "from-function a b");
300    }
301}