Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions bt-daemon/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,28 @@ or `bt trace doctor <agent>` for configuration, authentication, and recent
session diagnostics. Hook exit codes can be observed by the caller while the
coding agent decides whether to continue its turn.

## Repository-scoped tracing for Claude Code and Cursor

Install the agent integration with `bt trace setup claude` or `bt trace setup cursor`.
To trace only selected repositories, set `trace_to_braintrust` to `false` in the
corresponding user-level `braintrust.json`, then commit `.claude/braintrust.json`
or `.cursor/braintrust.json` in each selected repository:

```json
{
"trace_to_braintrust": true,
"project": "my-braintrust-project"
}
```

The hook uses the closest project file within the Git repository, including when
Claude Code starts in a subdirectory. For Cursor workspaces with multiple roots,
the first root containing a project file supplies the settings for the session.
Project settings can select `trace_to_braintrust` and `project`; other route
settings, including span plugins, come from the user settings. An explicit `bt trace disable` pauses persistent tracing even in opted-in
repositories; a managed `bt trace run` takes precedence over both. `bt trace doctor`
reports user-level settings, not the settings of a particular repository.

## Per-agent plugin settings

Each coding agent reads an independent non-credential `braintrust.json` file:
Expand Down
39 changes: 35 additions & 4 deletions bt-daemon/src/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Option<serde_json::Value>> {
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<serde_json::Value>,
) -> 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<T>(
Expand All @@ -193,6 +220,7 @@ async fn capture_hook(
mut args: HookArgs,
mut route: SessionRoute,
host: HostInfo,
payload: Option<serde_json::Value>,
) -> 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
Expand All @@ -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);

Expand Down
210 changes: 200 additions & 10 deletions bt-daemon/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -38,15 +38,73 @@ pub(crate) struct AgentSettings {
}

impl AgentSettings {
/// Hook invocations must report broken configuration instead of treating
/// it as a successful event. A managed run's invocation route is complete
/// and intentionally supersedes any persistent settings file.
pub(crate) fn load_for_hook(source: &str) -> anyhow::Result<Self> {
pub(crate) fn load_for_hook_payload(
source: &str,
payload: Option<&Value>,
) -> anyhow::Result<Self> {
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<Self> {
let path = match (invocation, project_path) {
(Some(_), _) | (_, None) => return Self::load_hook_from_sources(user_path, invocation),
(None, Some(path)) => path,
};
let raw = std::fs::read_to_string(path).map_err(|error| {
anyhow::anyhow!("read tracing settings at {}: {error}", path.display())
})?;
let project: Value = serde_json::from_str(&raw).map_err(|error| {
anyhow::anyhow!("parse tracing settings at {}: {error}", path.display())
})?;
let object = project.as_object().ok_or_else(|| {
anyhow::anyhow!("tracing settings at {} must be an object", path.display())
})?;
if object.contains_key("route") {
anyhow::bail!("repository tracing settings at {} cannot specify `route`; use `project` to select a destination", path.display());
}
let overlay: Self = serde_json::from_value(project.clone())?;
let mut settings = if user_path.exists() {
Self::load_hook_from_sources(user_path, None)?
} else {
Self::default()
};
if overlay.trace_to_braintrust.is_some() {
settings.trace_to_braintrust = overlay.trace_to_braintrust;
}
if let Some(project) = object.get("project") {
let name = project
.as_str()
.filter(|name| !name.trim().is_empty())
.ok_or_else(|| {
anyhow::anyhow!("project in {} must be a nonempty string", path.display())
})?;
let route = settings.route.get_or_insert_with(SessionRoute::default);
route.destination = Some(TraceDestination::ProjectLogs {
project_id: None,
project_name: Some(name.to_owned()),
});
}
// An explicit user pause must remain effective even when a repository opts in.
if user_path.exists() {
let user: Value = serde_json::from_str(&std::fs::read_to_string(user_path)?)?;
if user.get("tracing_disabled").and_then(Value::as_bool) == Some(true) {
settings.trace_to_braintrust = Some(false);
}
}
if settings.trace_to_braintrust.is_none() {
anyhow::bail!(
"tracing settings at {} have no `trace_to_braintrust` value",
path.display()
);
}
Ok(settings)
}

fn load_hook_from_sources(path: &Path, invocation: Option<&str>) -> anyhow::Result<Self> {
Expand Down Expand Up @@ -125,6 +183,46 @@ impl AgentSettings {
}
}

fn project_settings_path(source: &str, payload: &Value) -> Option<PathBuf> {
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(
Expand Down Expand Up @@ -210,6 +308,98 @@ fn write_json_atomic(path: &Path, settings: &Map<String, Value>) -> anyhow::Resu

#[cfg(test)]
mod tests {
#[test]
fn project_settings_override_user_and_managed_run_overrides_both() {
use super::*;
let temp = tempfile::tempdir().unwrap();
let user = temp.path().join("user.json");
let project = temp.path().join("project.json");
std::fs::write(
&user,
r#"{"trace_to_braintrust":false,"route":{"tags":["saved"]}}"#,
)
.unwrap();
std::fs::write(
&project,
r#"{"trace_to_braintrust":true,"project":"repo-project"}"#,
)
.unwrap();
let settings = AgentSettings::load_hook_with_project(&user, Some(&project), None).unwrap();
assert!(settings.tracing_enabled());
let route = settings.route.unwrap();
assert!(route.tags.contains("saved"));
assert!(
matches!(route.destination, Some(TraceDestination::ProjectLogs { project_name: Some(ref name), .. }) if name == "repo-project")
);
let invocation = r#"{"trace_to_braintrust":false,"route":{}}"#;
assert!(
!AgentSettings::load_hook_with_project(&user, Some(&project), Some(invocation))
.unwrap()
.tracing_enabled()
);
std::fs::write(
&user,
r#"{"trace_to_braintrust":false,"tracing_disabled":true}"#,
)
.unwrap();
assert!(
!AgentSettings::load_hook_with_project(&user, Some(&project), None)
.unwrap()
.tracing_enabled()
);
assert!(AgentSettings::load_hook_with_project(
&user,
Some(&project),
Some(r#"{"trace_to_braintrust":true,"route":{}}"#)
)
.unwrap()
.tracing_enabled());
std::fs::write(&project, r#"{"trace_to_braintrust":false}"#).unwrap();
assert!(
!AgentSettings::load_hook_with_project(&user, Some(&project), None)
.unwrap()
.tracing_enabled()
);
std::fs::remove_file(&user).unwrap();
std::fs::write(&project, r#"{"trace_to_braintrust":true,"project":"new"}"#).unwrap();
assert!(
AgentSettings::load_hook_with_project(&user, Some(&project), None)
.unwrap()
.tracing_enabled()
);
std::fs::write(
&project,
r#"{"trace_to_braintrust":true,"route":{"span_plugins":["./malicious.js"]}}"#,
)
.unwrap();
assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err());
std::fs::write(&project, "invalid").unwrap();
assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err());
}

#[test]
fn finds_repo_settings_for_nested_claude_and_cursor_workspaces() {
use super::*;
let temp = tempfile::tempdir().unwrap();
let repo = temp.path().join("repo");
let nested = repo.join("src/nested");
std::fs::create_dir_all(&nested).unwrap();
std::fs::create_dir(repo.join(".git")).unwrap();
for (source, dir) in [("claude", ".claude"), ("cursor", ".cursor")] {
std::fs::create_dir(repo.join(dir)).unwrap();
let path = repo.join(dir).join("braintrust.json");
std::fs::write(&path, "{}").unwrap();
let payload = if source == "claude" {
serde_json::json!({"cwd": nested})
} else {
serde_json::json!({"workspace_roots": [nested]})
};
assert_eq!(project_settings_path(source, &payload), Some(path));
}
let outside = temp.path().join("outside");
std::fs::create_dir(&outside).unwrap();
assert!(project_settings_path("claude", &serde_json::json!({"cwd": outside})).is_none());
}
use super::*;

#[test]
Expand Down
Loading
Loading