diff --git a/README.md b/README.md index e2fc35f5..e2db908e 100644 --- a/README.md +++ b/README.md @@ -33,15 +33,18 @@ then authenticate and enable tracing. For example: ```bash bt login -bt trace enable claude --project my-coding-agent +bt trace install claude --project my-coding-agent ``` Replace `claude` with your agent's CLI name below. Restart the agent after -setup and follow any plugin or hook trust prompts. +installation and follow any plugin or hook trust prompts. To opt a Git repository +in or out independently, run `bt trace enable claude --scope project` or +`bt trace disable claude --scope project` inside it. The repository's `.braintrust.json` applies to every agent; its settings +override user settings, and `bt trace run` overrides both. ## Supported agents -All six support `bt trace enable`, `update`, `disable`, and `doctor`. +All support `bt trace install`, `enable`, `update`, `disable`, and `doctor`. | Agent and setup guide | CLI name | One-off traced run | Import / live attach | Distribution | |---|---|---|---|---| @@ -77,7 +80,7 @@ bt trace disable claude `doctor` shows which configuration is in use and whether the running tracing daemon can authenticate it. `status` reports trace delivery. -`update` keeps your settings; `disable` removes the plugin and its settings. +`disable` pauses tracing and keeps your settings. Use `enable` to resume; it also sets up tracing when needed or when you pass new settings. Use `uninstall` to remove the plugin and its settings. For command hooks, `bt trace hook` exits nonzero when it cannot capture an event. Exit `0` means the daemon accepted the event into its journal; delivery diff --git a/bt-daemon/README.md b/bt-daemon/README.md index b96ab3de..04304027 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -58,6 +58,53 @@ 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. +## Project-scoped tracing + +Each developer installs the agent integration once. To trace only repositories +that opt in, install it with tracing disabled by default: + +```bash +bt trace install claude --disable --project my-default-project +``` + +A repository owner can configure tracing from anywhere inside the Git repository: + +```bash +bt trace install claude --scope project --project my-repository-project +bt trace disable claude --scope project +bt trace enable claude --scope project +bt trace uninstall claude --scope project +``` + +Project install writes `.braintrust.json` at the Git repository root. The same +file applies to every coding-agent integration. It contains the tracing switch +and explicitly supplied settings; commit it to share the opt-in. Each developer +still needs a user-level installation and usable credentials. Credentials are +never stored in project files. Project-scoped uninstall deletes the entire shared +`.braintrust.json`; user-level installations and settings remain in place. + +Project settings overlay user settings recursively: missing fields inherit, +objects merge by field, arrays append, and explicit scalar values replace +inherited values. Tags are deduplicated. Project span plugins are run after +user-level plugins, and their paths are relative to `.braintrust.json`: + +```bash +bt trace install claude --scope project --plugin ./scripts/redact.mjs +``` + +Use `--no-inherit-plugins` to run only the project's plugins; use +`--inherit-plugins` to restore the default. A project configuration can execute +the JavaScript plugins it names when tracing runs, so review them before using +tracing in a repository. + +Managed `bt trace run` takes precedence over both scopes. For example, +`bt trace run codex --inherit` starts from user and project settings before +applying invocation options; `--no-inherit-plugins` replaces the inherited +plugin chain for that invocation. `bt trace doctor ` shows the current +repository's effective configuration. For multi-root Cursor and Antigravity +workspaces, the first root with a project file supplies the settings. `setup` +remains an alias for `install`. + ## Per-agent plugin settings Each coding agent reads an independent non-credential `braintrust.json` file: @@ -146,7 +193,7 @@ Register both transforms persistently for ordinary Codex sessions. The redactor runs first and its returned span becomes the tagger's input: ```bash -bt trace enable codex --plugin ./redact.mjs --plugin ./tag-ci.mjs +bt trace install codex --plugin ./redact.mjs --plugin ./tag-ci.mjs ``` `run` and `import` plugins apply only to that command. They replace, rather than @@ -228,12 +275,12 @@ or provide it for one invocation with `bt trace run`. Both accept `--additional-metadata` or `BRAINTRUST_ADDITIONAL_METADATA`: ```bash -bt trace enable claude --additional-metadata '{"team":"platform"}' +bt trace install claude --additional-metadata '{"team":"platform"}' BRAINTRUST_ADDITIONAL_METADATA='{"ci":true,"run_id":"'"$JOB_ID"'"}' \ bt trace run codex -- "summarize this change" ``` -`bt trace enable`, `bt trace run`, and `bt trace import` are explicit, +`bt trace install`, `bt trace run`, and `bt trace import` are explicit, user-invoked commands, so all three accept routing (profile, organization, project, destination) and `additional_metadata` from either a flag or the matching `BRAINTRUST_*` environment variable, with the flag winning if both @@ -251,7 +298,7 @@ span produced by a route. The option is available on persistent setup, one-off runs, and transcript imports. ```bash -bt trace enable claude --tag ci --tag release-validation +bt trace install claude --tag ci --tag release-validation bt trace run codex --tag ci -- "summarize this change" bt trace import claude session-id --tag historical-import ``` @@ -263,9 +310,13 @@ one of those commands: BRAINTRUST_TAGS=ci,release-validation bt trace run codex -- "summarize this change" ``` -Use `bt trace disable ` to remove the installed tracing plugin and its -Braintrust settings. `bt trace setup ` remains an alias for `bt trace -enable ` for backwards compatibility. +Use `bt trace disable ` to pause tracing while keeping the plugin and settings. +Use `bt trace enable ` to resume. If there is no saved configuration, or you provide +explicit configuration options, `enable` runs installation and reports the result. Environment +defaults do not change an existing configuration during a plain `enable`. +Use `bt trace uninstall ` to remove +the plugin and its Braintrust settings. Use `bt trace install ` to install or +change the configuration. ## Build and test diff --git a/bt-daemon/src/args.rs b/bt-daemon/src/args.rs index 3f77bd30..5422ee77 100644 --- a/bt-daemon/src/args.rs +++ b/bt-daemon/src/args.rs @@ -297,6 +297,9 @@ impl ImportArgs { #[derive(Debug, Clone, Args)] #[command(trailing_var_arg = true)] pub struct RunArgs { + /// Inherit user and project tracing settings for this invocation. + #[arg(long)] + pub inherit: bool, /// Coding agent to launch. #[arg(value_enum)] pub source: RunSource, @@ -309,8 +312,11 @@ pub struct RunArgs { /// Tag applied to each root span for this invocation. May be repeated or comma-separated. #[arg(long = "tag", env = "BRAINTRUST_TAGS", value_delimiter = ',')] pub tags: Vec, - /// JavaScript span transform for this invocation. Repeat to compose an - /// isolated transform chain; persistent setup plugins are not included. + /// Replace inherited span plugins instead of appending to them. + #[arg(long)] + pub no_inherit_plugins: bool, + /// JavaScript span transform for this invocation. With --inherit, these + /// follow inherited plugins unless --no-inherit-plugins is supplied. #[arg(long, value_name = "PATH")] pub plugin: Vec, /// Arguments forwarded verbatim to the coding agent. diff --git a/bt-daemon/src/codex_hooks.rs b/bt-daemon/src/codex_hooks.rs index b3a7fd41..27952059 100644 --- a/bt-daemon/src/codex_hooks.rs +++ b/bt-daemon/src/codex_hooks.rs @@ -90,7 +90,7 @@ pub(crate) async fn activate() -> anyhow::Result<()> { }); anyhow::ensure!( installed, - "Codex tracing plugin is not installed and enabled; rerun `bt trace enable codex`" + "Codex tracing plugin is not installed and enabled; rerun `bt trace install codex`" ); let hooks = request( &mut stdin, diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index 58d28ced..cb401e61 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -54,11 +54,27 @@ impl From> for StatusCommandOutput { } #[derive(Debug, Clone, Serialize)] -pub struct SetupCommandOutput { +pub struct InstallCommandOutput { pub source: String, pub display_name: String, pub settings_path: PathBuf, pub restart_required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub configuration: Option<&'static str>, + pub scope: &'static str, + #[serde(skip_serializing_if = "is_false")] + pub applies_to_all_agents: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + +/// Backwards-compatible name for the shared install and enable output. +pub type SetupCommandOutput = InstallCommandOutput; + +fn is_false(value: &bool) -> bool { + !value } #[derive(Debug, Clone, Serialize)] @@ -153,6 +169,10 @@ pub struct DoctorCommandOutput { pub display_name: String, pub settings_path: PathBuf, pub settings_present: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub project_settings_path: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub project_settings_fields: Vec, pub enabled: bool, pub route_source: String, #[serde(skip_serializing_if = "Option::is_none")] @@ -168,11 +188,16 @@ pub struct DoctorCommandOutput { pub enum TraceCommandOutput { Status(StatusCommandOutput), Doctor(Box), - Enable(SetupCommandOutput), - Disable(SetupCommandOutput), + Install(InstallCommandOutput), + Enable(InstallCommandOutput), + Disable(InstallCommandOutput), + Uninstall(InstallCommandOutput), Update(UpdateCommandOutput), Stop(StopCommandOutput), - Import { summaries: Vec }, + Import { + /// Summaries for the imported sessions. + summaries: Vec, + }, } impl TraceCommandOutput { @@ -184,20 +209,102 @@ impl TraceCommandOutput { Self::Doctor(Box::new(output)) } - pub fn setup( + pub fn install( source: impl Into, display_name: impl Into, settings_path: impl Into, ) -> Self { let source = source.into(); - Self::Enable(SetupCommandOutput { + Self::Install(InstallCommandOutput { source, display_name: display_name.into(), settings_path: settings_path.into(), restart_required: true, + configuration: None, + scope: "user", + applies_to_all_agents: false, + enabled: None, + warnings: Vec::new(), }) } + /// Compatibility alias for creating install output. + pub fn setup( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::install(source, display_name, settings_path) + } + + pub fn enable( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Enable(InstallCommandOutput { + source: source.into(), + display_name: display_name.into(), + settings_path: settings_path.into(), + restart_required: true, + configuration: Some("reused"), + scope: "user", + applies_to_all_agents: false, + enabled: None, + warnings: Vec::new(), + }) + } + + pub fn project_install( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + let mut output = Self::install(source, display_name, settings_path).with_scope("project"); + if let Self::Install(setup) = &mut output { + setup.warnings.push("Settings not specified here must be supplied by each user's configuration. Each user needs a user-level installation and usable Braintrust credentials for their sessions to be captured.".into()); + setup.warnings.push( + "This shared project configuration applies to all coding agents in the repository." + .into(), + ); + } + output + } + + pub(crate) fn with_scope(mut self, scope: &'static str) -> Self { + match &mut self { + Self::Install(output) + | Self::Enable(output) + | Self::Disable(output) + | Self::Uninstall(output) => { + output.scope = scope; + output.applies_to_all_agents = scope == "project"; + } + _ => {} + } + self + } + + pub(crate) fn with_enabled(mut self, enabled: bool) -> Self { + if let Self::Install(output) = &mut self { + output.enabled = Some(enabled); + } + self + } + + pub(crate) fn into_enable(mut self, configuration: &'static str) -> Self { + match &mut self { + Self::Install(output) | Self::Enable(output) => { + output.configuration = Some(configuration) + } + _ => return self, + } + match self { + Self::Install(output) => Self::Enable(output), + _ => self, + } + } + pub fn stop(running: bool, stopped: bool) -> Self { Self::Stop(StopCommandOutput { running, stopped }) } @@ -211,11 +318,34 @@ impl TraceCommandOutput { display_name: impl Into, settings_path: impl Into, ) -> Self { - Self::Disable(SetupCommandOutput { + Self::Disable(InstallCommandOutput { + source: source.into(), + display_name: display_name.into(), + settings_path: settings_path.into(), + restart_required: true, + configuration: None, + scope: "user", + applies_to_all_agents: false, + enabled: None, + warnings: Vec::new(), + }) + } + + pub fn uninstall( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Uninstall(InstallCommandOutput { source: source.into(), display_name: display_name.into(), settings_path: settings_path.into(), restart_required: true, + configuration: None, + scope: "user", + applies_to_all_agents: false, + enabled: None, + warnings: Vec::new(), }) } @@ -259,6 +389,12 @@ impl TraceCommandOutput { doctor.route_source, route, ); + if let Some(path) = &doctor.project_settings_path { + rendered.push_str(&format!("\nProject settings: {}", path.display())); + if !doctor.project_settings_fields.is_empty() { + rendered.push_str(&format!("\nProject overrides: {}", doctor.project_settings_fields.join(", "))); + } + } push_auth_lines(&mut rendered, "", &doctor.auth); let daemon = &doctor.daemon; let status = match daemon.status { @@ -301,16 +437,43 @@ impl TraceCommandOutput { } Ok(rendered) } - Self::Enable(setup) => Ok(format!( - "The Braintrust tracing plugin is installed for {} and configured in {}.\nRestart the coding agent to load the tracing plugin.", + Self::Enable(enable) if enable.scope == "project" => Ok(format!( + "Braintrust tracing is enabled for all coding agents in this repository. Project configuration {} at {}.", + enable.configuration.unwrap_or("reused"), enable.settings_path.display() + )), + Self::Disable(disable) if disable.scope == "project" => Ok(format!( + "Braintrust tracing is disabled for all coding agents in this repository at {}.", disable.settings_path.display() + )), + Self::Enable(setup) if setup.configuration.is_some_and(|value| value != "reused") => Ok(format!( + "Braintrust tracing configuration {} for {} at {} scope in {}.\nRestart the coding agent to apply the change.", + setup.configuration.unwrap_or_default(), setup.display_name, setup.scope, setup.settings_path.display() + )), + Self::Install(setup) if setup.scope == "project" => Ok(format!( + "Project tracing settings for {} were written to {}.\nTracing is {}.\n{}", setup.display_name, setup.settings_path.display(), if setup.enabled == Some(false) { "disabled" } else { "enabled" }, setup.warnings.join("\n") + )), + Self::Install(setup) => Ok(format!( + "The Braintrust tracing plugin is installed for {} and configured in {}.{}\nRestart the coding agent to load the tracing plugin.", setup.display_name, - setup.settings_path.display() + setup.settings_path.display(), + if setup.enabled == Some(false) { " Tracing is disabled by default." } else { "" }, + )), + Self::Enable(enable) => Ok(format!( + "Braintrust tracing is enabled for {} at {} scope in {}.\nRestart the coding agent to apply the change.", + enable.display_name, enable.scope, enable.settings_path.display() )), Self::Disable(disable) => Ok(format!( - "The Braintrust tracing plugin and configuration were removed for {} from {}.\nRestart the coding agent to apply the change.", + "Braintrust tracing is disabled for {} at {} scope in {}.\nRestart the coding agent to apply the change.", disable.display_name, + disable.scope, disable.settings_path.display() )), + Self::Uninstall(uninstall) if uninstall.scope == "project" => Ok(format!( + "The shared repository tracing configuration was removed from {}. User-level settings now apply to all agents in this repository.", uninstall.settings_path.display() + )), + Self::Uninstall(uninstall) => Ok(format!( + "The Braintrust tracing plugin and configuration were removed for {} from {}.\nRestart the coding agent to apply the change.", + uninstall.display_name, uninstall.settings_path.display() + )), Self::Update(update) => Ok(format!( "The Braintrust tracing plugin was updated for {}.\nRestart the coding agent to load the update.", update.display_name, @@ -411,20 +574,33 @@ mod tests { } #[test] - fn enable_json_contains_stable_selection_fields_without_prose() { - let output = TraceCommandOutput::setup( + fn install_json_contains_stable_selection_fields_without_prose() { + let output = TraceCommandOutput::install( "opencode", "OpenCode", PathBuf::from("/tmp/opencode/braintrust.json"), ); let rendered = output.render(OutputFormat::Json).unwrap(); let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); - assert_eq!(value["command"], "enable"); + assert_eq!(value["command"], "install"); assert_eq!(value["source"], "opencode"); assert_eq!(value["restart_required"], true); assert!(!rendered.contains("installed for")); } + #[test] + fn resume_output_reports_enable() { + let output = TraceCommandOutput::enable("pi", "Pi", PathBuf::from("braintrust.json")); + let json: serde_json::Value = + serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); + assert_eq!(json["command"], "enable"); + assert_eq!(json["configuration"], "reused"); + assert!(output + .render(OutputFormat::Human) + .unwrap() + .contains("tracing is enabled")); + } + #[test] fn disable_output_is_explicit() { let output = TraceCommandOutput::disable( @@ -438,13 +614,13 @@ mod tests { assert!(output .render(OutputFormat::Human) .unwrap() - .contains("removed for Google Antigravity")); + .contains("disabled for Google Antigravity")); } #[test] fn codex_setup_and_updates_do_not_request_manual_trust() { for output in [ - TraceCommandOutput::setup("codex", "Codex", PathBuf::from("braintrust.json")), + TraceCommandOutput::install("codex", "Codex", PathBuf::from("braintrust.json")), TraceCommandOutput::update("codex", "Codex"), ] { let human = output.render(OutputFormat::Human).unwrap(); @@ -541,6 +717,8 @@ mod tests { display_name: "Codex".into(), settings_path: PathBuf::from("/tmp/braintrust.json"), settings_present: true, + project_settings_path: None, + project_settings_fields: Vec::new(), enabled: true, route_source: "settings_file".into(), route: Some(SessionRoute::default()), diff --git a/bt-daemon/src/env.rs b/bt-daemon/src/env.rs index 77e70cc5..f3132f8f 100644 --- a/bt-daemon/src/env.rs +++ b/bt-daemon/src/env.rs @@ -113,7 +113,7 @@ mod tests { const INTERNAL: &[&str] = &[ "BT_TRACE_INVOCATION_SETTINGS", "BT_TRACE_MANAGED_RUN_ID", - // Identifies Cursor hooks installed by `bt trace setup`. + // Identifies Cursor hooks installed by `bt trace install`. "BT_TRACE_CURSOR_USER_HOOK", // Fallback for `BRAINTRUST_BT_BIN` in the Cursor hook launchers. "BT_BIN", diff --git a/bt-daemon/src/hook.rs b/bt-daemon/src/hook.rs index 5be86afc..e4b4ce23 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -105,11 +105,22 @@ 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 + let selected = match settings.route { + Some(mut selected) => { + if selected.destination.is_none() { + selected.destination = route.destination; + } + selected + } + None => route, + }; + run_hook_with_payload(args, selected, host, payload).await } .await; if let Some(response) = response { @@ -172,7 +183,39 @@ 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 crate::paths::supports_project_settings(&args.source) { + use std::io::Read; + let mut raw = String::new(); + std::io::stdin().read_to_string(&mut raw)?; + if raw.trim().is_empty() { + return Ok(None); + } + Ok(Some(parse_hook_payload( + &raw, + 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 +236,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 +256,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/lib.rs b/bt-daemon/src/lib.rs index c2f79a9a..9ebcd76c 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -68,7 +68,8 @@ pub use client::{ pub use collections::inspect as storage_inspect; pub use command_output::{ AuthDiagnostic, DaemonDiagnostic, DaemonStatus, DoctorCommandOutput, ImportSummary, - OutputFormat, SetupCommandOutput, StatusCommandOutput, StopCommandOutput, TraceCommandOutput, + InstallCommandOutput, OutputFormat, SetupCommandOutput, StatusCommandOutput, StopCommandOutput, + TraceCommandOutput, }; pub use hook::run_hook; pub use hook_executable::delegate_hook_executable; @@ -80,14 +81,15 @@ pub use server::{ braintrust_serve_options, debug_serve_options, run_serve, AuthLease, AuthProvider, AuthResolveReason, ServeOptions, }; -pub use setup::{run_disable, run_enable, run_setup, run_update}; +pub use setup::{run_disable, run_enable, run_setup, run_uninstall, run_update}; pub use sink::{BraintrustSinkConfig, BraintrustSinkFactory, DebugSinkFactory, Sink, SinkFactory}; pub use trace_command::{ - DisableArgs, DoctorAgent, DoctorArgs, EnableArgs, SetupAgent, SetupArgs, StopArgs, TraceArgs, - TraceCommand, UpdateArgs, + DisableArgs, DoctorAgent, DoctorArgs, EnableArgs, SettingsScope, SetupAgent, SetupArgs, + StopArgs, TraceArgs, TraceCommand, UpdateArgs, }; pub use trace_runtime::{ - run_trace, HostRouteSelection, RouteRequirements, TraceHostContext, TraceHostServices, + run_trace, run_trace_with_matches, HostRouteSelection, RouteRequirements, TraceHostContext, + TraceHostServices, }; pub use transcript_import::{import_transcript, import_transcripts, run_import, ImportTarget}; pub use translate::{ diff --git a/bt-daemon/src/managed_run/mod.rs b/bt-daemon/src/managed_run/mod.rs index 255eb95b..62ff613c 100644 --- a/bt-daemon/src/managed_run/mod.rs +++ b/bt-daemon/src/managed_run/mod.rs @@ -115,7 +115,11 @@ async fn run_traced_inner( if let Some(components) = args.parent { route.destination = Some(wire::TraceDestination::ParentSpan { components }); } - apply_run_span_plugins(&mut route, &args.plugin)?; + apply_run_span_plugins( + &mut route, + &args.plugin, + args.inherit && !args.no_inherit_plugins, + )?; let name = args.source.identity().id; let agent = registrar() .run @@ -305,8 +309,17 @@ impl ManagedRunRuntime { } } -fn apply_run_span_plugins(route: &mut SessionRoute, plugins: &[PathBuf]) -> anyhow::Result<()> { - route.span_plugins = resolve_span_plugin_paths(plugins)?; +fn apply_run_span_plugins( + route: &mut SessionRoute, + plugins: &[PathBuf], + append: bool, +) -> anyhow::Result<()> { + let resolved = resolve_span_plugin_paths(plugins)?; + if append { + route.span_plugins.extend(resolved); + } else { + route.span_plugins = resolved; + } Ok(()) } @@ -365,7 +378,7 @@ mod tests { } #[test] - fn managed_run_plugins_replace_inherited_plugins() { + fn managed_run_plugins_append_or_replace_inherited_plugins() { let temp = tempfile::tempdir().unwrap(); let plugin = temp.path().join("run.mjs"); std::fs::write(&plugin, "export default span => span").unwrap(); @@ -374,11 +387,19 @@ mod tests { ..SessionRoute::default() }; - apply_run_span_plugins(&mut route, &[]).unwrap(); - assert!(route.span_plugins.is_empty()); + apply_run_span_plugins(&mut route, std::slice::from_ref(&plugin), true).unwrap(); + assert_eq!( + route.span_plugins, + [ + PathBuf::from("persisted.mjs"), + plugin.canonicalize().unwrap() + ] + ); - apply_run_span_plugins(&mut route, std::slice::from_ref(&plugin)).unwrap(); + apply_run_span_plugins(&mut route, std::slice::from_ref(&plugin), false).unwrap(); assert_eq!(route.span_plugins, [plugin.canonicalize().unwrap()]); + apply_run_span_plugins(&mut route, &[], false).unwrap(); + assert!(route.span_plugins.is_empty()); } fn test_run_hook_command() -> RunHookCommand { @@ -392,6 +413,8 @@ mod tests { async fn managed_run_rejects_a_missing_destination_before_launch() { let error = run_traced( RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, @@ -412,6 +435,8 @@ mod tests { async fn codex_managed_run_rejects_global_hook_trust_bypass_before_launch() { let error = run_traced( RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, diff --git a/bt-daemon/src/paths.rs b/bt-daemon/src/paths.rs index adf3962c..1e48d471 100644 --- a/bt-daemon/src/paths.rs +++ b/bt-daemon/src/paths.rs @@ -25,6 +25,44 @@ fn home() -> PathBuf { .unwrap_or_else(|| PathBuf::from(".")) } +/// Locate a repository root from the invocation directory. +pub(crate) fn repository_root(start: &Path) -> anyhow::Result { + start + .ancestors() + .find(|dir| dir.join(".git").exists()) + .map(Path::to_path_buf) + .ok_or_else(|| { + anyhow::anyhow!( + "project scope requires a Git repository (starting at {})", + start.display() + ) + }) +} + +/// Whether a source can load shared repository tracing settings. +pub(crate) fn supports_project_settings(source: &str) -> bool { + matches!( + source, + "claude" + | "claude-code" + | "cursor" + | "opencode" + | "pi" + | "codex" + | "muse" + | "muse-code" + | "grok" + | "antigravity" + ) +} + +pub(crate) fn project_settings_path(source: &str, start: &Path) -> anyhow::Result { + if !supports_project_settings(source) { + anyhow::bail!("project scope is not supported for {source}"); + } + Ok(repository_root(start)?.join(".braintrust.json")) +} + /// Resolve the socket path: explicit `override` → `$BRAINTRUST_DAEMON_SOCKET` → /// `$XDG_RUNTIME_DIR/braintrust/daemon.sock` → `~/.braintrust/run/daemon.sock`. pub fn socket_path(explicit: Option<&Path>) -> PathBuf { diff --git a/bt-daemon/src/server/auth.rs b/bt-daemon/src/server/auth.rs index e1be30fe..5b9a1748 100644 --- a/bt-daemon/src/server/auth.rs +++ b/bt-daemon/src/server/auth.rs @@ -86,7 +86,7 @@ impl Daemon { .ok_or_else(|| anyhow::anyhow!("event is missing its session route"))?; if requested_route.destination.is_none() { anyhow::bail!( - "session route is missing its trace destination; select a project or destination during `bt trace setup` or `bt trace run`" + "session route is missing its trace destination; select a project or destination during `bt trace install` or `bt trace run`" ); } let requested_key = DeliveryKey::new(&env.source, &env.session_id, &requested_route)?; diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 45873b14..cf31cdce 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -1,20 +1,40 @@ //! Per-agent, non-credential tracing settings. //! -//! Every coding agent owns an independent persistent file with the same schema. +//! Every coding agent has an independent user file; a repository can overlay +//! them all with one shared `.braintrust.json`. //! Authentication and backend URLs deliberately stay with the embedding `bt` //! CLI. `bt trace run` overlays invocation settings without mutating any //! persistent agent configuration. use crate::paths; -use crate::wire::SessionRoute; +use crate::wire::{AuthSource, SessionRoute, TraceDestination}; +use anyhow::Context; 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"; +/// Recursively overlay objects and append arrays; scalar values replace. +pub(crate) fn merge_json(base: &mut Value, overlay: Value) { + match (base, overlay) { + (Value::Object(base), Value::Object(overlay)) => { + for (key, value) in overlay { + match base.get_mut(&key) { + Some(existing) => merge_json(existing, value), + None => { + base.insert(key, value); + } + } + } + } + (Value::Array(base), Value::Array(overlay)) => base.extend(overlay), + (base, overlay) => *base = overlay, + } +} + /// Non-secret settings scoped to one `bt trace run` process tree. #[derive(Debug, Serialize, Deserialize)] pub(crate) struct InvocationSettings { @@ -38,15 +58,183 @@ 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()) + } + + /// Resolve persistent settings for commands running in a repository. + pub(crate) fn load_for_directory( + source: &str, + cwd: &Path, + ) -> anyhow::Result<(Self, Option)> { + let user = paths::agent_settings_path(source, None); + let project = paths::project_settings_path(source, cwd) + .ok() + .filter(|path| path.is_file()); + let settings = if project.is_some() { + Self::load_hook_with_project(&user, project.as_deref(), None)? + } else if user.exists() { + Self::load_hook_from_sources(&user, None)? + } else { + Self::default() + }; + Ok((settings, project)) + } + + 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()) + })?; + let mut settings = if user_path.exists() { + Self::load_hook_from_sources(user_path, None)? + } else { + Self::default() + }; + let inherit_plugins = object + .get("inherit_plugins") + .map(|value| { + value.as_bool().ok_or_else(|| { + anyhow::anyhow!("inherit_plugins in {} must be a boolean", path.display()) + }) + }) + .transpose()? + .unwrap_or(true); + if !inherit_plugins { + if let Some(route) = &mut settings.route { + route.span_plugins.clear(); + } + } + if let Some(project_route) = object.get("route") { + let project_route = project_route.as_object().ok_or_else(|| { + anyhow::anyhow!("project route in {} must be an object", path.display()) + })?; + let mut project_route = project_route.clone(); + if let Some(plugins) = project_route.get("span_plugins") { + let plugins: Vec = serde_json::from_value(plugins.clone()) + .with_context(|| format!("invalid span plugins at {}", path.display()))?; + let directory = path + .parent() + .ok_or_else(|| anyhow::anyhow!("project settings path has no parent"))?; + let plugins: Vec = plugins + .into_iter() + .map(|plugin| { + let full = if plugin.is_absolute() { + plugin + } else { + directory.join(plugin) + }; + std::fs::canonicalize(&full).unwrap_or(full) + }) + .collect(); + project_route.insert("span_plugins".into(), serde_json::to_value(plugins)?); + } + let mut route = serde_json::to_value(settings.route.take().unwrap_or_default())?; + if project_route + .get("auth") + .and_then(Value::as_object) + .is_some_and(|auth| { + auth.contains_key("profile") && !auth.contains_key("profile_id") + }) + { + if let Some(auth) = route.get_mut("auth").and_then(Value::as_object_mut) { + auth.remove("profile_id"); + auth.insert("source".into(), Value::String("saved_profile".into())); + } + } + if project_route + .get("destination") + .and_then(Value::as_object) + .is_some_and(|destination| { + destination.contains_key("project_name") + && !destination.contains_key("project_id") + }) + { + if let Some(destination) = + route.get_mut("destination").and_then(Value::as_object_mut) + { + destination.remove("project_id"); + } + } + merge_json(&mut route, Value::Object(project_route)); + settings.route = Some( + serde_json::from_value(route) + .with_context(|| format!("invalid project route at {}", path.display()))?, + ); + } + if let Some(value) = object.get("trace_to_braintrust") { + settings.trace_to_braintrust = Some(serde_json::from_value(value.clone())?); + } + 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()), + }); + } + for (field, is_profile) in [("profile", true), ("org_name", false)] { + if let Some(value) = object.get(field) { + let value = value + .as_str() + .filter(|s| !s.trim().is_empty()) + .ok_or_else(|| { + anyhow::anyhow!("{field} in {} must be a nonempty string", path.display()) + })?; + let route = settings.route.get_or_insert_with(SessionRoute::default); + if is_profile { + route.auth.source = AuthSource::SavedProfile; + route.auth.profile_id = None; + route.auth.profile = Some(value.to_owned()); + } else { + route.auth.org_name = Some(value.to_owned()); + } + } + } + if let Some(tags) = object.get("tags") { + let tags: std::collections::BTreeSet = serde_json::from_value(tags.clone()) + .with_context(|| format!("invalid project tags at {}", path.display()))?; + settings + .route + .get_or_insert_with(SessionRoute::default) + .tags + .extend(tags); + } + if let Some(metadata) = object.get("additional_metadata") { + if !metadata.is_object() { + anyhow::bail!("project metadata at {} must be an object", path.display()); + } + let route = settings.route.get_or_insert_with(SessionRoute::default); + match &mut route.additional_metadata { + Some(existing) => merge_json(existing, metadata.clone()), + None => route.additional_metadata = Some(metadata.clone()), + } + } + Ok(settings) } fn load_hook_from_sources(path: &Path, invocation: Option<&str>) -> anyhow::Result { @@ -74,14 +262,7 @@ impl AgentSettings { Ok(settings) } - pub(crate) fn load(source: &str) -> Self { - let invocation = std::env::var(INVOCATION_SETTINGS_ENV).ok(); - Self::load_from_sources( - &paths::agent_settings_path(source, None), - invocation.as_deref(), - ) - } - + #[cfg(test)] fn load_from_sources(path: &Path, invocation: Option<&str>) -> Self { let mut settings = Self::load_from(path); if let Some(raw) = invocation { @@ -102,6 +283,7 @@ impl AgentSettings { settings } + #[cfg(test)] fn load_from(path: &Path) -> Self { let raw = match std::fs::read_to_string(path) { Ok(raw) => raw, @@ -125,6 +307,51 @@ impl AgentSettings { } } +fn project_settings_path(source: &str, payload: &Value) -> Option { + if !paths::supports_project_settings(source) { + return None; + } + let roots: Vec<&str> = match source { + "cursor" => payload + .get("workspace_roots") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(), + "antigravity" => payload + .get("workspacePaths") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(), + _ => payload + .get("cwd") + .and_then(Value::as_str) + .into_iter() + .collect(), + }; + if roots.is_empty() { + let current = std::env::current_dir().ok()?; + let root = paths::repository_root(¤t).ok()?; + let candidate = root.join(".braintrust.json"); + return candidate.is_file().then_some(candidate); + } + for root in roots { + let path = Path::new(root); + if !path.is_absolute() { + continue; + } + let root = paths::repository_root(path).unwrap_or_else(|_| path.to_path_buf()); + let candidate = root.join(".braintrust.json"); + if candidate.is_file() { + return Some(candidate); + } + } + None +} + /// 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( @@ -175,12 +402,36 @@ pub(crate) fn with_settings_lock( .parent() .ok_or_else(|| anyhow::anyhow!("configuration path has no parent: {}", path.display()))?; std::fs::create_dir_all(parent)?; - let lock_path = path.with_extension(format!( - "{}lock", - path.extension() - .and_then(|extension| extension.to_str()) - .unwrap_or_default() - )); + let sibling_lock = || { + path.with_extension(format!( + "{}lock", + path.extension() + .and_then(|extension| extension.to_str()) + .unwrap_or_default() + )) + }; + // Keep repository locks out of the working tree. Worktrees use a .git file + // pointing to their own Git directory; ordinary repositories use a directory. + let lock_path = if path + .file_name() + .is_some_and(|name| name == ".braintrust.json") + { + let git = parent.join(".git"); + let git_dir = if git.is_dir() { + Some(git.clone()) + } else { + std::fs::read_to_string(&git) + .ok() + .and_then(|contents| contents.trim().strip_prefix("gitdir: ").map(str::to_owned)) + .map(|directory| parent.join(directory)) + .filter(|directory| directory.is_dir()) + }; + git_dir + .map(|directory| directory.join("braintrust-config.lock")) + .unwrap_or_else(sibling_lock) + } else { + sibling_lock() + }; let lock = std::fs::OpenOptions::new() .create(true) .read(true) @@ -210,6 +461,285 @@ 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}"#).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(); + let loaded = AgentSettings::load_hook_with_project(&user, Some(&project), None).unwrap(); + assert_eq!( + loaded.route.unwrap().span_plugins, + [temp.path().join("./malicious.js")] + ); + std::fs::write(&project, "invalid").unwrap(); + assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); + } + + #[test] + fn project_route_recursively_overlays_user_settings() { + 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":{"auth":{"profile_id":"old","org_name":"org"},"destination":{"type":"project_logs","project_id":"old","project_name":"global"},"tags":["user"],"span_plugins":["trusted"],"additional_metadata":{"nested":{"one":1,"two":2},"list":[1,2]}}}"#).unwrap(); + std::fs::write(&project, r#"{"trace_to_braintrust":true,"route":{"auth":{"profile":"local"},"destination":{"project_name":"new"},"tags":["project"],"span_plugins":[],"additional_metadata":{"nested":{"two":3},"list":[4]}}}"#).unwrap(); + let route = AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap(); + assert_eq!(route.span_plugins, [PathBuf::from("trusted")]); + assert_eq!(route.auth.profile_id, None); + assert_eq!(route.auth.profile.as_deref(), Some("local")); + assert_eq!(route.auth.org_name.as_deref(), Some("org")); + assert!( + matches!(route.destination, Some(TraceDestination::ProjectLogs { project_id: None, project_name: Some(ref name) }) if name == "new") + ); + assert_eq!( + route.tags.into_iter().collect::>(), + ["project", "user"] + ); + assert_eq!( + route.additional_metadata, + Some(serde_json::json!({"nested":{"one":1,"two":3},"list":[1,2,4]})) + ); + } + + #[test] + fn project_settings_locks_stay_in_git_metadata_for_repos_and_worktrees() { + for worktree in [false, true] { + let temp = tempfile::tempdir().unwrap(); + let repo = temp.path().join("repo"); + let metadata = if worktree { + temp.path().join("worktree-git") + } else { + repo.join(".git") + }; + std::fs::create_dir_all(&metadata).unwrap(); + if worktree { + std::fs::create_dir_all(&repo).unwrap(); + std::fs::write( + repo.join(".git"), + format!("gitdir: {}\n", metadata.display()), + ) + .unwrap(); + } + let path = repo.join(".braintrust.json"); + with_settings_lock(&path, || { + std::fs::write(&path, "{}")?; + Ok(()) + }) + .unwrap(); + assert!(metadata.join("braintrust-config.lock").exists()); + assert!(!repo.join(".braintrust.jsonlock").exists()); + } + } + + #[test] + fn project_plugins_append_in_order_or_replace_the_user_chain() { + let temp = tempfile::tempdir().unwrap(); + let user = temp.path().join("user.json"); + let project = temp.path().join(".braintrust.json"); + let plugin = temp.path().join("plugin.mjs"); + std::fs::write(&plugin, "export default span => span").unwrap(); + std::fs::write( + &user, + r#"{"trace_to_braintrust":true,"route":{"span_plugins":["user.mjs"]}}"#, + ) + .unwrap(); + std::fs::write(&project, r#"{"route":{"span_plugins":["./plugin.mjs"]}}"#).unwrap(); + let route = AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap(); + assert_eq!( + route.span_plugins, + [PathBuf::from("user.mjs"), plugin.canonicalize().unwrap()] + ); + std::fs::write( + &project, + r#"{"inherit_plugins":false,"route":{"span_plugins":["./plugin.mjs"]}}"#, + ) + .unwrap(); + let route = AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap(); + assert_eq!(route.span_plugins, [plugin.canonicalize().unwrap()]); + std::fs::write(&project, r#"{"inherit_plugins":false}"#).unwrap(); + assert!( + AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap() + .span_plugins + .is_empty() + ); + } + + #[test] + fn resolved_project_plugin_runs_after_user_plugin() { + use crate::translate::{SpanOp, SpanRow}; + let temp = tempfile::tempdir().unwrap(); + let user_config = temp.path().join("user.json"); + let project_config = temp.path().join(".braintrust.json"); + let user_plugin = temp.path().join("user.mjs"); + let project_plugin = temp.path().join("project.mjs"); + std::fs::write( + &user_plugin, + "export default span => ({...span, name: `${span.name}:user`})", + ) + .unwrap(); + std::fs::write( + &project_plugin, + "export default span => ({...span, name: `${span.name}:project`})", + ) + .unwrap(); + std::fs::write( + &user_config, + serde_json::json!({"trace_to_braintrust":true,"route":{"span_plugins":[user_plugin]}}) + .to_string(), + ) + .unwrap(); + let row = SpanOp::Insert(SpanRow { + span_id: "span".into(), + root_span_id: "root".into(), + name: "start".into(), + ..Default::default() + }); + for (inherit, expected) in [(true, "start:user:project"), (false, "start:project")] { + std::fs::write(&project_config, serde_json::json!({"inherit_plugins":inherit,"route":{"span_plugins":["./project.mjs"]}}).to_string()).unwrap(); + let route = + AgentSettings::load_hook_with_project(&user_config, Some(&project_config), None) + .unwrap() + .route + .unwrap(); + let result = + crate::span_processor::process(&route.span_plugins, &row, "claude", "test") + .unwrap(); + let Some(SpanOp::Insert(row)) = result.op else { + panic!("plugins did not produce a span") + }; + assert_eq!(row.name, expected); + } + } + + #[test] + fn project_fields_inherit_and_override_the_user_route() { + 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":{"auth":{"source":"environment","profile_id":"old","org_name":"org"},"destination":{"type":"project_logs","project_name":"global"},"tags":["user"],"additional_metadata":{"origin":"user"},"span_plugins":["trusted.js"]}}"#).unwrap(); + std::fs::write( + &project, + r#"{"trace_to_braintrust":true,"profile":"new","project":"local"}"#, + ) + .unwrap(); + let settings = AgentSettings::load_hook_with_project(&user, Some(&project), None).unwrap(); + assert!(settings.tracing_enabled()); + let route = settings.route.unwrap(); + assert_eq!(route.auth.source, AuthSource::SavedProfile); + assert_eq!(route.auth.profile.as_deref(), Some("new")); + assert_eq!(route.auth.profile_id, None); + assert_eq!(route.auth.org_name.as_deref(), Some("org")); + assert!( + matches!(route.destination, Some(TraceDestination::ProjectLogs { project_name: Some(ref name), .. }) if name == "local") + ); + assert!(route.tags.contains("user")); + assert_eq!( + route.additional_metadata, + Some(serde_json::json!({"origin":"user"})) + ); + assert_eq!(route.span_plugins, vec![PathBuf::from("trusted.js")]); + } + + #[test] + fn finds_one_shared_repository_file_for_every_agent() { + 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(); + std::fs::create_dir(repo.join(".claude")).unwrap(); + std::fs::write(repo.join(".claude/braintrust.json"), "{}").unwrap(); + assert!(project_settings_path("claude", &serde_json::json!({"cwd": nested})).is_none()); + let path = repo.join(".braintrust.json"); + std::fs::write(&path, "{}").unwrap(); + for source in [ + "claude", + "cursor", + "codex", + "muse", + "grok", + "antigravity", + "pi", + "opencode", + ] { + let payload = match source { + "cursor" => serde_json::json!({"workspace_roots": [nested]}), + "antigravity" => serde_json::json!({"workspacePaths": [nested]}), + _ => serde_json::json!({"cwd": nested}), + }; + assert_eq!(project_settings_path(source, &payload), Some(path.clone())); + } + 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/setup/antigravity.rs b/bt-daemon/src/setup/antigravity.rs index 361751c8..79dafa97 100644 --- a/bt-daemon/src/setup/antigravity.rs +++ b/bt-daemon/src/setup/antigravity.rs @@ -79,7 +79,7 @@ fn update_at(runner: &mut dyn CommandRunner, config_dir: &Path) -> anyhow::Resul }); if !installed { bail!( - "Google Antigravity tracing plugin is not installed; run `bt trace enable antigravity`" + "Google Antigravity tracing plugin is not installed; run `bt trace install antigravity`" ); } runner.run_in_home("agy", &["plugin", "install", PLUGIN_SOURCE], home) diff --git a/bt-daemon/src/setup/claude.rs b/bt-daemon/src/setup/claude.rs index 0968e395..1212065c 100644 --- a/bt-daemon/src/setup/claude.rs +++ b/bt-daemon/src/setup/claude.rs @@ -64,7 +64,7 @@ impl Setup for Claude { fn update(&self, runner: &mut dyn CommandRunner) -> anyhow::Result<()> { if installed_plugin(&list_plugins(runner)?).is_none() { - bail!("Claude Code tracing plugin is not installed; run `bt trace enable claude`"); + bail!("Claude Code tracing plugin is not installed; run `bt trace install claude`"); } MARKETPLACE.refresh_published(runner, "Claude Code", "claude")?; runner.run("claude", &["plugin", "update", PLUGIN]) @@ -260,7 +260,7 @@ mod tests { assert_eq!( error, - "Claude Code tracing marketplace is not the published Braintrust marketplace; run `bt trace enable claude`" + "Claude Code tracing marketplace is not the published Braintrust marketplace; run `bt trace install claude`" ); assert!(!runner.called("claude plugin marketplace update braintrust-claude-plugin")); } diff --git a/bt-daemon/src/setup/common.rs b/bt-daemon/src/setup/common.rs index f9471094..78b47f17 100644 --- a/bt-daemon/src/setup/common.rs +++ b/bt-daemon/src/setup/common.rs @@ -133,7 +133,7 @@ impl Marketplace { /// Refresh the marketplace, which must already be the published one. /// `display_name` and `agent` phrase the error that tells the user to - /// run `bt trace enable ` instead. + /// run `bt trace install ` instead. pub fn refresh_published( &self, runner: &mut dyn CommandRunner, @@ -143,12 +143,12 @@ impl Marketplace { let marketplaces = self.list(runner)?; let marketplace = (self.find)(&marketplaces).ok_or_else(|| { anyhow::anyhow!( - "{display_name} tracing marketplace is not installed; run `bt trace enable {agent}`" + "{display_name} tracing marketplace is not installed; run `bt trace install {agent}`" ) })?; if !(self.is_published)(marketplace) { bail!( - "{display_name} tracing marketplace is not the published Braintrust marketplace; run `bt trace enable {agent}`" + "{display_name} tracing marketplace is not the published Braintrust marketplace; run `bt trace install {agent}`" ); } runner.run( diff --git a/bt-daemon/src/setup/cursor/mod.rs b/bt-daemon/src/setup/cursor/mod.rs index 63797b6a..030a2708 100644 --- a/bt-daemon/src/setup/cursor/mod.rs +++ b/bt-daemon/src/setup/cursor/mod.rs @@ -130,7 +130,7 @@ impl Setup for Cursor { fn activation_warning(&self) -> Option<&'static str> { (!capture_hooks_are_installed_at(&paths::cursor_config_dir())) - .then_some("Cursor user capture hooks are missing; run `bt trace enable cursor`") + .then_some("Cursor user capture hooks are missing; run `bt trace install cursor`") } } @@ -271,14 +271,14 @@ fn remove_plugin_at(plugin_dir: &Path) -> anyhow::Result<()> { fn update_plugin_at(runner: &mut dyn CommandRunner, plugin_dir: &Path) -> anyhow::Result<()> { const NOT_INSTALLED: &str = - "Cursor tracing plugin is not installed; run `bt trace enable cursor`"; + "Cursor tracing plugin is not installed; run `bt trace install cursor`"; if !plugin_dir.exists() { bail!(NOT_INSTALLED); } ensure_ours( plugin_dir, NOT_INSTALLED, - "Cursor tracing plugin is not the Braintrust plugin; run `bt trace enable cursor`", + "Cursor tracing plugin is not the Braintrust plugin; run `bt trace install cursor`", )?; install_plugin_at(runner, plugin_dir) } diff --git a/bt-daemon/src/setup/grok.rs b/bt-daemon/src/setup/grok.rs index 1d1272fa..a3c42275 100644 --- a/bt-daemon/src/setup/grok.rs +++ b/bt-daemon/src/setup/grok.rs @@ -29,7 +29,7 @@ fn list_plugins(runner: &mut dyn CommandRunner) -> anyhow::Result { impl Setup for Grok { fn enable(&self, runner: &mut dyn CommandRunner) -> anyhow::Result<()> { let plugins = list_plugins(runner)?; - // `bt trace enable grok` is the user's trust boundary. Grok's `--trust` + // `bt trace install grok` is the user's trust boundary. Grok's `--trust` // applies to this plugin installation and does not change folder trust. match installed_plugin(&plugins) { Some(plugin) if is_published(plugin) => { @@ -54,11 +54,11 @@ impl Setup for Grok { fn update(&self, runner: &mut dyn CommandRunner) -> anyhow::Result<()> { let plugins = list_plugins(runner)?; let plugin = installed_plugin(&plugins).ok_or_else(|| { - anyhow::anyhow!("Grok tracing plugin is not installed; run `bt trace enable grok`") + anyhow::anyhow!("Grok tracing plugin is not installed; run `bt trace install grok`") })?; if !is_published(plugin) { bail!( - "Grok tracing plugin is not the published Braintrust plugin; run `bt trace enable grok`" + "Grok tracing plugin is not the published Braintrust plugin; run `bt trace install grok`" ); } runner.run("grok", &["plugin", "update", PLUGIN]) diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index d751f4bd..36e8f410 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -16,7 +16,7 @@ pub(crate) mod pi; use crate::agents::{registrar, Agent}; use crate::paths; -use crate::trace_command::{EnableArgs, SetupAgent}; +use crate::trace_command::{SettingsScope, SetupAgent, SetupArgs}; use crate::wire::SessionRoute; use crate::TraceCommandOutput; use anyhow::Context; @@ -62,33 +62,267 @@ pub(crate) fn update_warning(source: &str) -> Option { stale.then(|| format!("tracing plugin is out of date; run `bt trace update {source}`")) } +fn scoped_path(agent: SetupAgent, scope: SettingsScope) -> anyhow::Result { + let source = agent.identity().id; + match scope { + SettingsScope::User => Ok(paths::agent_settings_path(source, None)), + SettingsScope::Project => paths::project_settings_path(source, &std::env::current_dir()?), + } +} + +pub(crate) fn run_scoped_toggle( + agent: SetupAgent, + scope: SettingsScope, + enabled: bool, +) -> anyhow::Result { + let path = scoped_path(agent, scope)?; + let existed = path.exists(); + common::edit_object(&path, FileAccess::OwnerOnly, |settings, _| { + settings.insert("trace_to_braintrust".into(), Value::Bool(enabled)); + Ok(()) + })?; + let id = agent.identity(); + Ok((if enabled { + let output = TraceCommandOutput::enable(id.id, id.display_name, path); + if existed { + output + } else { + output.into_enable("created") + } + } else { + TraceCommandOutput::disable(id.id, id.display_name, path) + }) + .with_scope(match scope { + SettingsScope::User => "user", + SettingsScope::Project => "project", + })) +} + +/// Remove the shared repository configuration without touching user installations. +pub(crate) fn run_project_uninstall(agent: SetupAgent) -> anyhow::Result { + let path = scoped_path(agent, SettingsScope::Project)?; + crate::settings::with_settings_lock(&path, || remove_tracing_settings(&path))?; + let id = agent.identity(); + Ok(TraceCommandOutput::uninstall(id.id, id.display_name, path).with_scope("project")) +} + +pub(crate) fn run_project_setup( + args: SetupArgs, + selection: crate::HostRouteSelection, + as_enable: bool, +) -> anyhow::Result { + let path = scoped_path(args.agent, SettingsScope::Project)?; + let existed = path.exists(); + write_project_setup_at(&path, &args, &selection)?; + let id = args.agent.identity(); + let output = TraceCommandOutput::project_install(id.id, id.display_name, path) + .with_enabled(!args.disable); + Ok(if as_enable { + output.into_enable(if existed { "updated" } else { "created" }) + } else { + output + }) +} + +fn write_project_setup_at( + path: &Path, + args: &SetupArgs, + selection: &crate::HostRouteSelection, +) -> anyhow::Result<()> { + let root = path + .parent() + .ok_or_else(|| anyhow::anyhow!("project settings path has no parent"))?; + let root = root.canonicalize()?; + let plugins = args + .plugin + .iter() + .map(|plugin| { + let absolute = if plugin.is_absolute() { + plugin.clone() + } else { + root.join(plugin) + }; + let absolute = absolute + .canonicalize() + .with_context(|| format!("could not resolve span plugin {}", absolute.display()))?; + let relative = absolute.strip_prefix(&root).map_err(|_| { + anyhow::anyhow!( + "project span plugin {} must be inside the repository", + absolute.display() + ) + })?; + Ok((absolute.clone(), relative.to_path_buf())) + }) + .collect::>>()?; + if !plugins.is_empty() { + crate::span_processor::validate( + &plugins + .iter() + .map(|(absolute, _)| absolute.clone()) + .collect::>(), + )?; + } + common::edit_object(path, FileAccess::OwnerOnly, |settings, _| { + settings.insert("trace_to_braintrust".into(), Value::Bool(!args.disable)); + for (key, value) in [ + ("project", selection.project_name.as_deref()), + ("profile", selection.auth.profile.as_deref()), + ("org_name", selection.auth.org_name.as_deref()), + ] { + if let Some(value) = value { + settings.insert(key.into(), Value::String(value.to_owned())); + } + } + if args.no_inherit_plugins { + settings.insert("inherit_plugins".into(), Value::Bool(false)); + } + if args.inherit_plugins { + settings.insert("inherit_plugins".into(), Value::Bool(true)); + } + if !plugins.is_empty() { + let route = settings + .entry("route") + .or_insert_with(|| Value::Object(Default::default())); + let route = route + .as_object_mut() + .ok_or_else(|| anyhow::anyhow!("project route must be an object"))?; + route.insert( + "span_plugins".into(), + serde_json::to_value( + plugins + .iter() + .map(|(_, relative)| { + relative + .to_string_lossy() + .replace(std::path::MAIN_SEPARATOR, "/") + }) + .collect::>(), + )?, + ); + } + if let Some(metadata) = args.additional_metadata.as_deref() { + let parsed: Value = serde_json::from_str(metadata)?; + if !parsed.is_object() { + anyhow::bail!("additional metadata must be a JSON object"); + } + settings.insert("additional_metadata".into(), parsed); + } + if !args.tags.is_empty() { + settings.insert("tags".into(), serde_json::to_value(&args.tags)?); + } + Ok(()) + })?; + Ok(()) +} + /// Install or refresh one agent's published tracing adapter and persist its /// non-secret route selection. -pub fn run_enable(args: EnableArgs, route: SessionRoute) -> anyhow::Result { +pub fn run_setup(args: SetupArgs, route: SessionRoute) -> anyhow::Result { let agent = adapter(args.agent); agent.enable(&mut SystemCommandRunner)?; let identity = agent.identity(); - let settings_path = enable_tracing(identity.id, route)?; - Ok(TraceCommandOutput::setup( + let settings_path = enable_tracing(identity.id, route, !args.disable, args.no_inherit_plugins)?; + Ok( + TraceCommandOutput::install(identity.id, identity.display_name, settings_path) + .with_enabled(!args.disable), + ) +} + +/// Check whether there is a usable saved configuration, without overwriting errors. +pub(crate) fn has_saved_setup(agent: SetupAgent) -> anyhow::Result { + let path = paths::agent_settings_path(agent.identity().id, None); + saved_setup_at(&path) +} + +fn saved_setup_at(path: &Path) -> anyhow::Result { + let raw = match std::fs::read_to_string(path) { + Ok(raw) => raw, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(e) => return Err(e).with_context(|| format!("failed to read {}", path.display())), + }; + let value: Value = serde_json::from_str(&raw) + .with_context(|| format!("invalid tracing settings at {}", path.display()))?; + let object = value.as_object().ok_or_else(|| { + anyhow::anyhow!("tracing settings at {} must be an object", path.display()) + })?; + if !object + .get("trace_to_braintrust") + .is_some_and(Value::is_boolean) + { + anyhow::bail!( + "tracing settings at {} have no valid `trace_to_braintrust`", + path.display() + ); + } + if let Some(route) = object.get("route") { + let _: SessionRoute = serde_json::from_value(route.clone()) + .with_context(|| format!("invalid tracing route at {}", path.display()))?; + } + Ok(!(object.len() == 1 && object.get("trace_to_braintrust") == Some(&Value::Bool(false)))) +} + +/// Resume tracing without reinstalling the adapter or replacing its route. +pub fn run_enable(agent: SetupAgent) -> anyhow::Result { + let identity = agent.identity(); + let path = paths::agent_settings_path(identity.id, None); + enable_existing_at(&path)?; + Ok(TraceCommandOutput::enable( identity.id, identity.display_name, - settings_path, + path, )) } -/// Backwards-compatible library entry point for hosts that used the former setup name. -pub fn run_setup(args: EnableArgs, route: SessionRoute) -> anyhow::Result { - run_enable(args, route) +fn enable_existing_at(path: &Path) -> anyhow::Result<()> { + if !path.exists() { + anyhow::bail!( + "tracing is not configured at {}; run `bt trace install` first", + path.display() + ); + } + common::edit_object(path, FileAccess::OwnerOnly, |settings, exists| { + if !exists + || !settings + .get("trace_to_braintrust") + .is_some_and(Value::is_boolean) + { + anyhow::bail!( + "tracing is not configured at {}; run `bt trace install` first", + path.display() + ); + } + settings.insert("trace_to_braintrust".into(), Value::Bool(true)); + Ok(()) + }) } -/// Uninstall an agent's tracing adapter and remove its Braintrust-owned settings. +/// Disable tracing while retaining the installed adapter and saved route. pub fn run_disable(agent: SetupAgent) -> anyhow::Result { + let identity = agent.identity(); + let path = paths::agent_settings_path(identity.id, None); + disable_tracing_at(&path)?; + Ok(TraceCommandOutput::disable( + identity.id, + identity.display_name, + path, + )) +} + +fn disable_tracing_at(path: &Path) -> anyhow::Result<()> { + common::edit_object(path, FileAccess::OwnerOnly, |settings, _| { + settings.insert("trace_to_braintrust".into(), Value::Bool(false)); + Ok(()) + }) +} + +/// Uninstall an agent's tracing adapter and remove its Braintrust-owned settings. +pub fn run_uninstall(agent: SetupAgent) -> anyhow::Result { let agent = adapter(agent); let adapter_result = agent.disable(&mut SystemCommandRunner); let identity = agent.identity(); let settings_path = paths::agent_settings_path(identity.id, None); finish_disable(adapter_result, &settings_path)?; - Ok(TraceCommandOutput::disable( + Ok(TraceCommandOutput::uninstall( identity.id, identity.display_name, settings_path, @@ -107,16 +341,31 @@ pub fn run_update(agent: SetupAgent) -> anyhow::Result { )) } -fn enable_tracing(source: &str, route: SessionRoute) -> anyhow::Result { +fn enable_tracing( + source: &str, + route: SessionRoute, + enabled: bool, + replace_plugins: bool, +) -> anyhow::Result { let path = paths::agent_settings_path(source, None); - enable_tracing_at(&path, route)?; + write_tracing_at(&path, route, enabled, replace_plugins)?; Ok(path) } /// Write the route to an agent's Braintrust settings, keeping saved metadata, /// tags, and span plugins unless the new route replaces them, and dropping /// keys from earlier settings formats. -fn enable_tracing_at(path: &Path, mut route: SessionRoute) -> anyhow::Result<()> { +#[cfg(test)] +fn enable_tracing_at(path: &Path, route: SessionRoute) -> anyhow::Result<()> { + write_tracing_at(path, route, true, false) +} + +fn write_tracing_at( + path: &Path, + mut route: SessionRoute, + enabled: bool, + replace_plugins: bool, +) -> anyhow::Result<()> { let mut settings = load_object(path)?; if route.additional_metadata.is_none() { route.additional_metadata = settings @@ -140,14 +389,14 @@ fn enable_tracing_at(path: &Path, mut route: SessionRoute) -> anyhow::Result<()> }) .unwrap_or_default(); } - if route.span_plugins.is_empty() { + if route.span_plugins.is_empty() && !replace_plugins { route.span_plugins = settings .get("route") .and_then(|route| route.get("span_plugins")) .and_then(|plugins| serde_json::from_value(plugins.clone()).ok()) .unwrap_or_default(); } - settings.insert("trace_to_braintrust".into(), Value::Bool(true)); + settings.insert("trace_to_braintrust".into(), Value::Bool(enabled)); settings.insert("route".into(), serde_json::to_value(route)?); for key in [ "traceToBraintrust", @@ -203,6 +452,109 @@ mod tests { } } + #[test] + fn project_setup_writes_only_explicit_values_and_preserves_existing_fields() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join(".braintrust.json"); + let mut args = SetupArgs { + no_inherit_plugins: false, + inherit_plugins: false, + disable: false, + scope: SettingsScope::Project, + agent: SetupAgent::Claude, + additional_metadata: None, + tags: vec![], + plugin: vec![], + }; + write_project_setup_at(&path, &args, &crate::HostRouteSelection::default()).unwrap(); + let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(value, serde_json::json!({"trace_to_braintrust": true})); + args.tags = vec!["team".into()]; + args.additional_metadata = Some(r#"{"ci":true}"#.into()); + let selection = crate::HostRouteSelection { + project_name: Some("project".into()), + ..Default::default() + }; + write_project_setup_at(&path, &args, &selection).unwrap(); + let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!( + value, + serde_json::json!({"trace_to_braintrust": true,"project":"project","tags":["team"],"additional_metadata":{"ci":true}}) + ); + let plugins = temp.path().join("plugins"); + std::fs::create_dir(&plugins).unwrap(); + std::fs::write(plugins.join("redact.mjs"), "export default span => span").unwrap(); + args.plugin.push("plugins/redact.mjs".into()); + args.no_inherit_plugins = true; + write_project_setup_at(&path, &args, &selection).unwrap(); + let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!( + value["route"]["span_plugins"], + serde_json::json!(["plugins/redact.mjs"]) + ); + assert_eq!(value["inherit_plugins"], false); + args.no_inherit_plugins = false; + args.inherit_plugins = true; + write_project_setup_at(&path, &args, &selection).unwrap(); + let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(value["inherit_plugins"], true); + args.plugin.clear(); + args.plugin.push("bad.js".into()); + assert!(write_project_setup_at(&path, &args, &selection).is_err()); + assert_eq!( + serde_json::from_slice::(&std::fs::read(&path).unwrap()).unwrap(), + value + ); + } + + #[test] + fn disable_preserves_route_and_is_idempotent() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("braintrust.json"); + std::fs::write( + &path, + r#"{"trace_to_braintrust":true,"route":{"auth":{"profile":"saved-profile","org_name":"saved-org"},"destination":{"type":"project_logs","project_name":"saved-project"},"tags":["saved"],"span_plugins":["/tmp/plugin.js"]},"custom":1}"#, + ) + .unwrap(); + disable_tracing_at(&path).unwrap(); + disable_tracing_at(&path).unwrap(); + let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(value["trace_to_braintrust"], false); + assert_eq!(value["route"]["tags"][0], "saved"); + assert_eq!(value["custom"], 1); + enable_existing_at(&path).unwrap(); + let enabled: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(enabled["trace_to_braintrust"], true); + assert_eq!(enabled["route"], value["route"]); + assert_eq!(enabled["custom"], value["custom"]); + let missing = temp.path().join("missing/braintrust.json"); + assert!(enable_existing_at(&missing).is_err()); + assert!(!missing.exists()); + disable_tracing_at(&missing).unwrap(); + let created: Value = serde_json::from_slice(&std::fs::read(&missing).unwrap()).unwrap(); + assert_eq!(created["trace_to_braintrust"], false); + } + + #[test] + fn saved_setup_detection_preserves_errors_and_distinguishes_pause_only() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("braintrust.json"); + assert!(!saved_setup_at(&path).unwrap()); + disable_tracing_at(&path).unwrap(); + assert!(!saved_setup_at(&path).unwrap()); + std::fs::write(&path, r#"{"trace_to_braintrust":false,"route":{"destination":{"type":"project_logs","project_name":"saved"}}}"#).unwrap(); + assert!(saved_setup_at(&path).unwrap()); + std::fs::write(&path, "broken").unwrap(); + assert!(saved_setup_at(&path).is_err()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "broken"); + std::fs::write( + &path, + r#"{"trace_to_braintrust":true,"route":{"destination":"invalid"}}"#, + ) + .unwrap(); + assert!(saved_setup_at(&path).is_err()); + } + #[test] fn tracing_settings_preserve_unrelated_fields_and_remove_legacy_keys() { let temp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/setup/muse.rs b/bt-daemon/src/setup/muse.rs index 49fac6ad..0caaabae 100644 --- a/bt-daemon/src/setup/muse.rs +++ b/bt-daemon/src/setup/muse.rs @@ -181,7 +181,7 @@ fn update_muse_at(config_dir: &Path) -> anyhow::Result<()> { if !settings.hook_overlay()?.contains_braintrust_hook() && owned_managed_path(config_dir, &settings)?.is_none() { - bail!("Muse tracing hooks are not installed; run `bt trace enable muse`"); + bail!("Muse tracing hooks are not installed; run `bt trace install muse`"); } setup_muse_at(config_dir) } @@ -230,7 +230,7 @@ pub(crate) fn muse_doctor_warnings(config_dir: &Path) -> Vec { upgraded.remove_owned(); upgraded.append_owned(MUSE_HOOK_COMMAND); if current != upgraded { - warnings.push("Muse Braintrust hooks are missing or outdated; run `bt trace update muse` or `bt trace enable muse`".into()); + warnings.push("Muse Braintrust hooks are missing or outdated; run `bt trace update muse` or `bt trace install muse`".into()); } } } diff --git a/bt-daemon/src/setup/opencode.rs b/bt-daemon/src/setup/opencode.rs index 6ff644d7..acab192c 100644 --- a/bt-daemon/src/setup/opencode.rs +++ b/bt-daemon/src/setup/opencode.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; const PACKAGE: &str = "@braintrust/trace-opencode"; const PACKAGE_MANIFEST: &str = plugin_source!("opencode/content/package.json"); const NOT_INSTALLED: &str = - "OpenCode tracing plugin is not installed; run `bt trace enable opencode`"; + "OpenCode tracing plugin is not installed; run `bt trace install opencode`"; /// The plugin entry for the bundled major version, e.g. `…@^1`. fn plugin_spec() -> anyhow::Result { diff --git a/bt-daemon/src/trace_command.rs b/bt-daemon/src/trace_command.rs index cbe81fd2..f60915e4 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -20,11 +20,15 @@ pub struct TraceArgs { // clearer than boxing individual command variants for stack-size savings. #[allow(clippy::large_enum_variant)] pub enum TraceCommand { - /// Install or enable the published Braintrust tracing plugin for a coding agent. - #[command(name = "enable", alias = "setup")] - Setup(EnableArgs), - /// Uninstall the Braintrust tracing plugin and remove its saved configuration. + /// Install and configure the Braintrust tracing plugin for a coding agent. + #[command(visible_alias = "setup")] + Install(SetupArgs), + /// Enable tracing, setting it up when needed or when settings are supplied. + Enable(EnableArgs), + /// Disable tracing while preserving the plugin and its configuration. Disable(DisableArgs), + /// Uninstall the tracing plugin or remove the shared project configuration. + Uninstall(DisableArgs), /// Update an already installed Braintrust tracing plugin without changing its configuration. Update(UpdateArgs), /// Run the tracing daemon (foreground). @@ -91,32 +95,70 @@ impl DoctorAgent { } } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)] +pub enum SettingsScope { + #[default] + User, + Project, +} + #[derive(Debug, Clone, Args)] -pub struct EnableArgs { +pub struct SetupArgs { + /// Install with tracing disabled until explicitly enabled. + #[arg(long, global = true)] + pub disable: bool, + /// Where the tracing settings are stored. + #[arg(long, global = true, value_enum, default_value_t = SettingsScope::User)] + pub scope: SettingsScope, #[command(subcommand)] pub agent: SetupAgent, /// JSON object persisted in this agent's tracing route and merged into root-span metadata. - #[arg(long, global = true, env = "BRAINTRUST_ADDITIONAL_METADATA")] + #[arg(long, global = true)] pub additional_metadata: Option, /// Tag applied to each root span. May be repeated or comma-separated. - #[arg( - long = "tag", - global = true, - env = "BRAINTRUST_TAGS", - value_delimiter = ',' - )] + #[arg(long = "tag", global = true, value_delimiter = ',')] pub tags: Vec, + /// Replace inherited span plugins instead of appending to them. + #[arg(long, global = true, conflicts_with = "inherit_plugins")] + pub no_inherit_plugins: bool, + /// Restore inheritance of user-level span plugins. + #[arg(long, global = true)] + pub inherit_plugins: bool, /// JavaScript span transform to persist for this agent. Repeat to compose /// transforms in order. #[arg(long, global = true, value_name = "PATH")] pub plugin: Vec, } -/// Backwards-compatible API name for hosts that mounted the former setup command. -pub type SetupArgs = EnableArgs; +#[derive(Debug, Clone, Args)] +pub struct EnableArgs { + /// Where the tracing settings are stored. + #[arg(long, global = true, value_enum, default_value_t = SettingsScope::User)] + pub scope: SettingsScope, + #[command(subcommand)] + pub agent: SetupAgent, + /// JSON object merged into root-span metadata. + #[arg(long, global = true)] + pub additional_metadata: Option, + /// Tag applied to each root span. May be repeated or comma-separated. + #[arg(long = "tag", global = true, value_delimiter = ',')] + pub tags: Vec, + /// Replace inherited span plugins instead of appending to them. + #[arg(long, global = true, conflicts_with = "inherit_plugins")] + pub no_inherit_plugins: bool, + /// Restore inheritance of user-level span plugins. + #[arg(long, global = true)] + pub inherit_plugins: bool, + /// JavaScript span transform to persist. May be repeated. + #[arg(long, global = true, value_name = "PATH")] + pub plugin: Vec, +} #[derive(Debug, Clone, Args)] pub struct DisableArgs { + /// Where the tracing settings are stored. + #[arg(long, global = true, value_enum, default_value_t = SettingsScope::User)] + pub scope: SettingsScope, #[command(subcommand)] pub agent: SetupAgent, } @@ -179,7 +221,7 @@ mod tests { fn every_public_trace_ingress_accepts_additional_metadata() { let setup = Cli::try_parse_from([ "bt", - "setup", + "install", "claude", "--additional-metadata", r#"{"setup":true}"#, @@ -187,7 +229,7 @@ mod tests { .unwrap(); assert!(matches!( setup.trace.command, - TraceCommand::Setup(SetupArgs { + TraceCommand::Install(SetupArgs { agent: SetupAgent::Claude, additional_metadata: Some(ref value), .. @@ -197,7 +239,7 @@ mod tests { let legacy_setup = Cli::try_parse_from(["bt", "setup", "codex"]).unwrap(); assert!(matches!( legacy_setup.trace.command, - TraceCommand::Setup(SetupArgs { + TraceCommand::Install(SetupArgs { agent: SetupAgent::Codex, .. }) @@ -270,7 +312,7 @@ mod tests { Cli::try_parse_from(["bt", "setup", "claude", "--tag", "ci", "--tag", "docs"]).unwrap(); assert!(matches!( setup.trace.command, - TraceCommand::Setup(SetupArgs { ref tags, .. }) if tags.as_slice() == ["ci", "docs"] + TraceCommand::Install(SetupArgs { ref tags, .. }) if tags.as_slice() == ["ci", "docs"] )); let run = Cli::try_parse_from(["bt", "run", "codex", "--tag", "ci,docs", "--", "status"]) @@ -313,6 +355,7 @@ mod tests { assert!(matches!( parsed.trace.command, TraceCommand::Run(RunArgs { + inherit: false, source: crate::RunSource::Cursor, parent: Some(ref parent), ref agent_args, @@ -351,11 +394,11 @@ mod tests { #[test] fn antigravity_uses_shared_enable_and_disable_commands() { - for command in ["enable", "setup"] { - let parsed = Cli::try_parse_from(["bt", command, "antigravity"]).unwrap(); + { + let parsed = Cli::try_parse_from(["bt", "setup", "antigravity"]).unwrap(); assert!(matches!( parsed.trace.command, - TraceCommand::Setup(SetupArgs { + TraceCommand::Install(SetupArgs { agent: SetupAgent::Antigravity, .. }) @@ -366,20 +409,21 @@ mod tests { assert!(matches!( parsed.trace.command, TraceCommand::Disable(DisableArgs { - agent: SetupAgent::Antigravity + agent: SetupAgent::Antigravity, + .. }) )); - assert!(Cli::try_parse_from(["bt", "setup", "antigravity", "--disable"]).is_err()); + assert!(Cli::try_parse_from(["bt", "install", "antigravity", "--disable"]).is_ok()); } #[test] fn grok_uses_shared_enable_and_disable_commands() { - for command in ["enable", "setup"] { - let parsed = Cli::try_parse_from(["bt", command, "grok"]).unwrap(); + { + let parsed = Cli::try_parse_from(["bt", "setup", "grok"]).unwrap(); assert!(matches!( parsed.trace.command, - TraceCommand::Setup(SetupArgs { + TraceCommand::Install(SetupArgs { agent: SetupAgent::Grok, .. }) @@ -390,7 +434,86 @@ mod tests { assert!(matches!( parsed.trace.command, TraceCommand::Disable(DisableArgs { - agent: SetupAgent::Grok + agent: SetupAgent::Grok, + .. + }) + )); + } + + #[test] + fn scoped_commands_accept_project_before_or_after_agent() { + for command in ["install", "setup", "enable", "disable", "uninstall"] { + for args in [ + vec!["bt", command, "--scope", "project", "claude"], + vec!["bt", command, "claude", "--scope", "project"], + ] { + let parsed = Cli::try_parse_from(args).unwrap(); + let scope = match parsed.trace.command { + TraceCommand::Install(args) => args.scope, + TraceCommand::Enable(args) => args.scope, + TraceCommand::Disable(args) | TraceCommand::Uninstall(args) => args.scope, + _ => panic!("wrong command"), + }; + assert_eq!(scope, SettingsScope::Project); + } + } + } + + #[test] + fn project_plugin_inheritance_flags_are_exclusive() { + assert!(Cli::try_parse_from([ + "bt", + "install", + "claude", + "--scope", + "project", + "--no-inherit-plugins" + ]) + .is_ok()); + assert!(Cli::try_parse_from([ + "bt", + "enable", + "claude", + "--scope", + "project", + "--inherit-plugins" + ]) + .is_ok()); + assert!(Cli::try_parse_from([ + "bt", + "install", + "claude", + "--no-inherit-plugins", + "--inherit-plugins" + ]) + .is_err()); + assert!( + Cli::try_parse_from(["bt", "run", "codex", "--inherit", "--no-inherit-plugins"]) + .is_ok() + ); + } + + #[test] + fn enable_accepts_explicit_tracing_settings() { + let parsed = Cli::try_parse_from(["bt", "enable", "pi"]).unwrap(); + assert!(matches!( + parsed.trace.command, + TraceCommand::Enable(EnableArgs { + agent: SetupAgent::Pi, + .. + }) + )); + assert!(Cli::try_parse_from(["bt", "enable", "pi", "--tag", "changed"]).is_ok()); + } + + #[test] + fn uninstall_accepts_an_agent() { + let parsed = Cli::try_parse_from(["bt", "uninstall", "pi"]).unwrap(); + assert!(matches!( + parsed.trace.command, + TraceCommand::Uninstall(DisableArgs { + agent: SetupAgent::Pi, + .. }) )); } @@ -450,7 +573,7 @@ mod tests { ] { let parsed = Cli::try_parse_from(args).unwrap(); let plugins = match parsed.trace.command { - TraceCommand::Setup(args) => args.plugin, + TraceCommand::Install(args) => args.plugin, TraceCommand::Run(args) => args.plugin, TraceCommand::Import(args) => args.plugin, _ => unreachable!(), diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index f5709781..7a9eb9a8 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -6,7 +6,7 @@ //! the coding-agent integrations. use crate::route::{apply_additional_metadata, apply_tags, resolve_span_plugin_paths}; -use crate::trace_command::{DoctorAgent, DoctorArgs, SetupAgent, TraceCommand}; +use crate::trace_command::{DoctorAgent, DoctorArgs, SettingsScope, SetupAgent, TraceCommand}; use crate::wire::{AuthSelection, AuthSource, SessionConfig, SessionRoute, TraceDestination}; use crate::{ braintrust_serve_options, paths, run_disable, run_enable, run_import, run_serve, run_status, @@ -501,16 +501,63 @@ fn daemon_warnings( async fn doctor_output(host: &TraceHostContext, args: DoctorArgs) -> DoctorCommandOutput { let source = args.agent.identity().id; - let settings = crate::settings::AgentSettings::load(source); + let resolved = std::env::current_dir().and_then(|cwd| { + crate::settings::AgentSettings::load_for_directory(source, &cwd) + .map_err(std::io::Error::other) + }); + let (settings, project_path, error) = match resolved { + Ok((settings, path)) => (settings, path, None), + Err(error) => ( + crate::settings::AgentSettings::default(), + None, + Some(error.to_string()), + ), + }; let socket = paths::socket_path(None); - doctor_output_at( + let mut output = doctor_output_at( host, args, &socket, paths::agent_settings_path(source, None), settings, ) - .await + .await; + if let Some(path) = project_path { + fn collect_fields(prefix: &str, value: &serde_json::Value, fields: &mut Vec) { + if let Some(object) = value.as_object().filter(|object| !object.is_empty()) { + for (key, child) in object { + let name = if prefix.is_empty() { + key.clone() + } else { + format!("{prefix}.{key}") + }; + collect_fields(&name, child, fields); + } + } else { + fields.push(prefix.to_owned()); + } + } + if let Ok(raw) = std::fs::read_to_string(&path) { + if let Ok(value) = serde_json::from_str(&raw) { + collect_fields("", &value, &mut output.project_settings_fields); + } + } + output.project_settings_path = Some(path); + if output.route_source == "settings_file" { + output.route_source = if output.settings_present { + "user_and_project_settings" + } else { + "project_settings" + } + .into(); + } + } + if let Some(error) = error { + output + .warnings + .push(format!("effective settings could not be read: {error}")); + } + output } async fn doctor_output_at( @@ -527,7 +574,7 @@ async fn doctor_output_at( if !settings_present { warnings.push(format!( - "settings file is missing; run `bt trace enable {source}`" + "settings file is missing; run `bt trace install {source}`" )); } else if !enabled { warnings.push(format!( @@ -638,6 +685,8 @@ async fn doctor_output_at( display_name: args.agent.identity().display_name.into(), settings_path, settings_present, + project_settings_path: None, + project_settings_fields: Vec::new(), enabled, route_source, route, @@ -648,33 +697,180 @@ async fn doctor_output_at( } } +async fn run_install_command( + mut args: crate::SetupArgs, + host: &TraceHostContext, + configuration: Option<&'static str>, + explicit: &HostRouteSelection, +) -> anyhow::Result<()> { + if args.scope == SettingsScope::Project { + return print_output( + crate::setup::run_project_setup(args, explicit.clone(), configuration.is_some())?, + host.output_format, + ); + } + if args.additional_metadata.is_none() { + args.additional_metadata = crate::env::var("BRAINTRUST_ADDITIONAL_METADATA"); + } + if args.tags.is_empty() { + args.tags = crate::env::var("BRAINTRUST_TAGS") + .unwrap_or_default() + .split(',') + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect(); + } + let mut route = resolve_command_route( + host, + RouteRequirements { + destination_required: true, + interactive_auth: true, + persistent_auth: true, + }, + ) + .await?; + apply_additional_metadata(&mut route, args.additional_metadata.as_deref())?; + apply_tags(&mut route, &args.tags)?; + if !args.plugin.is_empty() { + route.span_plugins = resolve_span_plugin_paths(&args.plugin)?; + } + let codex = matches!(args.agent, SetupAgent::Codex); + let mut output = crate::run_setup(args, route)?; + if let Some(configuration) = configuration { + if let TraceCommandOutput::Install(mut setup) = output { + setup.configuration = Some(configuration); + output = TraceCommandOutput::Enable(setup); + } + } + if codex { + crate::codex_hooks::activate().await?; + } + print_output(output, host.output_format) +} + +fn enable_needs_setup(configured: bool, args: &crate::EnableArgs, explicit_route: bool) -> bool { + !configured + || explicit_route + || args.additional_metadata.is_some() + || !args.tags.is_empty() + || !args.plugin.is_empty() + || args.no_inherit_plugins + || args.inherit_plugins +} + /// Execute the complete mounted trace command. pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Result<()> { + run_trace_with_matches(args, host, None).await +} + +/// Run mounted commands with the host's parsed arguments and their value sources. +pub async fn run_trace_with_matches( + args: TraceArgs, + host: TraceHostContext, + matches: Option<&clap::ArgMatches>, +) -> anyhow::Result<()> { + fn explicit(matches: &clap::ArgMatches, id: &str) -> Option { + if matches.try_contains_id(id).is_ok() + && matches.value_source(id) == Some(clap::parser::ValueSource::CommandLine) + { + return matches.try_get_one::(id).ok().flatten().cloned(); + } + matches + .subcommand() + .and_then(|(_, child)| explicit(child, id)) + } + let selection = HostRouteSelection { + auth: AuthSelection { + profile: matches.and_then(|m| explicit(m, "profile")), + org_name: matches.and_then(|m| explicit(m, "org_name")), + ..AuthSelection::default() + }, + project_name: matches.and_then(|m| explicit(m, "project")), + }; + let has_explicit = selection.auth.profile.is_some() + || selection.auth.org_name.is_some() + || selection.project_name.is_some(); match args.command { - TraceCommand::Setup(enable_args) => { - let mut route = resolve_command_route( - &host, - RouteRequirements { - destination_required: true, - interactive_auth: true, - persistent_auth: true, - }, - ) - .await?; - apply_additional_metadata(&mut route, enable_args.additional_metadata.as_deref())?; - apply_tags(&mut route, &enable_args.tags)?; - if !enable_args.plugin.is_empty() { - route.span_plugins = resolve_span_plugin_paths(&enable_args.plugin)?; + TraceCommand::Install(args) => run_install_command(args, &host, None, &selection).await, + TraceCommand::Enable(args) => { + if args.scope == SettingsScope::Project { + if args.additional_metadata.is_some() + || !args.tags.is_empty() + || !args.plugin.is_empty() + || args.no_inherit_plugins + || args.inherit_plugins + || has_explicit + { + let setup = crate::SetupArgs { + no_inherit_plugins: args.no_inherit_plugins, + inherit_plugins: args.inherit_plugins, + disable: false, + scope: args.scope, + agent: args.agent, + additional_metadata: args.additional_metadata, + tags: args.tags, + plugin: args.plugin, + }; + return run_install_command(setup, &host, Some("updated"), &selection).await; + } + return print_output( + crate::setup::run_scoped_toggle(args.agent, args.scope, true)?, + host.output_format, + ); } - let codex = matches!(enable_args.agent, SetupAgent::Codex); - let output = run_enable(enable_args, route)?; - if codex { - crate::codex_hooks::activate().await?; + let configured = crate::setup::has_saved_setup(args.agent)?; + if !enable_needs_setup(configured, &args, has_explicit) { + print_output(run_enable(args.agent)?, host.output_format) + } else { + let setup = crate::SetupArgs { + no_inherit_plugins: args.no_inherit_plugins, + inherit_plugins: args.inherit_plugins, + disable: false, + scope: args.scope, + agent: args.agent, + additional_metadata: args + .additional_metadata + .or_else(|| crate::env::var("BRAINTRUST_ADDITIONAL_METADATA")), + tags: if args.tags.is_empty() { + crate::env::var("BRAINTRUST_TAGS") + .unwrap_or_default() + .split(',') + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect() + } else { + args.tags + }, + plugin: args.plugin, + }; + run_install_command( + setup, + &host, + Some(if configured { "updated" } else { "created" }), + &selection, + ) + .await } - print_output(output, host.output_format) } TraceCommand::Disable(disable_args) => { - print_output(run_disable(disable_args.agent)?, host.output_format) + if disable_args.scope == SettingsScope::Project { + print_output( + crate::setup::run_scoped_toggle(disable_args.agent, disable_args.scope, false)?, + host.output_format, + ) + } else { + print_output(run_disable(disable_args.agent)?, host.output_format) + } + } + TraceCommand::Uninstall(args) => { + if args.scope == SettingsScope::Project { + print_output( + crate::setup::run_project_uninstall(args.agent)?, + host.output_format, + ) + } else { + print_output(crate::run_uninstall(args.agent)?, host.output_format) + } } TraceCommand::Update(update_args) => { let codex = matches!(update_args.agent, SetupAgent::Codex); @@ -707,8 +903,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 { @@ -762,17 +962,88 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul } TraceCommand::Run(run_args) => { run_args.validate_parent()?; - let mut route = resolve_command_route( - &host, - RouteRequirements { - destination_required: run_args.parent.is_none(), - interactive_auth: true, - persistent_auth: false, - }, - ) - .await?; + let requirements = RouteRequirements { + destination_required: run_args.parent.is_none(), + interactive_auth: true, + persistent_auth: false, + }; + let inherited = if run_args.inherit { + crate::settings::AgentSettings::load_for_directory( + run_args.source.identity().id, + &std::env::current_dir()?, + )? + .0 + .route + } else { + None + }; + let mut route = if let Some(mut route) = inherited { + if let Some(profile) = &selection.auth.profile { + route.auth.source = crate::wire::AuthSource::SavedProfile; + route.auth.profile_id = None; + route.auth.profile = Some(profile.clone()); + } + if let Some(org) = &selection.auth.org_name { + route.auth.org_name = Some(org.clone()); + } + if let Some(project) = &selection.project_name { + route.destination = Some(crate::wire::TraceDestination::ProjectLogs { + project_id: None, + project_name: Some(project.clone()), + }); + } + let needs_auth = route.auth.source == crate::wire::AuthSource::Auto + && route.auth.profile.is_none() + && route.auth.profile_id.is_none(); + let needs_destination = route.destination.is_none() && run_args.parent.is_none(); + if needs_auth || needs_destination { + let defaults = resolve_host_route( + &host, + RouteRequirements { + destination_required: needs_destination, + ..requirements + }, + ) + .await?; + if needs_auth { + let selected_org = route.auth.org_name.take(); + route.auth = defaults.auth; + if selected_org.is_some() { + route.auth.org_name = selected_org; + } + } + if needs_destination { + route.destination = defaults.destination; + } + } + let lease = host + .services + .resolve_auth(&route.auth, AuthResolveReason::Initial) + .await?; + let org = require_resolved_org(&route, &lease)?; + route.auth = lease.selection; + route.auth.org_name = Some(org); + route + } else { + resolve_command_route(&host, requirements).await? + }; + let inherited_metadata = if run_args.inherit { + route.additional_metadata.take() + } else { + None + }; apply_additional_metadata(&mut route, run_args.additional_metadata.as_deref())?; + if let Some(mut metadata) = inherited_metadata { + if let Some(overlay) = route.additional_metadata.take() { + crate::settings::merge_json(&mut metadata, overlay); + } + route.additional_metadata = Some(metadata); + } + let inherited_tags = run_args.inherit.then(|| route.tags.clone()); apply_tags(&mut route, &run_args.tags)?; + if let Some(tags) = inherited_tags { + route.tags.extend(tags); + } let hook_command = child_command(&host.command, "hook"); let status = run_traced_with_host(run_args, hook_command, route, host_info(&host)).await?; @@ -785,20 +1056,36 @@ 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(()); } crate::hook::with_hook_capture_timeout(hook_args.capture_timeout_ms, async { let route = match settings.route { + Some(mut route) if route.destination.is_none() => { + route.destination = resolve_host_route(host, RouteRequirements::default()) + .await? + .destination; + route + } 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 } @@ -812,6 +1099,144 @@ mod tests { use std::path::PathBuf; use std::sync::Mutex; + #[test] + fn enable_uses_setup_only_when_missing_or_explicitly_changed() { + let mut args = crate::EnableArgs { + no_inherit_plugins: false, + inherit_plugins: false, + scope: SettingsScope::User, + agent: SetupAgent::Pi, + additional_metadata: None, + tags: vec![], + plugin: vec![], + }; + assert!(enable_needs_setup(false, &args, false)); + assert!(!enable_needs_setup(true, &args, false)); + assert!(enable_needs_setup(true, &args, true)); + args.tags.push("tag".into()); + assert!(enable_needs_setup(true, &args, false)); + args.tags.clear(); + args.additional_metadata = Some("{}".into()); + assert!(enable_needs_setup(true, &args, false)); + args.additional_metadata = None; + args.plugin.push("plugin.js".into()); + assert!(enable_needs_setup(true, &args, false)); + } + + #[tokio::test] + async fn plain_enable_resumes_without_host_resolution_or_route_changes() { + const CHILD_ENV: &str = "BRAINTRUST_TEST_RESUME_EXISTING"; + if std::env::var_os(CHILD_ENV).is_some() { + let args = crate::EnableArgs { + no_inherit_plugins: false, + inherit_plugins: false, + scope: SettingsScope::User, + agent: SetupAgent::Pi, + additional_metadata: None, + tags: vec![], + plugin: vec![], + }; + run_trace( + TraceArgs { + command: TraceCommand::Enable(args), + }, + test_host(Arc::new(PanicHost)), + ) + .await + .unwrap(); + return; + } + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("braintrust.json"); + let original = serde_json::json!({"trace_to_braintrust": false, "route": {"destination": {"type": "project_logs", "project_name": "saved"}, "auth": {"profile": "saved"}}, "other": "kept"}); + std::fs::write(&path, original.to_string()).unwrap(); + let output = crate::subprocess::interactive_command(std::env::current_exe().unwrap()) + .args(["--exact", "trace_runtime::tests::plain_enable_resumes_without_host_resolution_or_route_changes", "--nocapture"]) + .env(CHILD_ENV, "1") + .env(crate::paths::SETTINGS_ENV, &path) + .env("BRAINTRUST_TAGS", "environment-default") + .env("BRAINTRUST_ADDITIONAL_METADATA", "{\"environment\":true}") + .output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let updated: serde_json::Value = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(updated["route"], original["route"]); + assert_eq!(updated["other"], original["other"]); + assert_eq!(updated["trace_to_braintrust"], true); + assert!(String::from_utf8_lossy(&output.stdout).contains(r#""command":"enable""#)); + } + + #[tokio::test] + async fn enable_sets_up_when_missing_or_options_are_explicit() { + const CHILD_ENV: &str = "BRAINTRUST_TEST_ENABLE_SETUP"; + if let Ok(mode) = std::env::var(CHILD_ENV) { + let services = Arc::new(RecordingHost::new(None, None)); + let args = crate::EnableArgs { + no_inherit_plugins: false, + inherit_plugins: false, + scope: SettingsScope::User, + agent: SetupAgent::OpenCode, + additional_metadata: None, + tags: if mode == "updated" { + vec!["explicit".into()] + } else { + vec![] + }, + plugin: vec![], + }; + run_trace( + TraceArgs { + command: TraceCommand::Enable(args), + }, + test_host(services.clone()), + ) + .await + .unwrap(); + assert_eq!(services.route_requests.lock().unwrap().len(), 1); + return; + } + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("braintrust.json"); + for mode in ["created", "updated"] { + let output = crate::subprocess::interactive_command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "trace_runtime::tests::enable_sets_up_when_missing_or_options_are_explicit", + "--nocapture", + ]) + .env(CHILD_ENV, mode) + .env(crate::paths::SETTINGS_ENV, &path) + .env("HOME", temp.path()) + .env("XDG_CONFIG_HOME", temp.path()) + .env_remove("BRAINTRUST_TAGS") + .env_remove("BRAINTRUST_ADDITIONAL_METADATA") + .output() + .unwrap(); + assert!( + output.status.success(), + "{} {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let output = String::from_utf8_lossy(&output.stdout); + assert!( + output.contains(&format!(r#""configuration":"{mode}""#)), + "{output}" + ); + } + let saved: serde_json::Value = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!( + saved["route"]["destination"]["project_name"], + "test-project" + ); + assert_eq!(saved["route"]["tags"], serde_json::json!(["explicit"])); + } + #[test] fn mounted_child_commands_preserve_the_host_prefix() { let mounted = RunHookCommand { @@ -994,6 +1419,8 @@ mod tests { #[tokio::test] async fn setup_and_run_request_a_destination_only_when_needed() { let run = RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, @@ -1010,7 +1437,11 @@ mod tests { .unwrap(); for (command, persistent_auth, destination_required) in [ ( - TraceCommand::Setup(SetupArgs { + TraceCommand::Install(SetupArgs { + no_inherit_plugins: false, + inherit_plugins: false, + disable: false, + scope: SettingsScope::User, agent: SetupAgent::OpenCode, additional_metadata: None, tags: Default::default(), @@ -1052,6 +1483,8 @@ mod tests { ) .unwrap(); let args = RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Claude, parent: Some(parent), additional_metadata: None, @@ -1243,7 +1676,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{}", @@ -1331,7 +1776,7 @@ mod tests { _: AuthResolveReason, ) -> anyhow::Result { anyhow::bail!( - "saved profile ID 'daemon-only' no longer exists; run `bt trace enable` to select a profile" + "saved profile ID 'daemon-only' no longer exists; run `bt trace install` to select a profile" ) } } diff --git a/bt-daemon/tests/command_output.rs b/bt-daemon/tests/command_output.rs index aa170279..c0176fdc 100644 --- a/bt-daemon/tests/command_output.rs +++ b/bt-daemon/tests/command_output.rs @@ -105,6 +105,69 @@ fn standalone_hook_exit_status_distinguishes_capture_failures_from_disabled_trac ); } +#[test] +fn all_hook_integrations_honor_pause_and_managed_run() { + let temp = tempfile::tempdir().unwrap(); + let settings = temp.path().join("braintrust.json"); + std::fs::write(&settings, r#"{"trace_to_braintrust":false}"#).unwrap(); + #[cfg(unix)] + let socket = temp.path().join("absent.sock"); + #[cfg(windows)] + let socket = std::path::PathBuf::from(format!( + r"\\.\pipe\missing-bt-daemon-{}", + uuid::Uuid::new_v4() + )); + for source in [ + "antigravity", + "claude-code", + "codex", + "cursor", + "grok", + "muse", + ] { + for managed in [false, true] { + let mut command = Command::new(env!("CARGO_BIN_EXE_bt-daemon")); + command + .args(["hook", "--source", source, "--no-spawn", "--socket"]) + .arg(&socket) + .env("BRAINTRUST_DAEMON_CONFIG", &settings) + .env_remove("BT_TRACE_INVOCATION_SETTINGS") + .env_remove("_BT_TRACE_MANAGED_RUN") + .env_remove("CURSOR_PLUGIN_ROOT") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if managed { + command.env("BT_TRACE_INVOCATION_SETTINGS", r#"{"trace_to_braintrust":true,"route":{"destination":{"type":"project_logs","project_name":"test"}}}"#); + } + let mut child = command.spawn().unwrap(); + let _ = child + .stdin + .take() + .unwrap() + .write_all(br#"{"session_id":"test","hook_event_name":"SessionStart"}"#); + let output = child.wait_with_output().unwrap(); + if managed { + assert!( + !output.status.success(), + "{source}: managed run did not attempt capture" + ); + assert!( + String::from_utf8_lossy(&output.stderr).contains("--no-spawn is set"), + "{source}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } else { + assert!( + output.status.success(), + "{source}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + } + } +} + #[test] fn standalone_hook_honors_deprecated_bt_env_names() { let temp = tempfile::tempdir().unwrap(); @@ -200,3 +263,98 @@ 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"}), + ), + ( + "codex", + ".codex", + serde_json::json!({"cwd":repo,"session_id":"s","hook_event_name":"Stop"}), + ), + ( + "muse", + ".muse", + serde_json::json!({"cwd":repo,"session_id":"s","hook_event_name":"Stop"}), + ), + ( + "grok", + ".grok", + serde_json::json!({"cwd":repo,"session_id":"s","hook_event_name":"Stop"}), + ), + ( + "antigravity", + ".gemini", + serde_json::json!({"workspacePaths":[repo],"session_id":"s","hook_event_name":"Stop"}), + ), + ] { + let _ = dir; + let config = repo.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/bt-daemon/tests/muse_managed_startup.rs b/bt-daemon/tests/muse_managed_startup.rs index 73ceaf80..4128d6aa 100644 --- a/bt-daemon/tests/muse_managed_startup.rs +++ b/bt-daemon/tests/muse_managed_startup.rs @@ -57,6 +57,8 @@ if [ "$1" = "--version" ]; then echo 'Muse Code 1.4.11'; exit 0; fi let _marker = Env::set("MUSE_TEST_MARKER", &marker); let result = run_traced_with_host( RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Muse, parent: None, additional_metadata: None, diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index 7361d113..3b6405da 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -2952,6 +2952,8 @@ esac let run = |session_id: &str, mode: &str| { run_traced( RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, @@ -3055,6 +3057,8 @@ async fn muse_managed_run_preserves_saved_settings_and_foreign_hooks() { let binary = env!("CARGO_BIN_EXE_bt-daemon"); let status = run_traced( RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Muse, parent: None, additional_metadata: None, @@ -3158,6 +3162,8 @@ async fn muse_managed_run_starts_its_isolated_daemon_before_sanitized_hooks() { let binary = env!("CARGO_BIN_EXE_bt-daemon"); let status = run_traced( RunArgs { + no_inherit_plugins: false, + inherit: false, source: RunSource::Muse, parent: None, additional_metadata: None, diff --git a/docs/coding-agent-tracing-plugin-spec.md b/docs/coding-agent-tracing-plugin-spec.md index f089f694..c7de657b 100644 --- a/docs/coding-agent-tracing-plugin-spec.md +++ b/docs/coding-agent-tracing-plugin-spec.md @@ -395,13 +395,27 @@ translator rather than separate trace builders. ## 8. Product surfaces -### 8.1 Persistent setup +### 8.1 Persistent installation -`bt trace enable ` MUST install or update capture idempotently and store +`bt trace install ` (with `setup` as an alias) MUST install or update capture idempotently and store only non-secret route settings. It MUST preserve unrelated user configuration. -`bt trace disable ` MUST remove only Braintrust-managed state and MUST be -safe when repeated. +`bt trace enable ` MUST resume an existing configuration without changing its route or reinstalling capture when no settings are explicitly supplied. If configuration is absent or settings are explicitly supplied, enable MUST run installation. + +Install, enable, and disable support user and project scope. Project settings overlay +user settings field by field; managed-run settings take precedence over both. +Project install writes only explicitly selected fields and enables tracing without +installing a global adapter. It MUST explain that each user needs a user-level +installation and credentials. `install --disable` installs the user integration +with tracing disabled by default. The shared repository-root `.braintrust.json` +overlays user settings: objects merge recursively and arrays append. Project span +plugins resolve relative to that file and follow user plugins by default; +`--no-inherit-plugins` replaces the inherited plugin chain. + +`bt trace disable ` MUST preserve the adapter and configuration while disabling tracing. +`bt trace uninstall ` MUST remove Braintrust-managed user state; with project scope it MUST remove the entire shared `.braintrust.json` without uninstalling any user-level integration. Both MUST be safe when repeated. + +Doctor SHOULD include the current repository settings and effective values. Doctor/status output SHOULD diagnose: @@ -611,7 +625,7 @@ features that require native evidence remain conditional under section 3. | 4. Correlation | CORR-01 | Cross-agent parent-child linking | Process ancestry and native evidence can link child coding-agent sessions beneath spawning tools, including concurrent, recursive, and restart cases, while ambiguity fails safe. | | 4. Operations | OPS-01 | Daemon status and delivery diagnostics | Operators can inspect daemon reachability, active sessions, pending delivery, last error, compatibility, and permalink without exposing credentials or payloads. | | 4. Operations | OPS-02 | Opt-in sensitive diagnostics | Raw event and transcript diagnostics are private, bounded, clearly documented as sensitive, and disabled unless explicitly requested. | -| 5. Product | SETUP-01 | Persistent enable and disable | Setup installs or updates capture idempotently, stores only non-secret routing, preserves unrelated configuration, and removes only Braintrust-managed state. | +| 5. Product | SETUP-01 | Persistent enable and disable | Setup installs or updates capture idempotently, stores only non-secret routing, preserves unrelated configuration, and supports disabling and uninstalling. | | 5. Product | SETUP-02 | Agent-specific doctor/status | Diagnostics cover agent installation, capture activation, plugin and daemon compatibility, route validity, credential availability, and restart or reload requirements. | | 5. Product | RUN-01 | Invocation-local managed run | One process tree receives an isolated route and temporary capture without mutating persistent configuration or duplicating inherited capture. | | 5. Product | HIST-01 | Historical transcript import | Stable native sessions can be located safely and replayed through the production translator with project, experiment, or parent overrides. | diff --git a/src/plugins/antigravity/content/README.md b/src/plugins/antigravity/content/README.md index 2bcd635f..ac002433 100644 --- a/src/plugins/antigravity/content/README.md +++ b/src/plugins/antigravity/content/README.md @@ -27,7 +27,7 @@ Install the plugin and choose where traces are sent: ```bash bt login -bt trace enable antigravity --project my-coding-agent +bt trace install antigravity --project my-coding-agent ``` Setup installs the hooks and saves non-secret routing settings in diff --git a/src/plugins/claude/content/README.md b/src/plugins/claude/content/README.md index c530ec6b..6e6d8414 100644 --- a/src/plugins/claude/content/README.md +++ b/src/plugins/claude/content/README.md @@ -33,7 +33,7 @@ Authenticate and install the published tracing plugin: ```bash bt login -bt trace enable claude --project my-coding-agent +bt trace install claude --project my-coding-agent ``` Setup adds the marketplace and installs or enables `trace-claude-code`. @@ -41,7 +41,7 @@ The plugin forwards lifecycle events locally; `bt` owns authentication, trace construction, and delivery. Use `--profile` or `--org` when needed. Setup stores only non-secret routing -settings under `~/.claude/braintrust.json`. Restart Claude Code after setup. +settings under `~/.claude/braintrust.json`. Restart Claude Code after installation. Every registered lifecycle event is forwarded synchronously to `bt trace hook --source claude-code`, preserving per-session ordering. Hook @@ -66,7 +66,7 @@ Braintrust. Redaction cannot remove data that has already been delivered. ## Additional root metadata -For a persistent route, pass a JSON object to `bt trace enable claude +For a persistent route, pass a JSON object to `bt trace install claude --additional-metadata ''` to tag the root span of every Claude Code session. Standard session metadata takes precedence if keys conflict. @@ -82,7 +82,7 @@ route. Tags can be persisted with setup, supplied to one invocation, or added while importing a transcript: ```bash -bt trace enable claude --tag ci --tag release-validation +bt trace install claude --tag ci --tag release-validation bt trace run claude --tag ci -- "review this change" bt trace import claude session-id --tag historical-import ``` @@ -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#project-scoped-tracing). diff --git a/src/plugins/claude/content/plugins/trace-claude-code/README.md b/src/plugins/claude/content/plugins/trace-claude-code/README.md index dbcaaa41..36811697 100644 --- a/src/plugins/claude/content/plugins/trace-claude-code/README.md +++ b/src/plugins/claude/content/plugins/trace-claude-code/README.md @@ -6,7 +6,7 @@ This plugin synchronously forwards Claude Code lifecycle payloads to: bt trace hook --source claude-code ``` -Use `bt trace enable claude --project ` to install and configure it. +Use `bt trace install claude --project ` to install and configure it. Claude Code directly executes the configured `bt` CLI for each hook; it does not launch a shell or an intermediate forwarding script. The plugin is credential-free; the `bt` CLI and shared daemon own authentication, event @@ -18,7 +18,7 @@ This plugin supports Claude Code CLI and Claude Code mode in the desktop app. Cursor automatically imports installed Claude plugins when third-party imports are enabled. This plugin includes a Cursor manifest with no hooks so that Cursor uses the native Braintrust Cursor integration for tracing. Enable that -integration with `bt trace enable cursor --project `. +integration with `bt trace install cursor --project `. It does not support the Cowork tab. Cowork executes hooks in a separate VM that does not inherit the host's `bt` binary, saved Braintrust route, or credentials, @@ -26,9 +26,9 @@ so installing this plugin there does not enable tracing. To add fields to each root trace span, pass a JSON object (as `--additional-metadata` or `BRAINTRUST_ADDITIONAL_METADATA`) to -`bt trace enable claude` for a persistent configuration, or to +`bt trace install claude` for a persistent configuration, or to `bt trace run claude` for one invocation. The hook itself never reads that -environment variable — only `bt trace enable`, `bt trace run`, and +environment variable — only `bt trace install`, `bt trace run`, and `bt trace import` do. ## Tags and diagnostics @@ -37,7 +37,7 @@ Use repeatable `--tag` flags for filterable root-span tags. Inspect the effectiv configuration with `doctor` and delivery state with `status`: ```bash -bt trace enable claude --tag coding-agent --tag development +bt trace install claude --tag coding-agent --tag development bt trace doctor claude bt trace status ``` diff --git a/src/plugins/codex/content/README.md b/src/plugins/codex/content/README.md index bb7f8293..6db6db3d 100644 --- a/src/plugins/codex/content/README.md +++ b/src/plugins/codex/content/README.md @@ -38,7 +38,7 @@ Install Codex and the ```bash bt login -bt trace enable codex --project my-coding-agent +bt trace install codex --project my-coding-agent ``` Setup adds the published marketplace, installs the plugin, and saves routing diff --git a/src/plugins/codex/content/plugins/trace-codex/README.md b/src/plugins/codex/content/plugins/trace-codex/README.md index 93b8ca52..895127b2 100644 --- a/src/plugins/codex/content/plugins/trace-codex/README.md +++ b/src/plugins/codex/content/plugins/trace-codex/README.md @@ -37,7 +37,7 @@ falling back. The marketplace hook definition stays unchanged. Install and configure the published plugin with the Braintrust CLI: ```bash -bt trace enable codex --project my-coding-agent +bt trace install codex --project my-coding-agent ``` Use `--profile` or `--org` when needed. Setup activates Braintrust tracing in @@ -60,7 +60,7 @@ the daemon cannot accept an event, Codex reports the hook failure and continues. ## Additional root metadata -For a persistent route, pass a JSON object to `bt trace enable codex +For a persistent route, pass a JSON object to `bt trace install codex --additional-metadata ''` to tag the root span of every Codex session. Standard session metadata takes precedence if keys conflict. @@ -75,7 +75,7 @@ Use repeatable `--tag` flags for filterable root-span tags. Inspect the effectiv configuration with `doctor` and delivery state with `status`: ```bash -bt trace enable codex --tag coding-agent --tag development +bt trace install codex --tag coding-agent --tag development bt trace doctor codex bt trace status ``` diff --git a/src/plugins/cursor/content/README.md b/src/plugins/cursor/content/README.md index a20b3a06..c73ff94c 100644 --- a/src/plugins/cursor/content/README.md +++ b/src/plugins/cursor/content/README.md @@ -20,7 +20,7 @@ the Braintrust VS Code extension for Cursor. Use `/add-plugin` in Cursor and search for **Braintrust**, or install from the [Cursor Marketplace](https://cursor.com/marketplace). The plugin registers the Braintrust MCP server and tracing hooks. For tracing, install and authenticate -the `bt` CLI, then run `bt trace enable cursor --project my-coding-agent`. +the `bt` CLI, then run `bt trace install cursor --project my-coding-agent`. The Braintrust MCP server uses `https://api.braintrust.dev/mcp`. Configure its `BRAINTRUST_API_KEY` variable in Cursor's plugin settings. MCP access and tracing @@ -36,7 +36,7 @@ server named `braintrust`; use one MCP installation to avoid duplicates. The plugin works with Cursor CLI and desktop. Its hooks invoke `bt trace hook`, so the Braintrust CLI must be on -Cursor's `PATH` when hooks run. `bt trace enable cursor` also installs capture +Cursor's `PATH` when hooks run. `bt trace install cursor` also installs capture hooks in `~/.cursor/hooks.json`. These user hooks work with third-party imports disabled and when a marketplace installation takes precedence over the local plugin. Plugin hooks skip capture for events covered by these user hooks. @@ -49,13 +49,13 @@ Authenticate and enable tracing: ```bash bt login -bt trace enable cursor --project my-coding-agent +bt trace install cursor --project my-coding-agent ``` Setup uses Git to install or refresh the local `braintrust` plugin from the latest published [distribution](https://github.com/braintrustdata/braintrust-cursor-extension), configures the hooks needed to trace Cursor sessions, and saves the selected route in -`~/.cursor/braintrust.json`. If Git is not installed or not on `PATH`, setup and +`~/.cursor/braintrust.json`. If Git is not installed or not on `PATH`, install and `bt trace update cursor` install the plugin bundled with your `bt` build and print a warning that it may be older. Install Git and run `bt trace update cursor` to get the latest published version. Other download failures preserve the previous @@ -83,7 +83,7 @@ that must not be sent to Braintrust. Add a JSON object to the root span of every Cursor session: ```bash -bt trace enable cursor --project my-coding-agent \ +bt trace install cursor --project my-coding-agent \ --additional-metadata '{"team":"platform","environment":"dev"}' ``` @@ -94,7 +94,7 @@ Standard session metadata takes precedence if keys conflict. Use repeatable `--tag` options for filterable tags on root spans: ```bash -bt trace enable cursor --tag ci --tag release-validation +bt trace install cursor --tag ci --tag release-validation bt trace run cursor --tag ci bt trace import cursor SESSION_ID --tag historical-import ``` @@ -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#project-scoped-tracing). diff --git a/src/plugins/grok/content/README.md b/src/plugins/grok/content/README.md index 50528c81..f28dbab5 100644 --- a/src/plugins/grok/content/README.md +++ b/src/plugins/grok/content/README.md @@ -18,7 +18,7 @@ Install: ```bash bt login -bt trace enable grok --project my-coding-agent +bt trace install grok --project my-coding-agent ``` Setup installs and enables the published plugin and saves non-secret routing diff --git a/src/plugins/opencode/content/README.md b/src/plugins/opencode/content/README.md index 3fe5b5b9..e16bc1a5 100644 --- a/src/plugins/opencode/content/README.md +++ b/src/plugins/opencode/content/README.md @@ -15,7 +15,7 @@ Install OpenCode and the ```bash bt login -bt trace enable opencode --project my-coding-agent +bt trace install opencode --project my-coding-agent opencode ``` @@ -73,7 +73,7 @@ at the top level: a project `route` replaces the global `route`. | `debug` | `false` | Enable debug logging; override with `BRAINTRUST_DEBUG` | Older files can still use top-level `profile`, `org_name`, `project`, and -`additional_metadata`. For new files, use `bt trace enable` or the nested +`additional_metadata`. For new files, use `bt trace install` or the nested `route` format above. Include a destination when supplying a route. Only `enable_tools` and `debug` read environment variables directly. Tracing diff --git a/src/plugins/opencode/content/install.sh b/src/plugins/opencode/content/install.sh index 4462a811..5642ecc1 100755 --- a/src/plugins/opencode/content/install.sh +++ b/src/plugins/opencode/content/install.sh @@ -37,7 +37,7 @@ echo "1. Authenticate the bt CLI:" echo " bt auth login" echo "" echo "2. (Optional) Configure project name:" -echo " bt trace enable opencode --project my-project" +echo " bt trace install opencode --project my-project" echo "" echo "3. Run OpenCode:" echo " opencode" diff --git a/src/plugins/opencode/content/src/config.ts b/src/plugins/opencode/content/src/config.ts index 416aceb0..38fbb5b2 100644 --- a/src/plugins/opencode/content/src/config.ts +++ b/src/plugins/opencode/content/src/config.ts @@ -25,6 +25,8 @@ export interface PluginConfig { enable_tools?: boolean; debug?: boolean; additional_metadata?: Record; + tags?: string[]; + inherit_plugins?: boolean; route?: DaemonSessionRoute; } @@ -74,7 +76,7 @@ export function loadConfig(pluginConfig?: PluginConfig): BraintrustConfig { if (pluginConfig.org_name) defaults.orgName = pluginConfig.org_name; if (pluginConfig.project) defaults.projectName = pluginConfig.project; // A nested route is canonical. Top-level fields are a compatibility - // fallback only for files that `bt trace enable` has not migrated yet. + // fallback only for files that `bt trace install` has not migrated yet. if (auth?.profile) defaults.profile = auth.profile; if (auth?.org_name) defaults.orgName = auth.org_name; if ( @@ -106,11 +108,12 @@ export function loadConfig(pluginConfig?: PluginConfig): BraintrustConfig { ...(defaults.orgName ? { org_name: defaults.orgName } : {}), }, }; - if (!pluginConfig?.route || pluginConfig.project !== undefined) { + if (!pluginConfig?.route || pluginConfig.route.destination === undefined) { persistentRoute.destination = { type: "project_logs", project_name: defaults.projectName }; } if (defaults.additionalMetadata) persistentRoute.additional_metadata = defaults.additionalMetadata; + if (pluginConfig?.tags !== undefined) persistentRoute.tags = pluginConfig.tags; const traceSettings = resolveDaemonTraceSettings({ trace_to_braintrust: defaults.tracingEnabled, route: persistentRoute, diff --git a/src/plugins/opencode/content/src/index.test.ts b/src/plugins/opencode/content/src/index.test.ts index 452a9d40..7af6671f 100644 --- a/src/plugins/opencode/content/src/index.test.ts +++ b/src/plugins/opencode/content/src/index.test.ts @@ -125,6 +125,125 @@ describe("BraintrustPlugin", () => { expect(hooks.tool).toBeUndefined(); }); + it("lets project tracing override the user default and managed runs override both", async () => { + const global = join(directory, ".config", "opencode"); + const project = directory; + mkdirSync(global, { recursive: true }); + mkdirSync(project, { recursive: true }); + writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: false })); + writeFileSync(join(project, ".braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + const { BraintrustPlugin } = await import("./index"); + expect((await BraintrustPlugin(createInput(directory))).event).toBeDefined(); + writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + writeFileSync( + join(project, ".braintrust.json"), + JSON.stringify({ trace_to_braintrust: false }), + ); + const paused = await BraintrustPlugin(createInput(directory)); + expect(paused.event).toBeUndefined(); + expect(paused.tool).toBeDefined(); + process.env.BT_TRACE_INVOCATION_SETTINGS = JSON.stringify({ + trace_to_braintrust: true, + route: { destination: { type: "project_logs", project_name: "managed" } }, + }); + expect((await BraintrustPlugin(createInput(directory))).event).toBeDefined(); + }); + + it("does not bypass a project opt-out when its plugin list is invalid", async () => { + const global = join(directory, ".config", "opencode"); + mkdirSync(global, { recursive: true }); + writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + writeFileSync( + join(directory, ".braintrust.json"), + JSON.stringify({ trace_to_braintrust: false, route: { span_plugins: [null] } }), + ); + const { BraintrustPlugin } = await import("./index"); + expect((await BraintrustPlugin(createInput(directory))).event).toBeUndefined(); + process.env.BT_TRACE_INVOCATION_SETTINGS = JSON.stringify({ + trace_to_braintrust: true, + route: { destination: { type: "project_logs", project_name: "run" } }, + }); + expect((await BraintrustPlugin(createInput(directory))).event).toBeDefined(); + }); + + it("recursively merges project metadata and appends arrays", async () => { + const global = join(directory, ".config", "opencode"); + const project = directory; + mkdirSync(global, { recursive: true }); + mkdirSync(project, { recursive: true }); + writeFileSync( + join(global, "braintrust.json"), + JSON.stringify({ + trace_to_braintrust: false, + route: { + destination: { type: "project_logs", project_name: "global" }, + additional_metadata: { nested: { a: 1, b: 2 }, list: [1, 2] }, + }, + }), + ); + writeFileSync( + join(project, ".braintrust.json"), + JSON.stringify({ + trace_to_braintrust: true, + route: { additional_metadata: { nested: { b: 3 }, list: [4] } }, + }), + ); + const { readPluginConfig } = await import("./tracing/plugin"); + const { loadConfig } = await import("./config"); + const config = loadConfig(await readPluginConfig({ directory })); + expect(config.tracingEnabled).toBe(true); + expect(config.route.additional_metadata).toEqual({ nested: { a: 1, b: 3 }, list: [1, 2, 4] }); + }); + + it("inherits the user route while applying explicit project selections", async () => { + const global = join(directory, ".config", "opencode"); + const project = directory; + mkdirSync(global, { recursive: true }); + mkdirSync(project, { recursive: true }); + mkdirSync(join(directory, ".git")); + const nested = join(directory, "src"); + mkdirSync(nested); + writeFileSync( + join(global, "braintrust.json"), + JSON.stringify({ + trace_to_braintrust: true, + route: { + auth: { source: "environment", profile_id: "old", org_name: "org" }, + destination: { type: "project_logs", project_name: "global" }, + span_plugins: ["trusted.js"], + }, + }), + ); + writeFileSync( + join(project, ".braintrust.json"), + JSON.stringify({ + project: "local", + profile: "new", + route: { span_plugins: ["untrusted.js"] }, + }), + ); + const { readPluginConfig } = await import("./tracing/plugin"); + const { loadConfig } = await import("./config"); + const config = loadConfig(await readPluginConfig({ directory: nested })); + expect(config.route.destination).toEqual({ type: "project_logs", project_name: "local" }); + expect(config.route.auth).toMatchObject({ + source: "saved_profile", + profile: "new", + org_name: "org", + }); + expect(config.route.auth?.profile_id).toBeUndefined(); + expect(config.route.span_plugins).toEqual(["trusted.js", join(directory, "untrusted.js")]); + writeFileSync( + join(project, ".braintrust.json"), + JSON.stringify({ + inherit_plugins: false, + route: { span_plugins: ["project.js"] }, + }), + ); + const replaced = loadConfig(await readPluginConfig({ directory: nested })); + expect(replaced.route.span_plugins).toEqual([join(directory, "project.js")]); + }); + it("provides a trace-only managed entrypoint without data tools", async () => { process.env.BT_TRACE_MANAGED_RUN_ID = `trace-only-${Date.now()}`; process.env.BT_TRACE_INVOCATION_SETTINGS = JSON.stringify({ diff --git a/src/plugins/opencode/content/src/server.pause.test.ts b/src/plugins/opencode/content/src/server.pause.test.ts new file mode 100644 index 00000000..2ead16a7 --- /dev/null +++ b/src/plugins/opencode/content/src/server.pause.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("./runtime/daemon-client", async (importOriginal) => ({ + ...(await importOriginal()), + DaemonClient: class { + async close() {} + }, +})); + +import plugin from "./server"; + +let directory: string; +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "opencode-pause-")); + vi.stubEnv("XDG_CONFIG_HOME", join(directory, "config")); + vi.stubEnv("BRAINTRUST_OPENCODE_ENABLE_TOOLS", "false"); + vi.stubEnv("BT_TRACE_INVOCATION_SETTINGS", undefined); + vi.stubEnv("BT_TRACE_MANAGED_RUN_ID", undefined); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(directory, { recursive: true, force: true }); +}); + +it("applies the project opt-out to OpenCode 2 and permits a managed run", async () => { + const global = join(directory, "config", "opencode"); + const project = directory; + mkdirSync(global, { recursive: true }); + mkdirSync(project, { recursive: true }); + writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + writeFileSync(join(project, ".braintrust.json"), JSON.stringify({ trace_to_braintrust: false })); + const hook = vi.fn(async () => {}); + const subscribe = vi.fn(async function* () {}); + const ctx = { + app: { version: "2.2.5" }, + location: { directory }, + session: { hook, get: async () => ({}) }, + event: { subscribe }, + tool: { transform: async () => {} }, + }; + expect(await plugin.setup(ctx)).toBeUndefined(); + expect(hook).not.toHaveBeenCalled(); + expect(subscribe).not.toHaveBeenCalled(); + vi.stubEnv( + "BT_TRACE_INVOCATION_SETTINGS", + JSON.stringify({ + trace_to_braintrust: true, + route: { destination: { type: "project_logs", project_name: "managed" } }, + }), + ); + const cleanup = await plugin.setup(ctx); + expect(hook).toHaveBeenCalled(); + expect(subscribe).toHaveBeenCalled(); + await cleanup?.(); +}); diff --git a/src/plugins/opencode/content/src/tracing/plugin.ts b/src/plugins/opencode/content/src/tracing/plugin.ts index 11d6d7e0..c2a75524 100644 --- a/src/plugins/opencode/content/src/tracing/plugin.ts +++ b/src/plugins/opencode/content/src/tracing/plugin.ts @@ -1,6 +1,11 @@ import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin"; import { loadConfig, type PluginConfig } from "../config"; -import { claimManagedTracingInstance } from "../runtime/daemon-client"; +import { + claimManagedTracingInstance, + mergeConfigObjects, + mergeProjectRoute, + projectSettingsPath, +} from "../runtime/daemon-client"; import { createDaemonTracingHooks } from "./daemon"; export async function readPluginConfig(input: { @@ -14,16 +19,79 @@ export async function readPluginConfig(input: { const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"); const configPaths = [ path.join(configHome, "opencode", "braintrust.json"), - path.join(input.directory, ".opencode", "braintrust.json"), + projectSettingsPath(input.directory), ]; - for (const configPath of configPaths) { + for (const [index, configPath] of configPaths.entries()) { try { if (fs.existsSync(configPath)) { const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as PluginConfig; - pluginConfig = pluginConfig ? { ...pluginConfig, ...parsed } : parsed; + if (index === 0) { + pluginConfig = parsed; + } else { + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) + throw new TypeError("project settings must be an object"); + const { route: projectRoute, inherit_plugins: inheritPlugins, ...safe } = parsed; + if ( + projectRoute !== undefined && + (!projectRoute || typeof projectRoute !== "object" || Array.isArray(projectRoute)) + ) + throw new TypeError("project route must be an object"); + if (inheritPlugins !== undefined && typeof inheritPlugins !== "boolean") + throw new TypeError("inherit_plugins must be a boolean"); + const userRoute = mergeProjectRoute( + pluginConfig?.route, + projectRoute, + configPath, + inheritPlugins !== false, + ); + if (safe.tags) { + safe.tags = [ + ...new Set([...(userRoute?.tags ?? pluginConfig?.tags ?? []), ...safe.tags]), + ]; + } + if (safe.additional_metadata) { + safe.additional_metadata = mergeConfigObjects( + userRoute?.additional_metadata ?? pluginConfig?.additional_metadata ?? {}, + safe.additional_metadata, + ); + } else if (projectRoute?.additional_metadata) { + safe.additional_metadata = userRoute?.additional_metadata; + } + const auth = userRoute?.auth; + const projectAuth = + safe.profile || safe.org_name + ? { + ...auth, + ...(safe.profile + ? { + source: "saved_profile" as const, + profile_id: undefined, + profile: safe.profile, + } + : {}), + ...(safe.org_name ? { org_name: safe.org_name } : {}), + } + : auth; + pluginConfig = { + ...pluginConfig, + ...safe, + ...(userRoute + ? { + route: { + ...userRoute, + ...(projectAuth ? { auth: projectAuth } : {}), + ...(safe.project + ? { destination: { type: "project_logs", project_name: safe.project } } + : {}), + }, + } + : {}), + }; + } } } catch { - // Malformed optional config is fail-open; continue to the next layer. + // Do not bypass a project opt-out when its settings cannot be read. + if (index === 1) pluginConfig = { ...pluginConfig, trace_to_braintrust: false }; } } } catch { diff --git a/src/plugins/pi/content/README.md b/src/plugins/pi/content/README.md index 362f8597..1c8f50b0 100644 --- a/src/plugins/pi/content/README.md +++ b/src/plugins/pi/content/README.md @@ -40,7 +40,7 @@ Install Pi and the ```bash bt login -bt trace enable pi --project my-coding-agent +bt trace install pi --project my-coding-agent pi ``` @@ -50,7 +50,7 @@ The footer shows tracing status and a link to the trace when available. To install the npm extension separately, use `pi install npm:@braintrust/pi-extension`, then configure tracing with -`bt trace enable pi`. +`bt trace install pi`. For one invocation without changing global tracing configuration: @@ -115,7 +115,7 @@ Example: | `show_trace_link` | `true` | Show the trace link; override with `BRAINTRUST_SHOW_TRACE_LINK` | Older files can still use top-level `profile`, `org_name`, `project`, and -`additional_metadata`. For new files, use `bt trace enable` or the nested +`additional_metadata`. For new files, use `bt trace install` or the nested `route` format above. Include a destination when supplying a route. Only the display settings read environment variables directly. Tracing settings diff --git a/src/plugins/pi/content/src/config.test.ts b/src/plugins/pi/content/src/config.test.ts index 45d6b962..5b79ff5d 100644 --- a/src/plugins/pi/content/src/config.test.ts +++ b/src/plugins/pi/content/src/config.test.ts @@ -82,7 +82,7 @@ describe("loadConfig", () => { project: "global-project", additional_metadata: { source: "global" }, }); - writeJson(join(cwd, ".pi", "braintrust.json"), { + writeJson(join(cwd, ".braintrust.json"), { profile: "project", project: "project-project", show_trace_link: false, @@ -97,7 +97,7 @@ describe("loadConfig", () => { showUi: true, showTraceLink: false, route: { - auth: { profile: "project", org_name: "global-org" }, + auth: { profile: "project", org_name: "global-org", source: "saved_profile" }, destination: { type: "project_logs", project_name: "project-project" }, flush_mode: "flush_on_turn_end", additional_metadata: { source: "global" }, @@ -105,6 +105,58 @@ describe("loadConfig", () => { }); }); + it("merges nested project metadata and appends arrays", () => { + writeJson(join(home, ".pi", "agent", "braintrust.json"), { + trace_to_braintrust: false, + route: { + destination: { type: "project_logs", project_name: "global" }, + additional_metadata: { nested: { a: 1, b: 2 }, list: [1, 2] }, + }, + }); + writeJson(join(cwd, ".braintrust.json"), { + trace_to_braintrust: true, + route: { additional_metadata: { nested: { b: 3 }, list: [4] } }, + }); + expect(loadConfig(cwd).route.additional_metadata).toEqual({ + nested: { a: 1, b: 3 }, + list: [1, 2, 4], + }); + expect(loadConfig(cwd).enabled).toBe(true); + }); + + it("finds the shared repository file from a nested directory", () => { + mkdirSync(join(cwd, ".git")); + const nested = join(cwd, "src", "nested"); + mkdirSync(nested, { recursive: true }); + writeJson(join(cwd, ".braintrust.json"), { trace_to_braintrust: true, project: "repo" }); + expect(loadConfig(nested)).toMatchObject({ enabled: true, projectName: "repo" }); + }); + + it("appends repository plugins relative to the shared configuration and can replace user plugins", () => { + writeJson(join(home, ".pi", "agent", "braintrust.json"), { + trace_to_braintrust: false, + route: { + destination: { type: "project_logs", project_name: "global" }, + span_plugins: ["user.mjs"], + }, + }); + const path = join(cwd, ".braintrust.json"); + writeJson(path, { + trace_to_braintrust: true, + route: { span_plugins: ["scripts/project.mjs"] }, + }); + expect(loadConfig(cwd).route.span_plugins).toEqual([ + "user.mjs", + join(cwd, "scripts/project.mjs"), + ]); + writeJson(path, { + trace_to_braintrust: true, + inherit_plugins: false, + route: { span_plugins: ["scripts/project.mjs"] }, + }); + expect(loadConfig(cwd).route.span_plugins).toEqual([join(cwd, "scripts/project.mjs")]); + }); + it("prefers a canonical route over stale top-level routing", () => { writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: true, @@ -162,6 +214,34 @@ describe("loadConfig", () => { expect(loadConfig(cwd)).toEqual(DEFAULT_CONFIG); }); + it("does not bypass a project opt-out when its plugin list is invalid", () => { + writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: true }); + writeJson(join(cwd, ".braintrust.json"), { + trace_to_braintrust: false, + route: { span_plugins: [null] }, + }); + expect(loadConfig(cwd).enabled).toBe(false); + process.env.BT_TRACE_INVOCATION_SETTINGS = JSON.stringify({ + trace_to_braintrust: true, + route: { destination: { type: "project_logs", project_name: "run" } }, + }); + expect(loadConfig(cwd).enabled).toBe(true); + }); + + it("lets project tracing override the user default, and managed runs override both", () => { + writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: false }); + writeJson(join(cwd, ".braintrust.json"), { trace_to_braintrust: true }); + expect(loadConfig(cwd).enabled).toBe(true); + writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: true }); + writeJson(join(cwd, ".braintrust.json"), { trace_to_braintrust: false }); + expect(loadConfig(cwd).enabled).toBe(false); + process.env.BT_TRACE_INVOCATION_SETTINGS = JSON.stringify({ + trace_to_braintrust: true, + route: { destination: { type: "project_logs", project_name: "run" } }, + }); + expect(loadConfig(cwd).enabled).toBe(true); + }); + it("uses managed-run settings without replacing the agent's global file", () => { writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: true, diff --git a/src/plugins/pi/content/src/config.ts b/src/plugins/pi/content/src/config.ts index fe7d26af..f4a88255 100644 --- a/src/plugins/pi/content/src/config.ts +++ b/src/plugins/pi/content/src/config.ts @@ -1,8 +1,13 @@ import { existsSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; -import { type DaemonSessionRoute, resolveDaemonTraceSettings } from "./runtime/daemon-client.ts"; -import { runningPiPackage } from "./pi-package.ts"; +import { + type DaemonSessionRoute, + projectSettingsPath, + mergeConfigObjects, + mergeProjectRoute, + resolveDaemonTraceSettings, +} from "./runtime/daemon-client.ts"; export interface PiConfig { enabled: boolean; @@ -17,8 +22,6 @@ export interface PiConfig { type ConfigRecord = Record; -const PROJECT_CONFIG_DIR_NAME = runningPiPackage().configDir; - function record(value: unknown): ConfigRecord | undefined { return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as ConfigRecord) @@ -71,11 +74,20 @@ function applyConfig(config: PiConfig, source: ConfigRecord | undefined): void { config.orgName = orgName ?? config.orgName; config.projectName = projectName ?? config.projectName; config.enabled = boolean(source.trace_to_braintrust) ?? config.enabled; - config.additionalMetadata = record(source.additional_metadata) ?? config.additionalMetadata; + const metadata = record(source.additional_metadata); + config.additionalMetadata = metadata + ? mergeConfigObjects( + config.additionalMetadata ?? config.route.additional_metadata ?? {}, + metadata, + ) + : config.additionalMetadata; config.showUi = boolean(source.show_ui) ?? config.showUi; config.showTraceLink = boolean(source.show_trace_link) ?? config.showTraceLink; const additionalMetadata = record(source.additional_metadata); + if (Array.isArray(source.tags) && source.tags.every((tag) => typeof tag === "string")) { + config.route.tags = [...new Set([...(config.route.tags ?? []), ...source.tags])]; + } if (profile || orgName) { config.route.auth = { ...config.route.auth, @@ -86,7 +98,11 @@ function applyConfig(config: PiConfig, source: ConfigRecord | undefined): void { if (projectName) { config.route.destination = { type: "project_logs", project_name: projectName }; } - if (additionalMetadata) config.route.additional_metadata = additionalMetadata; + if (additionalMetadata) + config.route.additional_metadata = mergeConfigObjects( + config.route.additional_metadata ?? {}, + additionalMetadata, + ); } export function loadConfig(cwd = process.cwd()): PiConfig { @@ -101,8 +117,44 @@ export function loadConfig(cwd = process.cwd()): PiConfig { }, }; - applyConfig(config, readConfig(join(homedir(), ".pi", "agent", "braintrust.json"))); - applyConfig(config, readConfig(join(cwd, PROJECT_CONFIG_DIR_NAME, "braintrust.json"))); + const userConfig = readConfig(join(homedir(), ".pi", "agent", "braintrust.json")); + applyConfig(config, userConfig); + const projectPath = projectSettingsPath(cwd); + const projectConfig = readConfig(projectPath); + if (projectConfig) { + try { + const { + route: projectRoute, + inherit_plugins: inheritPlugins, + ...safeProjectConfig + } = projectConfig; + if (projectRoute !== undefined && !record(projectRoute)) + throw new TypeError("project route must be an object"); + if (inheritPlugins !== undefined && typeof inheritPlugins !== "boolean") + throw new TypeError("inherit_plugins must be a boolean"); + if (record(projectRoute) || inheritPlugins === false) { + config.route = + mergeProjectRoute( + config.route, + projectRoute as DaemonSessionRoute | undefined, + projectPath, + inheritPlugins !== false, + ) ?? config.route; + applyConfig(config, { route: config.route }); + if (config.route.additional_metadata) + config.additionalMetadata = config.route.additional_metadata; + } + if (nonEmptyString(safeProjectConfig.profile) && config.route.auth) { + delete config.route.auth.profile_id; + config.route.auth.source = "saved_profile"; + } + applyConfig(config, safeProjectConfig); + } catch { + config.enabled = false; + } + } else if (existsSync(projectPath)) { + config.enabled = false; + } config.showUi = boolean(process.env.BRAINTRUST_SHOW_UI) ?? config.showUi; config.showTraceLink = boolean(process.env.BRAINTRUST_SHOW_TRACE_LINK) ?? config.showTraceLink; diff --git a/src/runtime/js-daemon-client/src/index.ts b/src/runtime/js-daemon-client/src/index.ts index f519b5e1..a4ed59e3 100644 --- a/src/runtime/js-daemon-client/src/index.ts +++ b/src/runtime/js-daemon-client/src/index.ts @@ -1,13 +1,15 @@ import { spawnBackground } from "./background-process.ts" import { createHash } from "node:crypto" +import { existsSync, realpathSync } from "node:fs" import { createConnection, type Socket } from "node:net" import { homedir } from "node:os" -import { join } from "node:path" +import { dirname, join, resolve } from "node:path" export const DAEMON_PROTOCOL_VERSION = 1 export interface DaemonSessionRoute { auth?: { + source?: "auto" | "saved_profile" | "environment" /** Immutable saved-profile identifier. Preferred over legacy `profile`. */ profile_id?: string /** Mutable display name retained to read settings written before profile IDs. */ @@ -18,6 +20,7 @@ export interface DaemonSessionRoute { flush_mode?: "fire_and_forget" | "flush_on_turn_end" additional_metadata?: Record span_plugins?: string[] + tags?: string[] } export interface DaemonTraceSettings { @@ -25,6 +28,58 @@ export interface DaemonTraceSettings { route?: DaemonSessionRoute } +/** Find project settings at the Git root, or in the starting directory outside Git. */ +export function projectSettingsPath(directory: string): string { + const start = resolve(directory) + let current = start + while (true) { + if (existsSync(join(current, ".git"))) return join(current, ".braintrust.json") + const parent = dirname(current) + if (parent === current) return join(start, ".braintrust.json") + current = parent + } +} + +/** Recursively overlay objects and append arrays; scalar values replace. */ +export function mergeConfigObjects(base: Record, overlay: Record): Record { + const result = { ...base } + for (const [key, value] of Object.entries(overlay)) { + const prior = Object.hasOwn(result, key) ? result[key] : undefined + const merged = Array.isArray(prior) && Array.isArray(value) ? [...prior, ...value] : prior !== null && typeof prior === "object" && !Array.isArray(prior) && value !== null && typeof value === "object" && !Array.isArray(value) + ? mergeConfigObjects(prior as Record, value as Record) + : value + Object.defineProperty(result, key, { value: merged, enumerable: true, writable: true, configurable: true }) + } + return result +} + +/** Apply project-relative span plugins after inherited user plugins. */ +export function mergeProjectRoute(base: DaemonSessionRoute | undefined, overlay: DaemonSessionRoute | undefined, configPath: string, inheritPlugins = true): DaemonSessionRoute | undefined { + if (!base && !overlay) return undefined + if (!overlay && inheritPlugins) return base + const original = structuredClone(base ?? { destination: undefined }) as DaemonSessionRoute + if (!inheritPlugins) original.span_plugins = [] + if (!overlay) return original + const safe = structuredClone(overlay) + if (safe.span_plugins !== undefined) { + if (!Array.isArray(safe.span_plugins) || !safe.span_plugins.every((plugin) => typeof plugin === "string" && plugin.length > 0)) { + throw new TypeError("project span_plugins must be an array of paths") + } + safe.span_plugins = safe.span_plugins.map((plugin) => { + const absolute = resolve(dirname(configPath), plugin) + try { return realpathSync(absolute) } catch { return absolute } + }) + } + if (safe.auth?.profile && !safe.auth.profile_id && original.auth) { + delete original.auth.profile_id + original.auth.source = "saved_profile" + } + const nextDestination = safe.destination as Record | undefined + const oldDestination = original.destination as Record | undefined + if (nextDestination?.project_name && !nextDestination.project_id && oldDestination) delete oldDestination.project_id + return mergeConfigObjects(original as unknown as Record, safe as unknown as Record) as unknown as DaemonSessionRoute +} + const MANAGED_INSTANCE_CLAIMS = Symbol.for("braintrust.coding-agent.managed-instance-claims") /** Keep one live forwarding adapter when a managed run loads both its diff --git a/src/runtime/js-daemon-client/tests/client.test.ts b/src/runtime/js-daemon-client/tests/client.test.ts index eeb8cf6c..ff907875 100644 --- a/src/runtime/js-daemon-client/tests/client.test.ts +++ b/src/runtime/js-daemon-client/tests/client.test.ts @@ -8,9 +8,32 @@ import { claimManagedTracingInstance, DaemonClient, daemonSocketPath, + mergeProjectRoute, + mergeConfigObjects, resolveDaemonTraceSettings, } from "../src/index.ts" +describe("project route overlay", () => { + test("preserves special JSON keys without changing object prototypes", () => { + const overlay = JSON.parse('{"__proto__":{"polluted":true},"nested":{"list":[3]}}') + const merged = mergeConfigObjects({ nested: { keep: 1, list: [1, 2] } }, overlay) + assert.equal(Object.getPrototypeOf(merged), Object.prototype) + assert.deepEqual(merged["__proto__"], { polluted: true }) + assert.deepEqual(merged.nested, { keep: 1, list: [1, 2, 3] }) + }) + test("appends project plugins and can replace the inherited chain", () => { + const base = { destination: { type: "project_logs", project_name: "global" }, span_plugins: ["trusted"], tags: ["global"] } + const projectPath = join(tmpdir(), "example", ".braintrust.json") + const overlay = { destination: base.destination, span_plugins: ["project.mjs"], tags: ["project"] } + const appended = mergeProjectRoute(base, overlay, projectPath)! + assert.deepEqual(appended.span_plugins, ["trusted", join(tmpdir(), "example", "project.mjs")]) + assert.deepEqual(appended.tags, ["global", "project"]) + const replaced = mergeProjectRoute(base, overlay, projectPath, false)! + assert.deepEqual(replaced.span_plugins, [join(tmpdir(), "example", "project.mjs")]) + assert.deepEqual(base.span_plugins, ["trusted"]) + }) +}) + describe("managed adapter claims", () => { test("deduplicates only the same source and managed run", () => { const target = {} as typeof globalThis