Skip to main content

agentmux_bashwrap/
container_verbs.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The `gh` commands a container agent cannot run with its own token, and what it does instead.
5//!
6//! A container's GitHub token reads contents and writes pull requests, issues and the rest; it cannot write contents.
7//! Two kinds of `gh` command need that:
8//!
9//! - `gh pr merge` merges a pull request. srv does it for the container (`POST /api/v1/github/pr-merge`) with the
10//!   host's `gh-agent`, from a repository, a number and three options. Anything else a merge takes is refused here,
11//!   with what to do.
12//! - A raw `gh api` write that changes a ref, a tag, a release or a file (`DELETE .../git/refs/heads/x`, `PUT
13//!   .../contents/f`, `POST .../releases`) would only fail at GitHub with "Resource not accessible by integration". It
14//!   is refused here instead, naming the command that does the job: `git push`, `gh pr merge --delete-branch`.
15//!
16//! `github-container -- <gh args>` is what the `gh` function calls for a container's command. It exits 0 when it did the
17//! job, 1 when it refused or failed (the reason on stderr), and 3 when the command is not one of these and `gh` should
18//! run as usual.
19
20use std::time::Duration;
21
22use serde_json::{json, Value};
23
24use crate::github::{default_repo_source, owner_repo_of_path, repo_of_default, repo_of_spec};
25use crate::mps_client::WpsClient;
26
27/// srv runs the merge on the host and may wait on GitHub and a merge queue.
28const MERGE_TIMEOUT: Duration = Duration::from_secs(100);
29
30/// Exit status meaning "not for this command: run `gh` as usual".
31pub const NOT_HANDLED: i32 = 3;
32
33/// A merge as the container asked for it.
34#[derive(Debug, Default, PartialEq, Eq)]
35pub struct Merge {
36    pub repo: Option<(String, String)>,
37    pub number: u64,
38    pub method: Option<&'static str>,
39    pub auto: bool,
40    pub delete_branch: bool,
41}
42
43/// What `gh pr merge <args>` means: a merge srv can do, `Help` for `--help`, or why it cannot be done here.
44#[derive(Debug, PartialEq, Eq)]
45pub enum Parsed {
46    Merge(Merge),
47    Help,
48}
49
50fn unsupported(flag: &str) -> String {
51    format!(
52        "srv merges for a container with a fixed set of options (--squash, --merge, --rebase, --auto, --delete-branch, -R); {flag} is not one of them. \
53         Merge the pull request without it, or ask your leader"
54    )
55}
56
57const BY_NUMBER: &str = "name the pull request by its number: gh pr merge <number> (a branch name or the current branch cannot be merged from a container)";
58
59/// `gh pr merge`'s arguments (`args` start with `pr merge`).
60pub fn parse_merge(args: &[String]) -> Result<Parsed, String> {
61    let mut m = Merge::default();
62    let mut positional: Option<&str> = None;
63    let mut it = args.iter().skip(2);
64    while let Some(a) = it.next() {
65        let a = a.as_str();
66        let set_method = |m: &mut Merge, name: &'static str| match m.method {
67            Some(prev) if prev != name => Err("choose one of --squash, --merge, --rebase".to_string()),
68            _ => {
69                m.method = Some(name);
70                Ok(())
71            }
72        };
73        match a {
74            "-h" | "--help" => return Ok(Parsed::Help),
75            "--squash" | "-s" => set_method(&mut m, "squash")?,
76            "--merge" | "-m" => set_method(&mut m, "merge")?,
77            "--rebase" | "-r" => set_method(&mut m, "rebase")?,
78            "--auto" => m.auto = true,
79            "--delete-branch" | "-d" => m.delete_branch = true,
80            "--admin" => {
81                return Err("--admin is not available to a container agent: the repository's own rules (a review, the checks, the merge queue) decide".to_string());
82            }
83            "-R" | "--repo" => m.repo = Some(repo_of_flag(it.next().map(String::as_str))?),
84            _ if a.starts_with("--repo=") => m.repo = Some(repo_of_flag(Some(&a["--repo=".len()..]))?),
85            _ if a.starts_with("-R") && a.len() > 2 => m.repo = Some(repo_of_flag(Some(a[2..].trim_start_matches('=')))?),
86            _ if a.starts_with('-') => return Err(unsupported(a)),
87            _ => {
88                if positional.replace(a).is_some() {
89                    return Err("gh pr merge from a container takes one pull request".to_string());
90                }
91            }
92        }
93    }
94    let target = positional.ok_or_else(|| BY_NUMBER.to_string())?;
95    if let Some(rest) = target.strip_prefix("https://github.com/") {
96        // https://github.com/OWNER/REPO/pull/N
97        let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
98        match parts.as_slice() {
99            [owner, repo, "pull", n] if n.bytes().all(|b| b.is_ascii_digit()) && !n.is_empty() => {
100                m.number = n.parse().map_err(|_| BY_NUMBER.to_string())?;
101                m.repo = m.repo.or_else(|| owner_repo_of_path(&format!("{owner}/{repo}")));
102            }
103            _ => return Err(BY_NUMBER.to_string()),
104        }
105    } else if !target.is_empty() && target.bytes().all(|b| b.is_ascii_digit()) {
106        m.number = target.parse().map_err(|_| BY_NUMBER.to_string())?;
107    } else {
108        return Err(BY_NUMBER.to_string());
109    }
110    Ok(Parsed::Merge(m))
111}
112
113/// The repository a `-R`/`--repo`/`GH_REPO` value names. The whole spec must be `OWNER/REPO` or `github.com/OWNER/REPO`:
114/// another host, or a longer path, names a repository this step cannot merge on, and is never cut down to its first two
115/// parts (that would merge on a different repository than the one named).
116fn repo_of_flag(value: Option<&str>) -> Result<(String, String), String> {
117    let spec = value.ok_or_else(|| "-R needs OWNER/REPO".to_string())?;
118    repo_of_spec(spec).ok_or_else(|| format!("{spec} is not OWNER/REPO or github.com/OWNER/REPO"))
119}
120
121/// The repository a merge is on: the one the merge names, else a leading `-R`, else `GH_REPO`, else the working
122/// directory's. A `GH_REPO` that is not a plain repository is refused, not replaced by the working directory's.
123fn merge_repo(merge: &Merge, lead_repo: Option<(String, String)>) -> Result<(String, String), String> {
124    if let Some(found) = merge.repo.clone().or(lead_repo) {
125        return Ok(found);
126    }
127    if let Some(env) = std::env::var("GH_REPO").ok().filter(|r| !r.is_empty()) {
128        return repo_of_flag(Some(&env)).map_err(|why| format!("GH_REPO: {why}"));
129    }
130    default_repo_source(None)
131        .and_then(|s| repo_of_default(&s))
132        .ok_or_else(|| "no repository: pass -R OWNER/REPO, or run it in a clone of the repository".to_string())
133}
134
135/// The refusal for a raw `gh api` write a container's token cannot make, with the command that does the job; `None` for
136/// every other `gh` command. `args` are `gh`'s own, starting with `api`.
137pub fn refused_command(args: &[String]) -> Option<String> {
138    match args.first().map(String::as_str)? {
139        "api" => refused_api(args),
140        "release" => match args.get(1).map(String::as_str)? {
141            "create" | "edit" | "delete" | "delete-asset" | "upload" => Some(RELEASE.to_string()),
142            _ => None,
143        },
144        _ => None,
145    }
146}
147
148const RELEASE: &str = "a container agent cannot create or change a release: the API call needs a credential that writes contents. \
149Push the tag with git (git push origin <tag>, which is checked first), or ask your leader for the release workflow";
150
151fn refused_api(args: &[String]) -> Option<String> {
152    let mut method: Option<String> = None;
153    let mut fields = false;
154    let mut endpoint: Option<&str> = None;
155    let mut it = args.iter().skip(1);
156    while let Some(a) = it.next() {
157        match a.as_str() {
158            "-X" | "--method" => method = it.next().map(|v| v.to_ascii_uppercase()),
159            a if a.starts_with("-X") && a.len() > 2 => method = Some(a[2..].to_ascii_uppercase()),
160            "-H" | "--header" | "-q" | "--jq" | "-t" | "--template" | "--hostname" | "--cache" | "-p" | "--preview" => {
161                it.next();
162            }
163            "-f" | "--raw-field" | "-F" | "--field" | "--input" => {
164                fields = true;
165                it.next();
166            }
167            a if a.starts_with("--method=") => method = Some(a["--method=".len()..].to_ascii_uppercase()),
168            a if a.starts_with("--input=") || a.starts_with("--field=") || a.starts_with("--raw-field=") => fields = true,
169            a if a.starts_with('-') => {}
170            a => {
171                endpoint.get_or_insert(a);
172            }
173        }
174    }
175    let method = method.unwrap_or_else(|| if fields { "POST".to_string() } else { "GET".to_string() });
176    if method == "GET" || method == "HEAD" {
177        return None;
178    }
179    let path = endpoint?.trim_start_matches('/');
180    let rest = path.strip_prefix("repos/")?;
181    let mut parts = rest.splitn(3, '/');
182    let (_owner, _repo, tail) = (parts.next()?, parts.next()?, parts.next()?);
183    let in_group = |prefix: &str| tail == prefix || tail.starts_with(&format!("{prefix}/"));
184    if in_group("git/refs") && method == "DELETE" {
185        return Some(
186            "a container agent cannot delete a branch or tag through the API: the call needs a credential that writes contents. \
187             Use gh pr merge --delete-branch, or git push origin --delete <branch>"
188                .to_string(),
189        );
190    }
191    if in_group("git/refs") || in_group("git/tags") || in_group("git/commits") || in_group("git/blobs") || in_group("git/trees") {
192        return Some(
193            "a container agent cannot create or move refs, tags or commits through the API: the call needs a credential that writes contents. \
194             Use git (git commit, git push, git push origin <tag>); a push is checked before it publishes"
195                .to_string(),
196        );
197    }
198    if tail == "merges" {
199        return Some("a container agent cannot merge branches through the API: use git merge and git push, or gh pr merge for a pull request".to_string());
200    }
201    if tail.starts_with("pulls/") && tail.ends_with("/merge") && method == "PUT" {
202        return Some("use gh pr merge <number> (srv does the merge for a container); the API merge call needs a credential that writes contents".to_string());
203    }
204    if tail.starts_with("contents/") || in_group("contents") {
205        return Some(
206            "a container agent cannot change a file through the contents API: the call needs a credential that writes contents. \
207             Change the file in the clone and push with git (git push), which is checked before it publishes"
208                .to_string(),
209        );
210    }
211    if in_group("releases") {
212        return Some(RELEASE.to_string());
213    }
214    None
215}
216
217/// Whether this container's machine narrows its GitHub tokens: it has a gh-agent (`AGENTMUX_PUBLISH_GUARD` is `1`, or
218/// `older-gh-agent` where it is installed but too old to narrow, which srv then says out loud). With `0`, no value or any
219/// other value there is no gh-agent on the machine, the container's token comes from the person's own GitHub connection,
220/// and its `gh` commands run as they always did.
221pub fn narrowing_machine(marker: Option<&str>) -> bool {
222    matches!(marker, Some("1" | "older-gh-agent"))
223}
224
225/// A repository flag in front of the command word (`gh -R o/r pr merge 7`, which `gh` accepts): the repository it names, and
226/// the arguments without it. `None` for a command that does not start with one, or whose flag is not `OWNER/REPO` (then
227/// `gh` itself says what is wrong).
228pub fn lead_repo_flag(args: &[String]) -> Option<(Option<(String, String)>, &[String])> {
229    let first = args.first()?.as_str();
230    let (value, used) = match first {
231        "-R" | "--repo" => (args.get(1)?.as_str(), 2),
232        _ if first.starts_with("--repo=") => (&first["--repo=".len()..], 1),
233        _ if first.starts_with("-R") && first.len() > 2 => (first[2..].trim_start_matches('='), 1),
234        _ => return Some((None, args)),
235    };
236    Some((Some(repo_of_flag(Some(value)).ok()?), &args[used..]))
237}
238
239/// `github-container -- <gh args>`.
240pub fn run_github_container(gh_args: &[String]) -> i32 {
241    if !narrowing_machine(std::env::var("AGENTMUX_PUBLISH_GUARD").ok().as_deref()) {
242        return NOT_HANDLED;
243    }
244    let Some((lead_repo, gh_args)) = lead_repo_flag(gh_args) else { return NOT_HANDLED };
245    if let Some(why) = refused_command(gh_args) {
246        eprintln!("agentmux: not run: {why}");
247        return 1;
248    }
249    if gh_args.first().map(String::as_str) != Some("pr") || gh_args.get(1).map(String::as_str) != Some("merge") {
250        return NOT_HANDLED;
251    }
252    let merge = match parse_merge(gh_args) {
253        Ok(Parsed::Merge(m)) => m,
254        Ok(Parsed::Help) => return NOT_HANDLED,
255        Err(why) => {
256            eprintln!("agentmux: gh pr merge not run: {why}");
257            return 1;
258        }
259    };
260    let (owner, repo) = match merge_repo(&merge, lead_repo) {
261        Ok(found) => found,
262        Err(why) => {
263            eprintln!("agentmux: gh pr merge not run: {why}");
264            return 1;
265        }
266    };
267    match ask_merge(&owner, &repo, &merge) {
268        Ok(said) => {
269            if !said.is_empty() {
270                println!("{said}");
271            }
272            0
273        }
274        Err(why) => {
275            eprintln!("agentmux: gh pr merge #{} on {owner}/{repo} was not done: {why}", merge.number);
276            1
277        }
278    }
279}
280
281/// The request srv gets: the repository, the number and the three options, nothing else.
282pub fn merge_body(owner: &str, repo: &str, m: &Merge) -> Value {
283    let mut body = json!({ "owner": owner, "repo": repo, "number": m.number, "auto": m.auto, "delete_branch": m.delete_branch });
284    if let Some(method) = m.method {
285        body["method"] = json!(method);
286    }
287    body
288}
289
290fn ask_merge(owner: &str, repo: &str, m: &Merge) -> Result<String, String> {
291    let client = WpsClient::from_env().ok_or_else(|| "AGENTMUX_LOCAL_URL / AGENTMUX_AUTH_KEY aren't set: run this from an agent's own shell".to_string())?;
292    let agent_token = std::env::var("AGENTMUX_AGENT_TOKEN").ok();
293    let rt = tokio::runtime::Runtime::new().map_err(|e| format!("couldn't start: {e}"))?;
294    match rt.block_on(client.post_json_status("/api/v1/github/pr-merge", agent_token.as_deref(), &merge_body(owner, repo, m), MERGE_TIMEOUT)) {
295        Ok((status, answer)) if (200..300).contains(&status) => Ok(answer.get("message").and_then(Value::as_str).unwrap_or_default().to_string()),
296        Ok((status, answer)) => Err(answer.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("AgentMux refused ({status})"))),
297        Err(e) => Err(format!("couldn't reach AgentMux: {e}")),
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    fn args(a: &[&str]) -> Vec<String> {
306        a.iter().map(|s| s.to_string()).collect()
307    }
308
309    fn merge(a: &[&str]) -> Merge {
310        match parse_merge(&args(a)) {
311            Ok(Parsed::Merge(m)) => m,
312            other => panic!("{other:?}"),
313        }
314    }
315
316    #[test]
317    fn a_merge_by_number_with_its_few_options() {
318        let m = merge(&["pr", "merge", "42", "--squash", "--auto", "-d", "-R", "agentmuxai/agentmux"]);
319        assert_eq!((m.number, m.method, m.auto, m.delete_branch), (42, Some("squash"), true, true));
320        assert_eq!(m.repo, Some(("agentmuxai".into(), "agentmux".into())));
321        let m = merge(&["pr", "merge", "https://github.com/octo/hello/pull/7"]);
322        assert_eq!((m.number, m.repo, m.method), (7, Some(("octo".into(), "hello".into())), None));
323        assert_eq!(merge(&["pr", "merge", "9", "--repo=octo/hello", "--rebase"]).method, Some("rebase"));
324    }
325
326    #[test]
327    fn what_srv_does_not_do_is_refused_and_says_what_to_do() {
328        let no = |a: &[&str]| parse_merge(&args(a)).unwrap_err();
329        assert!(no(&["pr", "merge", "42", "--admin"]).contains("--admin is not available"));
330        assert!(no(&["pr", "merge", "42", "--body", "x"]).contains("is not one of them"));
331        assert!(no(&["pr", "merge", "42", "--match-head-commit", "abc"]).contains("--match-head-commit"));
332        assert!(no(&["pr", "merge", "my-branch"]).contains("by its number"));
333        assert!(no(&["pr", "merge"]).contains("by its number"));
334        assert!(no(&["pr", "merge", "1", "2"]).contains("one pull request"));
335        assert!(no(&["pr", "merge", "1", "--squash", "--rebase"]).contains("choose one"));
336        assert!(no(&["pr", "merge", "https://github.com/o/r/issues/3"]).contains("by its number"));
337        assert_eq!(parse_merge(&args(&["pr", "merge", "--help"])), Ok(Parsed::Help));
338    }
339
340    #[test]
341    fn the_request_to_srv_carries_nothing_but_the_merge() {
342        let m = merge(&["pr", "merge", "42", "--squash", "-d"]);
343        let body = merge_body("o", "r", &m);
344        assert_eq!(body, json!({ "owner": "o", "repo": "r", "number": 42, "auto": false, "delete_branch": true, "method": "squash" }));
345        assert!(merge_body("o", "r", &merge(&["pr", "merge", "5"])).get("method").is_none(), "no method leaves the choice to the repository");
346    }
347
348    #[test]
349    fn a_raw_api_write_that_needs_contents_write_names_the_command_that_does_the_job() {
350        let said = |a: &[&str]| refused_command(&args(a));
351        let del = said(&["api", "-X", "DELETE", "repos/o/r/git/refs/heads/x"]).unwrap();
352        assert!(del.contains("gh pr merge --delete-branch") && del.contains("git push origin --delete"), "{del}");
353        assert!(said(&["api", "--method", "DELETE", "/repos/o/r/git/refs/tags/v1"]).is_some());
354        assert!(said(&["api", "repos/o/r/git/refs", "-f", "ref=refs/heads/x", "-f", "sha=abc"]).unwrap().contains("git push"));
355        assert!(said(&["api", "-X", "PATCH", "repos/o/r/git/refs/heads/x", "-f", "sha=abc"]).is_some());
356        assert!(said(&["api", "-X", "POST", "repos/o/r/git/tags"]).is_some());
357        assert!(said(&["api", "-X", "POST", "repos/o/r/merges", "-f", "base=a", "-f", "head=b"]).unwrap().contains("git merge"));
358        assert!(said(&["api", "-X", "PUT", "repos/o/r/pulls/3/merge"]).unwrap().contains("gh pr merge <number>"));
359        assert!(said(&["api", "-X", "PUT", "repos/o/r/contents/docs/a.md", "-f", "message=m"]).unwrap().contains("git push"));
360        assert!(said(&["api", "-X", "POST", "repos/o/r/releases", "-f", "tag_name=v1"]).unwrap().contains("release workflow"));
361        assert!(said(&["release", "create", "v1"]).unwrap().contains("release workflow"));
362        assert!(said(&["release", "upload", "v1", "a.zip"]).is_some());
363    }
364
365    #[test]
366    fn only_a_machine_with_gh_agent_gets_these_steps() {
367        assert!(narrowing_machine(Some("1")));
368        assert!(narrowing_machine(Some("older-gh-agent")));
369        for off in [None, Some("0"), Some(""), Some("true"), Some("yes")] {
370            assert!(!narrowing_machine(off), "{off:?}");
371        }
372    }
373
374    #[test]
375    fn without_the_marker_every_command_runs_as_before() {
376        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
377        for value in [None, Some("0")] {
378            match value {
379                Some(v) => std::env::set_var("AGENTMUX_PUBLISH_GUARD", v),
380                None => std::env::remove_var("AGENTMUX_PUBLISH_GUARD"),
381            }
382            for cmd in [&["pr", "merge", "7", "--admin"][..], &["release", "create", "v1"], &["api", "-X", "DELETE", "repos/o/r/git/refs/heads/x"]] {
383                assert_eq!(run_github_container(&args(cmd)), NOT_HANDLED, "{value:?} {cmd:?}");
384            }
385        }
386        std::env::set_var("AGENTMUX_PUBLISH_GUARD", "1");
387        assert_eq!(run_github_container(&args(&["release", "create", "v1"])), 1, "on a machine with gh-agent it is refused");
388        assert_eq!(run_github_container(&args(&["issue", "list"])), NOT_HANDLED);
389        std::env::remove_var("AGENTMUX_PUBLISH_GUARD");
390    }
391
392    #[test]
393    fn a_repository_flag_in_front_of_the_command_is_read_and_set_aside() {
394        let rest = |a: &[&str]| lead_repo_flag(&args(a)).map(|(r, rest)| (r, rest.to_vec()));
395        let repo = Some(("octo".to_string(), "hello".to_string()));
396        let tail = args(&["pr", "merge", "7"]);
397        for lead in [&["-R", "octo/hello"][..], &["--repo", "octo/hello"], &["--repo=octo/hello"], &["-Rocto/hello"], &["-R=octo/hello"], &["--repo", "github.com/octo/hello"]] {
398            let mut a = lead.to_vec();
399            a.extend(["pr", "merge", "7"]);
400            assert_eq!(rest(&a), Some((repo.clone(), tail.clone())), "{lead:?}");
401        }
402        // No flag in front: the arguments as they are. A flag that is not OWNER/REPO or has no value: not ours, gh says what is wrong.
403        assert_eq!(rest(&["pr", "merge", "7"]), Some((None, tail.clone())));
404        assert_eq!(rest(&["-R", "not-a-repo", "pr", "merge", "7"]), None);
405        assert_eq!(rest(&["-R"]), None);
406    }
407
408    #[test]
409    fn a_repository_that_is_not_owner_repo_is_never_cut_down_to_its_first_two_parts() {
410        let repo = |v: &str| repo_of_flag(Some(v)).ok();
411        let octo = Some(("octo".to_string(), "hello".to_string()));
412        assert_eq!(repo("octo/hello"), octo);
413        assert_eq!(repo("github.com/octo/hello"), octo);
414        assert_eq!(repo("GitHub.com/octo/hello"), octo);
415        for bad in ["enterprise/team/project", "github.com/octo/hello/extra", "ghe.example.com/octo/hello", "octo", "octo/", "/hello", "octo/hello/", ""] {
416            assert_eq!(repo(bad), None, "{bad:?}");
417        }
418        // A merge that names such a repository is refused, whichever way it is written, rather than sent for another repository.
419        for flag in [&["-R", "enterprise/team/project"][..], &["--repo=enterprise/team/project"], &["-Renterprise/team/project"], &["-R=ghe.example.com/octo/hello"]] {
420            let mut a = vec!["pr", "merge", "7"];
421            a.extend(flag);
422            assert!(matches!(parse_merge(&args(&a)), Err(why) if why.contains("OWNER/REPO")), "{flag:?}");
423        }
424        let attached = parse_merge(&args(&["pr", "merge", "7", "-Rocto/hello"]));
425        assert!(matches!(attached, Ok(Parsed::Merge(m)) if m.repo == octo && m.number == 7));
426        // In front of the command it is left to gh.
427        assert_eq!(lead_repo_flag(&args(&["-R", "enterprise/team/project", "pr", "merge", "7"])), None);
428    }
429
430    #[test]
431    fn a_github_repo_that_is_not_owner_repo_is_refused_not_replaced_by_the_working_directory() {
432        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
433        let merge = Merge { number: 7, ..Merge::default() };
434        std::env::set_var("GH_REPO", "enterprise/team/project");
435        let why = merge_repo(&merge, None).unwrap_err();
436        assert!(why.contains("GH_REPO") && why.contains("OWNER/REPO"), "{why}");
437        std::env::set_var("GH_REPO", "octo/hello");
438        assert_eq!(merge_repo(&merge, None), Ok(("octo".to_string(), "hello".to_string())));
439        // A repository the merge or a leading flag names wins over GH_REPO.
440        let lead = Some(("lead".to_string(), "repo".to_string()));
441        assert_eq!(merge_repo(&merge, lead.clone()), Ok(("lead".to_string(), "repo".to_string())));
442        std::env::remove_var("GH_REPO");
443    }
444
445    #[test]
446    fn a_leading_repository_flag_does_not_hide_a_command_from_the_container_steps() {
447        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
448        std::env::set_var("AGENTMUX_PUBLISH_GUARD", "1");
449        for cmd in [&["-R", "o/r", "release", "create", "v1"][..], &["--repo=o/r", "release", "delete", "v1"], &["-Ro/r", "api", "-X", "DELETE", "repos/o/r/git/refs/heads/x"]] {
450            assert_eq!(run_github_container(&args(cmd)), 1, "{cmd:?}");
451        }
452        assert_eq!(run_github_container(&args(&["-R", "o/r", "issue", "list"])), NOT_HANDLED);
453        assert_eq!(run_github_container(&args(&["-R", "o/r", "pr", "list"])), NOT_HANDLED);
454        assert_eq!(run_github_container(&args(&["-R", "not-a-repo", "pr", "merge", "7"])), NOT_HANDLED);
455        std::env::remove_var("AGENTMUX_PUBLISH_GUARD");
456    }
457
458    #[test]
459    fn a_method_written_attached_to_the_flag_is_read() {
460        let a = args(&["api", "-XDELETE", "repos/o/r/git/refs/heads/x"]);
461        assert!(refused_command(&a).is_some());
462    }
463
464    #[test]
465    fn reads_and_the_writes_a_container_can_make_are_left_alone() {
466        let said = |a: &[&str]| refused_command(&args(a));
467        for ok in [
468            &["api", "repos/o/r/git/refs/heads/x"][..],
469            &["api", "repos/o/r/contents/README.md"],
470            &["api", "repos/o/r/releases/latest"],
471            &["api", "-X", "GET", "repos/o/r/git/refs"],
472            &["api", "-X", "POST", "repos/o/r/issues/3/comments", "-f", "body=hi"],
473            &["api", "-X", "PATCH", "repos/o/r/pulls/3", "-f", "title=t"],
474            &["api", "-X", "PUT", "repos/o/r/pulls/3/update-branch"],
475            &["api", "graphql", "-f", "query=query{viewer{login}}"],
476            &["release", "list"],
477            &["release", "view", "v1"],
478            &["pr", "create", "--fill"],
479            &["issue", "close", "3"],
480        ] {
481            assert_eq!(said(ok), None, "{ok:?}");
482        }
483    }
484
485    #[test]
486    fn a_header_value_or_a_field_name_is_not_taken_for_the_endpoint() {
487        let a = args(&["api", "-H", "Accept: application/vnd.github+json", "-X", "DELETE", "repos/o/r/git/refs/heads/x"]);
488        assert!(refused_command(&a).is_some());
489        let b = args(&["api", "--jq", ".sha", "repos/o/r/git/refs/heads/x"]);
490        assert_eq!(refused_command(&b), None);
491    }
492}