Skip to content

Commit d1b7da4

Browse files
wpfleger96Duncan
andauthored
feat(acp): add BUZZ_GIT_IDENTITY switch for agent commit identity (#8024)
🤖 This adds an operator switch for whose identity an agent's commits carry, and removes the reason agents were clearing their git identity env vars. Replaces #6177. Since #7819, every agent authors and signs commits as its nostr identity through `GIT_CONFIG_*` env vars, which beat repo and global config in every shell the agent runs. Operators had no way to opt out of that. **`BUZZ_GIT_IDENTITY=agent|user`.** It's read once in `GitEnvironment::install`. Unset or `agent` keeps today's behavior. `user` keeps only relay git auth (the credential helper and keyfile) and installs no identity, no `git-sign-nostr` and no signing config, so git uses the operator's own config. It also drops inherited `GIT_CONFIG_*` entries for the agent identity and signing keys, `author.*`/`committer.*`, and `include.path`/`includeIf.*.path`, so a nested agent in `user` mode can't pick up its parent agent's identity. Any other value fails startup with an error naming the variable and both allowed values. The resolved mode is forwarded in the managed env to MCP servers, which `buzz-agent` starts with a cleared env, so a nested `buzz-acp` launched from an MCP shell keeps the operator's choice instead of falling back to `agent`. **Known limitation:** in `user` mode, an operator whose own git config signs with `git-sign-nostr` has commits refused with a key-mismatch error, because the agent shell's `BUZZ_PRIVATE_KEY` (needed by the `buzz` CLI) loads ahead of `nostr.keyfile` and NIP-GS requires the signer to exit when the loaded key doesn't match `-u`. Nothing is signed with the wrong key. SSH and GPG signing are unaffected. **Desktop reserves `GIT_CONFIG*`.** User env overrides are layered onto the spawn command after the relay credential helper, so a single `GIT_CONFIG_COUNT=0` used to silently drop it. `GIT_CONFIG` and every `GIT_CONFIG_*` name are now reserved keys. **`session_new_forwards_complete_git_block_without_duplicate_names` no longer reads the runner's env.** Run inside an agent session, it picked up the session's own inherited `GIT_CONFIG_*` and failed. Agents worked around that by unsetting `GIT_CONFIG_COUNT`, and any commit made in that shell fell back to the human's git identity and signing key. The test now hides the runner's `GIT_CONFIG*` and `BUZZ_GIT_IDENTITY` under `ENV_LOCK` and restores them afterwards. **Agent instructions.** `base_prompt.md` and the nest `AGENTS.md` now say the runtime sets the agent's commit identity and signing, and that agents shouldn't override them with `user.*` config, `-c user.*`, `--author` or another signing key. Trailers are added only when the repository or the person the agent works for requires them. If a repository requires a different author, the agent tells the operator, who can switch to `BUZZ_GIT_IDENTITY=user`, instead of overriding the identity. The nest `AGENTS.md` scopes this to agents Buzz runs through its stock `buzz-acp` harness, and notes that custom harnesses get only relay git auth and control their own attribution. `NEST_AGENTS_VERSION` goes from 5 to 6. --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent 15772c5 commit d1b7da4

9 files changed

Lines changed: 538 additions & 42 deletions

File tree

‎crates/buzz-acp/src/base_prompt.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ These are guidelines, not a fixed procedure — apply judgment to the task in fr
132132
- After selecting a repository or worktree, read its root `AGENTS.md` and any path-local `AGENTS.md` files that apply before planning or editing. The workspace-level file is team context; it does not replace repository-owned instructions.
133133
- Treat repository-owned product, architecture, and vision documents as design constraints, not optional background. Read the relevant documents before making non-trivial plans, and surface any intentional conflict with them.
134134
- Make file changes in a worktree, not on the default branch. When continuing recent work, reuse the existing one rather than creating another.
135-
- Before committing, read the repo-local git `user.name` / `user.email`; if email is empty, stop and ask. Include the trailers the repo requires.
135+
- The runtime sets your git commit identity and signing. Don't override them with `user.*` config, `-c user.*`, `--author` or another signing key. Add co-author or sign-off trailers only when the repository or the person you're working for requires them. If a repository requires a different commit author, tell the person running you instead of overriding the identity; they can switch your commits to their own git identity with `BUZZ_GIT_IDENTITY=user`.
136136

137137
## Autonomy
138138

‎crates/buzz-acp/src/git.rs‎

Lines changed: 193 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,13 @@ impl GitEnvironment {
2828
relay_url: &str,
2929
executable: &Path,
3030
) -> anyhow::Result<Self> {
31+
let agent = GitIdentityMode::from_value(std::env::var_os(GIT_IDENTITY_ENV).as_deref())?
32+
== GitIdentityMode::Agent;
3133
let dir = tempfile::Builder::new().prefix("buzz-acp-git-").tempdir()?;
3234
set_owner_only(dir.path())?;
33-
for name in ["git-credential-nostr", "git-sign-nostr"] {
34-
symlink(executable, &dir.path().join(name))?;
35+
symlink(executable, &dir.path().join("git-credential-nostr"))?;
36+
if agent {
37+
symlink(executable, &dir.path().join("git-sign-nostr"))?;
3538
}
3639
let keyfile = dir.path().join(".nostr-key");
3740
let secret = Zeroizing::new(keys.secret_key().to_secret_hex());
@@ -55,14 +58,32 @@ impl GitEnvironment {
5558
.map_err(|_| anyhow::anyhow!("invalid Git relay URL"))?;
5659
relay.set_query(None);
5760
relay.set_fragment(None);
58-
let inherited = inherited_config()?;
59-
let display_name = std::env::var("BUZZ_ACP_DISPLAY_NAME").ok();
60-
let mut env = build_git_env(
61-
&info,
62-
relay.as_str().trim_end_matches('/'),
63-
display_name.as_deref(),
64-
inherited,
65-
);
61+
let relay = relay.as_str().trim_end_matches('/');
62+
// `user` mode keeps only relay auth; its commits carry the operator's
63+
// own identity, so no attribution or signing is installed.
64+
let managed = if agent {
65+
let display_name = std::env::var("BUZZ_ACP_DISPLAY_NAME").ok();
66+
identity_entries(&info, relay, display_name.as_deref())
67+
} else {
68+
vec![("nostr.keyfile".into(), info.keyfile_path.clone())]
69+
};
70+
// In `user` mode nothing later overrides inherited identity or signing,
71+
// so drop agent mode's own managed keys, the author/committer
72+
// overrides and includes.
73+
let mut inherited = inherited_config()?;
74+
if !agent {
75+
let managed_keys = identity_entries(&info, relay, None);
76+
inherited.retain(|(key, _)| {
77+
!is_config_include(key)
78+
&& !AUTHOR_COMMITTER_KEYS
79+
.iter()
80+
.any(|identity| same_config_key(identity, key))
81+
&& !managed_keys
82+
.iter()
83+
.any(|(managed, _)| same_config_key(managed, key))
84+
});
85+
}
86+
let mut env = build_git_env(relay, &managed, inherited);
6687
let mut paths = vec![dir.path().to_path_buf()];
6788
paths.extend(std::env::split_paths(
6889
&std::env::var_os("PATH").unwrap_or_default(),
@@ -77,6 +98,12 @@ impl GitEnvironment {
7798
// CLI flags must work even when the caller did not export these variables.
7899
env.push(("BUZZ_PRIVATE_KEY".into(), secret.to_string()));
79100
env.push(("BUZZ_RELAY_URL".into(), relay_url.to_owned()));
101+
// MCP children start from a cleared env; forward the resolved mode so a
102+
// nested harness keeps it instead of defaulting to `agent`.
103+
env.push((
104+
GIT_IDENTITY_ENV.into(),
105+
if agent { "agent" } else { "user" }.into(),
106+
));
80107
Ok(Self { _dir: dir, env })
81108
}
82109
}
@@ -104,6 +131,79 @@ fn inherited_config() -> anyhow::Result<Vec<(String, String)>> {
104131
.collect()
105132
}
106133

134+
/// Operator selector for commit identity, read once at harness startup.
135+
const GIT_IDENTITY_ENV: &str = "BUZZ_GIT_IDENTITY";
136+
137+
#[derive(Debug, PartialEq, Eq)]
138+
enum GitIdentityMode {
139+
/// Default: commits are authored and signed as the agent.
140+
Agent,
141+
/// The operator's own git config authors commits; only relay auth is kept.
142+
User,
143+
}
144+
145+
impl GitIdentityMode {
146+
/// Unset means `Agent`; any value other than `agent` or `user` is an error
147+
/// rather than a silent fallback.
148+
fn from_value(raw: Option<&std::ffi::OsStr>) -> anyhow::Result<Self> {
149+
match raw.map(|value| value.to_str()) {
150+
None => Ok(Self::Agent),
151+
Some(Some("agent")) => Ok(Self::Agent),
152+
Some(Some("user")) => Ok(Self::User),
153+
Some(value) => anyhow::bail!(
154+
"{GIT_IDENTITY_ENV} must be `agent` or `user`, got {:?}",
155+
value.unwrap_or("<non-UTF-8>")
156+
),
157+
}
158+
}
159+
}
160+
161+
/// Per-role identity keys that override `user.*`; not agent-managed entries.
162+
const AUTHOR_COMMITTER_KEYS: [&str; 4] = [
163+
"author.name",
164+
"author.email",
165+
"committer.name",
166+
"committer.email",
167+
];
168+
169+
/// Split a Git config key into section, optional subsection and variable. The
170+
/// subsection is everything between the first and last dot, so it may itself
171+
/// contain dots.
172+
fn split_config_key(key: &str) -> Option<(&str, Option<&str>, &str)> {
173+
let (section, rest) = key.split_once('.')?;
174+
Some(match rest.rsplit_once('.') {
175+
Some((subsection, variable)) => (section, Some(subsection), variable),
176+
None => (section, None, rest),
177+
})
178+
}
179+
180+
/// Git's key equality: section and variable ignore ASCII case, the subsection
181+
/// does not.
182+
fn same_config_key(a: &str, b: &str) -> bool {
183+
match (split_config_key(a), split_config_key(b)) {
184+
(Some((a_section, a_sub, a_var)), Some((b_section, b_sub, b_var))) => {
185+
a_section.eq_ignore_ascii_case(b_section)
186+
&& a_sub == b_sub
187+
&& a_var.eq_ignore_ascii_case(b_var)
188+
}
189+
_ => false,
190+
}
191+
}
192+
193+
/// `include.path` or `includeIf.<condition>.path`: an included file could set
194+
/// any identity key.
195+
fn is_config_include(key: &str) -> bool {
196+
match split_config_key(key) {
197+
Some((section, None, variable)) => {
198+
section.eq_ignore_ascii_case("include") && variable.eq_ignore_ascii_case("path")
199+
}
200+
Some((section, Some(_), variable)) => {
201+
section.eq_ignore_ascii_case("includeIf") && variable.eq_ignore_ascii_case("path")
202+
}
203+
None => false,
204+
}
205+
}
206+
107207
/// Write `data` to `path` with 0600 permissions set at creation time via
108208
/// `OpenOptions::mode()` (no window where the file is world-readable).
109209
/// Non-Unix: plain write — acceptable inside our 0700 tempdir.
@@ -224,39 +324,53 @@ fn sanitize_git_user_name(raw: &str) -> Option<String> {
224324
name.chars().any(|c| !is_git_crud(c)).then_some(name)
225325
}
226326

227-
/// Compose a complete config block, including the caller's entries, for env-cleared MCP children.
228-
fn build_git_env(
327+
/// The agent's attribution and signing config. `user` mode also uses these
328+
/// keys to drop inherited agent identity.
329+
fn identity_entries(
229330
info: &KeyInfo,
230331
relay: &str,
231332
display_name: Option<&str>,
232-
mut entries: Vec<(String, String)>,
233333
) -> Vec<(String, String)> {
234334
let host = url::Url::parse(relay)
235335
.ok()
236336
.and_then(|url| url.host_str().map(str::to_owned))
237337
.filter(|host| !host.starts_with("localhost") && !host.starts_with("127."))
238338
.unwrap_or_else(|| "buzz".into());
239-
let scope = format!("credential.{relay}/git");
240-
entries.extend([
339+
let mut entries = vec![
241340
(
242341
"user.name".into(),
243342
display_name
244343
.and_then(sanitize_git_user_name)
245344
.unwrap_or_else(|| info.npub.clone()),
246345
),
247346
("user.email".into(), format!("{}@{host}", info.pubkey_hex)),
248-
// Reset helpers only inside this relay's Git URL namespace. Unrelated
249-
// remotes retain their own helper chain and never receive this key.
250-
(format!("{scope}.helper"), String::new()),
251-
(format!("{scope}.helper"), "nostr".into()),
252-
(format!("{scope}.useHttpPath"), "true".into()),
253-
("nostr.keyfile".into(), info.keyfile_path.clone()),
347+
];
348+
entries.extend([
254349
("gpg.format".into(), "x509".into()),
255350
("gpg.x509.program".into(), "git-sign-nostr".into()),
256351
("commit.gpgSign".into(), "true".into()),
257352
("tag.gpgSign".into(), "true".into()),
258353
("user.signingkey".into(), info.pubkey_hex.clone()),
354+
("nostr.keyfile".into(), info.keyfile_path.clone()),
259355
]);
356+
entries
357+
}
358+
359+
/// Compose a complete config block, including the caller's entries, for env-cleared MCP children.
360+
fn build_git_env(
361+
relay: &str,
362+
managed: &[(String, String)],
363+
mut entries: Vec<(String, String)>,
364+
) -> Vec<(String, String)> {
365+
let scope = format!("credential.{relay}/git");
366+
entries.extend([
367+
// Reset helpers only inside this relay's Git URL namespace. Unrelated
368+
// remotes retain their own helper chain and never receive this key.
369+
(format!("{scope}.helper"), String::new()),
370+
(format!("{scope}.helper"), "nostr".into()),
371+
(format!("{scope}.useHttpPath"), "true".into()),
372+
]);
373+
entries.extend_from_slice(managed);
260374
let mut env = vec![("GIT_CONFIG_COUNT".into(), entries.len().to_string())];
261375
for (i, (key, value)) in entries.into_iter().enumerate() {
262376
env.push((format!("GIT_CONFIG_KEY_{i}"), key));
@@ -270,7 +384,11 @@ pub(crate) fn is_managed_env(name: &str) -> bool {
270384
name.starts_with("GIT_CONFIG_")
271385
|| matches!(
272386
name,
273-
"PATH" | "GIT_TERMINAL_PROMPT" | "BUZZ_PRIVATE_KEY" | "BUZZ_RELAY_URL"
387+
"PATH"
388+
| "GIT_TERMINAL_PROMPT"
389+
| "BUZZ_PRIVATE_KEY"
390+
| "BUZZ_RELAY_URL"
391+
| GIT_IDENTITY_ENV
274392
)
275393
}
276394

@@ -303,8 +421,8 @@ fn symlink(src: &Path, dst: &Path) -> std::io::Result<()> {
303421
#[cfg(test)]
304422
mod git_user_name_tests {
305423
use super::{
306-
build_git_env, is_git_crud, is_unicode_format, sanitize_git_user_name, KeyInfo,
307-
MAX_GIT_USER_NAME_CHARS,
424+
build_git_env, identity_entries, is_git_crud, is_unicode_format, sanitize_git_user_name,
425+
KeyInfo, MAX_GIT_USER_NAME_CHARS,
308426
};
309427

310428
const PUBKEY_HEX: &str = "dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95";
@@ -318,6 +436,15 @@ mod git_user_name_tests {
318436
}
319437
}
320438

439+
fn git_env(display_name: Option<&str>) -> Vec<(String, String)> {
440+
let relay = "https://localhost:3000";
441+
build_git_env(
442+
relay,
443+
&identity_entries(&key_info(), relay, display_name),
444+
vec![],
445+
)
446+
}
447+
321448
/// Read a git config value back out of the flat GIT_CONFIG_KEY_n/VALUE_n pairs.
322449
fn git_config(env: &[(String, String)], key: &str) -> Option<String> {
323450
let idx = env
@@ -563,12 +690,7 @@ mod git_user_name_tests {
563690

564691
#[test]
565692
fn test_build_git_env_uses_display_name_and_leaves_email_on_the_pubkey() {
566-
let env = build_git_env(
567-
&key_info(),
568-
"https://localhost:3000",
569-
Some("Duncan"),
570-
vec![],
571-
);
693+
let env = git_env(Some("Duncan"));
572694

573695
assert_eq!(git_config(&env, "user.name").as_deref(), Some("Duncan"));
574696
// The pubkey — the thing NIP-98 auth, NIP-GS signing, and contributor
@@ -585,7 +707,7 @@ mod git_user_name_tests {
585707

586708
#[test]
587709
fn test_build_git_env_falls_back_to_npub_when_display_name_unset() {
588-
let env = build_git_env(&key_info(), "https://localhost:3000", None, vec![]);
710+
let env = git_env(None);
589711

590712
// Without a display name, attribution falls back to the npub.
591713
assert_eq!(git_config(&env, "user.name").as_deref(), Some(NPUB));
@@ -600,7 +722,7 @@ mod git_user_name_tests {
600722
// Crud-only and format-only names both reach git as the npub — one
601723
// would abort every commit, the other would render as blank.
602724
for raw in ["<>", "\u{200B}"] {
603-
let env = build_git_env(&key_info(), "https://localhost:3000", Some(raw), vec![]);
725+
let env = git_env(Some(raw));
604726
assert_eq!(
605727
git_config(&env, "user.name").as_deref(),
606728
Some(NPUB),
@@ -620,3 +742,42 @@ mod git_user_name_tests {
620742
}
621743
}
622744
}
745+
746+
#[cfg(test)]
747+
mod git_identity_mode_tests {
748+
use super::{GitIdentityMode, GIT_IDENTITY_ENV};
749+
use std::ffi::OsStr;
750+
751+
#[test]
752+
fn unset_defaults_to_agent() {
753+
assert_eq!(
754+
GitIdentityMode::from_value(None).unwrap(),
755+
GitIdentityMode::Agent
756+
);
757+
}
758+
759+
#[test]
760+
fn explicit_values_select_their_mode() {
761+
assert_eq!(
762+
GitIdentityMode::from_value(Some(OsStr::new("agent"))).unwrap(),
763+
GitIdentityMode::Agent
764+
);
765+
assert_eq!(
766+
GitIdentityMode::from_value(Some(OsStr::new("user"))).unwrap(),
767+
GitIdentityMode::User
768+
);
769+
}
770+
771+
#[test]
772+
fn unrecognized_value_names_the_variable_and_both_modes() {
773+
for raw in ["", "User", "human"] {
774+
let err = GitIdentityMode::from_value(Some(OsStr::new(raw)))
775+
.unwrap_err()
776+
.to_string();
777+
assert!(
778+
err.contains(GIT_IDENTITY_ENV) && err.contains("`agent`") && err.contains("`user`"),
779+
"{err}"
780+
);
781+
}
782+
}
783+
}

0 commit comments

Comments
 (0)