Skip to main content

agentmux_srv_core/identity/
github_hooks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The git hooks directory of an agent whose GitHub access goes through AgentMux.
5//!
6//! srv writes a script for every client-side hook and points the agent's `core.hooksPath` at the
7//! directory (`identity::github_tokens::apply_agent_git_in`). Git looks for each hook there and
8//! nowhere else, so the directory has to stand in for the repository's own (husky, the
9//! pre-commit framework, commitlint, git-lfs): every script only starts `agentmux-bashwrap
10//! git-hook`, which runs the repository's own hook of the same name and, for `pre-push` (the
11//! secret scan) and `prepare-commit-msg` (the `Agent:` and owner trailers), does AgentMux's part.
12//! The logic is Rust (`crates/bashwrap/src/git_hooks.rs`), so the scripts never need to change.
13
14use std::path::{Path, PathBuf};
15use std::sync::OnceLock;
16
17/// The hooks AgentMux installs: the client-side ones git runs, each forwarded to the repository's own.
18pub const HOOK_NAMES: &[&str] = &[
19    "applypatch-msg",
20    "pre-applypatch",
21    "post-applypatch",
22    "pre-commit",
23    "pre-merge-commit",
24    "prepare-commit-msg",
25    "commit-msg",
26    "post-commit",
27    "pre-rebase",
28    "post-checkout",
29    "post-merge",
30    "pre-push",
31    "pre-auto-gc",
32    "post-rewrite",
33    "reference-transaction",
34    "post-index-change",
35    "sendemail-validate",
36];
37
38/// What the directory is called under the AgentMux root.
39const DIR_NAME: &str = "github-hooks";
40
41/// A hook's script: git runs hooks through sh, on Windows too.
42pub fn hook_script(name: &str) -> String {
43    format!("#!/bin/sh\n# Written by AgentMux for agents whose GitHub access goes through it.\nexec agentmux-bashwrap git-hook {name} \"$@\"\n")
44}
45
46/// Write the hooks under `root` (what is already right is left alone) and return their directory.
47pub fn ensure_hooks_dir(root: &Path) -> std::io::Result<PathBuf> {
48    let dir = root.join(DIR_NAME);
49    std::fs::create_dir_all(&dir)?;
50    for name in HOOK_NAMES {
51        let path = dir.join(name);
52        let script = hook_script(name);
53        if std::fs::read_to_string(&path).ok().as_deref() != Some(script.as_str()) {
54            std::fs::write(&path, script)?;
55        }
56        #[cfg(unix)]
57        {
58            use std::os::unix::fs::PermissionsExt;
59            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
60        }
61    }
62    Ok(dir)
63}
64
65/// This install's hooks directory, written the first time it is asked for.
66pub fn hooks_dir() -> Option<PathBuf> {
67    static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
68    DIR.get_or_init(|| {
69        let root = agentmux_common::data_paths::agentmux_root().ok()?;
70        match ensure_hooks_dir(&root) {
71            Ok(dir) => Some(dir),
72            Err(e) => {
73                tracing::warn!(target: "identity", error = %e, "identity.github: couldn't write the agents' git hooks; pushes won't be scanned");
74                None
75            }
76        }
77    })
78    .clone()
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    #[test]
86    fn the_hooks_are_written_once_and_start_bashwrap_with_their_own_name() {
87        // The ones a repository's tooling relies on are there, not only the two AgentMux has work in.
88        for name in ["pre-commit", "commit-msg", "post-checkout", "post-merge", "post-commit", "pre-push", "prepare-commit-msg"] {
89            assert!(HOOK_NAMES.contains(&name), "{name}");
90        }
91        let root = tempfile::tempdir().unwrap();
92        let dir = ensure_hooks_dir(root.path()).unwrap();
93        for name in HOOK_NAMES {
94            let text = std::fs::read_to_string(dir.join(name)).unwrap();
95            assert!(text.starts_with("#!/bin/sh\n"));
96            assert!(text.contains(&format!("exec agentmux-bashwrap git-hook {name} \"$@\"")), "{name}");
97        }
98        // A second call finds them right and leaves them.
99        let before = std::fs::metadata(dir.join("pre-push")).unwrap().modified().unwrap();
100        ensure_hooks_dir(root.path()).unwrap();
101        assert_eq!(std::fs::metadata(dir.join("pre-push")).unwrap().modified().unwrap(), before);
102        // One that was changed is put back.
103        std::fs::write(dir.join("pre-push"), "#!/bin/sh\nexit 0\n").unwrap();
104        ensure_hooks_dir(root.path()).unwrap();
105        assert!(std::fs::read_to_string(dir.join("pre-push")).unwrap().contains("git-hook pre-push"));
106    }
107}