Skip to main content

agentmux_srv_core/backend/
git_program_settings.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The git settings that name a program, taken from the environment for a host agent in a folder a container
5//! agent can write.
6//!
7//! In such a folder (`mcp_folder_rule`) the folder's own `.git/config` is not the person's: a container agent
8//! can write it, and a plain `git status` by the host agent runs what it names. Git reads configuration from the
9//! environment (`GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_<n>`, `GIT_CONFIG_VALUE_<n>`) after every file, so the
10//! settings below are given there, by the same entries as `core.hooksPath` (`publish_guard`), with a value that
11//! runs nothing of the folder's. For the settings a person chooses for themselves (their ssh command, their
12//! signing programs, their editors) the value is the one git gives from the person's system and global
13//! configuration alone, and the neutral value is used only when neither sets one: the folder's value is never
14//! used. Every other agent's git is left as it is.
15//!
16//! What is set, checked against git 2.52 (a value is read the last one wins, except `core.gitProxy`, where the
17//! first wins, so that one is set by its own variable):
18//!
19//! - `core.sshCommand` (`ssh`), `core.editor` and `sequence.editor` (`true`), `gpg.program` and
20//!   `gpg.openpgp.program` (`gpg`), `gpg.ssh.program` (`ssh-keygen`), `gpg.x509.program` (`gpgsm`), `gpg.ssh.defaultKeyCommand` (`true`): the person's
21//!   own value, else the one in brackets;
22//! - `core.fsmonitor` `false`, `core.pager` `cat`, `pager.<command>` `false` for every git command (a pager the
23//!   folder names for one command, such as `pager.log`, takes precedence over `core.pager`), `core.askPass` empty (no program asked, no fallback to
24//!   `SSH_ASKPASS`);
25//! - `protocol.ext.allow` `never`: the folder's remote cannot name a command (`ext::`) to run;
26//! - `credential.helper` empty, first of the entries, which clears every helper the files named, so the helpers the
27//!   environment lists after it (the GitHub broker's, under `credential.<url>.helper`) are the only ones; a
28//!   `credential.helper` the environment itself lists is left;
29//! - `GIT_PROXY_COMMAND` empty (no proxy command), unless the environment already has a value.
30
31use std::collections::HashMap;
32use std::path::Path;
33use std::sync::Mutex;
34use std::time::{Duration, Instant};
35
36use agentmux_common::win32::NoWindow;
37
38use crate::backend::publish_guard::{declared_count, git_config_entries, git_config_has_value, git_config_prepend, git_config_slots, HOOKS_PATH_KEY, MAX_CARRIED, MAX_ENTRIES};
39
40/// The settings that name a program, and the value that runs none of the folder's.
41const SETTINGS: &[(&str, &str)] = &[
42    ("core.fsmonitor", "false"),
43    ("core.sshCommand", "ssh"),
44    ("core.pager", "cat"),
45    ("core.editor", "true"),
46    ("sequence.editor", "true"),
47    ("core.askPass", ""),
48    ("gpg.program", "gpg"),
49    ("gpg.openpgp.program", "gpg"),
50    ("gpg.ssh.program", "ssh-keygen"),
51    ("gpg.x509.program", "gpgsm"),
52    ("gpg.ssh.defaultKeyCommand", "true"),
53    ("protocol.ext.allow", "never"),
54];
55/// The commands of git 2.52 (`git --list-cmds=builtins`): `pager.<command>` is `false` for each, since a folder's own
56/// `pager.<command>` is read before `core.pager` and `GIT_PAGER`.
57const PAGED_COMMANDS: &[&str] = &[
58    "add", "am", "annotate", "apply", "archive", "backfill", "bisect", "blame", "branch", "bugreport", "bundle",
59    "cat-file", "check-attr", "check-ignore", "check-mailmap", "check-ref-format", "checkout",
60    "checkout--worker", "checkout-index", "cherry", "cherry-pick", "clean", "clone", "column", "commit",
61    "commit-graph", "commit-tree", "config", "count-objects", "credential", "credential-cache",
62    "credential-cache--daemon", "credential-store", "describe", "diagnose", "diff", "diff-files", "diff-index",
63    "diff-pairs", "diff-tree", "difftool", "fast-export", "fast-import", "fetch", "fetch-pack", "fmt-merge-msg",
64    "for-each-ref", "for-each-repo", "format-patch", "fsck", "fsck-objects", "fsmonitor--daemon", "gc",
65    "get-tar-commit-id", "grep", "hash-object", "help", "hook", "index-pack", "init", "init-db",
66    "interpret-trailers", "last-modified", "log", "ls-files", "ls-remote", "ls-tree", "mailinfo", "mailsplit",
67    "maintenance", "merge", "merge-base", "merge-file", "merge-index", "merge-ours", "merge-recursive",
68    "merge-recursive-ours", "merge-recursive-theirs", "merge-subtree", "merge-tree", "mktag", "mktree",
69    "multi-pack-index", "mv", "name-rev", "notes", "pack-objects", "pack-redundant", "pack-refs", "patch-id",
70    "pickaxe", "prune", "prune-packed", "pull", "push", "range-diff", "read-tree", "rebase", "receive-pack",
71    "reflog", "refs", "remote", "remote-ext", "remote-fd", "repack", "replace", "replay", "repo", "rerere",
72    "reset", "restore", "rev-list", "rev-parse", "revert", "rm", "send-pack", "shortlog", "show", "show-branch",
73    "show-index", "show-ref", "sparse-checkout", "stage", "stash", "status", "stripspace", "submodule--helper",
74    "survey", "switch", "symbolic-ref", "tag", "unpack-file", "unpack-objects", "update-index", "update-ref",
75    "update-server-info", "upload-archive", "upload-archive--writer", "upload-pack", "var", "verify-commit",
76    "verify-pack", "verify-tag", "version", "whatchanged", "worktree", "write-tree"
77];
78/// The settings of [`SETTINGS`] a person chooses for themselves: their own value, from the system and global
79/// configuration, is kept.
80const PERSONS: &[&str] = &["core.sshCommand", "core.editor", "sequence.editor", "gpg.program", "gpg.openpgp.program", "gpg.ssh.program", "gpg.x509.program", "gpg.ssh.defaultKeyCommand"];
81/// The names of [`PERSONS`] as git matches them (section and name in lower case).
82const PERSONS_PATTERN: &str = r"^(core\.sshcommand|core\.editor|sequence\.editor|gpg\.program|gpg\.(openpgp|ssh|x509)\.program|gpg\.ssh\.defaultkeycommand)$";
83/// The key under which [`persons_values`] holds the OpenPGP program git uses: `gpg.program` is the legacy name of
84/// `gpg.openpgp.program`, so the one set last, of the two, is the person's.
85const OPENPGP_EFFECTIVE: &str = "gpg.(openpgp)";
86/// How long what was read from the person's configuration is kept.
87const PERSONS_KEPT: Duration = Duration::from_secs(30);
88const CREDENTIAL_HELPER: &str = "credential.helper";
89/// Git reads this variable before `core.gitProxy`, and the first `core.gitProxy` it finds wins, so the
90/// environment has to name it for the folder's not to be used.
91const PROXY_COMMAND: &str = "GIT_PROXY_COMMAND";
92
93/// The meta key of a shell pane of such an agent that says its git is given [`entries_over`].
94pub const META_KEY_PTYSHELL_GIT_PROGRAM_SETTINGS: &str = "pty:git-program-settings";
95
96/// The person's own value (lower-cased name to value) for each of [`PERSONS`] that their system or global git
97/// configuration sets, read outside any repository: what git gives with no folder's configuration. Kept for a
98/// short while, so a start of several agents asks git once.
99pub fn persons_values() -> HashMap<String, String> {
100    static KEPT: Mutex<Option<(Instant, HashMap<String, String>)>> = Mutex::new(None);
101    let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
102    if let Some((at, values)) = kept.as_ref() {
103        if at.elapsed() < PERSONS_KEPT {
104            return values.clone();
105        }
106    }
107    let values = read_persons(None);
108    *kept = Some((Instant::now(), values.clone()));
109    values
110}
111
112/// [`persons_values`] read now; `home` names the person's home folder when it is not this process's.
113fn read_persons(home: Option<&Path>) -> HashMap<String, String> {
114    let mut cmd = std::process::Command::new("git");
115    cmd.args(["config", "--show-scope", "--get-regexp", PERSONS_PATTERN]);
116    cmd.current_dir(home.map_or_else(std::env::temp_dir, Path::to_path_buf)).env_remove("GIT_DIR").env_remove("GIT_WORK_TREE");
117    if let Some(home) = home {
118        cmd.env("HOME", home).env("USERPROFILE", home);
119    }
120    cmd.no_window();
121    crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
122    match cmd.output() {
123        Ok(out) if out.status.success() => parse_scoped(&String::from_utf8_lossy(&out.stdout)),
124        _ => HashMap::new(),
125    }
126}
127
128/// The values of `git config --show-scope --get-regexp` lines (`<scope>\t<name> <value>`) that the system or the
129/// global configuration gave, the later one over the earlier.
130fn parse_scoped(output: &str) -> HashMap<String, String> {
131    let mut out = HashMap::new();
132    for line in output.lines() {
133        let Some((scope, rest)) = line.split_once('\t') else { continue };
134        if scope != "system" && scope != "global" {
135            continue;
136        }
137        let (name, value) = rest.split_once(' ').unwrap_or((rest, ""));
138        let (name, value) = (name.to_ascii_lowercase(), value.trim_end_matches('\r').to_string());
139        if name == "gpg.program" || name == "gpg.openpgp.program" {
140            out.insert(OPENPGP_EFFECTIVE.to_string(), value.clone());
141        }
142        out.insert(name, value);
143    }
144    out
145}
146
147/// The `GIT_CONFIG_*` list `get` carries cut to what leaves room for the settings added beside it, as the
148/// variables that replace it; none when it already fits. What is kept: the first entries, and the last
149/// `core.hooksPath` wherever it is (the publish guard), in their order.
150fn cut_to_fit(get: &impl Fn(&str) -> Option<String>) -> Vec<(String, String)> {
151    let declared = declared_count(get);
152    if declared > MAX_ENTRIES {
153        tracing::warn!(declared, "git program settings: the GIT_CONFIG count is more than any list has; read as none");
154        return git_config_slots(&[]);
155    }
156    if declared <= MAX_CARRIED {
157        return Vec::new();
158    }
159    let all: Vec<(String, String)> =
160        (0..declared).filter_map(|i| Some((get(&format!("GIT_CONFIG_KEY_{i}"))?, get(&format!("GIT_CONFIG_VALUE_{i}")).unwrap_or_default()))).collect();
161    let guard = all.iter().rposition(|(k, _)| k.eq_ignore_ascii_case(HOOKS_PATH_KEY));
162    let mut kept: Vec<(String, String)> = Vec::new();
163    for (i, entry) in all.iter().enumerate() {
164        let is_guard = guard == Some(i);
165        let others_left = MAX_CARRIED - usize::from(guard.is_some()) - kept.iter().filter(|(k, _)| !k.eq_ignore_ascii_case(HOOKS_PATH_KEY)).count();
166        let is_hooks = entry.0.eq_ignore_ascii_case(HOOKS_PATH_KEY);
167        if is_guard || (!is_hooks && others_left > 0) {
168            kept.push(entry.clone());
169        }
170    }
171    tracing::warn!(declared, kept = kept.len(), "git program settings: the environment carries more GIT_CONFIG entries than fit beside them; the first ones and the hooks path are kept");
172    git_config_slots(&kept)
173}
174
175/// The variables that give git the settings above, on top of the entries `get` already sees; `own` is
176/// [`persons_values`].
177pub fn entries_over(get: impl Fn(&str) -> Option<String>, own: &HashMap<String, String>) -> Vec<(String, String)> {
178    // What the environment carries is kept, up to what leaves room for ours: a list longer than
179    // `MAX_CARRIED` is cut to its first entries and the last `core.hooksPath` (and said so), never the
180    // settings below left out. A count no list can have (past `MAX_ENTRIES`) is read as none, as everywhere else.
181    let carried: HashMap<String, String> = cut_to_fit(&get).into_iter().collect();
182    let get = |name: &str| carried.get(name).cloned().or_else(|| get(name));
183    let mut out: HashMap<String, String> = carried.clone();
184    if !git_config_has_value(&get, CREDENTIAL_HELPER, "") {
185        out.extend(git_config_prepend(&get, CREDENTIAL_HELPER, ""));
186    }
187    let mut set = |out: &mut HashMap<String, String>, key: &str, value: &str| {
188        let entries = git_config_entries(|name| out.get(name).cloned().or_else(|| get(name)), key, value);
189        out.extend(entries);
190    };
191    for (key, value) in SETTINGS {
192        let lookup = if matches!(*key, "gpg.program" | "gpg.openpgp.program") { OPENPGP_EFFECTIVE.to_string() } else { key.to_ascii_lowercase() };
193        let kept = PERSONS.contains(key).then(|| own.get(&lookup)).flatten();
194        set(&mut out, key, kept.map_or(*value, String::as_str));
195    }
196    for command in PAGED_COMMANDS {
197        set(&mut out, &format!("pager.{command}"), "false");
198    }
199    if get(PROXY_COMMAND).is_none() {
200        out.insert(PROXY_COMMAND.to_string(), String::new());
201    }
202    out.into_iter().collect()
203}
204
205/// The spawn environment of an agent whose pane has `block_meta`: given the settings when it is a host agent in a
206/// folder the rule holds for, and left as it is otherwise.
207pub fn apply_for_spawn(env: &mut HashMap<String, String>, block_meta: &crate::backend::obj::MetaMapType) {
208    if crate::backend::mcp_folder_rule::folder_of(block_meta).is_none() {
209        return;
210    }
211    let entries = entries_over(|k| env.get(k).cloned().or_else(|| std::env::var(k).ok()), &persons_values());
212    env.extend(entries);
213}
214
215#[cfg(test)]
216#[path = "git_program_settings_tests.rs"]
217mod tests;