diff --git a/bt-daemon/README.md b/bt-daemon/README.md index b96ab3de..55ccfb4c 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -58,6 +58,28 @@ or `bt trace doctor ` for configuration, authentication, and recent session diagnostics. Hook exit codes can be observed by the caller while the coding agent decides whether to continue its turn. +## Repository-scoped tracing for Claude Code and Cursor + +Install the agent integration with `bt trace setup claude` or `bt trace setup cursor`. +To trace only selected repositories, set `trace_to_braintrust` to `false` in the +corresponding user-level `braintrust.json`, then commit `.claude/braintrust.json` +or `.cursor/braintrust.json` in each selected repository: + +```json +{ + "trace_to_braintrust": true, + "project": "my-braintrust-project" +} +``` + +The hook uses the closest project file within the Git repository, including when +Claude Code starts in a subdirectory. For Cursor workspaces with multiple roots, +the first root containing a project file supplies the settings for the session. +Project settings can select `trace_to_braintrust` and `project`; other route +settings, including span plugins, come from the user settings. An explicit `bt trace disable` pauses persistent tracing even in opted-in +repositories; a managed `bt trace run` takes precedence over both. `bt trace doctor` +reports user-level settings, not the settings of a particular repository. + ## Per-agent plugin settings Each coding agent reads an independent non-credential `braintrust.json` file: diff --git a/bt-daemon/src/hook.rs b/bt-daemon/src/hook.rs index 5be86afc..53429f09 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -105,11 +105,13 @@ pub async fn run_hook(args: HookArgs, route: SessionRoute, host: HostInfo) -> an if args.managed_context.is_some() { return run_hook_with_route(args, route, host).await; } - let settings = settings::AgentSettings::load_for_hook(&args.source)?; + let payload = read_project_hook_payload(&args)?; + let settings = + settings::AgentSettings::load_for_hook_payload(&args.source, payload.as_ref())?; if !settings.tracing_enabled() { return Ok(()); } - run_hook_with_route(args, settings.route.unwrap_or(route), host).await + run_hook_with_payload(args, settings.route.unwrap_or(route), host, payload).await } .await; if let Some(response) = response { @@ -172,7 +174,32 @@ pub(crate) async fn run_hook_with_route( route: SessionRoute, host: HostInfo, ) -> anyhow::Result<()> { - with_hook_capture_timeout(args.capture_timeout_ms, capture_hook(args, route, host)).await + run_hook_with_payload(args, route, host, None).await +} + +pub(crate) fn read_project_hook_payload( + args: &HookArgs, +) -> anyhow::Result> { + if matches!(args.source.as_str(), "claude" | "claude-code" | "cursor") { + Ok(Some(read_stdin_json( + args.transcript_path_field.as_deref(), + )?)) + } else { + Ok(None) + } +} + +pub(crate) async fn run_hook_with_payload( + args: HookArgs, + route: SessionRoute, + host: HostInfo, + payload: Option, +) -> anyhow::Result<()> { + with_hook_capture_timeout( + args.capture_timeout_ms, + capture_hook(args, route, host, payload), + ) + .await } pub(crate) async fn with_hook_capture_timeout( @@ -193,6 +220,7 @@ async fn capture_hook( mut args: HookArgs, mut route: SessionRoute, host: HostInfo, + payload: Option, ) -> anyhow::Result<()> { let managed_context = if let Some(path) = &args.managed_context { if crate::translate::canonical_source_name(&args.source) != "muse" || !args.managed_run_hook @@ -212,7 +240,10 @@ async fn capture_hook( } else { None }; - let mut payload = read_stdin_json(args.transcript_path_field.as_deref())?; + let mut payload = match payload { + Some(payload) => payload, + None => read_stdin_json(args.transcript_path_field.as_deref())?, + }; resolve_dynamic_hook_versions(&mut args, &payload); diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 45873b14..fb709424 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -6,12 +6,12 @@ //! persistent agent configuration. use crate::paths; -use crate::wire::SessionRoute; +use crate::wire::{SessionRoute, TraceDestination}; use fs2::FileExt; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; pub(crate) const INVOCATION_SETTINGS_ENV: &str = "BT_TRACE_INVOCATION_SETTINGS"; @@ -38,15 +38,73 @@ pub(crate) struct AgentSettings { } impl AgentSettings { - /// Hook invocations must report broken configuration instead of treating - /// it as a successful event. A managed run's invocation route is complete - /// and intentionally supersedes any persistent settings file. - pub(crate) fn load_for_hook(source: &str) -> anyhow::Result { + pub(crate) fn load_for_hook_payload( + source: &str, + payload: Option<&Value>, + ) -> anyhow::Result { let invocation = std::env::var(INVOCATION_SETTINGS_ENV).ok(); - Self::load_hook_from_sources( - &paths::agent_settings_path(source, None), - invocation.as_deref(), - ) + let user_path = paths::agent_settings_path(source, None); + let project_path = payload.and_then(|payload| project_settings_path(source, payload)); + Self::load_hook_with_project(&user_path, project_path.as_deref(), invocation.as_deref()) + } + + fn load_hook_with_project( + user_path: &Path, + project_path: Option<&Path>, + invocation: Option<&str>, + ) -> anyhow::Result { + let path = match (invocation, project_path) { + (Some(_), _) | (_, None) => return Self::load_hook_from_sources(user_path, invocation), + (None, Some(path)) => path, + }; + let raw = std::fs::read_to_string(path).map_err(|error| { + anyhow::anyhow!("read tracing settings at {}: {error}", path.display()) + })?; + let project: Value = serde_json::from_str(&raw).map_err(|error| { + anyhow::anyhow!("parse tracing settings at {}: {error}", path.display()) + })?; + let object = project.as_object().ok_or_else(|| { + anyhow::anyhow!("tracing settings at {} must be an object", path.display()) + })?; + if object.contains_key("route") { + anyhow::bail!("repository tracing settings at {} cannot specify `route`; use `project` to select a destination", path.display()); + } + let overlay: Self = serde_json::from_value(project.clone())?; + let mut settings = if user_path.exists() { + Self::load_hook_from_sources(user_path, None)? + } else { + Self::default() + }; + if overlay.trace_to_braintrust.is_some() { + settings.trace_to_braintrust = overlay.trace_to_braintrust; + } + if let Some(project) = object.get("project") { + let name = project + .as_str() + .filter(|name| !name.trim().is_empty()) + .ok_or_else(|| { + anyhow::anyhow!("project in {} must be a nonempty string", path.display()) + })?; + let route = settings.route.get_or_insert_with(SessionRoute::default); + route.destination = Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some(name.to_owned()), + }); + } + // An explicit user pause must remain effective even when a repository opts in. + if user_path.exists() { + let user: Value = serde_json::from_str(&std::fs::read_to_string(user_path)?)?; + if user.get("tracing_disabled").and_then(Value::as_bool) == Some(true) { + settings.trace_to_braintrust = Some(false); + } + } + if settings.trace_to_braintrust.is_none() { + anyhow::bail!( + "tracing settings at {} have no `trace_to_braintrust` value", + path.display() + ); + } + Ok(settings) } fn load_hook_from_sources(path: &Path, invocation: Option<&str>) -> anyhow::Result { @@ -125,6 +183,46 @@ impl AgentSettings { } } +fn project_settings_path(source: &str, payload: &Value) -> Option { + let directory = match source { + "claude" | "claude-code" => ".claude", + "cursor" => ".cursor", + _ => return None, + }; + let roots: Vec<&str> = if source == "cursor" { + payload + .get("workspace_roots") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect() + } else { + payload + .get("cwd") + .and_then(Value::as_str) + .into_iter() + .collect() + }; + roots + .into_iter() + .filter_map(|root| { + let root = Path::new(root); + if !root.is_absolute() { + return None; + } + let boundary = root + .ancestors() + .find(|dir| dir.join(".git").exists()) + .unwrap_or(root); + root.ancestors() + .take_while(|dir| dir.starts_with(boundary)) + .map(|dir| dir.join(directory).join("braintrust.json")) + .find(|path| path.is_file()) + }) + .next() +} + /// Replace a still-matching name-only route with the host-canonical route. /// The caller must hold the settings lock used by setup while invoking this. pub(crate) fn migrate_persisted_route( @@ -210,6 +308,98 @@ fn write_json_atomic(path: &Path, settings: &Map) -> anyhow::Resu #[cfg(test)] mod tests { + #[test] + fn project_settings_override_user_and_managed_run_overrides_both() { + use super::*; + let temp = tempfile::tempdir().unwrap(); + let user = temp.path().join("user.json"); + let project = temp.path().join("project.json"); + std::fs::write( + &user, + r#"{"trace_to_braintrust":false,"route":{"tags":["saved"]}}"#, + ) + .unwrap(); + std::fs::write( + &project, + r#"{"trace_to_braintrust":true,"project":"repo-project"}"#, + ) + .unwrap(); + let settings = AgentSettings::load_hook_with_project(&user, Some(&project), None).unwrap(); + assert!(settings.tracing_enabled()); + let route = settings.route.unwrap(); + assert!(route.tags.contains("saved")); + assert!( + matches!(route.destination, Some(TraceDestination::ProjectLogs { project_name: Some(ref name), .. }) if name == "repo-project") + ); + let invocation = r#"{"trace_to_braintrust":false,"route":{}}"#; + assert!( + !AgentSettings::load_hook_with_project(&user, Some(&project), Some(invocation)) + .unwrap() + .tracing_enabled() + ); + std::fs::write( + &user, + r#"{"trace_to_braintrust":false,"tracing_disabled":true}"#, + ) + .unwrap(); + assert!( + !AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .tracing_enabled() + ); + assert!(AgentSettings::load_hook_with_project( + &user, + Some(&project), + Some(r#"{"trace_to_braintrust":true,"route":{}}"#) + ) + .unwrap() + .tracing_enabled()); + std::fs::write(&project, r#"{"trace_to_braintrust":false}"#).unwrap(); + assert!( + !AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .tracing_enabled() + ); + std::fs::remove_file(&user).unwrap(); + std::fs::write(&project, r#"{"trace_to_braintrust":true,"project":"new"}"#).unwrap(); + assert!( + AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .tracing_enabled() + ); + std::fs::write( + &project, + r#"{"trace_to_braintrust":true,"route":{"span_plugins":["./malicious.js"]}}"#, + ) + .unwrap(); + assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); + std::fs::write(&project, "invalid").unwrap(); + assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); + } + + #[test] + fn finds_repo_settings_for_nested_claude_and_cursor_workspaces() { + use super::*; + let temp = tempfile::tempdir().unwrap(); + let repo = temp.path().join("repo"); + let nested = repo.join("src/nested"); + std::fs::create_dir_all(&nested).unwrap(); + std::fs::create_dir(repo.join(".git")).unwrap(); + for (source, dir) in [("claude", ".claude"), ("cursor", ".cursor")] { + std::fs::create_dir(repo.join(dir)).unwrap(); + let path = repo.join(dir).join("braintrust.json"); + std::fs::write(&path, "{}").unwrap(); + let payload = if source == "claude" { + serde_json::json!({"cwd": nested}) + } else { + serde_json::json!({"workspace_roots": [nested]}) + }; + assert_eq!(project_settings_path(source, &payload), Some(path)); + } + let outside = temp.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + assert!(project_settings_path("claude", &serde_json::json!({"cwd": outside})).is_none()); + } use super::*; #[test] diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index f5709781..819c1835 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -707,8 +707,12 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul ) .await; } - let settings = crate::settings::AgentSettings::load_for_hook(&hook_args.source)?; - run_hook_command(hook_args, &host, settings).await + let payload = crate::hook::read_project_hook_payload(&hook_args)?; + let settings = crate::settings::AgentSettings::load_for_hook_payload( + &hook_args.source, + payload.as_ref(), + )?; + run_hook_command_with_payload(hook_args, &host, settings, payload).await } .await; if let Some(response) = response { @@ -785,10 +789,20 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul } } +#[cfg(test)] async fn run_hook_command( hook_args: crate::HookArgs, host: &TraceHostContext, settings: crate::settings::AgentSettings, +) -> anyhow::Result<()> { + run_hook_command_with_payload(hook_args, host, settings, None).await +} + +async fn run_hook_command_with_payload( + hook_args: crate::HookArgs, + host: &TraceHostContext, + settings: crate::settings::AgentSettings, + payload: Option, ) -> anyhow::Result<()> { if !settings.tracing_enabled() { return Ok(()); @@ -798,7 +812,7 @@ async fn run_hook_command( Some(route) => route, None => resolve_host_route(host, RouteRequirements::default()).await?, }; - crate::hook::run_hook_with_route(hook_args, route, host_info(host)).await + crate::hook::run_hook_with_payload(hook_args, route, host_info(host), payload).await }) .await } @@ -1243,7 +1257,19 @@ mod tests { if user_hook { child.env(crate::setup::cursor::USER_HOOK_ENV, "1"); } - let output = child.output().unwrap(); + use std::io::Write; + child + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + let mut process = child.spawn().unwrap(); + process + .stdin + .take() + .unwrap() + .write_all(br#"{"workspace_roots":[]}"#) + .unwrap(); + let output = process.wait_with_output().unwrap(); assert!( output.status.success(), "user_hook={user_hook}: {}\n{}", diff --git a/bt-daemon/tests/command_output.rs b/bt-daemon/tests/command_output.rs index aa170279..19321f75 100644 --- a/bt-daemon/tests/command_output.rs +++ b/bt-daemon/tests/command_output.rs @@ -200,3 +200,79 @@ fn standalone_run_mirrors_an_explicit_socket_to_the_deprecated_name() { ); } } + +#[test] +fn project_settings_control_hook_capture_from_native_payload() { + let temp = tempfile::tempdir().unwrap(); + let repo = temp.path().join("repo"); + std::fs::create_dir_all(repo.join(".git")).unwrap(); + let user = temp.path().join("user.json"); + #[cfg(unix)] + let socket = temp.path().join("missing.sock"); + #[cfg(windows)] + let socket = std::path::PathBuf::from(format!( + r"\\.\pipe\missing-bt-daemon-{}", + uuid::Uuid::new_v4() + )); + std::fs::write(&user, r#"{"trace_to_braintrust":false}"#).unwrap(); + for (source, dir, payload) in [ + ( + "claude", + ".claude", + serde_json::json!({"cwd":repo,"session_id":"s","hook_event_name":"Stop"}), + ), + ( + "cursor", + ".cursor", + serde_json::json!({"workspace_roots":[repo],"conversation_id":"s","hook_event_name":"stop"}), + ), + ] { + let config_dir = repo.join(dir); + std::fs::create_dir_all(&config_dir).unwrap(); + let config = config_dir.join("braintrust.json"); + let run = |enabled: bool| { + std::fs::write( + &config, + format!(r#"{{"trace_to_braintrust":{enabled},"project":"test"}}"#), + ) + .unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_bt-daemon")) + .args([ + "hook", + "--source", + source, + "--no-spawn", + "--session-id-field", + if source == "cursor" { + "conversation_id" + } else { + "session_id" + }, + ]) + .env("BRAINTRUST_DAEMON_CONFIG", &user) + .env("BRAINTRUST_DAEMON_SOCKET", &socket) + .env("HOME", temp.path()) + .env_remove("BT_TRACE_INVOCATION_SETTINGS") + .env_remove("_BT_TRACE_MANAGED_RUN") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(payload.to_string().as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() + }; + assert!(run(false).status.success()); + let enabled = run(true); + assert!( + !enabled.status.success(), + "enabled hook should try to connect to the absent daemon" + ); + assert!(!enabled.stderr.is_empty()); + } +} diff --git a/src/plugins/claude/content/README.md b/src/plugins/claude/content/README.md index c530ec6b..a4685530 100644 --- a/src/plugins/claude/content/README.md +++ b/src/plugins/claude/content/README.md @@ -116,3 +116,5 @@ bt trace disable claude See the [tracing plugin guide](plugins/trace-claude-code/README.md) for the capture architecture and supported surfaces. + +For repository-scoped tracing, see the [daemon configuration guide](https://github.com/braintrustdata/braintrust-coding-agent-plugins/blob/main/bt-daemon/README.md#repository-scoped-tracing-for-claude-code-and-cursor). diff --git a/src/plugins/cursor/content/README.md b/src/plugins/cursor/content/README.md index a20b3a06..4281561f 100644 --- a/src/plugins/cursor/content/README.md +++ b/src/plugins/cursor/content/README.md @@ -124,3 +124,5 @@ bt trace status bt trace update cursor bt trace disable cursor ``` + +For repository-scoped tracing, see the [daemon configuration guide](https://github.com/braintrustdata/braintrust-coding-agent-plugins/blob/main/bt-daemon/README.md#repository-scoped-tracing-for-claude-code-and-cursor).