Skip to main content

agentmux_srv_core/backend/
git_exclude.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Keeps the startup files AgentMux writes for an agent out of the commits of the folder they are written into.
5//!
6//! An agent's working folder can be a git repository, and the startup file AgentMux composes for it (`CLAUDE.md`
7//! and the other harnesses' equivalents, or `.claude/AGENTMUX_MEMORY.md` beside a `CLAUDE.md` that is the
8//! person's own) holds the agent's instructions and the memory it is given: it is not part of the project. So each
9//! time AgentMux writes one of these files, it first adds the file's path to the repository's own
10//! `.git/info/exclude`. That file is local to the clone: it is never committed or pushed, and it changes no tracked
11//! file. A file the project already tracks stays tracked, as an exclude entry does not apply to it.
12//!
13//! The check is made at every write, so a folder that becomes a repository after the file was first written is
14//! covered by the next launch. It looks for the repository from the folder upward, as git does, and understands a
15//! linked worktree or a submodule (`.git` a file that points to the real git folder). It is best effort: a folder
16//! that is no repository is left alone, and a failure to write the exclude is logged and never stops a launch.
17
18use std::fs;
19use std::io::Write;
20use std::path::{Path, PathBuf};
21
22/// How far above the folder the repository is looked for.
23const MOST_PARENTS: usize = 64;
24const COMMENT: &str = "# AgentMux: the startup files it writes for an agent, kept out of commits";
25
26/// Adds each of `names`, files AgentMux writes in `work_dir` (a path relative to it, with `/`), to the exclude list of
27/// the git repository `work_dir` is in, if it is in one and the entry is not there yet.
28pub fn keep_out_of_git(work_dir: &Path, names: &[&str]) {
29    // The folder as the filesystem names it: a link to a folder in a repository is searched from where it leads, not from
30    // the link's own parents. Falls back to the path as given when it cannot be resolved.
31    let resolved = fs::canonicalize(work_dir).unwrap_or_else(|_| work_dir.to_path_buf());
32    let work_dir = resolved.as_path();
33    let Some((root, exclude)) = find_exclude(work_dir) else {
34        return;
35    };
36    let Ok(under_root) = work_dir.strip_prefix(&root) else {
37        return;
38    };
39    let patterns: Vec<String> = names
40        .iter()
41        .map(|name| pattern_for(under_root, name))
42        .collect();
43    if let Err(e) = add_patterns(&exclude, &patterns) {
44        tracing::warn!(exclude = %exclude.display(), error = %e, "git_exclude: could not keep the startup file out of commits");
45    }
46}
47
48/// The repository root above `work_dir` (or `work_dir` itself) and the path of its `info/exclude`.
49fn find_exclude(work_dir: &Path) -> Option<(PathBuf, PathBuf)> {
50    for dir in work_dir.ancestors().take(MOST_PARENTS) {
51        let dot_git = dir.join(".git");
52        let meta = match fs::symlink_metadata(&dot_git) {
53            Ok(m) => m,
54            Err(_) => continue,
55        };
56        let git_dir = if meta.is_dir() {
57            dot_git
58        } else if meta.is_file() {
59            git_dir_from_file(dir, &dot_git)?
60        } else {
61            return None;
62        };
63        return Some((
64            dir.to_path_buf(),
65            common_dir(&git_dir).join("info").join("exclude"),
66        ));
67    }
68    None
69}
70
71/// The git folder a `.git` file (a linked worktree, a submodule) names with `gitdir: <path>`; a relative path is
72/// relative to the folder that holds the file.
73fn git_dir_from_file(dir: &Path, dot_git: &Path) -> Option<PathBuf> {
74    let text = fs::read_to_string(dot_git).ok()?;
75    let target = text.lines().find_map(|l| l.strip_prefix("gitdir:"))?.trim();
76    if target.is_empty() {
77        return None;
78    }
79    Some(dir.join(target))
80}
81
82/// A linked worktree's git folder points to the main one with `commondir`, and `info/exclude` is read from there.
83fn common_dir(git_dir: &Path) -> PathBuf {
84    match fs::read_to_string(git_dir.join("commondir")) {
85        Ok(text) if !text.trim().is_empty() => git_dir.join(text.trim()),
86        _ => git_dir.to_path_buf(),
87    }
88}
89
90/// The exclude line for `name` in the folder `under_root` (the folder's path below the repository root): anchored at the
91/// root with a leading `/`, and with the characters git reads as a pattern escaped.
92fn pattern_for(under_root: &Path, name: &str) -> String {
93    let mut parts: Vec<String> = under_root
94        .components()
95        .map(|c| c.as_os_str().to_string_lossy().into_owned())
96        .collect();
97    parts.extend(
98        name.split('/')
99            .filter(|p| !p.is_empty())
100            .map(str::to_string),
101    );
102    format!("/{}", escape(&parts.join("/")))
103}
104
105fn escape(path: &str) -> String {
106    let mut out = String::with_capacity(path.len());
107    for c in path.chars() {
108        if matches!(c, '\\' | '*' | '?' | '[') {
109            out.push('\\');
110        }
111        out.push(c);
112    }
113    if out.ends_with(' ') {
114        out.insert(out.len() - 1, '\\');
115    }
116    out
117}
118
119fn add_patterns(exclude: &Path, patterns: &[String]) -> std::io::Result<()> {
120    // Never through a link: the file is the repository's own.
121    if let Ok(m) = fs::symlink_metadata(exclude) {
122        if !m.is_file() {
123            return Ok(());
124        }
125    }
126    let existing = fs::read_to_string(exclude).unwrap_or_default();
127    let missing: Vec<&String> = patterns
128        .iter()
129        .filter(|p| !existing.lines().any(|l| l.trim_end() == p.as_str()))
130        .collect();
131    if missing.is_empty() {
132        return Ok(());
133    }
134    if let Some(parent) = exclude.parent() {
135        fs::create_dir_all(parent)?;
136    }
137    let mut add = String::new();
138    if !existing.is_empty() && !existing.ends_with('\n') {
139        add.push('\n');
140    }
141    if !existing.lines().any(|l| l == COMMENT) {
142        add.push_str(COMMENT);
143        add.push('\n');
144    }
145    for p in missing {
146        add.push_str(p);
147        add.push('\n');
148    }
149    fs::OpenOptions::new()
150        .create(true)
151        .append(true)
152        .open(exclude)?
153        .write_all(add.as_bytes())
154}
155
156#[cfg(test)]
157#[path = "git_exclude_tests.rs"]
158mod tests;