From 9a5c20cbfac6665039434c900eb13f5270aa0696 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 17:28:59 +0800 Subject: [PATCH 01/18] Preserve tracing setup when disabled --- README.md | 2 +- bt-daemon/README.md | 5 +-- bt-daemon/src/command_output.rs | 22 ++++++++++-- bt-daemon/src/lib.rs | 2 +- bt-daemon/src/settings.rs | 2 +- bt-daemon/src/setup/mod.rs | 45 ++++++++++++++++++++++-- bt-daemon/src/trace_command.rs | 15 +++++++- bt-daemon/src/trace_runtime.rs | 28 +++++++++++++-- docs/coding-agent-tracing-plugin-spec.md | 6 ++-- 9 files changed, 112 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index e2fc35f5..c22eaf6b 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,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, or `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..51a91301 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -263,8 +263,9 @@ 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 +Use `bt trace disable ` to pause tracing while keeping the plugin and settings. +Use `bt trace enable ` to resume, or `bt trace uninstall ` to remove +the plugin and its Braintrust settings. `bt trace setup ` remains an alias for `bt trace enable ` for backwards compatibility. ## Build and test diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index 58d28ced..643f9a5d 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -170,6 +170,7 @@ pub enum TraceCommandOutput { Doctor(Box), Enable(SetupCommandOutput), Disable(SetupCommandOutput), + Uninstall(SetupCommandOutput), Update(UpdateCommandOutput), Stop(StopCommandOutput), Import { summaries: Vec }, @@ -219,6 +220,19 @@ impl TraceCommandOutput { }) } + pub fn uninstall( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Uninstall(SetupCommandOutput { + source: source.into(), + display_name: display_name.into(), + settings_path: settings_path.into(), + restart_required: true, + }) + } + pub fn update(source: impl Into, display_name: impl Into) -> Self { let source = source.into(); Self::Update(UpdateCommandOutput { @@ -307,10 +321,14 @@ impl TraceCommandOutput { setup.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 {} in {}.\nRestart the coding agent to apply the change.", disable.display_name, disable.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, @@ -438,7 +456,7 @@ mod tests { assert!(output .render(OutputFormat::Human) .unwrap() - .contains("removed for Google Antigravity")); + .contains("disabled for Google Antigravity")); } #[test] diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index c2f79a9a..f0326726 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -80,7 +80,7 @@ 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, diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 45873b14..4a73d584 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -102,7 +102,7 @@ impl AgentSettings { settings } - fn load_from(path: &Path) -> Self { + pub(crate) fn load_from(path: &Path) -> Self { let raw = match std::fs::read_to_string(path) { Ok(raw) => raw, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Self::default(), diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index d751f4bd..2a6da624 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -81,14 +81,35 @@ pub fn run_setup(args: EnableArgs, route: SessionRoute) -> anyhow::Result 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, exists| { + if exists { + 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, @@ -203,6 +224,26 @@ mod tests { } } + #[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":{"tags":["saved"]},"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); + let missing = temp.path().join("missing/braintrust.json"); + disable_tracing_at(&missing).unwrap(); + assert!(!missing.exists()); + } + #[test] fn tracing_settings_preserve_unrelated_fields_and_remove_legacy_keys() { let temp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/trace_command.rs b/bt-daemon/src/trace_command.rs index cbe81fd2..3ae66e34 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -23,8 +23,10 @@ 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. + /// Disable tracing while preserving the plugin and its configuration. Disable(DisableArgs), + /// Uninstall the tracing plugin and remove its saved configuration. + Uninstall(DisableArgs), /// Update an already installed Braintrust tracing plugin without changing its configuration. Update(UpdateArgs), /// Run the tracing daemon (foreground). @@ -395,6 +397,17 @@ mod tests { )); } + #[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 + }) + )); + } + #[test] fn update_accepts_every_setup_agent() { for agent in [ diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index f5709781..91331dec 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -652,15 +652,36 @@ async fn doctor_output_at( pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Result<()> { match args.command { TraceCommand::Setup(enable_args) => { - let mut route = resolve_command_route( + let saved = crate::settings::AgentSettings::load_from(&paths::agent_settings_path( + enable_args.agent.identity().id, + None, + )) + .route; + let mut route = resolve_host_route( &host, RouteRequirements { - destination_required: true, + destination_required: saved + .as_ref() + .and_then(|route| route.destination.as_ref()) + .is_none(), interactive_auth: true, persistent_auth: true, }, ) .await?; + if route.destination.is_none() { + if let Some(saved) = saved { + route.destination = saved.destination; + route.auth = saved.auth; + } + } + let lease = host + .services + .resolve_auth(&route.auth, AuthResolveReason::Initial) + .await?; + let org_name = require_resolved_org(&route, &lease)?; + route.auth = lease.selection; + route.auth.org_name = Some(org_name); apply_additional_metadata(&mut route, enable_args.additional_metadata.as_deref())?; apply_tags(&mut route, &enable_args.tags)?; if !enable_args.plugin.is_empty() { @@ -676,6 +697,9 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul TraceCommand::Disable(disable_args) => { print_output(run_disable(disable_args.agent)?, host.output_format) } + TraceCommand::Uninstall(args) => { + print_output(crate::run_uninstall(args.agent)?, host.output_format) + } TraceCommand::Update(update_args) => { let codex = matches!(update_args.agent, SetupAgent::Codex); let output = crate::run_update(update_args.agent)?; diff --git a/docs/coding-agent-tracing-plugin-spec.md b/docs/coding-agent-tracing-plugin-spec.md index f089f694..2482760a 100644 --- a/docs/coding-agent-tracing-plugin-spec.md +++ b/docs/coding-agent-tracing-plugin-spec.md @@ -400,8 +400,8 @@ translator rather than separate trace builders. `bt trace enable ` 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 disable ` MUST preserve the adapter and configuration while disabling tracing. +`bt trace uninstall ` MUST remove only Braintrust-managed state. Both MUST be safe when repeated. Doctor/status output SHOULD diagnose: @@ -611,7 +611,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. | From 1bcd2f17fdb32fd7aa4b8017e7cf438898657dac Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 17:32:09 +0800 Subject: [PATCH 02/18] Support repository-scoped tracing settings --- bt-daemon/README.md | 21 +++ bt-daemon/src/hook.rs | 39 ++++- bt-daemon/src/settings.rs | 180 +++++++++++++++++++++-- bt-daemon/src/trace_runtime.rs | 20 ++- bt-daemon/tests/project_hook_settings.rs | 72 +++++++++ src/plugins/claude/content/README.md | 2 + src/plugins/cursor/content/README.md | 2 + 7 files changed, 319 insertions(+), 17 deletions(-) create mode 100644 bt-daemon/tests/project_hook_settings.rs diff --git a/bt-daemon/README.md b/bt-daemon/README.md index b96ab3de..8d6589b5 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -58,6 +58,27 @@ or `bt trace doctor ` for configuration, authentication, and recent session diagnostics. Hook exit codes can be observed by the caller while the coding agent decides whether to continue its turn. +## Repository-scoped tracing for Claude Code and Cursor + +Install the agent integration with `bt trace enable claude` or `bt trace enable cursor`. +To trace only selected repositories, set `trace_to_braintrust` to `false` in the +corresponding user-level `braintrust.json`, then commit `.claude/braintrust.json` +or `.cursor/braintrust.json` in each selected repository: + +```json +{ + "trace_to_braintrust": true, + "project": "my-braintrust-project" +} +``` + +The hook uses the closest project file within the Git repository, including when +Claude Code starts in a subdirectory. For Cursor workspaces with multiple roots, +the first root containing a project file supplies the settings for the session. +Project settings override user settings; omitted top-level fields inherit from the +user settings. A project `route` replaces the user route. A managed `bt trace run` takes precedence over both. `bt trace doctor` +reports user-level settings, not the settings of a particular repository. + ## Per-agent plugin settings Each coding agent reads an independent non-credential `braintrust.json` file: diff --git a/bt-daemon/src/hook.rs b/bt-daemon/src/hook.rs index 5be86afc..53429f09 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -105,11 +105,13 @@ pub async fn run_hook(args: HookArgs, route: SessionRoute, host: HostInfo) -> an if args.managed_context.is_some() { return run_hook_with_route(args, route, host).await; } - let settings = settings::AgentSettings::load_for_hook(&args.source)?; + let payload = read_project_hook_payload(&args)?; + let settings = + settings::AgentSettings::load_for_hook_payload(&args.source, payload.as_ref())?; if !settings.tracing_enabled() { return Ok(()); } - run_hook_with_route(args, settings.route.unwrap_or(route), host).await + run_hook_with_payload(args, settings.route.unwrap_or(route), host, payload).await } .await; if let Some(response) = response { @@ -172,7 +174,32 @@ pub(crate) async fn run_hook_with_route( route: SessionRoute, host: HostInfo, ) -> anyhow::Result<()> { - with_hook_capture_timeout(args.capture_timeout_ms, capture_hook(args, route, host)).await + run_hook_with_payload(args, route, host, None).await +} + +pub(crate) fn read_project_hook_payload( + args: &HookArgs, +) -> anyhow::Result> { + if matches!(args.source.as_str(), "claude" | "claude-code" | "cursor") { + Ok(Some(read_stdin_json( + args.transcript_path_field.as_deref(), + )?)) + } else { + Ok(None) + } +} + +pub(crate) async fn run_hook_with_payload( + args: HookArgs, + route: SessionRoute, + host: HostInfo, + payload: Option, +) -> anyhow::Result<()> { + with_hook_capture_timeout( + args.capture_timeout_ms, + capture_hook(args, route, host, payload), + ) + .await } pub(crate) async fn with_hook_capture_timeout( @@ -193,6 +220,7 @@ async fn capture_hook( mut args: HookArgs, mut route: SessionRoute, host: HostInfo, + payload: Option, ) -> anyhow::Result<()> { let managed_context = if let Some(path) = &args.managed_context { if crate::translate::canonical_source_name(&args.source) != "muse" || !args.managed_run_hook @@ -212,7 +240,10 @@ async fn capture_hook( } else { None }; - let mut payload = read_stdin_json(args.transcript_path_field.as_deref())?; + let mut payload = match payload { + Some(payload) => payload, + None => read_stdin_json(args.transcript_path_field.as_deref())?, + }; resolve_dynamic_hook_versions(&mut args, &payload); diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 45873b14..aa7c0c8c 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -6,12 +6,12 @@ //! persistent agent configuration. use crate::paths; -use crate::wire::SessionRoute; +use crate::wire::{SessionRoute, TraceDestination}; use fs2::FileExt; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; pub(crate) const INVOCATION_SETTINGS_ENV: &str = "BT_TRACE_INVOCATION_SETTINGS"; @@ -38,15 +38,66 @@ pub(crate) struct AgentSettings { } impl AgentSettings { - /// Hook invocations must report broken configuration instead of treating - /// it as a successful event. A managed run's invocation route is complete - /// and intentionally supersedes any persistent settings file. - pub(crate) fn load_for_hook(source: &str) -> anyhow::Result { + pub(crate) fn load_for_hook_payload( + source: &str, + payload: Option<&Value>, + ) -> anyhow::Result { let invocation = std::env::var(INVOCATION_SETTINGS_ENV).ok(); - Self::load_hook_from_sources( - &paths::agent_settings_path(source, None), - invocation.as_deref(), - ) + let user_path = paths::agent_settings_path(source, None); + let project_path = payload.and_then(|payload| project_settings_path(source, payload)); + Self::load_hook_with_project(&user_path, project_path.as_deref(), invocation.as_deref()) + } + + fn load_hook_with_project( + user_path: &Path, + project_path: Option<&Path>, + invocation: Option<&str>, + ) -> anyhow::Result { + let path = match (invocation, project_path) { + (Some(_), _) | (_, None) => return Self::load_hook_from_sources(user_path, invocation), + (None, Some(path)) => path, + }; + let raw = std::fs::read_to_string(path).map_err(|error| { + anyhow::anyhow!("read tracing settings at {}: {error}", path.display()) + })?; + let project: Value = serde_json::from_str(&raw).map_err(|error| { + anyhow::anyhow!("parse tracing settings at {}: {error}", path.display()) + })?; + let object = project.as_object().ok_or_else(|| { + anyhow::anyhow!("tracing settings at {} must be an object", path.display()) + })?; + let overlay: Self = serde_json::from_value(project.clone())?; + let mut settings = if user_path.exists() { + Self::load_hook_from_sources(user_path, None)? + } else { + Self::default() + }; + if overlay.trace_to_braintrust.is_some() { + settings.trace_to_braintrust = overlay.trace_to_braintrust; + } + if overlay.route.is_some() { + settings.route = overlay.route; + } + 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()), + }); + } + if settings.trace_to_braintrust.is_none() { + anyhow::bail!( + "tracing settings at {} have no `trace_to_braintrust` value", + path.display() + ); + } + Ok(settings) } fn load_hook_from_sources(path: &Path, invocation: Option<&str>) -> anyhow::Result { @@ -125,6 +176,46 @@ impl AgentSettings { } } +fn project_settings_path(source: &str, payload: &Value) -> Option { + let directory = match source { + "claude" | "claude-code" => ".claude", + "cursor" => ".cursor", + _ => return None, + }; + let roots: Vec<&str> = if source == "cursor" { + payload + .get("workspace_roots") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect() + } else { + payload + .get("cwd") + .and_then(Value::as_str) + .into_iter() + .collect() + }; + roots + .into_iter() + .filter_map(|root| { + let root = Path::new(root); + if !root.is_absolute() { + return None; + } + let boundary = root + .ancestors() + .find(|dir| dir.join(".git").exists()) + .unwrap_or(root); + root.ancestors() + .take_while(|dir| dir.starts_with(boundary)) + .map(|dir| dir.join(directory).join("braintrust.json")) + .find(|path| path.is_file()) + }) + .next() +} + /// Replace a still-matching name-only route with the host-canonical route. /// The caller must hold the settings lock used by setup while invoking this. pub(crate) fn migrate_persisted_route( @@ -210,6 +301,75 @@ 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(&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, "invalid").unwrap(); + assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); + } + + #[test] + fn finds_repo_settings_for_nested_claude_and_cursor_workspaces() { + use super::*; + let temp = tempfile::tempdir().unwrap(); + let repo = temp.path().join("repo"); + let nested = repo.join("src/nested"); + std::fs::create_dir_all(&nested).unwrap(); + std::fs::create_dir(repo.join(".git")).unwrap(); + for (source, dir) in [("claude", ".claude"), ("cursor", ".cursor")] { + std::fs::create_dir(repo.join(dir)).unwrap(); + let path = repo.join(dir).join("braintrust.json"); + std::fs::write(&path, "{}").unwrap(); + let payload = if source == "claude" { + serde_json::json!({"cwd": nested}) + } else { + serde_json::json!({"workspace_roots": [nested]}) + }; + assert_eq!(project_settings_path(source, &payload), Some(path)); + } + let outside = temp.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + assert!(project_settings_path("claude", &serde_json::json!({"cwd": outside})).is_none()); + } use super::*; #[test] diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index f5709781..9ef2a65e 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -707,8 +707,12 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul ) .await; } - let settings = crate::settings::AgentSettings::load_for_hook(&hook_args.source)?; - run_hook_command(hook_args, &host, settings).await + let payload = crate::hook::read_project_hook_payload(&hook_args)?; + let settings = crate::settings::AgentSettings::load_for_hook_payload( + &hook_args.source, + payload.as_ref(), + )?; + run_hook_command_with_payload(hook_args, &host, settings, payload).await } .await; if let Some(response) = response { @@ -785,10 +789,20 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul } } +#[cfg(test)] async fn run_hook_command( hook_args: crate::HookArgs, host: &TraceHostContext, settings: crate::settings::AgentSettings, +) -> anyhow::Result<()> { + run_hook_command_with_payload(hook_args, host, settings, None).await +} + +async fn run_hook_command_with_payload( + hook_args: crate::HookArgs, + host: &TraceHostContext, + settings: crate::settings::AgentSettings, + payload: Option, ) -> anyhow::Result<()> { if !settings.tracing_enabled() { return Ok(()); @@ -798,7 +812,7 @@ async fn run_hook_command( Some(route) => route, None => resolve_host_route(host, RouteRequirements::default()).await?, }; - crate::hook::run_hook_with_route(hook_args, route, host_info(host)).await + crate::hook::run_hook_with_payload(hook_args, route, host_info(host), payload).await }) .await } diff --git a/bt-daemon/tests/project_hook_settings.rs b/bt-daemon/tests/project_hook_settings.rs new file mode 100644 index 00000000..dfdaec04 --- /dev/null +++ b/bt-daemon/tests/project_hook_settings.rs @@ -0,0 +1,72 @@ +#![cfg(feature = "cli")] + +use std::io::Write; +use std::process::{Command, Stdio}; + +#[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"); + std::fs::write(&user, r#"{"trace_to_braintrust":false}"#).unwrap(); + for (source, dir, payload) in [ + ( + "claude", + ".claude", + serde_json::json!({"cwd":repo,"session_id":"s","hook_event_name":"Stop"}), + ), + ( + "cursor", + ".cursor", + serde_json::json!({"workspace_roots":[repo],"conversation_id":"s","hook_event_name":"stop"}), + ), + ] { + let config_dir = repo.join(dir); + std::fs::create_dir_all(&config_dir).unwrap(); + let config = config_dir.join("braintrust.json"); + let run = |enabled: bool| { + std::fs::write( + &config, + format!(r#"{{"trace_to_braintrust":{enabled},"project":"test"}}"#), + ) + .unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_bt-daemon")) + .args([ + "hook", + "--source", + source, + "--no-spawn", + "--session-id-field", + if source == "cursor" { + "conversation_id" + } else { + "session_id" + }, + ]) + .env("BRAINTRUST_DAEMON_CONFIG", &user) + .env("HOME", temp.path()) + .env_remove("BT_TRACE_INVOCATION_SETTINGS") + .env_remove("_BT_TRACE_MANAGED_RUN") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(payload.to_string().as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() + }; + assert!(run(false).status.success()); + let enabled = run(true); + assert!( + !enabled.status.success(), + "enabled hook should try to connect to the absent daemon" + ); + assert!(!enabled.stderr.is_empty()); + } +} diff --git a/src/plugins/claude/content/README.md b/src/plugins/claude/content/README.md index c530ec6b..a4685530 100644 --- a/src/plugins/claude/content/README.md +++ b/src/plugins/claude/content/README.md @@ -116,3 +116,5 @@ bt trace disable claude See the [tracing plugin guide](plugins/trace-claude-code/README.md) for the capture architecture and supported surfaces. + +For repository-scoped tracing, see the [daemon configuration guide](https://github.com/braintrustdata/braintrust-coding-agent-plugins/blob/main/bt-daemon/README.md#repository-scoped-tracing-for-claude-code-and-cursor). diff --git a/src/plugins/cursor/content/README.md b/src/plugins/cursor/content/README.md index a20b3a06..4281561f 100644 --- a/src/plugins/cursor/content/README.md +++ b/src/plugins/cursor/content/README.md @@ -124,3 +124,5 @@ bt trace status bt trace update cursor bt trace disable cursor ``` + +For repository-scoped tracing, see the [daemon configuration guide](https://github.com/braintrustdata/braintrust-coding-agent-plugins/blob/main/bt-daemon/README.md#repository-scoped-tracing-for-claude-code-and-cursor). From 6234abc7a8b4577ae98cbb5f533e6f603cfe2a21 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 17:41:39 +0800 Subject: [PATCH 03/18] Restrict repository tracing settings and fix hook tests --- bt-daemon/README.md | 4 +- bt-daemon/src/settings.rs | 12 +++- bt-daemon/src/trace_runtime.rs | 14 ++++- bt-daemon/tests/command_output.rs | 68 ++++++++++++++++++++++ bt-daemon/tests/project_hook_settings.rs | 72 ------------------------ 5 files changed, 92 insertions(+), 78 deletions(-) delete mode 100644 bt-daemon/tests/project_hook_settings.rs diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 8d6589b5..0cbed7c1 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -75,8 +75,8 @@ or `.cursor/braintrust.json` in each selected repository: The hook uses the closest project file within the Git repository, including when Claude Code starts in a subdirectory. For Cursor workspaces with multiple roots, the first root containing a project file supplies the settings for the session. -Project settings override user settings; omitted top-level fields inherit from the -user settings. A project `route` replaces the user route. A managed `bt trace run` takes precedence over both. `bt trace doctor` +Project settings can select `trace_to_braintrust` and `project`; other route +settings, including span plugins, come from the user settings. A managed `bt trace run` takes precedence over both. `bt trace doctor` reports user-level settings, not the settings of a particular repository. ## Per-agent plugin settings diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index aa7c0c8c..75431174 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -66,6 +66,9 @@ impl AgentSettings { let object = project.as_object().ok_or_else(|| { anyhow::anyhow!("tracing settings at {} must be an object", path.display()) })?; + if object.contains_key("route") { + anyhow::bail!("repository tracing settings at {} cannot specify `route`; use `project` to select a destination", path.display()); + } let overlay: Self = serde_json::from_value(project.clone())?; let mut settings = if user_path.exists() { Self::load_hook_from_sources(user_path, None)? @@ -75,9 +78,6 @@ impl AgentSettings { if overlay.trace_to_braintrust.is_some() { settings.trace_to_braintrust = overlay.trace_to_braintrust; } - if overlay.route.is_some() { - settings.route = overlay.route; - } if let Some(project) = object.get("project") { let name = project .as_str() @@ -343,6 +343,12 @@ mod tests { .unwrap() .tracing_enabled() ); + std::fs::write( + &project, + r#"{"trace_to_braintrust":true,"route":{"span_plugins":["./malicious.js"]}}"#, + ) + .unwrap(); + assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); std::fs::write(&project, "invalid").unwrap(); assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); } diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 9ef2a65e..819c1835 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -1257,7 +1257,19 @@ mod tests { if user_hook { child.env(crate::setup::cursor::USER_HOOK_ENV, "1"); } - let output = child.output().unwrap(); + use std::io::Write; + child + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + let mut process = child.spawn().unwrap(); + process + .stdin + .take() + .unwrap() + .write_all(br#"{"workspace_roots":[]}"#) + .unwrap(); + let output = process.wait_with_output().unwrap(); assert!( output.status.success(), "user_hook={user_hook}: {}\n{}", diff --git a/bt-daemon/tests/command_output.rs b/bt-daemon/tests/command_output.rs index aa170279..1dd1e5c5 100644 --- a/bt-daemon/tests/command_output.rs +++ b/bt-daemon/tests/command_output.rs @@ -200,3 +200,71 @@ 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"); + std::fs::write(&user, r#"{"trace_to_braintrust":false}"#).unwrap(); + for (source, dir, payload) in [ + ( + "claude", + ".claude", + serde_json::json!({"cwd":repo,"session_id":"s","hook_event_name":"Stop"}), + ), + ( + "cursor", + ".cursor", + serde_json::json!({"workspace_roots":[repo],"conversation_id":"s","hook_event_name":"stop"}), + ), + ] { + let config_dir = repo.join(dir); + std::fs::create_dir_all(&config_dir).unwrap(); + let config = config_dir.join("braintrust.json"); + let run = |enabled: bool| { + std::fs::write( + &config, + format!(r#"{{"trace_to_braintrust":{enabled},"project":"test"}}"#), + ) + .unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_bt-daemon")) + .args([ + "hook", + "--source", + source, + "--no-spawn", + "--session-id-field", + if source == "cursor" { + "conversation_id" + } else { + "session_id" + }, + ]) + .env("BRAINTRUST_DAEMON_CONFIG", &user) + .env("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/project_hook_settings.rs b/bt-daemon/tests/project_hook_settings.rs deleted file mode 100644 index dfdaec04..00000000 --- a/bt-daemon/tests/project_hook_settings.rs +++ /dev/null @@ -1,72 +0,0 @@ -#![cfg(feature = "cli")] - -use std::io::Write; -use std::process::{Command, Stdio}; - -#[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"); - std::fs::write(&user, r#"{"trace_to_braintrust":false}"#).unwrap(); - for (source, dir, payload) in [ - ( - "claude", - ".claude", - serde_json::json!({"cwd":repo,"session_id":"s","hook_event_name":"Stop"}), - ), - ( - "cursor", - ".cursor", - serde_json::json!({"workspace_roots":[repo],"conversation_id":"s","hook_event_name":"stop"}), - ), - ] { - let config_dir = repo.join(dir); - std::fs::create_dir_all(&config_dir).unwrap(); - let config = config_dir.join("braintrust.json"); - let run = |enabled: bool| { - std::fs::write( - &config, - format!(r#"{{"trace_to_braintrust":{enabled},"project":"test"}}"#), - ) - .unwrap(); - let mut child = Command::new(env!("CARGO_BIN_EXE_bt-daemon")) - .args([ - "hook", - "--source", - source, - "--no-spawn", - "--session-id-field", - if source == "cursor" { - "conversation_id" - } else { - "session_id" - }, - ]) - .env("BRAINTRUST_DAEMON_CONFIG", &user) - .env("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()); - } -} From 315a5a96520a33bd1c95c89fc15bbf213540b373 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 17:42:59 +0800 Subject: [PATCH 04/18] Respect explicit pause and selected authentication --- bt-daemon/src/setup/mod.rs | 8 +++++ bt-daemon/src/trace_runtime.rs | 44 ++++++++++++++++++++++- src/plugins/pi/content/src/config.test.ts | 14 ++++++++ src/plugins/pi/content/src/config.ts | 5 +-- 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index 2a6da624..cb3c095b 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -97,6 +97,7 @@ fn disable_tracing_at(path: &Path) -> anyhow::Result<()> { common::edit_object(path, FileAccess::OwnerOnly, |settings, exists| { if exists { settings.insert("trace_to_braintrust".into(), Value::Bool(false)); + settings.insert("tracing_disabled".into(), Value::Bool(true)); } Ok(()) }) @@ -169,6 +170,7 @@ fn enable_tracing_at(path: &Path, mut route: SessionRoute) -> anyhow::Result<()> .unwrap_or_default(); } settings.insert("trace_to_braintrust".into(), Value::Bool(true)); + settings.remove("tracing_disabled"); settings.insert("route".into(), serde_json::to_value(route)?); for key in [ "traceToBraintrust", @@ -237,8 +239,14 @@ mod tests { 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["tracing_disabled"], true); assert_eq!(value["route"]["tags"][0], "saved"); assert_eq!(value["custom"], 1); + enable_tracing_at(&path, SessionRoute::default()).unwrap(); + let enabled: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(enabled["trace_to_braintrust"], true); + assert!(enabled.get("tracing_disabled").is_none()); + assert_eq!(enabled["route"]["tags"][0], "saved"); let missing = temp.path().join("missing/braintrust.json"); disable_tracing_at(&missing).unwrap(); assert!(!missing.exists()); diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 91331dec..baea2be1 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -291,6 +291,21 @@ async fn resolve_command_route( Ok(route) } +fn merge_saved_auth(mut selected: AuthSelection, saved: AuthSelection) -> AuthSelection { + let selected_profile = selected.source != AuthSource::Auto + || selected.profile_id.is_some() + || selected.profile.is_some(); + if !selected_profile { + selected.source = saved.source; + selected.profile_id = saved.profile_id; + selected.profile = saved.profile; + if selected.org_name.is_none() { + selected.org_name = saved.org_name; + } + } + selected +} + fn print_output(output: TraceCommandOutput, format: OutputFormat) -> anyhow::Result<()> { println!("{}", output.render(format)?); Ok(()) @@ -672,7 +687,7 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul if route.destination.is_none() { if let Some(saved) = saved { route.destination = saved.destination; - route.auth = saved.auth; + route.auth = merge_saved_auth(route.auth, saved.auth); } } let lease = host @@ -836,6 +851,33 @@ mod tests { use std::path::PathBuf; use std::sync::Mutex; + #[test] + fn saved_auth_fills_only_unselected_credentials() { + let saved = AuthSelection { + source: AuthSource::SavedProfile, + profile: Some("old".into()), + org_name: Some("old-org".into()), + ..Default::default() + }; + let selected = AuthSelection { + source: AuthSource::SavedProfile, + profile: Some("new".into()), + ..Default::default() + }; + assert_eq!(merge_saved_auth(selected.clone(), saved.clone()), selected); + let org = AuthSelection { + org_name: Some("new-org".into()), + ..Default::default() + }; + let merged = merge_saved_auth(org, saved.clone()); + assert_eq!(merged.profile.as_deref(), Some("old")); + assert_eq!(merged.org_name.as_deref(), Some("new-org")); + assert_eq!( + merge_saved_auth(AuthSelection::default(), saved.clone()), + saved + ); + } + #[test] fn mounted_child_commands_preserve_the_host_prefix() { let mounted = RunHookCommand { diff --git a/src/plugins/pi/content/src/config.test.ts b/src/plugins/pi/content/src/config.test.ts index 45d6b962..f20e0532 100644 --- a/src/plugins/pi/content/src/config.test.ts +++ b/src/plugins/pi/content/src/config.test.ts @@ -162,6 +162,20 @@ describe("loadConfig", () => { expect(loadConfig(cwd)).toEqual(DEFAULT_CONFIG); }); + it("honors an explicit user pause even when a project enables tracing", () => { + writeJson(join(home, ".pi", "agent", "braintrust.json"), { + trace_to_braintrust: false, + tracing_disabled: true, + }); + writeJson(join(cwd, ".pi", "braintrust.json"), { trace_to_braintrust: true }); + 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..59f8706e 100644 --- a/src/plugins/pi/content/src/config.ts +++ b/src/plugins/pi/content/src/config.ts @@ -101,14 +101,15 @@ export function loadConfig(cwd = process.cwd()): PiConfig { }, }; - applyConfig(config, readConfig(join(homedir(), ".pi", "agent", "braintrust.json"))); + const userConfig = readConfig(join(homedir(), ".pi", "agent", "braintrust.json")); + applyConfig(config, userConfig); applyConfig(config, readConfig(join(cwd, PROJECT_CONFIG_DIR_NAME, "braintrust.json"))); config.showUi = boolean(process.env.BRAINTRUST_SHOW_UI) ?? config.showUi; config.showTraceLink = boolean(process.env.BRAINTRUST_SHOW_TRACE_LINK) ?? config.showTraceLink; const traceSettings = resolveDaemonTraceSettings({ - trace_to_braintrust: config.enabled, + trace_to_braintrust: userConfig?.tracing_disabled === true ? false : config.enabled, route: config.route, }); config.enabled = traceSettings.trace_to_braintrust === true; From 81465de7ad462ac32c6893aa112e3666c799b54c Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 17:44:04 +0800 Subject: [PATCH 05/18] Honor explicit tracing pauses in repositories --- bt-daemon/README.md | 3 ++- bt-daemon/src/settings.rs | 24 ++++++++++++++++++++++++ bt-daemon/tests/command_output.rs | 8 ++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 0cbed7c1..6efdc808 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -76,7 +76,8 @@ The hook uses the closest project file within the Git repository, including when Claude Code starts in a subdirectory. For Cursor workspaces with multiple roots, the first root containing a project file supplies the settings for the session. Project settings can select `trace_to_braintrust` and `project`; other route -settings, including span plugins, come from the user settings. A managed `bt trace run` takes precedence over both. `bt trace doctor` +settings, including span plugins, come from the user settings. An explicit `bt trace disable` pauses persistent tracing even in opted-in +repositories; a managed `bt trace run` takes precedence over both. `bt trace doctor` reports user-level settings, not the settings of a particular repository. ## Per-agent plugin settings diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 75431174..fb709424 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -91,6 +91,13 @@ impl AgentSettings { project_name: Some(name.to_owned()), }); } + // An explicit user pause must remain effective even when a repository opts in. + if user_path.exists() { + let user: Value = serde_json::from_str(&std::fs::read_to_string(user_path)?)?; + if user.get("tracing_disabled").and_then(Value::as_bool) == Some(true) { + settings.trace_to_braintrust = Some(false); + } + } if settings.trace_to_braintrust.is_none() { anyhow::bail!( "tracing settings at {} have no `trace_to_braintrust` value", @@ -330,6 +337,23 @@ mod tests { .unwrap() .tracing_enabled() ); + std::fs::write( + &user, + r#"{"trace_to_braintrust":false,"tracing_disabled":true}"#, + ) + .unwrap(); + assert!( + !AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .tracing_enabled() + ); + assert!(AgentSettings::load_hook_with_project( + &user, + Some(&project), + Some(r#"{"trace_to_braintrust":true,"route":{}}"#) + ) + .unwrap() + .tracing_enabled()); std::fs::write(&project, r#"{"trace_to_braintrust":false}"#).unwrap(); assert!( !AgentSettings::load_hook_with_project(&user, Some(&project), None) diff --git a/bt-daemon/tests/command_output.rs b/bt-daemon/tests/command_output.rs index 1dd1e5c5..19321f75 100644 --- a/bt-daemon/tests/command_output.rs +++ b/bt-daemon/tests/command_output.rs @@ -207,6 +207,13 @@ fn project_settings_control_hook_capture_from_native_payload() { 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 [ ( @@ -243,6 +250,7 @@ fn project_settings_control_hook_capture_from_native_payload() { }, ]) .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") From 87e3adbd79f74f27f58e8882007a4105c699075d Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 17:45:02 +0800 Subject: [PATCH 06/18] Pause tracing without existing user settings --- bt-daemon/src/setup/mod.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index cb3c095b..57248d76 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -94,11 +94,9 @@ pub fn run_disable(agent: SetupAgent) -> anyhow::Result { } fn disable_tracing_at(path: &Path) -> anyhow::Result<()> { - common::edit_object(path, FileAccess::OwnerOnly, |settings, exists| { - if exists { - settings.insert("trace_to_braintrust".into(), Value::Bool(false)); - settings.insert("tracing_disabled".into(), Value::Bool(true)); - } + common::edit_object(path, FileAccess::OwnerOnly, |settings, _| { + settings.insert("trace_to_braintrust".into(), Value::Bool(false)); + settings.insert("tracing_disabled".into(), Value::Bool(true)); Ok(()) }) } @@ -249,7 +247,9 @@ mod tests { assert_eq!(enabled["route"]["tags"][0], "saved"); let missing = temp.path().join("missing/braintrust.json"); disable_tracing_at(&missing).unwrap(); - assert!(!missing.exists()); + let created: Value = serde_json::from_slice(&std::fs::read(&missing).unwrap()).unwrap(); + assert_eq!(created["tracing_disabled"], true); + assert_eq!(created["trace_to_braintrust"], false); } #[test] From 5e3f1f702a9a09109607c98260c35ddf084f6783 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 18:05:07 +0800 Subject: [PATCH 07/18] Separate tracing setup from enable --- README.md | 4 +- bt-daemon/README.md | 12 +-- bt-daemon/src/codex_hooks.rs | 2 +- bt-daemon/src/command_output.rs | 36 ++++++++- bt-daemon/src/settings.rs | 2 +- bt-daemon/src/setup/antigravity.rs | 2 +- bt-daemon/src/setup/claude.rs | 4 +- bt-daemon/src/setup/common.rs | 6 +- bt-daemon/src/setup/cursor/mod.rs | 6 +- bt-daemon/src/setup/grok.rs | 6 +- bt-daemon/src/setup/mod.rs | 50 +++++++++++-- bt-daemon/src/setup/muse.rs | 4 +- bt-daemon/src/setup/opencode.rs | 2 +- bt-daemon/src/trace_command.rs | 36 ++++++--- bt-daemon/src/trace_runtime.rs | 74 ++----------------- docs/coding-agent-tracing-plugin-spec.md | 4 +- src/plugins/antigravity/content/README.md | 2 +- src/plugins/claude/content/README.md | 6 +- .../plugins/trace-claude-code/README.md | 10 +-- src/plugins/codex/content/README.md | 2 +- .../content/plugins/trace-codex/README.md | 6 +- src/plugins/cursor/content/README.md | 10 +-- src/plugins/grok/content/README.md | 2 +- src/plugins/opencode/content/README.md | 4 +- src/plugins/opencode/content/install.sh | 2 +- src/plugins/opencode/content/src/config.ts | 2 +- src/plugins/pi/content/README.md | 6 +- 27 files changed, 161 insertions(+), 141 deletions(-) diff --git a/README.md b/README.md index c22eaf6b..5edda7dd 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ then authenticate and enable tracing. For example: ```bash bt login -bt trace enable claude --project my-coding-agent +bt trace setup claude --project my-coding-agent ``` Replace `claude` with your agent's CLI name below. Restart the agent after @@ -41,7 +41,7 @@ setup and follow any plugin or hook trust prompts. ## Supported agents -All six support `bt trace enable`, `update`, `disable`, and `doctor`. +All six support `bt trace setup`, `enable`, `update`, `disable`, and `doctor`. | Agent and setup guide | CLI name | One-off traced run | Import / live attach | Distribution | |---|---|---|---|---| diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 51a91301..be29b2bb 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -146,7 +146,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 setup codex --plugin ./redact.mjs --plugin ./tag-ci.mjs ``` `run` and `import` plugins apply only to that command. They replace, rather than @@ -228,12 +228,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 setup 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 setup`, `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 +251,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 setup claude --tag ci --tag release-validation bt trace run codex --tag ci -- "summarize this change" bt trace import claude session-id --tag historical-import ``` @@ -265,8 +265,8 @@ BRAINTRUST_TAGS=ci,release-validation bt trace run codex -- "summarize this chan Use `bt trace disable ` to pause tracing while keeping the plugin and settings. Use `bt trace enable ` to resume, or `bt trace uninstall ` to remove -the plugin and its Braintrust settings. `bt trace setup ` remains an alias for `bt trace -enable ` for backwards compatibility. +the plugin and its Braintrust settings. Use `bt trace setup ` to install or +change the configuration. ## Build and test diff --git a/bt-daemon/src/codex_hooks.rs b/bt-daemon/src/codex_hooks.rs index b3a7fd41..4a2efdb7 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 setup codex`" ); let hooks = request( &mut stdin, diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index 643f9a5d..942af479 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -168,6 +168,7 @@ pub struct DoctorCommandOutput { pub enum TraceCommandOutput { Status(StatusCommandOutput), Doctor(Box), + Setup(SetupCommandOutput), Enable(SetupCommandOutput), Disable(SetupCommandOutput), Uninstall(SetupCommandOutput), @@ -191,7 +192,7 @@ impl TraceCommandOutput { settings_path: impl Into, ) -> Self { let source = source.into(); - Self::Enable(SetupCommandOutput { + Self::Setup(SetupCommandOutput { source, display_name: display_name.into(), settings_path: settings_path.into(), @@ -199,6 +200,19 @@ impl TraceCommandOutput { }) } + pub fn enable( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Enable(SetupCommandOutput { + source: source.into(), + display_name: display_name.into(), + settings_path: settings_path.into(), + restart_required: true, + }) + } + pub fn stop(running: bool, stopped: bool) -> Self { Self::Stop(StopCommandOutput { running, stopped }) } @@ -315,11 +329,15 @@ impl TraceCommandOutput { } Ok(rendered) } - Self::Enable(setup) => Ok(format!( + Self::Setup(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() )), + Self::Enable(enable) => Ok(format!( + "Braintrust tracing is enabled for {} in {}.\nRestart the coding agent to apply the change.", + enable.display_name, enable.settings_path.display() + )), Self::Disable(disable) => Ok(format!( "Braintrust tracing is disabled for {} in {}.\nRestart the coding agent to apply the change.", disable.display_name, @@ -437,12 +455,24 @@ mod tests { ); 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"], "setup"); 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!(output + .render(OutputFormat::Human) + .unwrap() + .contains("tracing is enabled")); + } + #[test] fn disable_output_is_explicit() { let output = TraceCommandOutput::disable( diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 4a73d584..45873b14 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -102,7 +102,7 @@ impl AgentSettings { settings } - pub(crate) fn load_from(path: &Path) -> Self { + fn load_from(path: &Path) -> Self { let raw = match std::fs::read_to_string(path) { Ok(raw) => raw, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Self::default(), diff --git a/bt-daemon/src/setup/antigravity.rs b/bt-daemon/src/setup/antigravity.rs index 361751c8..7e6fcc89 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 setup 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..f2ea6f1e 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 setup 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 setup 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..146dc38f 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 setup ` 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 setup {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 setup {agent}`" ); } runner.run( diff --git a/bt-daemon/src/setup/cursor/mod.rs b/bt-daemon/src/setup/cursor/mod.rs index 63797b6a..98e01da7 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 setup 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 setup 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 setup 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..013fb31d 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 setup 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 setup 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 setup grok`" ); } runner.run("grok", &["plugin", "update", PLUGIN]) diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index 57248d76..7ba662c9 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::{SetupAgent, SetupArgs}; use crate::wire::SessionRoute; use crate::TraceCommandOutput; use anyhow::Context; @@ -64,7 +64,7 @@ pub(crate) fn update_warning(source: &str) -> Option { /// 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(); @@ -76,9 +76,40 @@ pub fn run_enable(args: EnableArgs, route: SessionRoute) -> anyhow::Result anyhow::Result { - run_enable(args, route) +/// 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, + path, + )) +} + +fn enable_existing_at(path: &Path) -> anyhow::Result<()> { + if !path.exists() { + anyhow::bail!( + "tracing is not configured at {}; run `bt trace setup` 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 setup` first", + path.display() + ); + } + settings.insert("trace_to_braintrust".into(), Value::Bool(true)); + settings.remove("tracing_disabled"); + Ok(()) + }) } /// Disable tracing while retaining the installed adapter and saved route. @@ -230,7 +261,7 @@ mod tests { let path = temp.path().join("braintrust.json"); std::fs::write( &path, - r#"{"trace_to_braintrust":true,"route":{"tags":["saved"]},"custom":1}"#, + 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(); @@ -240,12 +271,15 @@ mod tests { assert_eq!(value["tracing_disabled"], true); assert_eq!(value["route"]["tags"][0], "saved"); assert_eq!(value["custom"], 1); - enable_tracing_at(&path, SessionRoute::default()).unwrap(); + 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!(enabled.get("tracing_disabled").is_none()); - assert_eq!(enabled["route"]["tags"][0], "saved"); + 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["tracing_disabled"], true); diff --git a/bt-daemon/src/setup/muse.rs b/bt-daemon/src/setup/muse.rs index 49fac6ad..162dbc42 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 setup 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 setup muse`".into()); } } } diff --git a/bt-daemon/src/setup/opencode.rs b/bt-daemon/src/setup/opencode.rs index 6ff644d7..a4941e13 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 setup 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 3ae66e34..addd3461 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -20,9 +20,10 @@ 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), + /// Install and configure the Braintrust tracing plugin for a coding agent. + Setup(SetupArgs), + /// Resume tracing with the existing configuration. + Enable(EnableArgs), /// Disable tracing while preserving the plugin and its configuration. Disable(DisableArgs), /// Uninstall the tracing plugin and remove its saved configuration. @@ -94,7 +95,7 @@ impl DoctorAgent { } #[derive(Debug, Clone, Args)] -pub struct EnableArgs { +pub struct SetupArgs { #[command(subcommand)] pub agent: SetupAgent, /// JSON object persisted in this agent's tracing route and merged into root-span metadata. @@ -114,8 +115,11 @@ pub struct EnableArgs { 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 { + #[command(subcommand)] + pub agent: SetupAgent, +} #[derive(Debug, Clone, Args)] pub struct DisableArgs { @@ -353,8 +357,8 @@ 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 { @@ -377,8 +381,8 @@ mod tests { #[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 { @@ -397,6 +401,18 @@ mod tests { )); } + #[test] + fn enable_only_accepts_an_agent() { + 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_err()); + } + #[test] fn uninstall_accepts_an_agent() { let parsed = Cli::try_parse_from(["bt", "uninstall", "pi"]).unwrap(); diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index baea2be1..64a63653 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -291,21 +291,6 @@ async fn resolve_command_route( Ok(route) } -fn merge_saved_auth(mut selected: AuthSelection, saved: AuthSelection) -> AuthSelection { - let selected_profile = selected.source != AuthSource::Auto - || selected.profile_id.is_some() - || selected.profile.is_some(); - if !selected_profile { - selected.source = saved.source; - selected.profile_id = saved.profile_id; - selected.profile = saved.profile; - if selected.org_name.is_none() { - selected.org_name = saved.org_name; - } - } - selected -} - fn print_output(output: TraceCommandOutput, format: OutputFormat) -> anyhow::Result<()> { println!("{}", output.render(format)?); Ok(()) @@ -542,7 +527,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 setup {source}`" )); } else if !enabled { warnings.push(format!( @@ -667,48 +652,28 @@ async fn doctor_output_at( pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Result<()> { match args.command { TraceCommand::Setup(enable_args) => { - let saved = crate::settings::AgentSettings::load_from(&paths::agent_settings_path( - enable_args.agent.identity().id, - None, - )) - .route; - let mut route = resolve_host_route( + let mut route = resolve_command_route( &host, RouteRequirements { - destination_required: saved - .as_ref() - .and_then(|route| route.destination.as_ref()) - .is_none(), + destination_required: true, interactive_auth: true, persistent_auth: true, }, ) .await?; - if route.destination.is_none() { - if let Some(saved) = saved { - route.destination = saved.destination; - route.auth = merge_saved_auth(route.auth, saved.auth); - } - } - let lease = host - .services - .resolve_auth(&route.auth, AuthResolveReason::Initial) - .await?; - let org_name = require_resolved_org(&route, &lease)?; - route.auth = lease.selection; - route.auth.org_name = Some(org_name); 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)?; } let codex = matches!(enable_args.agent, SetupAgent::Codex); - let output = run_enable(enable_args, route)?; + let output = crate::run_setup(enable_args, route)?; if codex { crate::codex_hooks::activate().await?; } print_output(output, host.output_format) } + TraceCommand::Enable(args) => print_output(run_enable(args.agent)?, host.output_format), TraceCommand::Disable(disable_args) => { print_output(run_disable(disable_args.agent)?, host.output_format) } @@ -851,33 +816,6 @@ mod tests { use std::path::PathBuf; use std::sync::Mutex; - #[test] - fn saved_auth_fills_only_unselected_credentials() { - let saved = AuthSelection { - source: AuthSource::SavedProfile, - profile: Some("old".into()), - org_name: Some("old-org".into()), - ..Default::default() - }; - let selected = AuthSelection { - source: AuthSource::SavedProfile, - profile: Some("new".into()), - ..Default::default() - }; - assert_eq!(merge_saved_auth(selected.clone(), saved.clone()), selected); - let org = AuthSelection { - org_name: Some("new-org".into()), - ..Default::default() - }; - let merged = merge_saved_auth(org, saved.clone()); - assert_eq!(merged.profile.as_deref(), Some("old")); - assert_eq!(merged.org_name.as_deref(), Some("new-org")); - assert_eq!( - merge_saved_auth(AuthSelection::default(), saved.clone()), - saved - ); - } - #[test] fn mounted_child_commands_preserve_the_host_prefix() { let mounted = RunHookCommand { @@ -1397,7 +1335,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 setup` to select a profile" ) } } diff --git a/docs/coding-agent-tracing-plugin-spec.md b/docs/coding-agent-tracing-plugin-spec.md index 2482760a..18ed67b4 100644 --- a/docs/coding-agent-tracing-plugin-spec.md +++ b/docs/coding-agent-tracing-plugin-spec.md @@ -397,9 +397,11 @@ translator rather than separate trace builders. ### 8.1 Persistent setup -`bt trace enable ` MUST install or update capture idempotently and store +`bt trace setup ` MUST install or update capture idempotently and store only non-secret route settings. It MUST preserve unrelated user configuration. +`bt trace enable ` MUST resume an existing configuration without changing its route or reinstalling capture. + `bt trace disable ` MUST preserve the adapter and configuration while disabling tracing. `bt trace uninstall ` MUST remove only Braintrust-managed state. Both MUST be safe when repeated. diff --git a/src/plugins/antigravity/content/README.md b/src/plugins/antigravity/content/README.md index 2bcd635f..37624c60 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 setup 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..9d121c36 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 setup claude --project my-coding-agent ``` Setup adds the marketplace and installs or enables `trace-claude-code`. @@ -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 setup 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 setup claude --tag ci --tag release-validation bt trace run claude --tag ci -- "review this change" bt trace import claude session-id --tag historical-import ``` 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..93d81737 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 setup 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 setup 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 setup 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 setup`, `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 setup 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..45c69330 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 setup 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..921a9217 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 setup 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 setup 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 setup 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..3e6ff6a3 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 setup 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 setup 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,7 +49,7 @@ Authenticate and enable tracing: ```bash bt login -bt trace enable cursor --project my-coding-agent +bt trace setup cursor --project my-coding-agent ``` Setup uses Git to install or refresh the local `braintrust` plugin from the latest @@ -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 setup 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 setup cursor --tag ci --tag release-validation bt trace run cursor --tag ci bt trace import cursor SESSION_ID --tag historical-import ``` diff --git a/src/plugins/grok/content/README.md b/src/plugins/grok/content/README.md index 50528c81..b2939101 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 setup 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..68681942 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 setup 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 setup` 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..7226b8a3 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 setup 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..5aeecd9c 100644 --- a/src/plugins/opencode/content/src/config.ts +++ b/src/plugins/opencode/content/src/config.ts @@ -74,7 +74,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 setup` has not migrated yet. if (auth?.profile) defaults.profile = auth.profile; if (auth?.org_name) defaults.orgName = auth.org_name; if ( diff --git a/src/plugins/pi/content/README.md b/src/plugins/pi/content/README.md index 362f8597..0be94e2c 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 setup 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 setup 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 setup` or the nested `route` format above. Include a destination when supplying a route. Only the display settings read environment variables directly. Tracing settings From 2efae88c6e35938276556fcf36182bdd9847c48c Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 18:05:47 +0800 Subject: [PATCH 08/18] Use setup for repository tracing instructions --- bt-daemon/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 6efdc808..55ccfb4c 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -60,7 +60,7 @@ coding agent decides whether to continue its turn. ## Repository-scoped tracing for Claude Code and Cursor -Install the agent integration with `bt trace enable claude` or `bt trace enable cursor`. +Install the agent integration with `bt trace setup claude` or `bt trace setup cursor`. To trace only selected repositories, set `trace_to_braintrust` to `false` in the corresponding user-level `braintrust.json`, then commit `.claude/braintrust.json` or `.cursor/braintrust.json` in each selected repository: From 86abb60f7846630c9a98155b2044bc308c7b39c0 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 21:49:42 +0800 Subject: [PATCH 09/18] Preserve enable setup compatibility --- README.md | 2 +- bt-daemon/README.md | 5 +- bt-daemon/src/command_output.rs | 13 +- bt-daemon/src/setup/mod.rs | 55 ++++++ bt-daemon/src/trace_command.rs | 18 +- bt-daemon/src/trace_runtime.rs | 230 ++++++++++++++++++++--- docs/coding-agent-tracing-plugin-spec.md | 2 +- 7 files changed, 296 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 5edda7dd..61692c7d 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,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. -`disable` pauses tracing and keeps your settings. Use `enable` to resume, or `uninstall` to remove 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 be29b2bb..a5495aaf 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -264,7 +264,10 @@ BRAINTRUST_TAGS=ci,release-validation bt trace run codex -- "summarize this chan ``` Use `bt trace disable ` to pause tracing while keeping the plugin and settings. -Use `bt trace enable ` to resume, or `bt trace uninstall ` to remove +Use `bt trace enable ` to resume. If there is no saved setup, or you provide +explicit configuration options, `enable` runs setup 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 setup ` to install or change the configuration. diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index 942af479..21543374 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -59,6 +59,8 @@ pub struct SetupCommandOutput { pub display_name: String, pub settings_path: PathBuf, pub restart_required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub configuration: Option<&'static str>, } #[derive(Debug, Clone, Serialize)] @@ -197,6 +199,7 @@ impl TraceCommandOutput { display_name: display_name.into(), settings_path: settings_path.into(), restart_required: true, + configuration: None, }) } @@ -210,6 +213,7 @@ impl TraceCommandOutput { display_name: display_name.into(), settings_path: settings_path.into(), restart_required: true, + configuration: Some("reused"), }) } @@ -231,6 +235,7 @@ impl TraceCommandOutput { display_name: display_name.into(), settings_path: settings_path.into(), restart_required: true, + configuration: None, }) } @@ -244,6 +249,7 @@ impl TraceCommandOutput { display_name: display_name.into(), settings_path: settings_path.into(), restart_required: true, + configuration: None, }) } @@ -329,13 +335,17 @@ impl TraceCommandOutput { } Ok(rendered) } + Self::Enable(setup) if setup.configuration.is_some_and(|value| value != "reused") => Ok(format!( + "Braintrust tracing configuration {} for {} in {}.\nRestart the coding agent to load the tracing plugin.", + setup.configuration.unwrap_or_default(), setup.display_name, setup.settings_path.display() + )), Self::Setup(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() )), Self::Enable(enable) => Ok(format!( - "Braintrust tracing is enabled for {} in {}.\nRestart the coding agent to apply the change.", + "Braintrust tracing is enabled for {} using the existing configuration in {}.\nRestart the coding agent to apply the change.", enable.display_name, enable.settings_path.display() )), Self::Disable(disable) => Ok(format!( @@ -467,6 +477,7 @@ mod tests { 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() diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index 7ba662c9..3068c5e6 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -76,6 +76,41 @@ pub fn run_setup(args: SetupArgs, route: SessionRoute) -> anyhow::Result 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() == 2 + && object.get("trace_to_braintrust") == Some(&Value::Bool(false)) + && object.get("tracing_disabled") == Some(&Value::Bool(true)))) +} + /// Resume tracing without reinstalling the adapter or replacing its route. pub fn run_enable(agent: SetupAgent) -> anyhow::Result { let identity = agent.identity(); @@ -286,6 +321,26 @@ mod tests { 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/trace_command.rs b/bt-daemon/src/trace_command.rs index addd3461..a91b46b9 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -22,7 +22,7 @@ pub struct TraceArgs { pub enum TraceCommand { /// Install and configure the Braintrust tracing plugin for a coding agent. Setup(SetupArgs), - /// Resume tracing with the existing configuration. + /// 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), @@ -119,6 +119,15 @@ pub struct SetupArgs { pub struct EnableArgs { #[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, + /// JavaScript span transform to persist. May be repeated. + #[arg(long, global = true, value_name = "PATH")] + pub plugin: Vec, } #[derive(Debug, Clone, Args)] @@ -402,15 +411,16 @@ mod tests { } #[test] - fn enable_only_accepts_an_agent() { + 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 + agent: SetupAgent::Pi, + .. }) )); - assert!(Cli::try_parse_from(["bt", "enable", "pi", "--tag", "changed"]).is_err()); + assert!(Cli::try_parse_from(["bt", "enable", "pi", "--tag", "changed"]).is_ok()); } #[test] diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 64a63653..c4cabead 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -111,6 +111,11 @@ fn unconfirmed_auth_diagnostic( #[allow(clippy::double_must_use)] #[async_trait] pub trait TraceHostServices: Send + Sync { + /// Whether route flags were explicitly supplied on the command line. + fn has_explicit_route_selection(&self) -> bool { + false + } + /// Resolve only the host-owned auth and default project selections. /// Setup and managed run require a project and may prompt for auth; /// hooks use the current selection without prompting. The trace runtime @@ -648,32 +653,85 @@ async fn doctor_output_at( } } +async fn run_setup_command( + args: crate::SetupArgs, + host: &TraceHostContext, + configuration: Option<&'static str>, +) -> anyhow::Result<()> { + 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::Setup(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() +} + /// Execute the complete mounted trace command. pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Result<()> { 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)?; - } - let codex = matches!(enable_args.agent, SetupAgent::Codex); - let output = crate::run_setup(enable_args, route)?; - if codex { - crate::codex_hooks::activate().await?; + TraceCommand::Setup(args) => run_setup_command(args, &host, None).await, + TraceCommand::Enable(args) => { + let configured = crate::setup::has_saved_setup(args.agent)?; + if !enable_needs_setup( + configured, + &args, + host.services.has_explicit_route_selection(), + ) { + print_output(run_enable(args.agent)?, host.output_format) + } else { + let setup = crate::SetupArgs { + agent: args.agent, + additional_metadata: args + .additional_metadata + .or_else(|| std::env::var("BRAINTRUST_ADDITIONAL_METADATA").ok()), + tags: if args.tags.is_empty() { + std::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_setup_command( + setup, + &host, + Some(if configured { "updated" } else { "created" }), + ) + .await } - print_output(output, host.output_format) } - TraceCommand::Enable(args) => print_output(run_enable(args.agent)?, host.output_format), TraceCommand::Disable(disable_args) => { print_output(run_disable(disable_args.agent)?, host.output_format) } @@ -816,6 +874,136 @@ 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 { + 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 { + 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, "tracing_disabled": true, "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!(updated.get("tracing_disabled").is_none()); + 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 { + 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 { diff --git a/docs/coding-agent-tracing-plugin-spec.md b/docs/coding-agent-tracing-plugin-spec.md index 18ed67b4..57bcf23c 100644 --- a/docs/coding-agent-tracing-plugin-spec.md +++ b/docs/coding-agent-tracing-plugin-spec.md @@ -400,7 +400,7 @@ translator rather than separate trace builders. `bt trace setup ` MUST install or update capture idempotently and store only non-secret route settings. It MUST preserve unrelated user configuration. -`bt trace enable ` MUST resume an existing configuration without changing its route or reinstalling capture. +`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 setup. `bt trace disable ` MUST preserve the adapter and configuration while disabling tracing. `bt trace uninstall ` MUST remove only Braintrust-managed state. Both MUST be safe when repeated. From df963568a743509cbdeb63febe40ad88ed2e757a Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 18 Nov 2026 21:52:20 +0800 Subject: [PATCH 10/18] Read tracing defaults through environment helper --- bt-daemon/src/trace_runtime.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index c4cabead..85f1baf4 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -711,9 +711,9 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul agent: args.agent, additional_metadata: args .additional_metadata - .or_else(|| std::env::var("BRAINTRUST_ADDITIONAL_METADATA").ok()), + .or_else(|| crate::env::var("BRAINTRUST_ADDITIONAL_METADATA")), tags: if args.tags.is_empty() { - std::env::var("BRAINTRUST_TAGS") + crate::env::var("BRAINTRUST_TAGS") .unwrap_or_default() .split(',') .filter(|s| !s.is_empty()) From 803ee2f441a79926e2601ecf921071a4523eb4ff Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 19 Nov 2026 00:57:53 +0800 Subject: [PATCH 11/18] Respect global pause in OpenCode projects --- .../opencode/content/src/index.test.ts | 31 +++++++++++++++++++ .../opencode/content/src/tracing/plugin.ts | 9 ++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/plugins/opencode/content/src/index.test.ts b/src/plugins/opencode/content/src/index.test.ts index 452a9d40..2b437132 100644 --- a/src/plugins/opencode/content/src/index.test.ts +++ b/src/plugins/opencode/content/src/index.test.ts @@ -125,6 +125,37 @@ describe("BraintrustPlugin", () => { expect(hooks.tool).toBeUndefined(); }); + it("honors a global pause over project opt-in and allows managed runs", async () => { + const global = join(directory, ".config", "opencode"); + const project = join(directory, ".opencode"); + mkdirSync(global, { recursive: true }); + mkdirSync(project, { recursive: true }); + writeFileSync( + join(global, "braintrust.json"), + JSON.stringify({ trace_to_braintrust: false, tracing_disabled: true }), + ); + writeFileSync( + join(project, "braintrust.json"), + JSON.stringify({ trace_to_braintrust: true, tracing_disabled: false }), + ); + const { BraintrustPlugin } = await import("./index"); + const paused = await BraintrustPlugin(createInput(directory)); + expect(paused.event).toBeUndefined(); + expect(paused.tool).toBeDefined(); + // Re-enabling removes the pause marker; project opt-in applies again. + writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + expect((await BraintrustPlugin(createInput(directory))).event).toBeDefined(); + writeFileSync( + join(global, "braintrust.json"), + JSON.stringify({ trace_to_braintrust: false, tracing_disabled: true }), + ); + 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("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/tracing/plugin.ts b/src/plugins/opencode/content/src/tracing/plugin.ts index 11d6d7e0..e732cbf7 100644 --- a/src/plugins/opencode/content/src/tracing/plugin.ts +++ b/src/plugins/opencode/content/src/tracing/plugin.ts @@ -16,16 +16,21 @@ export async function readPluginConfig(input: { path.join(configHome, "opencode", "braintrust.json"), path.join(input.directory, ".opencode", "braintrust.json"), ]; - for (const configPath of configPaths) { + let globallyDisabled = false; + for (const [index, configPath] of configPaths.entries()) { try { if (fs.existsSync(configPath)) { - const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as PluginConfig; + const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as PluginConfig & { + tracing_disabled?: boolean; + }; + if (index === 0) globallyDisabled = parsed.tracing_disabled === true; pluginConfig = pluginConfig ? { ...pluginConfig, ...parsed } : parsed; } } catch { // Malformed optional config is fail-open; continue to the next layer. } } + if (globallyDisabled) pluginConfig = { ...pluginConfig, trace_to_braintrust: false }; } catch { // Config loading failed; invocation settings can still enable tracing. } From a9c7ce1d81cad1c9a3e43e0f6b0ead1965f3d4b5 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 19 Nov 2026 01:13:46 +0800 Subject: [PATCH 12/18] Centralize tracing pause for in-process adapters --- bt-daemon/tests/command_output.rs | 67 +++++++++++++++++++ src/plugins/opencode/content/src/config.ts | 2 + .../opencode/content/src/server.pause.test.ts | 61 +++++++++++++++++ .../opencode/content/src/tracing/plugin.ts | 6 +- src/plugins/pi/content/src/config.ts | 3 +- src/runtime/js-daemon-client/src/index.ts | 7 +- .../js-daemon-client/tests/client.test.ts | 9 +++ 7 files changed, 149 insertions(+), 6 deletions(-) create mode 100644 src/plugins/opencode/content/src/server.pause.test.ts diff --git a/bt-daemon/tests/command_output.rs b/bt-daemon/tests/command_output.rs index aa170279..a8634219 100644 --- a/bt-daemon/tests/command_output.rs +++ b/bt-daemon/tests/command_output.rs @@ -105,6 +105,73 @@ 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,"tracing_disabled":true}"#, + ) + .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(); diff --git a/src/plugins/opencode/content/src/config.ts b/src/plugins/opencode/content/src/config.ts index 5aeecd9c..c59cfb03 100644 --- a/src/plugins/opencode/content/src/config.ts +++ b/src/plugins/opencode/content/src/config.ts @@ -22,6 +22,7 @@ export interface PluginConfig { org_name?: string; project?: string; trace_to_braintrust?: boolean; + tracing_disabled?: boolean; enable_tools?: boolean; debug?: boolean; additional_metadata?: Record; @@ -113,6 +114,7 @@ export function loadConfig(pluginConfig?: PluginConfig): BraintrustConfig { persistentRoute.additional_metadata = defaults.additionalMetadata; const traceSettings = resolveDaemonTraceSettings({ trace_to_braintrust: defaults.tracingEnabled, + tracing_disabled: pluginConfig?.tracing_disabled, route: persistentRoute, }); const route = traceSettings.route ?? persistentRoute; 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..00ecbbbc --- /dev/null +++ b/src/plugins/opencode/content/src/server.pause.test.ts @@ -0,0 +1,61 @@ +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 global pause to OpenCode 2 and permits a managed run", async () => { + const global = join(directory, "config", "opencode"); + const project = join(directory, ".opencode"); + mkdirSync(global, { recursive: true }); + mkdirSync(project, { recursive: true }); + writeFileSync( + join(global, "braintrust.json"), + JSON.stringify({ trace_to_braintrust: false, tracing_disabled: true }), + ); + writeFileSync(join(project, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + 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 e732cbf7..a6cbea52 100644 --- a/src/plugins/opencode/content/src/tracing/plugin.ts +++ b/src/plugins/opencode/content/src/tracing/plugin.ts @@ -20,9 +20,7 @@ export async function readPluginConfig(input: { for (const [index, configPath] of configPaths.entries()) { try { if (fs.existsSync(configPath)) { - const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as PluginConfig & { - tracing_disabled?: boolean; - }; + const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as PluginConfig; if (index === 0) globallyDisabled = parsed.tracing_disabled === true; pluginConfig = pluginConfig ? { ...pluginConfig, ...parsed } : parsed; } @@ -30,7 +28,7 @@ export async function readPluginConfig(input: { // Malformed optional config is fail-open; continue to the next layer. } } - if (globallyDisabled) pluginConfig = { ...pluginConfig, trace_to_braintrust: false }; + if (pluginConfig) pluginConfig.tracing_disabled = globallyDisabled; } catch { // Config loading failed; invocation settings can still enable tracing. } diff --git a/src/plugins/pi/content/src/config.ts b/src/plugins/pi/content/src/config.ts index 59f8706e..bbd23d02 100644 --- a/src/plugins/pi/content/src/config.ts +++ b/src/plugins/pi/content/src/config.ts @@ -109,7 +109,8 @@ export function loadConfig(cwd = process.cwd()): PiConfig { config.showTraceLink = boolean(process.env.BRAINTRUST_SHOW_TRACE_LINK) ?? config.showTraceLink; const traceSettings = resolveDaemonTraceSettings({ - trace_to_braintrust: userConfig?.tracing_disabled === true ? false : config.enabled, + trace_to_braintrust: config.enabled, + tracing_disabled: userConfig?.tracing_disabled === true, route: config.route, }); config.enabled = traceSettings.trace_to_braintrust === true; diff --git a/src/runtime/js-daemon-client/src/index.ts b/src/runtime/js-daemon-client/src/index.ts index f519b5e1..15a52b69 100644 --- a/src/runtime/js-daemon-client/src/index.ts +++ b/src/runtime/js-daemon-client/src/index.ts @@ -22,6 +22,7 @@ export interface DaemonSessionRoute { export interface DaemonTraceSettings { trace_to_braintrust?: boolean + tracing_disabled?: boolean route?: DaemonSessionRoute } @@ -56,7 +57,11 @@ export function resolveDaemonTraceSettings( env: NodeJS.ProcessEnv = process.env, ): DaemonTraceSettings { const raw = env.BT_TRACE_INVOCATION_SETTINGS - if (raw === undefined) return persistent + if (raw === undefined) { + return persistent.tracing_disabled === true + ? { ...persistent, trace_to_braintrust: false } + : persistent + } try { const invocation = JSON.parse(raw) as DaemonTraceSettings if ( diff --git a/src/runtime/js-daemon-client/tests/client.test.ts b/src/runtime/js-daemon-client/tests/client.test.ts index eeb8cf6c..ec7fde72 100644 --- a/src/runtime/js-daemon-client/tests/client.test.ts +++ b/src/runtime/js-daemon-client/tests/client.test.ts @@ -95,6 +95,15 @@ describe("resolveDaemonTraceSettings", () => { assert.equal(persistent.route.auth.profile, "global") }) + test("applies a persistent pause while letting managed runs override it", () => { + const paused = { ...persistent, tracing_disabled: true } + assert.equal(resolveDaemonTraceSettings(paused, {}).trace_to_braintrust, false) + const invocation = { trace_to_braintrust: true, route: persistent.route } + assert.deepEqual(resolveDaemonTraceSettings(paused, { BT_TRACE_INVOCATION_SETTINGS: JSON.stringify(invocation) }), invocation) + assert.deepEqual(resolveDaemonTraceSettings(paused, { BT_TRACE_INVOCATION_SETTINGS: "{" }), { trace_to_braintrust: false }) + assert.equal(persistent.trace_to_braintrust, true) + }) + test("does not fall back when invocation settings are malformed", () => { assert.deepEqual( resolveDaemonTraceSettings(persistent, { BT_TRACE_INVOCATION_SETTINGS: "{" }), From b563d91223aa442d5cb6a6296dcba9606c56bc28 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 19 Nov 2026 02:58:01 +0800 Subject: [PATCH 13/18] Preserve hook destination for partial project settings --- bt-daemon/src/hook.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/bt-daemon/src/hook.rs b/bt-daemon/src/hook.rs index 2185917f..d63b7f05 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -111,7 +111,16 @@ pub async fn run_hook(args: HookArgs, route: SessionRoute, host: HostInfo) -> an if !settings.tracing_enabled() { return Ok(()); } - run_hook_with_payload(args, settings.route.unwrap_or(route), host, payload).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 { From 63b488c039cc9f94883ffaaa7a166a6029562d16 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 19 Nov 2026 20:45:25 +0800 Subject: [PATCH 14/18] Handle trace argument provenance in plugin runtime --- bt-daemon/src/lib.rs | 3 +- bt-daemon/src/trace_runtime.rs | 60 +++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 1691798e..e8fbc961 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -87,7 +87,8 @@ pub use trace_command::{ 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/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 28ec1600..6429bcd0 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -111,16 +111,6 @@ fn unconfirmed_auth_diagnostic( #[allow(clippy::double_must_use)] #[async_trait] pub trait TraceHostServices: Send + Sync { - /// Whether route flags were explicitly supplied on the command line. - fn has_explicit_route_selection(&self) -> bool { - false - } - - /// Route values explicitly supplied on the command line, excluding defaults. - fn explicit_route_selection(&self) -> HostRouteSelection { - HostRouteSelection::default() - } - /// Resolve only the host-owned auth and default project selections. /// Setup and managed run require a project and may prompt for auth; /// hooks use the current selection without prompting. The trace runtime @@ -662,14 +652,11 @@ async fn run_setup_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, - host.services.explicit_route_selection(), - configuration.is_some(), - )?, + crate::setup::run_project_setup(args, explicit.clone(), configuration.is_some())?, host.output_format, ); } @@ -722,14 +709,44 @@ fn enable_needs_setup(configured: bool, args: &crate::EnableArgs, explicit_route /// 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(args) => run_setup_command(args, &host, None).await, + TraceCommand::Setup(args) => run_setup_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() - || host.services.has_explicit_route_selection() + || has_explicit { let setup = crate::SetupArgs { scope: args.scope, @@ -738,7 +755,7 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul tags: args.tags, plugin: args.plugin, }; - return run_setup_command(setup, &host, Some("updated")).await; + return run_setup_command(setup, &host, Some("updated"), &selection).await; } return print_output( crate::setup::run_scoped_toggle(args.agent, args.scope, true)?, @@ -746,11 +763,7 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul ); } let configured = crate::setup::has_saved_setup(args.agent)?; - if !enable_needs_setup( - configured, - &args, - host.services.has_explicit_route_selection(), - ) { + if !enable_needs_setup(configured, &args, has_explicit) { print_output(run_enable(args.agent)?, host.output_format) } else { let setup = crate::SetupArgs { @@ -775,6 +788,7 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul setup, &host, Some(if configured { "updated" } else { "created" }), + &selection, ) .await } From 3dfb9ea11da7f2392a8f6d9bba2df379df5caa04 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 19 Nov 2026 21:52:45 +0800 Subject: [PATCH 15/18] Support scoped install and inherited tracing settings --- README.md | 4 +- bt-daemon/README.md | 37 +++-- bt-daemon/src/args.rs | 3 + bt-daemon/src/command_output.rs | 44 +++++- bt-daemon/src/managed_run/mod.rs | 6 +- bt-daemon/src/settings.rs | 134 +++++++++++++--- bt-daemon/src/setup/mod.rs | 30 ++-- bt-daemon/src/trace_command.rs | 9 +- bt-daemon/src/trace_runtime.rs | 145 ++++++++++++++++-- bt-daemon/tests/muse_managed_startup.rs | 1 + bt-daemon/tests/pipeline.rs | 3 + docs/coding-agent-tracing-plugin-spec.md | 11 +- .../opencode/content/src/index.test.ts | 29 ++++ .../opencode/content/src/tracing/plugin.ts | 17 +- src/plugins/pi/content/src/config.test.ts | 19 +++ src/plugins/pi/content/src/config.ts | 23 ++- src/runtime/js-daemon-client/src/index.ts | 29 ++++ .../js-daemon-client/tests/client.test.ts | 20 +++ 18 files changed, 490 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 327f6a12..ce6008a5 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ then authenticate and enable tracing. For example: ```bash bt login -bt trace setup 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 @@ -44,7 +44,7 @@ user settings; `bt trace run` overrides both. ## Supported agents -All six support `bt trace setup`, `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 | |---|---|---|---|---| diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 438b1800..b73f570f 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -60,26 +60,35 @@ coding agent decides whether to continue its turn. ## Project-scoped tracing -First install the integration with `bt trace setup `. To configure a Git -repository independently, run these commands from anywhere inside it: +Each developer installs the agent integration once. To trace only repositories +that opt in, install it with tracing disabled by default: ```bash -bt trace setup claude --scope project +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 ``` -Project setup writes `.claude/braintrust.json` at the repository root. Other -agents use their own project configuration directory. The project file initially -contains only `trace_to_braintrust`; explicitly supplied project, profile, -organization, tags, and metadata settings are also saved. Missing fields inherit -the user configuration. Project files cannot select executable span plugins. - -A managed `bt trace run` takes precedence over project settings, which take -precedence over user settings. When no setting enables tracing, it is disabled. -Project enable and disable change only the project file and do not install an -adapter. For multi-root Cursor and Antigravity workspaces, the first root with -a project file supplies the settings. `bt trace doctor` reports user settings. +Project install writes `.claude/braintrust.json` at the repository root; other +agents use their own project configuration directory. The file 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 settings overlay user settings recursively: missing fields inherit, +objects merge by field, and arrays and other explicitly supplied values replace +those inherited. Repository settings cannot select executable span plugins. +Managed `bt trace run` takes precedence over both; `bt trace run --inherit` +starts from user and project settings before applying invocation options. +`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 diff --git a/bt-daemon/src/args.rs b/bt-daemon/src/args.rs index 3f77bd30..aed39169 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, diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index a6d63d07..041cb463 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -62,6 +62,10 @@ pub struct SetupCommandOutput { #[serde(skip_serializing_if = "Option::is_none")] pub configuration: Option<&'static str>, pub scope: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, } #[derive(Debug, Clone, Serialize)] @@ -156,6 +160,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")] @@ -202,6 +210,8 @@ impl TraceCommandOutput { restart_required: true, configuration: None, scope: "user", + enabled: None, + warnings: Vec::new(), }) } @@ -217,6 +227,8 @@ impl TraceCommandOutput { restart_required: true, configuration: Some("reused"), scope: "user", + enabled: None, + warnings: Vec::new(), }) } @@ -225,7 +237,11 @@ impl TraceCommandOutput { display_name: impl Into, settings_path: impl Into, ) -> Self { - Self::setup(source, display_name, settings_path).with_scope("project") + let mut output = Self::setup(source, display_name, settings_path).with_scope("project"); + if let Self::Setup(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()); + } + output } pub(crate) fn with_scope(mut self, scope: &'static str) -> Self { @@ -239,6 +255,13 @@ impl TraceCommandOutput { self } + pub(crate) fn with_enabled(mut self, enabled: bool) -> Self { + if let Self::Setup(output) = &mut self { + output.enabled = Some(enabled); + } + self + } + pub(crate) fn into_enable(mut self, configuration: &'static str) -> Self { match &mut self { Self::Setup(output) | Self::Enable(output) => { @@ -272,6 +295,8 @@ impl TraceCommandOutput { restart_required: true, configuration: None, scope: "user", + enabled: None, + warnings: Vec::new(), }) } @@ -287,6 +312,8 @@ impl TraceCommandOutput { restart_required: true, configuration: None, scope: "user", + enabled: None, + warnings: Vec::new(), }) } @@ -330,6 +357,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 { @@ -377,12 +410,13 @@ impl TraceCommandOutput { setup.configuration.unwrap_or_default(), setup.display_name, setup.scope, setup.settings_path.display() )), Self::Setup(setup) if setup.scope == "project" => Ok(format!( - "Project tracing settings for {} were written to {}.", setup.display_name, setup.settings_path.display() + "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::Setup(setup) => Ok(format!( - "The Braintrust tracing plugin is installed for {} and configured in {}.\nRestart the coding agent to load the tracing plugin.", + "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.", @@ -641,6 +675,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/managed_run/mod.rs b/bt-daemon/src/managed_run/mod.rs index 255eb95b..a68709d5 100644 --- a/bt-daemon/src/managed_run/mod.rs +++ b/bt-daemon/src/managed_run/mod.rs @@ -115,7 +115,9 @@ 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)?; + if !args.inherit || !args.plugin.is_empty() { + apply_run_span_plugins(&mut route, &args.plugin)?; + } let name = args.source.identity().id; let agent = registrar() .run @@ -392,6 +394,7 @@ mod tests { async fn managed_run_rejects_a_missing_destination_before_launch() { let error = run_traced( RunArgs { + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, @@ -412,6 +415,7 @@ mod tests { async fn codex_managed_run_rejects_global_hook_trust_bypass_before_launch() { let error = run_traced( RunArgs { + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 7dba2e34..760d66f4 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -16,6 +16,23 @@ use std::path::{Path, PathBuf}; pub(crate) const INVOCATION_SETTINGS_ENV: &str = "BT_TRACE_INVOCATION_SETTINGS"; +/// Recursively overlay objects; every other value, including arrays, replaces. +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); + } + } + } + } + (base, overlay) => *base = overlay, + } +} + /// Non-secret settings scoped to one `bt trace run` process tree. #[derive(Debug, Serialize, Deserialize)] pub(crate) struct InvocationSettings { @@ -49,6 +66,25 @@ impl AgentSettings { 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>, @@ -67,17 +103,59 @@ impl AgentSettings { let object = project.as_object().ok_or_else(|| { anyhow::anyhow!("tracing settings at {} must be an object", path.display()) })?; - if object.contains_key("route") { - anyhow::bail!("repository tracing settings at {} cannot specify `route`; use `project` to select a destination", path.display()); - } - let overlay: Self = serde_json::from_value(project.clone())?; let mut settings = if user_path.exists() { Self::load_hook_from_sources(user_path, None)? } else { Self::default() }; - if overlay.trace_to_braintrust.is_some() { - settings.trace_to_braintrust = overlay.trace_to_braintrust; + if let Some(project_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()) + })?; + if project_route + .get("span_plugins") + .is_some_and(|plugins| !plugins.as_array().is_some_and(Vec::is_empty)) + { + anyhow::bail!( + "repository tracing settings at {} cannot select executable span plugins", + path.display() + ); + } + 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.clone())); + 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 @@ -122,10 +200,11 @@ impl AgentSettings { if !metadata.is_object() { anyhow::bail!("project metadata at {} must be an object", path.display()); } - settings - .route - .get_or_insert_with(SessionRoute::default) - .additional_metadata = Some(metadata.clone()); + 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) } @@ -155,14 +234,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 { @@ -183,6 +255,7 @@ impl AgentSettings { settings } + #[cfg(test)] fn load_from(path: &Path) -> Self { let raw = match std::fs::read_to_string(path) { Ok(raw) => raw, @@ -399,6 +472,31 @@ mod tests { 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!(route.span_plugins.is_empty()); + 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"]); + assert_eq!( + route.additional_metadata, + Some(serde_json::json!({"nested":{"one":1,"two":3},"list":[4]})) + ); + } + #[test] fn project_fields_inherit_and_override_the_user_route() { let temp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index 69b25d2e..6c3a0793 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -107,7 +107,8 @@ pub(crate) fn run_project_setup( let existed = path.exists(); write_project_setup_at(&path, &args, &selection)?; let id = args.agent.identity(); - let output = TraceCommandOutput::project_setup(id.id, id.display_name, path); + let output = + TraceCommandOutput::project_setup(id.id, id.display_name, path).with_enabled(!args.disable); Ok(if as_enable { output.into_enable(if existed { "updated" } else { "created" }) } else { @@ -124,7 +125,7 @@ fn write_project_setup_at( anyhow::bail!("project configuration cannot select executable span plugins"); } common::edit_object(path, FileAccess::OwnerOnly, |settings, _| { - settings.insert("trace_to_braintrust".into(), Value::Bool(true)); + 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()), @@ -155,12 +156,11 @@ pub fn run_setup(args: SetupArgs, route: SessionRoute) -> anyhow::Result anyhow::Result { )) } -fn enable_tracing(source: &str, route: SessionRoute) -> anyhow::Result { +fn enable_tracing(source: &str, route: SessionRoute, enabled: bool) -> anyhow::Result { let path = paths::agent_settings_path(source, None); - enable_tracing_at(&path, route)?; + write_tracing_at(&path, route, enabled)?; 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) +} + +fn write_tracing_at(path: &Path, mut route: SessionRoute, enabled: bool) -> anyhow::Result<()> { let mut settings = load_object(path)?; if route.additional_metadata.is_none() { route.additional_metadata = settings @@ -316,7 +321,7 @@ fn enable_tracing_at(path: &Path, mut route: SessionRoute) -> anyhow::Result<()> .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", @@ -377,6 +382,7 @@ mod tests { let temp = tempfile::tempdir().unwrap(); let path = temp.path().join(".claude/braintrust.json"); let mut args = SetupArgs { + disable: false, scope: SettingsScope::Project, agent: SetupAgent::Claude, additional_metadata: None, diff --git a/bt-daemon/src/trace_command.rs b/bt-daemon/src/trace_command.rs index 0e70f916..aebb506d 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -21,6 +21,7 @@ pub struct TraceArgs { #[allow(clippy::large_enum_variant)] pub enum TraceCommand { /// Install and configure the Braintrust tracing plugin for a coding agent. + #[command(name = "install", visible_alias = "setup")] Setup(SetupArgs), /// Enable tracing, setting it up when needed or when settings are supplied. Enable(EnableArgs), @@ -103,6 +104,9 @@ pub enum SettingsScope { #[derive(Debug, Clone, Args)] 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, @@ -339,6 +343,7 @@ mod tests { assert!(matches!( parsed.trace.command, TraceCommand::Run(RunArgs { + inherit: false, source: crate::RunSource::Cursor, parent: Some(ref parent), ref agent_args, @@ -397,7 +402,7 @@ mod tests { }) )); - assert!(Cli::try_parse_from(["bt", "setup", "antigravity", "--disable"]).is_err()); + assert!(Cli::try_parse_from(["bt", "install", "antigravity", "--disable"]).is_ok()); } #[test] @@ -425,7 +430,7 @@ mod tests { #[test] fn scoped_commands_accept_project_before_or_after_agent() { - for command in ["setup", "enable", "disable"] { + for command in ["install", "setup", "enable", "disable"] { for args in [ vec!["bt", command, "--scope", "project", "claude"], vec!["bt", command, "claude", "--scope", "project"], diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 6429bcd0..03cf9869 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -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( @@ -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, @@ -749,6 +798,7 @@ pub async fn run_trace_with_matches( || has_explicit { let setup = crate::SetupArgs { + disable: false, scope: args.scope, agent: args.agent, additional_metadata: args.additional_metadata, @@ -767,6 +817,7 @@ pub async fn run_trace_with_matches( print_output(run_enable(args.agent)?, host.output_format) } else { let setup = crate::SetupArgs { + disable: false, scope: args.scope, agent: args.agent, additional_metadata: args @@ -899,16 +950,83 @@ pub async fn run_trace_with_matches( } 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); + } apply_tags(&mut route, &run_args.tags)?; let hook_command = child_command(&host.command, "hook"); let status = @@ -1279,6 +1397,7 @@ mod tests { #[tokio::test] async fn setup_and_run_request_a_destination_only_when_needed() { let run = RunArgs { + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, @@ -1296,6 +1415,7 @@ mod tests { for (command, persistent_auth, destination_required) in [ ( TraceCommand::Setup(SetupArgs { + disable: false, scope: SettingsScope::User, agent: SetupAgent::OpenCode, additional_metadata: None, @@ -1338,6 +1458,7 @@ mod tests { ) .unwrap(); let args = RunArgs { + inherit: false, source: RunSource::Claude, parent: Some(parent), additional_metadata: None, diff --git a/bt-daemon/tests/muse_managed_startup.rs b/bt-daemon/tests/muse_managed_startup.rs index 73ceaf80..5b06dec7 100644 --- a/bt-daemon/tests/muse_managed_startup.rs +++ b/bt-daemon/tests/muse_managed_startup.rs @@ -57,6 +57,7 @@ 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 { + 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..b54899e1 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -2952,6 +2952,7 @@ esac let run = |session_id: &str, mode: &str| { run_traced( RunArgs { + inherit: false, source: RunSource::Codex, parent: None, additional_metadata: None, @@ -3055,6 +3056,7 @@ async fn muse_managed_run_preserves_saved_settings_and_foreign_hooks() { let binary = env!("CARGO_BIN_EXE_bt-daemon"); let status = run_traced( RunArgs { + inherit: false, source: RunSource::Muse, parent: None, additional_metadata: None, @@ -3158,6 +3160,7 @@ 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 { + 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 2366c3fc..bc45f812 100644 --- a/docs/coding-agent-tracing-plugin-spec.md +++ b/docs/coding-agent-tracing-plugin-spec.md @@ -397,19 +397,24 @@ translator rather than separate trace builders. ### 8.1 Persistent setup -`bt trace setup ` 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 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 setup. Setup, enable, and disable support user and project scope. Project settings overlay user settings field by field; managed-run settings take precedence over both. -Project setup writes only explicitly selected fields and enables tracing without -installing a global adapter. Project files cannot select executable span plugins. +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. Project objects merge recursively and arrays +replace inherited arrays. Project files cannot select executable span plugins. `bt trace disable ` MUST preserve the adapter and configuration while disabling tracing. `bt trace uninstall ` MUST remove only Braintrust-managed state. Both MUST be safe when repeated. +Doctor SHOULD include the current repository settings and effective values. + Doctor/status output SHOULD diagnose: - whether the agent is installed; diff --git a/src/plugins/opencode/content/src/index.test.ts b/src/plugins/opencode/content/src/index.test.ts index 744e719a..e17c6479 100644 --- a/src/plugins/opencode/content/src/index.test.ts +++ b/src/plugins/opencode/content/src/index.test.ts @@ -146,6 +146,35 @@ describe("BraintrustPlugin", () => { expect((await BraintrustPlugin(createInput(directory))).event).toBeDefined(); }); + it("recursively merges project metadata and replaces arrays", async () => { + const global = join(directory, ".config", "opencode"); + const project = join(directory, ".opencode"); + 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: [4] }); + }); + it("inherits the user route while applying explicit project selections", async () => { const global = join(directory, ".config", "opencode"); const project = join(directory, ".opencode"); diff --git a/src/plugins/opencode/content/src/tracing/plugin.ts b/src/plugins/opencode/content/src/tracing/plugin.ts index d5fea983..258dee10 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, projectSettingsPath } from "../runtime/daemon-client"; +import { + claimManagedTracingInstance, + mergeConfigObjects, + mergeProjectRoute, + projectSettingsPath, +} from "../runtime/daemon-client"; import { createDaemonTracingHooks } from "./daemon"; export async function readPluginConfig(input: { @@ -24,8 +29,14 @@ export async function readPluginConfig(input: { pluginConfig = parsed; } else { // Project files cannot select executable span plugins. - const { route: _route, ...safe } = parsed; - const userRoute = pluginConfig?.route; + const { route: projectRoute, ...safe } = parsed; + const userRoute = mergeProjectRoute(pluginConfig?.route, projectRoute); + if (safe.additional_metadata) { + safe.additional_metadata = mergeConfigObjects( + userRoute?.additional_metadata ?? pluginConfig?.additional_metadata ?? {}, + safe.additional_metadata, + ); + } const auth = userRoute?.auth; const projectAuth = safe.profile || safe.org_name diff --git a/src/plugins/pi/content/src/config.test.ts b/src/plugins/pi/content/src/config.test.ts index 12dc50eb..ef00c3a2 100644 --- a/src/plugins/pi/content/src/config.test.ts +++ b/src/plugins/pi/content/src/config.test.ts @@ -105,6 +105,25 @@ describe("loadConfig", () => { }); }); + it("merges nested project metadata and replaces 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, ".pi", "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: [4], + }); + expect(loadConfig(cwd).enabled).toBe(true); + }); + it("prefers a canonical route over stale top-level routing", () => { 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 153b52bc..a6b9298f 100644 --- a/src/plugins/pi/content/src/config.ts +++ b/src/plugins/pi/content/src/config.ts @@ -4,6 +4,8 @@ import { join } from "node:path"; import { type DaemonSessionRoute, projectSettingsPath, + mergeConfigObjects, + mergeProjectRoute, resolveDaemonTraceSettings, } from "./runtime/daemon-client.ts"; import { runningPiPackage } from "./pi-package.ts"; @@ -75,7 +77,13 @@ 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; @@ -93,7 +101,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 { @@ -115,7 +127,12 @@ export function loadConfig(cwd = process.cwd()): PiConfig { (PROJECT_CONFIG_DIR_NAME === ".pi" ? undefined : readConfig(projectSettingsPath(cwd, ".pi"))); if (projectConfig) { // Repository settings must not select executable span plugins. - const { route: _route, ...safeProjectConfig } = projectConfig; + const { route: projectRoute, ...safeProjectConfig } = projectConfig; + if (record(projectRoute)) { + config.route = + mergeProjectRoute(config.route, projectRoute as DaemonSessionRoute) ?? config.route; + applyConfig(config, { route: config.route }); + } if (nonEmptyString(safeProjectConfig.profile) && config.route.auth) { delete config.route.auth.profile_id; config.route.auth.source = "saved_profile"; diff --git a/src/runtime/js-daemon-client/src/index.ts b/src/runtime/js-daemon-client/src/index.ts index bf2a7388..45fbfe2e 100644 --- a/src/runtime/js-daemon-client/src/index.ts +++ b/src/runtime/js-daemon-client/src/index.ts @@ -40,6 +40,35 @@ export function projectSettingsPath(directory: string, configDir: string): strin } } +/** Recursively overlay objects while replacing arrays and scalar values. */ +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 = 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 +} + +/** Merge a repository route without allowing it to introduce executable plugins. */ +export function mergeProjectRoute(base: DaemonSessionRoute | undefined, overlay: DaemonSessionRoute | undefined): DaemonSessionRoute | undefined { + if (!overlay) return base + const { span_plugins: plugins, ...fields } = overlay + const safe = plugins?.length === 0 ? { ...fields, span_plugins: [] } : fields + const original = structuredClone(base ?? { destination: undefined }) as DaemonSessionRoute + 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..1ba4be24 100644 --- a/src/runtime/js-daemon-client/tests/client.test.ts +++ b/src/runtime/js-daemon-client/tests/client.test.ts @@ -8,9 +8,29 @@ 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: [3] }) + }) + test("replaces arrays without accepting executable project plugins", () => { + const base = { destination: { type: "project_logs", project_name: "global" }, span_plugins: ["trusted"], tags: ["global"] } + const cleared = mergeProjectRoute(base, { destination: base.destination, span_plugins: [], tags: [] })! + assert.deepEqual(cleared.span_plugins, []) + assert.deepEqual(cleared.tags, []) + const blocked = mergeProjectRoute(base, { destination: base.destination, span_plugins: ["untrusted"] })! + assert.deepEqual(blocked.span_plugins, ["trusted"]) + }) +}) + describe("managed adapter claims", () => { test("deduplicates only the same source and managed run", () => { const target = {} as typeof globalThis From f26264570b80feb083f8c615391cecb1c8502ef3 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 19 Nov 2026 22:37:03 +0800 Subject: [PATCH 16/18] Share project tracing configuration at repository root --- README.md | 6 +- bt-daemon/README.md | 53 ++-- bt-daemon/src/args.rs | 7 +- bt-daemon/src/codex_hooks.rs | 2 +- bt-daemon/src/command_output.rs | 32 ++- bt-daemon/src/env.rs | 2 +- bt-daemon/src/hook.rs | 2 +- bt-daemon/src/managed_run/mod.rs | 39 ++- bt-daemon/src/paths.rs | 37 +-- bt-daemon/src/server/auth.rs | 2 +- bt-daemon/src/settings.rs | 263 +++++++++++++++--- bt-daemon/src/setup/antigravity.rs | 2 +- bt-daemon/src/setup/claude.rs | 4 +- bt-daemon/src/setup/common.rs | 6 +- bt-daemon/src/setup/cursor/mod.rs | 6 +- bt-daemon/src/setup/grok.rs | 6 +- bt-daemon/src/setup/mod.rs | 117 +++++++- bt-daemon/src/setup/muse.rs | 4 +- bt-daemon/src/setup/opencode.rs | 2 +- bt-daemon/src/trace_command.rs | 52 +++- bt-daemon/src/trace_runtime.rs | 36 ++- bt-daemon/tests/command_output.rs | 5 +- bt-daemon/tests/muse_managed_startup.rs | 1 + bt-daemon/tests/pipeline.rs | 3 + docs/coding-agent-tracing-plugin-spec.md | 14 +- src/plugins/antigravity/content/README.md | 2 +- src/plugins/claude/content/README.md | 8 +- .../plugins/trace-claude-code/README.md | 10 +- src/plugins/codex/content/README.md | 2 +- .../content/plugins/trace-codex/README.md | 6 +- src/plugins/cursor/content/README.md | 12 +- src/plugins/grok/content/README.md | 2 +- src/plugins/opencode/content/README.md | 4 +- src/plugins/opencode/content/install.sh | 2 +- src/plugins/opencode/content/src/config.ts | 5 +- .../opencode/content/src/index.test.ts | 49 +++- .../opencode/content/src/server.pause.test.ts | 4 +- .../opencode/content/src/tracing/plugin.ts | 31 ++- src/plugins/pi/content/README.md | 6 +- src/plugins/pi/content/src/config.test.ts | 59 +++- src/plugins/pi/content/src/config.ts | 52 ++-- src/runtime/js-daemon-client/src/index.ts | 33 ++- .../js-daemon-client/tests/client.test.ts | 17 +- 43 files changed, 783 insertions(+), 224 deletions(-) diff --git a/README.md b/README.md index ce6008a5..e2db908e 100644 --- a/README.md +++ b/README.md @@ -37,10 +37,10 @@ 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. To opt a Git repository +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. Project settings override -user settings; `bt trace run` overrides both. +`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 diff --git a/bt-daemon/README.md b/bt-daemon/README.md index b73f570f..04304027 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -73,22 +73,37 @@ A repository owner can configure tracing from anywhere inside the Git repository 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 `.claude/braintrust.json` at the repository root; other -agents use their own project configuration directory. The file 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 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, and arrays and other explicitly supplied values replace -those inherited. Repository settings cannot select executable span plugins. -Managed `bt trace run` takes precedence over both; `bt trace run --inherit` -starts from user and project settings before applying invocation options. -`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`. +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 @@ -178,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 setup 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 @@ -260,12 +275,12 @@ or provide it for one invocation with `bt trace run`. Both accept `--additional-metadata` or `BRAINTRUST_ADDITIONAL_METADATA`: ```bash -bt trace setup 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 setup`, `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 @@ -283,7 +298,7 @@ span produced by a route. The option is available on persistent setup, one-off runs, and transcript imports. ```bash -bt trace setup 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 ``` @@ -296,11 +311,11 @@ BRAINTRUST_TAGS=ci,release-validation bt trace run codex -- "summarize this chan ``` Use `bt trace disable ` to pause tracing while keeping the plugin and settings. -Use `bt trace enable ` to resume. If there is no saved setup, or you provide -explicit configuration options, `enable` runs setup and reports the result. Environment +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 setup ` to install or +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 aed39169..5422ee77 100644 --- a/bt-daemon/src/args.rs +++ b/bt-daemon/src/args.rs @@ -312,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 4a2efdb7..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 setup 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 041cb463..097d6960 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -62,12 +62,18 @@ pub struct SetupCommandOutput { #[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, } +fn is_false(value: &bool) -> bool { + !value +} + #[derive(Debug, Clone, Serialize)] pub struct UpdateCommandOutput { pub source: String, @@ -179,6 +185,7 @@ pub struct DoctorCommandOutput { pub enum TraceCommandOutput { Status(StatusCommandOutput), Doctor(Box), + #[serde(rename = "install")] Setup(SetupCommandOutput), Enable(SetupCommandOutput), Disable(SetupCommandOutput), @@ -210,6 +217,7 @@ impl TraceCommandOutput { restart_required: true, configuration: None, scope: "user", + applies_to_all_agents: false, enabled: None, warnings: Vec::new(), }) @@ -227,6 +235,7 @@ impl TraceCommandOutput { restart_required: true, configuration: Some("reused"), scope: "user", + applies_to_all_agents: false, enabled: None, warnings: Vec::new(), }) @@ -240,6 +249,10 @@ impl TraceCommandOutput { let mut output = Self::setup(source, display_name, settings_path).with_scope("project"); if let Self::Setup(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 } @@ -249,7 +262,10 @@ impl TraceCommandOutput { Self::Setup(output) | Self::Enable(output) | Self::Disable(output) - | Self::Uninstall(output) => output.scope = scope, + | Self::Uninstall(output) => { + output.scope = scope; + output.applies_to_all_agents = scope == "project"; + } _ => {} } self @@ -295,6 +311,7 @@ impl TraceCommandOutput { restart_required: true, configuration: None, scope: "user", + applies_to_all_agents: false, enabled: None, warnings: Vec::new(), }) @@ -312,6 +329,7 @@ impl TraceCommandOutput { restart_required: true, configuration: None, scope: "user", + applies_to_all_agents: false, enabled: None, warnings: Vec::new(), }) @@ -405,6 +423,13 @@ impl TraceCommandOutput { } Ok(rendered) } + 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() @@ -428,6 +453,9 @@ impl TraceCommandOutput { 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() @@ -540,7 +568,7 @@ mod tests { ); let rendered = output.render(OutputFormat::Json).unwrap(); let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); - assert_eq!(value["command"], "setup"); + assert_eq!(value["command"], "install"); assert_eq!(value["source"], "opencode"); assert_eq!(value["restart_required"], true); assert!(!rendered.contains("installed for")); 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 d63b7f05..e4b4ce23 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -189,7 +189,7 @@ pub(crate) async fn run_hook_with_route( pub(crate) fn read_project_hook_payload( args: &HookArgs, ) -> anyhow::Result> { - if crate::paths::project_config_dir(&args.source).is_some() { + 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)?; diff --git a/bt-daemon/src/managed_run/mod.rs b/bt-daemon/src/managed_run/mod.rs index a68709d5..62ff613c 100644 --- a/bt-daemon/src/managed_run/mod.rs +++ b/bt-daemon/src/managed_run/mod.rs @@ -115,9 +115,11 @@ async fn run_traced_inner( if let Some(components) = args.parent { route.destination = Some(wire::TraceDestination::ParentSpan { components }); } - if !args.inherit || !args.plugin.is_empty() { - 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 @@ -307,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(()) } @@ -367,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(); @@ -376,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 { @@ -394,6 +413,7 @@ 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, @@ -415,6 +435,7 @@ 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, diff --git a/bt-daemon/src/paths.rs b/bt-daemon/src/paths.rs index fe051b30..1e48d471 100644 --- a/bt-daemon/src/paths.rs +++ b/bt-daemon/src/paths.rs @@ -39,27 +39,28 @@ pub(crate) fn repository_root(start: &Path) -> anyhow::Result { }) } -/// Agent-local project configuration directories with supported project capture. -pub(crate) fn project_config_dir(source: &str) -> Option<&'static str> { - match source { - "claude" | "claude-code" => Some(".claude"), - "cursor" => Some(".cursor"), - "opencode" => Some(".opencode"), - "pi" => Some(".pi"), - "codex" => Some(".codex"), - "muse" | "muse-code" => Some(".muse"), - "grok" => Some(".grok"), - "antigravity" => Some(".gemini"), - _ => None, - } +/// 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 { - let directory = project_config_dir(source) - .ok_or_else(|| anyhow::anyhow!("project scope is not supported for {source}"))?; - Ok(repository_root(start)? - .join(directory) - .join("braintrust.json")) + 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` → 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 760d66f4..cf31cdce 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -1,6 +1,7 @@ //! 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. @@ -16,7 +17,7 @@ use std::path::{Path, PathBuf}; pub(crate) const INVOCATION_SETTINGS_ENV: &str = "BT_TRACE_INVOCATION_SETTINGS"; -/// Recursively overlay objects; every other value, including arrays, replaces. +/// 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)) => { @@ -29,6 +30,7 @@ pub(crate) fn merge_json(base: &mut Value, overlay: Value) { } } } + (Value::Array(base), Value::Array(overlay)) => base.extend(overlay), (base, overlay) => *base = overlay, } } @@ -108,18 +110,43 @@ impl AgentSettings { } 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()) })?; - if project_route - .get("span_plugins") - .is_some_and(|plugins| !plugins.as_array().is_some_and(Vec::is_empty)) - { - anyhow::bail!( - "repository tracing settings at {} cannot select executable span plugins", - 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 @@ -148,7 +175,7 @@ impl AgentSettings { destination.remove("project_id"); } } - merge_json(&mut route, Value::Object(project_route.clone())); + 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()))?, @@ -189,12 +216,13 @@ impl AgentSettings { } } if let Some(tags) = object.get("tags") { - let tags = serde_json::from_value(tags.clone()) + 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 = tags; + .tags + .extend(tags); } if let Some(metadata) = object.get("additional_metadata") { if !metadata.is_object() { @@ -280,7 +308,9 @@ impl AgentSettings { } fn project_settings_path(source: &str, payload: &Value) -> Option { - let directory = paths::project_config_dir(source)?; + if !paths::supports_project_settings(source) { + return None; + } let roots: Vec<&str> = match source { "cursor" => payload .get("workspace_roots") @@ -305,7 +335,7 @@ fn project_settings_path(source: &str, payload: &Value) -> Option { if roots.is_empty() { let current = std::env::current_dir().ok()?; let root = paths::repository_root(¤t).ok()?; - let candidate = root.join(directory).join("braintrust.json"); + let candidate = root.join(".braintrust.json"); return candidate.is_file().then_some(candidate); } for root in roots { @@ -314,7 +344,7 @@ fn project_settings_path(source: &str, payload: &Value) -> Option { continue; } let root = paths::repository_root(path).unwrap_or_else(|_| path.to_path_buf()); - let candidate = root.join(directory).join("braintrust.json"); + let candidate = root.join(".braintrust.json"); if candidate.is_file() { return Some(candidate); } @@ -372,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) @@ -467,7 +521,11 @@ mod tests { r#"{"trace_to_braintrust":true,"route":{"span_plugins":["./malicious.js"]}}"#, ) .unwrap(); - assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); + 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()); } @@ -483,20 +541,142 @@ mod tests { .unwrap() .route .unwrap(); - assert!(route.span_plugins.is_empty()); + 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"]); + assert_eq!( + route.tags.into_iter().collect::>(), + ["project", "user"] + ); assert_eq!( route.additional_metadata, - Some(serde_json::json!({"nested":{"one":1,"two":3},"list":[4]})) + 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(); @@ -527,23 +707,34 @@ mod tests { } #[test] - fn finds_repo_settings_for_nested_claude_and_cursor_workspaces() { + 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(); - for (source, dir) in [("claude", ".claude"), ("cursor", ".cursor")] { - std::fs::create_dir(repo.join(dir)).unwrap(); - let path = repo.join(dir).join("braintrust.json"); - std::fs::write(&path, "{}").unwrap(); - let payload = if source == "claude" { - serde_json::json!({"cwd": nested}) - } else { - serde_json::json!({"workspace_roots": [nested]}) + 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)); + assert_eq!(project_settings_path(source, &payload), Some(path.clone())); } let outside = temp.path().join("outside"); std::fs::create_dir(&outside).unwrap(); diff --git a/bt-daemon/src/setup/antigravity.rs b/bt-daemon/src/setup/antigravity.rs index 7e6fcc89..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 setup 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 f2ea6f1e..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 setup 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 setup 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 146dc38f..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 setup ` 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 setup {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 setup {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 98e01da7..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 setup 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 setup 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 setup 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 013fb31d..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 setup 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 setup 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 setup 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 6c3a0793..ac7f3c64 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -98,6 +98,14 @@ pub(crate) fn run_scoped_toggle( })) } +/// 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, @@ -121,8 +129,38 @@ fn write_project_setup_at( args: &SetupArgs, selection: &crate::HostRouteSelection, ) -> anyhow::Result<()> { - if !args.plugin.is_empty() { - anyhow::bail!("project configuration cannot select executable span plugins"); + 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)); @@ -135,6 +173,33 @@ fn write_project_setup_at( 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() { @@ -156,7 +221,7 @@ pub fn run_setup(args: SetupArgs, route: SessionRoute) -> anyhow::Result anyhow::Result { fn enable_existing_at(path: &Path) -> anyhow::Result<()> { if !path.exists() { anyhow::bail!( - "tracing is not configured at {}; run `bt trace setup` first", + "tracing is not configured at {}; run `bt trace install` first", path.display() ); } @@ -222,7 +287,7 @@ fn enable_existing_at(path: &Path) -> anyhow::Result<()> { .is_some_and(Value::is_boolean) { anyhow::bail!( - "tracing is not configured at {}; run `bt trace setup` first", + "tracing is not configured at {}; run `bt trace install` first", path.display() ); } @@ -276,9 +341,14 @@ pub fn run_update(agent: SetupAgent) -> anyhow::Result { )) } -fn enable_tracing(source: &str, route: SessionRoute, enabled: bool) -> anyhow::Result { +fn enable_tracing( + source: &str, + route: SessionRoute, + enabled: bool, + replace_plugins: bool, +) -> anyhow::Result { let path = paths::agent_settings_path(source, None); - write_tracing_at(&path, route, enabled)?; + write_tracing_at(&path, route, enabled, replace_plugins)?; Ok(path) } @@ -287,10 +357,15 @@ fn enable_tracing(source: &str, route: SessionRoute, enabled: bool) -> anyhow::R /// keys from earlier settings formats. #[cfg(test)] fn enable_tracing_at(path: &Path, route: SessionRoute) -> anyhow::Result<()> { - write_tracing_at(path, route, true) + write_tracing_at(path, route, true, false) } -fn write_tracing_at(path: &Path, mut route: SessionRoute, enabled: bool) -> anyhow::Result<()> { +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 @@ -314,7 +389,7 @@ fn write_tracing_at(path: &Path, mut route: SessionRoute, enabled: bool) -> anyh }) .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")) @@ -380,8 +455,10 @@ mod tests { #[test] fn project_setup_writes_only_explicit_values_and_preserves_existing_fields() { let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join(".claude/braintrust.json"); + 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, @@ -404,6 +481,24 @@ mod tests { 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!( diff --git a/bt-daemon/src/setup/muse.rs b/bt-daemon/src/setup/muse.rs index 162dbc42..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 setup 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 setup 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 a4941e13..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 setup 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 aebb506d..f9073bb5 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -27,7 +27,7 @@ pub enum TraceCommand { Enable(EnableArgs), /// Disable tracing while preserving the plugin and its configuration. Disable(DisableArgs), - /// Uninstall the tracing plugin and remove its saved configuration. + /// 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), @@ -118,6 +118,12 @@ pub struct SetupArgs { /// 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 for this agent. Repeat to compose /// transforms in order. #[arg(long, global = true, value_name = "PATH")] @@ -137,6 +143,12 @@ pub struct EnableArgs { /// 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, @@ -430,7 +442,7 @@ mod tests { #[test] fn scoped_commands_accept_project_before_or_after_agent() { - for command in ["install", "setup", "enable", "disable"] { + for command in ["install", "setup", "enable", "disable", "uninstall"] { for args in [ vec!["bt", command, "--scope", "project", "claude"], vec!["bt", command, "claude", "--scope", "project"], @@ -439,7 +451,7 @@ mod tests { let scope = match parsed.trace.command { TraceCommand::Setup(args) => args.scope, TraceCommand::Enable(args) => args.scope, - TraceCommand::Disable(args) => args.scope, + TraceCommand::Disable(args) | TraceCommand::Uninstall(args) => args.scope, _ => panic!("wrong command"), }; assert_eq!(scope, SettingsScope::Project); @@ -447,6 +459,40 @@ mod tests { } } + #[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(); diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 03cf9869..a6c19087 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -574,7 +574,7 @@ async fn doctor_output_at( if !settings_present { warnings.push(format!( - "settings file is missing; run `bt trace setup {source}`" + "settings file is missing; run `bt trace install {source}`" )); } else if !enabled { warnings.push(format!( @@ -754,6 +754,8 @@ fn enable_needs_setup(configured: bool, args: &crate::EnableArgs, 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. @@ -795,9 +797,13 @@ pub async fn run_trace_with_matches( 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, @@ -817,6 +823,8 @@ pub async fn run_trace_with_matches( 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, @@ -855,10 +863,14 @@ pub async fn run_trace_with_matches( } } TraceCommand::Uninstall(args) => { - if args.scope != SettingsScope::User { - anyhow::bail!("uninstall applies only to user scope"); + 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) } - print_output(crate::run_uninstall(args.agent)?, host.output_format) } TraceCommand::Update(update_args) => { let codex = matches!(update_args.agent, SetupAgent::Codex); @@ -1027,7 +1039,11 @@ pub async fn run_trace_with_matches( } 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?; @@ -1086,6 +1102,8 @@ mod tests { #[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, @@ -1110,6 +1128,8 @@ mod tests { 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, @@ -1156,6 +1176,8 @@ mod tests { 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, @@ -1397,6 +1419,7 @@ 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, @@ -1415,6 +1438,8 @@ mod tests { for (command, persistent_auth, destination_required) in [ ( TraceCommand::Setup(SetupArgs { + no_inherit_plugins: false, + inherit_plugins: false, disable: false, scope: SettingsScope::User, agent: SetupAgent::OpenCode, @@ -1458,6 +1483,7 @@ mod tests { ) .unwrap(); let args = RunArgs { + no_inherit_plugins: false, inherit: false, source: RunSource::Claude, parent: Some(parent), @@ -1750,7 +1776,7 @@ mod tests { _: AuthResolveReason, ) -> anyhow::Result { anyhow::bail!( - "saved profile ID 'daemon-only' no longer exists; run `bt trace setup` 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 3a3faff9..c0176fdc 100644 --- a/bt-daemon/tests/command_output.rs +++ b/bt-daemon/tests/command_output.rs @@ -310,9 +310,8 @@ fn project_settings_control_hook_capture_from_native_payload() { serde_json::json!({"workspacePaths":[repo],"session_id":"s","hook_event_name":"Stop"}), ), ] { - let config_dir = repo.join(dir); - std::fs::create_dir_all(&config_dir).unwrap(); - let config = config_dir.join("braintrust.json"); + let _ = dir; + let config = repo.join(".braintrust.json"); let run = |enabled: bool| { std::fs::write( &config, diff --git a/bt-daemon/tests/muse_managed_startup.rs b/bt-daemon/tests/muse_managed_startup.rs index 5b06dec7..4128d6aa 100644 --- a/bt-daemon/tests/muse_managed_startup.rs +++ b/bt-daemon/tests/muse_managed_startup.rs @@ -57,6 +57,7 @@ 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, diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index b54899e1..3b6405da 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -2952,6 +2952,7 @@ esac let run = |session_id: &str, mode: &str| { run_traced( RunArgs { + no_inherit_plugins: false, inherit: false, source: RunSource::Codex, parent: None, @@ -3056,6 +3057,7 @@ 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, @@ -3160,6 +3162,7 @@ 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, diff --git a/docs/coding-agent-tracing-plugin-spec.md b/docs/coding-agent-tracing-plugin-spec.md index bc45f812..c7de657b 100644 --- a/docs/coding-agent-tracing-plugin-spec.md +++ b/docs/coding-agent-tracing-plugin-spec.md @@ -395,23 +395,25 @@ translator rather than separate trace builders. ## 8. Product surfaces -### 8.1 Persistent setup +### 8.1 Persistent installation `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 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 setup. +`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. -Setup, enable, and disable support user and project scope. Project settings overlay +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. Project objects merge recursively and arrays -replace inherited arrays. Project files cannot select executable span plugins. +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 only Braintrust-managed state. Both MUST be safe when repeated. +`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. diff --git a/src/plugins/antigravity/content/README.md b/src/plugins/antigravity/content/README.md index 37624c60..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 setup 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 19013a2d..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 setup 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 setup 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 setup 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 ``` 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 93d81737..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 setup 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 setup 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 setup 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 setup`, `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 setup 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 45c69330..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 setup 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 921a9217..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 setup 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 setup 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 setup 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 7ca196b0..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 setup 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 setup 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 setup 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 setup 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 setup 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 ``` diff --git a/src/plugins/grok/content/README.md b/src/plugins/grok/content/README.md index b2939101..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 setup 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 68681942..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 setup 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 setup` 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 7226b8a3..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 setup 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 a41aecce..38fbb5b2 100644 --- a/src/plugins/opencode/content/src/config.ts +++ b/src/plugins/opencode/content/src/config.ts @@ -26,6 +26,7 @@ export interface PluginConfig { debug?: boolean; additional_metadata?: Record; tags?: string[]; + inherit_plugins?: boolean; route?: DaemonSessionRoute; } @@ -75,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 setup` 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 ( @@ -107,7 +108,7 @@ export function loadConfig(pluginConfig?: PluginConfig): BraintrustConfig { ...(defaults.orgName ? { org_name: defaults.orgName } : {}), }, }; - if (!pluginConfig?.route) { + if (!pluginConfig?.route || pluginConfig.route.destination === undefined) { persistentRoute.destination = { type: "project_logs", project_name: defaults.projectName }; } if (defaults.additionalMetadata) diff --git a/src/plugins/opencode/content/src/index.test.ts b/src/plugins/opencode/content/src/index.test.ts index e17c6479..7af6671f 100644 --- a/src/plugins/opencode/content/src/index.test.ts +++ b/src/plugins/opencode/content/src/index.test.ts @@ -127,15 +127,18 @@ describe("BraintrustPlugin", () => { it("lets project tracing override the user default and managed runs override both", async () => { const global = join(directory, ".config", "opencode"); - const project = join(directory, ".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 })); + 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 })); + 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(); @@ -146,9 +149,26 @@ describe("BraintrustPlugin", () => { expect((await BraintrustPlugin(createInput(directory))).event).toBeDefined(); }); - it("recursively merges project metadata and replaces arrays", async () => { + 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 = join(directory, ".opencode"); + const project = directory; mkdirSync(global, { recursive: true }); mkdirSync(project, { recursive: true }); writeFileSync( @@ -162,7 +182,7 @@ describe("BraintrustPlugin", () => { }), ); writeFileSync( - join(project, "braintrust.json"), + join(project, ".braintrust.json"), JSON.stringify({ trace_to_braintrust: true, route: { additional_metadata: { nested: { b: 3 }, list: [4] } }, @@ -172,12 +192,12 @@ describe("BraintrustPlugin", () => { 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: [4] }); + 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 = join(directory, ".opencode"); + const project = directory; mkdirSync(global, { recursive: true }); mkdirSync(project, { recursive: true }); mkdirSync(join(directory, ".git")); @@ -195,7 +215,7 @@ describe("BraintrustPlugin", () => { }), ); writeFileSync( - join(project, "braintrust.json"), + join(project, ".braintrust.json"), JSON.stringify({ project: "local", profile: "new", @@ -212,7 +232,16 @@ describe("BraintrustPlugin", () => { org_name: "org", }); expect(config.route.auth?.profile_id).toBeUndefined(); - expect(config.route.span_plugins).toEqual(["trusted.js"]); + 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 () => { diff --git a/src/plugins/opencode/content/src/server.pause.test.ts b/src/plugins/opencode/content/src/server.pause.test.ts index 0db1ceac..2ead16a7 100644 --- a/src/plugins/opencode/content/src/server.pause.test.ts +++ b/src/plugins/opencode/content/src/server.pause.test.ts @@ -27,11 +27,11 @@ afterEach(() => { it("applies the project opt-out to OpenCode 2 and permits a managed run", async () => { const global = join(directory, "config", "opencode"); - const project = join(directory, ".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 })); + writeFileSync(join(project, ".braintrust.json"), JSON.stringify({ trace_to_braintrust: false })); const hook = vi.fn(async () => {}); const subscribe = vi.fn(async function* () {}); const ctx = { diff --git a/src/plugins/opencode/content/src/tracing/plugin.ts b/src/plugins/opencode/content/src/tracing/plugin.ts index 258dee10..c2a75524 100644 --- a/src/plugins/opencode/content/src/tracing/plugin.ts +++ b/src/plugins/opencode/content/src/tracing/plugin.ts @@ -19,7 +19,7 @@ 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"), - projectSettingsPath(input.directory, ".opencode"), + projectSettingsPath(input.directory), ]; for (const [index, configPath] of configPaths.entries()) { try { @@ -28,14 +28,34 @@ export async function readPluginConfig(input: { if (index === 0) { pluginConfig = parsed; } else { - // Project files cannot select executable span plugins. - const { route: projectRoute, ...safe } = parsed; - const userRoute = mergeProjectRoute(pluginConfig?.route, projectRoute); + 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 = @@ -70,7 +90,8 @@ export async function readPluginConfig(input: { } } } 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 0be94e2c..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 setup 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 setup 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 setup` 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 ef00c3a2..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, @@ -105,7 +105,7 @@ describe("loadConfig", () => { }); }); - it("merges nested project metadata and replaces arrays", () => { + it("merges nested project metadata and appends arrays", () => { writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: false, route: { @@ -113,17 +113,50 @@ describe("loadConfig", () => { additional_metadata: { nested: { a: 1, b: 2 }, list: [1, 2] }, }, }); - writeJson(join(cwd, ".pi", "braintrust.json"), { + 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: [4], + 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, @@ -181,12 +214,26 @@ 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, ".pi", "braintrust.json"), { trace_to_braintrust: true }); + 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, ".pi", "braintrust.json"), { trace_to_braintrust: false }); + 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, diff --git a/src/plugins/pi/content/src/config.ts b/src/plugins/pi/content/src/config.ts index a6b9298f..f4a88255 100644 --- a/src/plugins/pi/content/src/config.ts +++ b/src/plugins/pi/content/src/config.ts @@ -8,7 +8,6 @@ import { mergeProjectRoute, resolveDaemonTraceSettings, } from "./runtime/daemon-client.ts"; -import { runningPiPackage } from "./pi-package.ts"; export interface PiConfig { enabled: boolean; @@ -23,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) @@ -89,7 +86,7 @@ function applyConfig(config: PiConfig, source: ConfigRecord | undefined): void { const additionalMetadata = record(source.additional_metadata); if (Array.isArray(source.tags) && source.tags.every((tag) => typeof tag === "string")) { - config.route.tags = source.tags; + config.route.tags = [...new Set([...(config.route.tags ?? []), ...source.tags])]; } if (profile || orgName) { config.route.auth = { @@ -122,22 +119,41 @@ export function loadConfig(cwd = process.cwd()): PiConfig { const userConfig = readConfig(join(homedir(), ".pi", "agent", "braintrust.json")); applyConfig(config, userConfig); - const projectConfig = - readConfig(projectSettingsPath(cwd, PROJECT_CONFIG_DIR_NAME)) ?? - (PROJECT_CONFIG_DIR_NAME === ".pi" ? undefined : readConfig(projectSettingsPath(cwd, ".pi"))); + const projectPath = projectSettingsPath(cwd); + const projectConfig = readConfig(projectPath); if (projectConfig) { - // Repository settings must not select executable span plugins. - const { route: projectRoute, ...safeProjectConfig } = projectConfig; - if (record(projectRoute)) { - config.route = - mergeProjectRoute(config.route, projectRoute as DaemonSessionRoute) ?? config.route; - applyConfig(config, { route: config.route }); - } - if (nonEmptyString(safeProjectConfig.profile) && config.route.auth) { - delete config.route.auth.profile_id; - config.route.auth.source = "saved_profile"; + 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; } - applyConfig(config, safeProjectConfig); + } else if (existsSync(projectPath)) { + config.enabled = false; } config.showUi = boolean(process.env.BRAINTRUST_SHOW_UI) ?? config.showUi; diff --git a/src/runtime/js-daemon-client/src/index.ts b/src/runtime/js-daemon-client/src/index.ts index 45fbfe2e..a4ed59e3 100644 --- a/src/runtime/js-daemon-client/src/index.ts +++ b/src/runtime/js-daemon-client/src/index.ts @@ -1,6 +1,6 @@ import { spawnBackground } from "./background-process.ts" import { createHash } from "node:crypto" -import { existsSync } from "node:fs" +import { existsSync, realpathSync } from "node:fs" import { createConnection, type Socket } from "node:net" import { homedir } from "node:os" import { dirname, join, resolve } from "node:path" @@ -29,23 +29,23 @@ export interface DaemonTraceSettings { } /** Find project settings at the Git root, or in the starting directory outside Git. */ -export function projectSettingsPath(directory: string, configDir: string): string { +export function projectSettingsPath(directory: string): string { const start = resolve(directory) let current = start while (true) { - if (existsSync(join(current, ".git"))) return join(current, configDir, "braintrust.json") + if (existsSync(join(current, ".git"))) return join(current, ".braintrust.json") const parent = dirname(current) - if (parent === current) return join(start, configDir, "braintrust.json") + if (parent === current) return join(start, ".braintrust.json") current = parent } } -/** Recursively overlay objects while replacing arrays and scalar values. */ +/** 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 = prior !== null && typeof prior === "object" && !Array.isArray(prior) && value !== null && typeof value === "object" && !Array.isArray(value) + 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 }) @@ -53,12 +53,23 @@ export function mergeConfigObjects(base: Record, overlay: Recor return result } -/** Merge a repository route without allowing it to introduce executable plugins. */ -export function mergeProjectRoute(base: DaemonSessionRoute | undefined, overlay: DaemonSessionRoute | undefined): DaemonSessionRoute | undefined { - if (!overlay) return base - const { span_plugins: plugins, ...fields } = overlay - const safe = plugins?.length === 0 ? { ...fields, span_plugins: [] } : fields +/** 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" diff --git a/src/runtime/js-daemon-client/tests/client.test.ts b/src/runtime/js-daemon-client/tests/client.test.ts index 1ba4be24..ff907875 100644 --- a/src/runtime/js-daemon-client/tests/client.test.ts +++ b/src/runtime/js-daemon-client/tests/client.test.ts @@ -19,15 +19,18 @@ describe("project route overlay", () => { 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: [3] }) + assert.deepEqual(merged.nested, { keep: 1, list: [1, 2, 3] }) }) - test("replaces arrays without accepting executable project plugins", () => { + 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 cleared = mergeProjectRoute(base, { destination: base.destination, span_plugins: [], tags: [] })! - assert.deepEqual(cleared.span_plugins, []) - assert.deepEqual(cleared.tags, []) - const blocked = mergeProjectRoute(base, { destination: base.destination, span_plugins: ["untrusted"] })! - assert.deepEqual(blocked.span_plugins, ["trusted"]) + 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"]) }) }) From 280b5d9ee5b7f886ccba5c6f0a7087a61e581e0e Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 19 Nov 2026 22:42:44 +0800 Subject: [PATCH 17/18] Make import output formatting consistent --- bt-daemon/src/command_output.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index 097d6960..b8d63786 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -192,7 +192,10 @@ pub enum TraceCommandOutput { Uninstall(SetupCommandOutput), Update(UpdateCommandOutput), Stop(StopCommandOutput), - Import { summaries: Vec }, + Import { + /// Summaries for the imported sessions. + summaries: Vec, + }, } impl TraceCommandOutput { From 2804da4413d513bba4dd458050f3bd8c153326db Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Fri, 20 Nov 2026 20:48:34 +0800 Subject: [PATCH 18/18] Make install the canonical trace command --- bt-daemon/src/command_output.rs | 57 ++++++++++++++++++++------------- bt-daemon/src/lib.rs | 3 +- bt-daemon/src/setup/mod.rs | 6 ++-- bt-daemon/src/trace_command.rs | 20 ++++++------ bt-daemon/src/trace_runtime.rs | 12 +++---- 5 files changed, 55 insertions(+), 43 deletions(-) diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index b8d63786..cb401e61 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -54,7 +54,7 @@ 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, @@ -70,6 +70,9 @@ pub struct SetupCommandOutput { pub warnings: Vec, } +/// Backwards-compatible name for the shared install and enable output. +pub type SetupCommandOutput = InstallCommandOutput; + fn is_false(value: &bool) -> bool { !value } @@ -185,11 +188,10 @@ pub struct DoctorCommandOutput { pub enum TraceCommandOutput { Status(StatusCommandOutput), Doctor(Box), - #[serde(rename = "install")] - Setup(SetupCommandOutput), - Enable(SetupCommandOutput), - Disable(SetupCommandOutput), - Uninstall(SetupCommandOutput), + Install(InstallCommandOutput), + Enable(InstallCommandOutput), + Disable(InstallCommandOutput), + Uninstall(InstallCommandOutput), Update(UpdateCommandOutput), Stop(StopCommandOutput), Import { @@ -207,13 +209,13 @@ 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::Setup(SetupCommandOutput { + Self::Install(InstallCommandOutput { source, display_name: display_name.into(), settings_path: settings_path.into(), @@ -226,12 +228,21 @@ impl TraceCommandOutput { }) } + /// 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(SetupCommandOutput { + Self::Enable(InstallCommandOutput { source: source.into(), display_name: display_name.into(), settings_path: settings_path.into(), @@ -244,13 +255,13 @@ impl TraceCommandOutput { }) } - pub fn project_setup( + pub fn project_install( source: impl Into, display_name: impl Into, settings_path: impl Into, ) -> Self { - let mut output = Self::setup(source, display_name, settings_path).with_scope("project"); - if let Self::Setup(setup) = &mut output { + 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." @@ -262,7 +273,7 @@ impl TraceCommandOutput { pub(crate) fn with_scope(mut self, scope: &'static str) -> Self { match &mut self { - Self::Setup(output) + Self::Install(output) | Self::Enable(output) | Self::Disable(output) | Self::Uninstall(output) => { @@ -275,7 +286,7 @@ impl TraceCommandOutput { } pub(crate) fn with_enabled(mut self, enabled: bool) -> Self { - if let Self::Setup(output) = &mut self { + if let Self::Install(output) = &mut self { output.enabled = Some(enabled); } self @@ -283,13 +294,13 @@ impl TraceCommandOutput { pub(crate) fn into_enable(mut self, configuration: &'static str) -> Self { match &mut self { - Self::Setup(output) | Self::Enable(output) => { + Self::Install(output) | Self::Enable(output) => { output.configuration = Some(configuration) } _ => return self, } match self { - Self::Setup(output) => Self::Enable(output), + Self::Install(output) => Self::Enable(output), _ => self, } } @@ -307,7 +318,7 @@ 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(), @@ -325,7 +336,7 @@ impl TraceCommandOutput { display_name: impl Into, settings_path: impl Into, ) -> Self { - Self::Uninstall(SetupCommandOutput { + Self::Uninstall(InstallCommandOutput { source: source.into(), display_name: display_name.into(), settings_path: settings_path.into(), @@ -437,10 +448,10 @@ impl TraceCommandOutput { "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::Setup(setup) if setup.scope == "project" => Ok(format!( + 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::Setup(setup) => Ok(format!( + 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(), @@ -563,8 +574,8 @@ 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"), @@ -609,7 +620,7 @@ mod tests { #[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(); diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index e8fbc961..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; diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index ac7f3c64..36e8f410 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -115,8 +115,8 @@ pub(crate) fn run_project_setup( let existed = path.exists(); write_project_setup_at(&path, &args, &selection)?; let id = args.agent.identity(); - let output = - TraceCommandOutput::project_setup(id.id, id.display_name, path).with_enabled(!args.disable); + 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 { @@ -223,7 +223,7 @@ pub fn run_setup(args: SetupArgs, route: SessionRoute) -> anyhow::Result args.scope, + TraceCommand::Install(args) => args.scope, TraceCommand::Enable(args) => args.scope, TraceCommand::Disable(args) | TraceCommand::Uninstall(args) => args.scope, _ => panic!("wrong command"), @@ -573,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 a6c19087..7a9eb9a8 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -697,7 +697,7 @@ async fn doctor_output_at( } } -async fn run_setup_command( +async fn run_install_command( mut args: crate::SetupArgs, host: &TraceHostContext, configuration: Option<&'static str>, @@ -737,7 +737,7 @@ async fn run_setup_command( let codex = matches!(args.agent, SetupAgent::Codex); let mut output = crate::run_setup(args, route)?; if let Some(configuration) = configuration { - if let TraceCommandOutput::Setup(mut setup) = output { + if let TraceCommandOutput::Install(mut setup) = output { setup.configuration = Some(configuration); output = TraceCommandOutput::Enable(setup); } @@ -791,7 +791,7 @@ pub async fn run_trace_with_matches( || selection.auth.org_name.is_some() || selection.project_name.is_some(); match args.command { - TraceCommand::Setup(args) => run_setup_command(args, &host, None, &selection).await, + 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() @@ -811,7 +811,7 @@ pub async fn run_trace_with_matches( tags: args.tags, plugin: args.plugin, }; - return run_setup_command(setup, &host, Some("updated"), &selection).await; + return run_install_command(setup, &host, Some("updated"), &selection).await; } return print_output( crate::setup::run_scoped_toggle(args.agent, args.scope, true)?, @@ -843,7 +843,7 @@ pub async fn run_trace_with_matches( }, plugin: args.plugin, }; - run_setup_command( + run_install_command( setup, &host, Some(if configured { "updated" } else { "created" }), @@ -1437,7 +1437,7 @@ 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,