From 3bb18c928448e352e14be98ffe179b8c14a6f5ab Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 19:06:33 +0800 Subject: [PATCH 1/6] Support Grok Build tracing alongside Cursor and legacy Grok --- README.md | 6 +- bt-daemon/README.md | 3 +- bt-daemon/src/agents/cursor.rs | 2 +- bt-daemon/src/agents/grok.rs | 5 +- bt-daemon/src/agents/grok/hook_transcript.rs | 43 ++++ bt-daemon/src/agents/mod.rs | 2 +- bt-daemon/src/args.rs | 2 + bt-daemon/src/dispatch.rs | 11 +- bt-daemon/src/trace_command.rs | 79 +++++-- bt-daemon/src/transcript_mirror/payload.rs | 4 +- bt-daemon/src/translate/grok.rs | 70 ++++-- bt-daemon/src/translate/grok/agent_host.rs | 216 ++++++++++++++++++ bt-daemon/tests/grok_translator.rs | 71 ++++++ bt-daemon/tests/pipeline.rs | 1 + .../cursor/content/.cursor-plugin/plugin.json | 2 +- src/plugins/cursor/content/README.md | 76 +++--- src/plugins/cursor/content/package.json | 5 +- src/plugins/cursor/content/src/extension.ts | 2 +- .../grok/content/.grok-plugin/plugin.json | 2 +- src/plugins/grok/content/README.md | 39 ++-- 20 files changed, 524 insertions(+), 117 deletions(-) create mode 100644 bt-daemon/src/agents/grok/hook_transcript.rs create mode 100644 bt-daemon/src/translate/grok/agent_host.rs diff --git a/README.md b/README.md index e2db908e..3605ac73 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ All support `bt trace install`, `enable`, `update`, `disable`, and `doctor`. | [Google Antigravity](src/plugins/antigravity/content/README.md) | `antigravity` | — | Yes | [GitHub](https://github.com/braintrustdata/braintrust-antigravity-plugin) | | [Claude Code](src/plugins/claude/content/README.md) | `claude` | Yes | Yes | [GitHub](https://github.com/braintrustdata/braintrust-claude-plugin) | | [Codex](src/plugins/codex/content/README.md) | `codex` | Yes | Yes | [GitHub](https://github.com/braintrustdata/braintrust-codex-plugin) | -| [Cursor](src/plugins/cursor/content/README.md) | `cursor` | Yes | Yes, transcript-limited | [GitHub](https://github.com/braintrustdata/braintrust-cursor-extension) | -| [Grok](src/plugins/grok/content/README.md) | `grok` | — | — | [GitHub](https://github.com/braintrustdata/braintrust-grok-plugin) | +| [Grok Build desktop / Cursor](src/plugins/cursor/content/README.md) | `grok-build-desktop` (`cursor`) | Legacy Cursor CLI only | Yes, Cursor-format transcripts | [GitHub](https://github.com/braintrustdata/braintrust-cursor-extension) | +| [Grok Build TUI / legacy Grok](src/plugins/grok/content/README.md) | `grok-build` (`grok`) | — | — | [GitHub](https://github.com/braintrustdata/braintrust-grok-plugin) | | [OpenCode](src/plugins/opencode/content/README.md) | `opencode` | Yes | — | [npm](https://www.npmjs.com/package/@braintrust/trace-opencode) | | [Pi](src/plugins/pi/content/README.md) | `pi` | Yes | — | [npm](https://www.npmjs.com/package/@braintrust/pi-extension) | @@ -64,7 +64,7 @@ bt trace run --project my-coding-agent claude -- -p "summarize this repository" bt trace import claude SESSION_ID bt trace import claude SESSION_ID --attach bt trace run --project my-coding-agent cursor -bt trace import cursor SESSION_ID --attach +bt trace import grok-build-desktop SESSION_ID --attach ``` See the agent guides for limitations. diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 04304027..fdd10a63 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -116,7 +116,8 @@ Each coding agent reads an independent non-credential `braintrust.json` file: - OpenCode: `$XDG_CONFIG_HOME/opencode/braintrust.json`, falling back to `~/.config/opencode/braintrust.json` - Pi: `~/.pi/agent/braintrust.json` -- Grok: `~/.grok/braintrust.json` +- Grok Build desktop (`cursor`): `~/.cursor/braintrust.json` +- Grok Build TUI (`grok`): `~/.grok/braintrust.json` - Antigravity: `~/.gemini/config/braintrust.json` `BRAINTRUST_DAEMON_CONFIG` can override the path for isolated tests and managed diff --git a/bt-daemon/src/agents/cursor.rs b/bt-daemon/src/agents/cursor.rs index c7f210da..28d5bd02 100644 --- a/bt-daemon/src/agents/cursor.rs +++ b/bt-daemon/src/agents/cursor.rs @@ -8,7 +8,7 @@ pub(crate) const IDENTITY: Identity = Identity { id: "cursor", source: "cursor", aliases: &[], - display_name: "Cursor", + display_name: "Grok Build desktop", }; impl Agent for Cursor { diff --git a/bt-daemon/src/agents/grok.rs b/bt-daemon/src/agents/grok.rs index aca2b7f7..ca86b119 100644 --- a/bt-daemon/src/agents/grok.rs +++ b/bt-daemon/src/agents/grok.rs @@ -1,13 +1,16 @@ use super::{Agent, Identity, Register, Registrar}; use std::sync::Arc; +mod hook_transcript; +pub(crate) use hook_transcript::HookTranscript; + pub(crate) struct Grok; pub(crate) const IDENTITY: Identity = Identity { id: "grok", source: "grok", aliases: &[], - display_name: "Grok", + display_name: "Grok Build TUI", }; impl Agent for Grok { diff --git a/bt-daemon/src/agents/grok/hook_transcript.rs b/bt-daemon/src/agents/grok/hook_transcript.rs new file mode 100644 index 00000000..8fd923f0 --- /dev/null +++ b/bt-daemon/src/agents/grok/hook_transcript.rs @@ -0,0 +1,43 @@ +use crate::transcript_mirror::GrokReferences; +use serde::Deserialize; +use std::path::Path; + +/// Newer Grok versions send both path keys in one hook. Deserialize them +/// separately so sending both spellings does not invalidate the event. +#[derive(Deserialize)] +pub(crate) struct HookTranscript { + #[serde(rename = "transcriptPath")] + camel_case_path: Option, + transcript_path: Option, + #[serde(rename = "_bt_grok_transcript_mirrors")] + pub mirrors: Option, +} + +impl HookTranscript { + pub fn decode(payload: &serde_json::Value) -> serde_json::Result { + Self::deserialize(payload) + } + + pub fn path(&self) -> Option<&Path> { + self.camel_case_path + .as_deref() + .filter(|path| !path.is_empty()) + .or(self.transcript_path.as_deref()) + .filter(|path| !path.is_empty()) + .map(Path::new) + } + + pub fn is_agent_host(&self) -> bool { + // The unified CLI writes agent-transcripts//.jsonl. + // Legacy Grok reports updates.jsonl or chat_history.jsonl instead. + self.path().is_some_and(|path| { + path.extension() + .is_some_and(|extension| extension == "jsonl") + && path.parent().is_some_and(|dir| { + dir.file_name() == path.file_stem() + && dir.parent().and_then(Path::file_name) + == Some(std::ffi::OsStr::new("agent-transcripts")) + }) + }) + } +} diff --git a/bt-daemon/src/agents/mod.rs b/bt-daemon/src/agents/mod.rs index fbd70d4b..0109063b 100644 --- a/bt-daemon/src/agents/mod.rs +++ b/bt-daemon/src/agents/mod.rs @@ -9,7 +9,7 @@ pub(crate) mod antigravity; mod claude; mod codex; pub(crate) mod cursor; -mod grok; +pub(crate) mod grok; mod muse; mod opencode; mod pi; diff --git a/bt-daemon/src/args.rs b/bt-daemon/src/args.rs index 5422ee77..c84f8040 100644 --- a/bt-daemon/src/args.rs +++ b/bt-daemon/src/args.rs @@ -236,6 +236,7 @@ pub enum ImportSource { Codex, #[value(alias = "muse-code")] Muse, + #[value(name = "grok-build-desktop", alias = "cursor")] Cursor, #[value(name = "claude", alias = "claude-code")] Claude, @@ -350,6 +351,7 @@ pub enum RunSource { Codex, #[value(alias = "muse-code")] Muse, + /// Launch the legacy Cursor CLI. Cursor, #[value(name = "claude", alias = "claude-code")] Claude, diff --git a/bt-daemon/src/dispatch.rs b/bt-daemon/src/dispatch.rs index a75875e4..6484e45a 100644 --- a/bt-daemon/src/dispatch.rs +++ b/bt-daemon/src/dispatch.rs @@ -510,13 +510,13 @@ const GROK_TERMINAL_SNAPSHOT_QUIET_PERIOD: std::time::Duration = std::time::Duration::from_millis(10); async fn hydrate_grok_transcript_references(data_dir: &std::path::Path, env: &mut Envelope) { - let Ok(fields) = TranscriptPayload::decode(&env.payload) else { + let Ok(fields) = crate::agents::grok::HookTranscript::decode(&env.payload) else { return; }; - let Some(transcript) = fields.transcript_path.map(std::path::PathBuf::from) else { + if fields.is_agent_host() { return; - }; - let Some(session_dir) = transcript.parent() else { + } + let Some(session_dir) = fields.path().and_then(std::path::Path::parent) else { return; }; let mirror_session = crate::ids::session_namespace(&env.source, &env.session_id); @@ -741,7 +741,8 @@ mod tests { managed_run_id: None, capture: None, payload: serde_json::json!({ - "transcriptPath": session.join("chat_history.jsonl") + "transcriptPath": session.join("chat_history.jsonl"), + "transcript_path": session.join("chat_history.jsonl") }), route: None, config: None, diff --git a/bt-daemon/src/trace_command.rs b/bt-daemon/src/trace_command.rs index f60915e4..34e7e365 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -76,7 +76,9 @@ pub enum DoctorAgent { OpenCode, Pi, Antigravity, + #[value(name = "grok-build", alias = "grok")] Grok, + #[value(name = "grok-build-desktop", alias = "cursor")] Cursor, } @@ -183,9 +185,11 @@ pub enum SetupAgent { OpenCode, /// Install the published Pi tracing extension. Pi, - /// Install the published Grok tracing plugin. + /// Install tracing for the Grok Build TUI and legacy Grok CLI. + #[command(name = "grok-build", visible_alias = "grok")] Grok, - /// Install the published Cursor tracing plugin. + /// Install tracing for Grok Build desktop and legacy Cursor. + #[command(name = "grok-build-desktop", visible_alias = "cursor")] Cursor, /// Install the Google Antigravity tracing hooks. Antigravity, @@ -379,8 +383,20 @@ mod tests { "antigravity", "Google Antigravity", ), - ("grok", DoctorAgent::Grok, "grok", "Grok"), - ("cursor", DoctorAgent::Cursor, "cursor", "Cursor"), + ("grok", DoctorAgent::Grok, "grok", "Grok Build TUI"), + ("grok-build", DoctorAgent::Grok, "grok", "Grok Build TUI"), + ( + "cursor", + DoctorAgent::Cursor, + "cursor", + "Grok Build desktop", + ), + ( + "grok-build-desktop", + DoctorAgent::Cursor, + "cursor", + "Grok Build desktop", + ), ] { let cli = Cli::try_parse_from(["bt", "doctor", agent]).unwrap(); assert!(matches!( @@ -418,26 +434,45 @@ mod tests { } #[test] - fn grok_uses_shared_enable_and_disable_commands() { - { - let parsed = Cli::try_parse_from(["bt", "setup", "grok"]).unwrap(); - assert!(matches!( - parsed.trace.command, - TraceCommand::Install(SetupArgs { - agent: SetupAgent::Grok, - .. - }) - )); + fn grok_build_names_use_the_existing_setup_adapters_and_settings() { + for (old, new) in [("grok", "grok-build"), ("cursor", "grok-build-desktop")] { + for command in [ + "install", + "setup", + "enable", + "disable", + "update", + "uninstall", + ] { + for name in [old, new] { + let parsed = Cli::try_parse_from(["bt", command, name]).unwrap(); + let agent = match parsed.trace.command { + TraceCommand::Install(args) => args.agent, + TraceCommand::Enable(args) => args.agent, + TraceCommand::Disable(args) | TraceCommand::Uninstall(args) => args.agent, + TraceCommand::Update(args) => args.agent, + other => panic!("unexpected command for {command} {name}: {other:?}"), + }; + let identity = agent.identity(); + assert_eq!(identity.id, old); + assert_eq!(identity.source, old); + } + } } + } - let parsed = Cli::try_parse_from(["bt", "disable", "grok"]).unwrap(); - assert!(matches!( - parsed.trace.command, - TraceCommand::Disable(DisableArgs { - agent: SetupAgent::Grok, - .. - }) - )); + #[test] + fn desktop_import_names_use_the_cursor_transcript_source() { + for name in ["cursor", "grok-build-desktop"] { + let parsed = + Cli::try_parse_from(["bt", "import", name, "session-id", "--attach"]).unwrap(); + let TraceCommand::Import(args) = parsed.trace.command else { + panic!("expected import command for {name}"); + }; + assert_eq!(args.source, crate::ImportSource::Cursor); + assert_eq!(args.source.identity().source, "cursor"); + assert!(args.attach); + } } #[test] diff --git a/bt-daemon/src/transcript_mirror/payload.rs b/bt-daemon/src/transcript_mirror/payload.rs index 1b999e7e..716e74d1 100644 --- a/bt-daemon/src/transcript_mirror/payload.rs +++ b/bt-daemon/src/transcript_mirror/payload.rs @@ -1,4 +1,4 @@ -use super::{ClaudeChildReference, GrokReferences, Observation, Reference, Snapshot}; +use super::{ClaudeChildReference, Observation, Reference, Snapshot}; /// Decode the known capture protocol once at the envelope boundary. Native /// agent data remains in the raw journal and is decoded by its own translator. @@ -15,8 +15,6 @@ pub(crate) struct TranscriptPayload { pub mirror: Option, #[serde(rename = "_bt_claude_transcript_mirrors")] pub claude_mirrors: Option>, - #[serde(rename = "_bt_grok_transcript_mirrors")] - pub grok_mirrors: Option, #[serde(rename = "_bt_transcript_observation")] pub observation: Option, #[serde(rename = "_bt_transcript_snapshot")] diff --git a/bt-daemon/src/translate/grok.rs b/bt-daemon/src/translate/grok.rs index 832bb750..4df241e4 100644 --- a/bt-daemon/src/translate/grok.rs +++ b/bt-daemon/src/translate/grok.rs @@ -2,7 +2,9 @@ //! //! Hooks are wake-up and flush signals. `updates.jsonl` is the authoritative //! trace data source; `events.jsonl` is independently tailed, best-effort tool -//! enrichment. Both are mirrored into daemon-owned storage at hook boundaries. +//! enrichment for legacy Grok. The unified CLI reports turns directly in hooks. + +mod agent_host; use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet}; @@ -10,10 +12,11 @@ use super::tool::nonempty_error_text; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; +use crate::agents::grok::HookTranscript; use crate::agents::usage::CamelCaseUsage as NativeUsage; use crate::ids; use crate::json::Extensions; -use crate::transcript_mirror::{Reference, TranscriptPayload}; +use crate::transcript_mirror::{GrokReferences, Reference}; use crate::wire::Envelope; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; @@ -321,6 +324,10 @@ struct GrokTranslator { first_llm_parent_span_id: Option, first_llm_user_input: Option, pending: Option, + #[serde(default)] + agent_host: bool, + #[serde(default)] + pending_prompt: Option, cwd: Option, #[serde(skip, default = "GitMetadataCache::shared")] git: Arc, @@ -353,6 +360,8 @@ impl GrokTranslator { first_llm_parent_span_id: None, first_llm_user_input: None, pending: None, + agent_host: false, + pending_prompt: None, cwd: None, git, last_ts_ms: 0, @@ -374,13 +383,7 @@ impl GrokTranslator { self.last_ts_ms = 0; } - fn ensure_root( - &mut self, - ts_ms: i64, - event: &Envelope, - _ctx: &SessionCtx, - ops: &mut Vec, - ) { + fn ensure_root(&mut self, ts_ms: i64, event: &Envelope, ops: &mut Vec) { if self.root_open { return; } @@ -410,7 +413,12 @@ impl GrokTranslator { metadata.retain(|key, _| !key.starts_with("_bt_")); metadata.insert("source".into(), json!("grok")); metadata.insert("session_id".into(), json!(self.session_id)); - metadata.insert("trace_source".into(), json!("session_transcript")); + let (name, trace_source) = if self.agent_host { + ("Grok Build TUI", "hook") + } else { + ("Grok", "session_transcript") + }; + metadata.insert("trace_source".into(), json!(trace_source)); metadata.insert("username".into(), json!(local_username())); for field in ["cwd", "workspaceRoot", "permissionMode", "transcriptPath"] { if let Some(value) = event.payload.get(field) { @@ -427,7 +435,7 @@ impl GrokTranslator { span_id: self.session_span_id.clone(), root_span_id: self.root_span_id.clone(), parent_span_ids: self.session_parent_span_ids.clone(), - name: "Grok".into(), + name: name.into(), span_type: SpanType::Task, start_ms: Some(ts_ms), metadata: Some(Value::Object(metadata)), @@ -490,7 +498,7 @@ impl GrokTranslator { record: &NativeRecord, record_end_offset: u64, event: &Envelope, - ctx: &SessionCtx, + ts_ms: i64, ops: &mut Vec, ) { let Some(params) = record.params.as_ref() else { @@ -502,8 +510,6 @@ impl GrokTranslator { let Some(kind) = update.session_update.as_deref() else { return; }; - let ts_ms = record_ts_ms(record).unwrap_or(event.ts_ms); - if matches!( kind, "user_message_chunk" | "agent_thought_chunk" | "agent_message_chunk" @@ -552,7 +558,7 @@ impl GrokTranslator { } self.emitted_turns.insert(turn_key.clone()); self.close_incomplete_turn(ts_ms, "new_turn", None, false, false, ops); - self.ensure_root(ts_ms, event, ctx, ops); + self.ensure_root(ts_ms, event, ops); self.turn_seq = next_number; let span_id = ids::span_id(&self.session_id, &format!("turn:{turn_key}")); let model = meta.and_then(|m| m.model_id.clone()); @@ -1218,11 +1224,10 @@ impl GrokTranslator { fn process_transcripts( &mut self, event: &Envelope, - ctx: &SessionCtx, + mirrors: Option<&GrokReferences>, ) -> anyhow::Result<(Vec, bool)> { let mut ops = Vec::new(); - let fields = TranscriptPayload::decode(&event.payload)?; - let Some(mirrors) = fields.grok_mirrors else { + let Some(mirrors) = mirrors else { return Ok((ops, true)); }; // Updates are authoritative and advance before optional event @@ -1236,7 +1241,8 @@ impl GrokTranslator { self.updates = updates.cursor; self.process_system_prompt(mirrors.system_prompt.as_ref(), &mut ops); for record in updates.records { - self.process_update(&record.value, record.end_offset, event, ctx, &mut ops); + let ts_ms = record_ts_ms(&record.value).unwrap_or(event.ts_ms); + self.process_update(&record.value, record.end_offset, event, ts_ms, &mut ops); } let events_complete = self.process_event_enrichment(mirrors.events.as_ref(), &mut ops); Ok((ops, updates_complete && events_complete)) @@ -1300,7 +1306,7 @@ impl GrokTranslator { } impl AgentTranslator for GrokTranslator { - fn handle(&mut self, event: &Envelope, ctx: &SessionCtx) -> anyhow::Result> { + fn handle(&mut self, event: &Envelope, _ctx: &SessionCtx) -> anyhow::Result> { anyhow::ensure!( self.pending.is_none(), "Grok translator has pending catch-up work; drain it before handling another event" @@ -1308,7 +1314,23 @@ impl AgentTranslator for GrokTranslator { if let Some(cwd) = event.payload.get("cwd").and_then(Value::as_str) { self.cwd = Some(cwd.to_string()); } - let (mut ops, complete) = self.process_transcripts(event, ctx)?; + let transcript = HookTranscript::decode(&event.payload)?; + self.agent_host |= transcript.is_agent_host(); + let (mut ops, complete) = if self.agent_host { + (self.process_agent_host_hook(event)?, true) + } else { + if transcript.path().is_some() || transcript.mirrors.is_some() { + self.pending_prompt = None; + } else if matches!( + event.event.as_str(), + "UserPromptSubmit" | "user_prompt_submit" + ) { + // The first prompt can precede the transcript path. Legacy + // hooks may omit these fields and are reduced from transcripts. + self.pending_prompt = agent_host::PendingPrompt::decode(event).ok(); + } + self.process_transcripts(event, transcript.mirrors.as_ref())? + }; if complete { self.finish_hook(event, &mut ops); } else { @@ -1320,11 +1342,13 @@ impl AgentTranslator for GrokTranslator { Ok(ops) } - fn drain_pending(&mut self, ctx: &SessionCtx) -> anyhow::Result>> { + fn drain_pending(&mut self, _ctx: &SessionCtx) -> anyhow::Result>> { let Some(pending) = self.pending.clone() else { return Ok(None); }; - let (mut ops, complete) = self.process_transcripts(&pending.event, ctx)?; + let transcript = HookTranscript::decode(&pending.event.payload)?; + let (mut ops, complete) = + self.process_transcripts(&pending.event, transcript.mirrors.as_ref())?; if complete { self.pending = None; self.finish_hook(&pending.event, &mut ops); diff --git a/bt-daemon/src/translate/grok/agent_host.rs b/bt-daemon/src/translate/grok/agent_host.rs new file mode 100644 index 00000000..1246b751 --- /dev/null +++ b/bt-daemon/src/translate/grok/agent_host.rs @@ -0,0 +1,216 @@ +//! Reduce the unified CLI's native hooks. Its conversation transcript does +//! not contain the legacy Grok stream updates or per-call usage. + +use super::{GrokTranslator, NativeMeta, NativeParams, NativeRecord, NativeUpdate, TurnCompletion}; +use crate::translate::SpanOp; +use crate::wire::Envelope; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; + +#[derive(Deserialize, Serialize)] +pub(super) struct PendingPrompt { + ts_ms: i64, + fields: Prompt, +} + +impl PendingPrompt { + pub fn decode(event: &Envelope) -> serde_json::Result { + Ok(Self { + ts_ms: event.ts_ms, + fields: Prompt::deserialize(&event.payload)?, + }) + } +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct Prompt { + prompt_id: String, + prompt: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Tool { + tool_use_id: String, + tool_name: String, + // Arguments and results are tool-defined JSON. + tool_input: Option, + tool_result: Option, + error: Option, +} + +#[derive(Deserialize)] +#[serde(tag = "type")] +enum ToolResult { + Bash { + exit_code: Option, + }, + #[serde(other)] + Other, +} + +impl Tool { + fn command_error(&self) -> Option { + let result = ToolResult::deserialize(self.tool_result.as_ref()?).ok()?; + match result { + ToolResult::Bash { + exit_code: Some(code), + } if code != 0 => Some(format!("Command exited with status {code}")), + _ => None, + } + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Stop { + prompt_id: Option, + reason: Option, + last_assistant_message: Option, +} + +enum Hook { + Prompt(PendingPrompt), + ToolStart(Tool), + ToolEnd { tool: Tool, failed: bool }, + Stop(Stop), + Other, +} + +impl Hook { + fn decode(event: &Envelope) -> serde_json::Result { + Ok(match event.event.as_str() { + "UserPromptSubmit" | "user_prompt_submit" => { + Self::Prompt(PendingPrompt::decode(event)?) + } + "PreToolUse" | "pre_tool_use" => Self::ToolStart(Tool::deserialize(&event.payload)?), + "PostToolUse" | "post_tool_use" | "PostToolUseFailure" | "post_tool_use_failure" => { + Self::ToolEnd { + tool: Tool::deserialize(&event.payload)?, + failed: matches!( + event.event.as_str(), + "PostToolUseFailure" | "post_tool_use_failure" + ), + } + } + "Stop" | "stop" => Self::Stop(Stop::deserialize(&event.payload)?), + _ => Self::Other, + }) + } +} + +impl GrokTranslator { + pub(super) fn process_agent_host_hook( + &mut self, + event: &Envelope, + ) -> serde_json::Result> { + let hook = Hook::decode(event)?; + let mut ops = Vec::new(); + if let Some(prompt) = self.pending_prompt.take() { + self.start_agent_host_turn(event, prompt, &mut ops); + } + match hook { + Hook::Prompt(prompt) => { + self.start_agent_host_turn(event, prompt, &mut ops); + } + Hook::ToolStart(tool) => { + self.apply_agent_host_update( + event, + event.ts_ms, + NativeUpdate { + session_update: Some("tool_call".into()), + tool_call_id: Some(tool.tool_use_id), + title: Some(tool.tool_name), + raw_input: tool.tool_input, + ..Default::default() + }, + &mut ops, + ); + } + Hook::ToolEnd { tool, failed } => { + let command_error = tool.command_error(); + let error = tool.error.or(command_error); + let failed = failed || error.is_some(); + self.apply_agent_host_update( + event, + event.ts_ms, + NativeUpdate { + session_update: Some("tool_call_update".into()), + tool_call_id: Some(tool.tool_use_id), + title: Some(tool.tool_name), + raw_input: tool.tool_input, + raw_output: tool.tool_result, + content: error.map(Value::String), + status: Some(if failed { "failed" } else { "completed" }.into()), + ..Default::default() + }, + &mut ops, + ); + } + Hook::Stop(stop) => { + if let Some(turn) = self.current_turn.as_mut().filter(|turn| { + stop.reason.as_deref() == Some("end_turn") && turn.prompt_id == stop.prompt_id + }) { + if let Some(text) = stop.last_assistant_message { + turn.assistant_output + .push(json!({"type": "text", "text": text})); + } + self.close_turn( + event.ts_ms, + "end_turn", + Map::new(), + TurnCompletion { + metrics: None, + error: None, + late_merge_key: Some("end_turn".into()), + }, + &mut ops, + ); + } + } + Hook::Other => {} + } + Ok(ops) + } + + fn start_agent_host_turn( + &mut self, + event: &Envelope, + prompt: PendingPrompt, + ops: &mut Vec, + ) { + self.apply_agent_host_update( + event, + prompt.ts_ms, + NativeUpdate { + session_update: Some("user_message_chunk".into()), + meta: Some(NativeMeta { + prompt_id: Some(prompt.fields.prompt_id), + ..Default::default() + }), + content: Some(Value::String(prompt.fields.prompt)), + ..Default::default() + }, + ops, + ); + } + + fn apply_agent_host_update( + &mut self, + event: &Envelope, + ts_ms: i64, + update: NativeUpdate, + ops: &mut Vec, + ) { + let record = NativeRecord { + params: Some(NativeParams { + update: Some(update), + ..Default::default() + }), + ..Default::default() + }; + // This path uses no streamed chunks with byte-offset identities. + self.process_update(&record, 0, event, ts_ms, ops); + } +} diff --git a/bt-daemon/tests/grok_translator.rs b/bt-daemon/tests/grok_translator.rs index 1e77277f..debeae4f 100644 --- a/bt-daemon/tests/grok_translator.rs +++ b/bt-daemon/tests/grok_translator.rs @@ -108,6 +108,77 @@ fn drain(translator: &mut dyn AgentTranslator) -> Vec { ops } +#[test] +fn unified_grok_uses_native_hooks_after_the_transcript_layout_is_known() { + let hooks = [ + ( + "user_prompt_submit", + json!({"promptId":"prompt-1", "prompt":"check the shell"}), + ), + ( + "pre_tool_use", + json!({"toolUseId":"call-1", "toolName":"run_terminal_command", "toolInput":{"command":"false"}}), + ), + ( + "post_tool_use", + json!({"toolUseId":"call-1", "toolName":"run_terminal_command", "toolResult":{"type":"Bash", "exit_code":1}}), + ), + ( + "stop", + json!({"promptId":"prompt-1", "reason":"end_turn", "lastAssistantMessage":"The shell command failed."}), + ), + ("session_end", json!({"reason":"shutdown"})), + ("stop", json!({"reason":"shutdown"})), + ]; + let mut translator = Registry::default_agents().create("grok", "unified-session"); + let mut ops = Vec::new(); + for (index, (name, mut payload)) in hooks.into_iter().enumerate() { + // The unified CLI omits transcriptPath on UserPromptSubmit and sends + // both spellings once it creates the conversation transcript. + if index > 0 { + let path = "/grok/agent-host/projects/work/agent-transcripts/unified-session/unified-session.jsonl"; + payload["transcriptPath"] = json!(path); + payload["transcript_path"] = json!(path); + } + let event = Envelope { + source: "grok".into(), + event: name.into(), + session_id: "unified-session".into(), + ts_ms: 1000 + index as i64, + payload, + ..envelope(0, 0) + }; + let batch = handle(translator.as_mut(), &event); + if index == 0 || index == 5 { + assert!(batch.is_empty()); + } + ops.extend(batch); + } + let inserts: Vec<_> = ops + .iter() + .filter_map(|op| match op { + SpanOp::Insert(row) => Some(row), + SpanOp::Merge(_) => None, + }) + .collect(); + assert_eq!(inserts.len(), 3); + let root = inserts[0]; + assert_eq!(root.name, "Grok Build TUI"); + assert_eq!(root.metadata.as_ref().unwrap()["source"], "grok"); + let turn = inserts[1]; + assert_eq!(turn.start_ms, Some(1000)); + assert_eq!(turn.input, Some(json!("check the shell"))); + let tool = inserts[2]; + assert_eq!(tool.parent_span_ids, vec![turn.span_id.clone()]); + assert!(ops.iter().any(|op| matches!(op, SpanOp::Merge(row) + if row.span_id == tool.span_id && row.error.as_deref() == Some("Command exited with status 1")))); + assert!(ops.iter().any(|op| matches!(op, SpanOp::Merge(row) + if row.span_id == turn.span_id && row.end_ms == Some(1003) + && row.output == Some(json!([{"type":"text", "text":"The shell command failed."}]))))); + assert!(ops.iter().any(|op| matches!(op, SpanOp::Merge(row) + if row.span_id == root.span_id && row.end_ms == Some(1004)))); +} + #[test] fn grok_spans_under_a_turn_carry_its_turn_span_id() { let updates = std::fs::metadata(fixture("updates.jsonl")).unwrap().len(); diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index ad01c778..7286de2b 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -3718,6 +3718,7 @@ async fn packaged_grok_hook_replays_bounded_transcripts_to_isolated_debug_routes "sessionId": "grok-primary", "hookEventName": "stop", "transcriptPath": primary_chat, + "transcript_path": primary_chat, "cwd": "/repo/primary", "workspaceRoot": "/repo" }); diff --git a/src/plugins/cursor/content/.cursor-plugin/plugin.json b/src/plugins/cursor/content/.cursor-plugin/plugin.json index e21fc4b4..791d906c 100644 --- a/src/plugins/cursor/content/.cursor-plugin/plugin.json +++ b/src/plugins/cursor/content/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "name": "braintrust", "displayName": "Braintrust", "version": "0.5.3", - "description": "Connect Cursor to Braintrust MCP and trace agent sessions.", + "description": "Connect Grok Build desktop or Cursor to Braintrust MCP and trace agent sessions.", "author": { "name": "Braintrust Data, Inc.", "email": "support@braintrust.dev" }, "homepage": "https://braintrust.dev", "repository": "https://github.com/braintrustdata/braintrust-cursor-extension", diff --git a/src/plugins/cursor/content/README.md b/src/plugins/cursor/content/README.md index 3304cb43..3e202bdc 100644 --- a/src/plugins/cursor/content/README.md +++ b/src/plugins/cursor/content/README.md @@ -1,47 +1,47 @@ -# Braintrust tracing for Cursor +# Braintrust tracing for Grok Build desktop and Cursor > **This repository is generated.** It is built from > [braintrustdata/braintrust-coding-agent-plugins](https://github.com/braintrustdata/braintrust-coding-agent-plugins). > Make changes there; releases publish the generated plugin to this repository. -Connect Cursor to [Braintrust](https://braintrust.dev) through MCP and trace +Connect Grok Build desktop or Cursor to [Braintrust](https://braintrust.dev) through MCP and trace agent sessions with the `braintrust` plugin. The same repository also contains -the Braintrust VS Code extension for Cursor. +the Braintrust VS Code extension for both desktop apps. ## Prerequisites - A [Braintrust account](https://braintrust.dev) -- Cursor with the CLI or desktop app +- [Grok Build desktop](https://docs.grok.com/build/agents-window) or Cursor (desktop or legacy CLI) - The [Braintrust CLI](https://docs.braintrust.dev/reference/cli/quickstart) - A Braintrust API key to use the MCP server -## Install from Cursor Marketplace +## Install from the marketplace -Use `/add-plugin` in Cursor and search for **Braintrust**, or install from the +Use `/add-plugin` 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 install cursor --project my-coding-agent`. +the `bt` CLI, then run `bt trace install grok-build-desktop --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 use separate authentication: `bt login` authenticates the tracing CLI. -The existing VS Code extension remains available from Cursor's extension -panel. It reads `BRAINTRUST_API_KEY` from Cursor's environment and registers -the same MCP server through Cursor's extension API. If +The VS Code extension reads `BRAINTRUST_API_KEY` from the app's environment +and registers the same MCP server through the `vscode.cursor` extension API. If both the extension and plugin are installed, each attempts to register a server named `braintrust`; use one MCP installation to avoid duplicates. -## Supported Cursor surfaces +## Supported surfaces -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 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. -The Braintrust Claude Code plugin exposes no hooks when Cursor imports it; -Cursor tracing uses this integration's native hooks. +Grok Build desktop and legacy Cursor share the same plugin and hook configuration. +Use the [Grok Build TUI integration](https://github.com/braintrustdata/braintrust-grok-plugin) +for the unified CLI (`grok`). + +Desktop and legacy Cursor hooks invoke `bt trace hook`, so `bt` must be on the +app's `PATH`. `bt trace install grok-build-desktop` also installs user hooks in +`~/.cursor/hooks.json`. These 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. ## Quickstart @@ -49,18 +49,18 @@ Authenticate and enable tracing: ```bash bt login -bt trace install cursor --project my-coding-agent +bt trace install grok-build-desktop --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 +configures the hooks for desktop and legacy Cursor, and saves the selected route in `~/.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 +`bt trace update grok-build-desktop` install the plugin bundled with your `bt` build and print +a warning that it may be older. Install Git and run `bt trace update grok-build-desktop` to get the latest published version. Other download failures preserve the previous installation. -Reload the Cursor window after setup. Tracing uses the user hooks even when +Reload the desktop window after setup. Tracing uses the user hooks even when local plugin imports are unavailable. MCP access still requires an active plugin. Use `--profile` or `--org` to select a different Braintrust account or @@ -110,7 +110,7 @@ attribution. Add a JSON object to the root span of every Cursor session: ```bash -bt trace install cursor --project my-coding-agent \ +bt trace install grok-build-desktop --project my-coding-agent \ --additional-metadata '{"team":"platform","environment":"dev"}' ``` @@ -121,35 +121,39 @@ Standard session metadata takes precedence if keys conflict. Use repeatable `--tag` options for filterable tags on root spans: ```bash -bt trace install cursor --tag ci --tag release-validation +bt trace install grok-build-desktop --tag ci --tag release-validation bt trace run cursor --tag ci -bt trace import cursor SESSION_ID --tag historical-import +bt trace import grok-build-desktop SESSION_ID --tag historical-import ``` ## One-off runs and transcript import ```bash bt trace run --project my-coding-agent cursor -bt trace import cursor SESSION_ID -bt trace import cursor SESSION_ID --attach +bt trace import grok-build-desktop SESSION_ID +bt trace import grok-build-desktop SESSION_ID --attach ``` -`run` traces one Cursor invocation without changing saved settings. Import reads -a saved Cursor transcript; `--attach` follows it until Ctrl-C. Imports include +`run` traces one legacy Cursor CLI invocation. Import reads a saved Cursor-format +transcript, and `--attach` follows it until Ctrl-C. Imports include conversation text and the final recorded turn status. They omit tool activity and usage, and session timing may be approximate. Cursor may retain only the latest turn in a transcript. -Managed Cursor runs require interactive CLI mode. Cursor's `-p`/`--print` mode -does not provide the full lifecycle needed for a complete trace. +Managed runs use the legacy Cursor CLI and require an interactive terminal. +If `agent` now points to the unified Grok Build TUI, set `CURSOR_BIN` to a legacy +Cursor CLI executable before using `bt trace run cursor`. ## Manage tracing +`cursor` remains an alias for `grok-build-desktop` in tracing setup, +management, and transcript import commands. Both use `~/.cursor/braintrust.json`. + ```bash -bt trace doctor cursor +bt trace doctor grok-build-desktop bt trace status -bt trace update cursor -bt trace disable cursor +bt trace update grok-build-desktop +bt trace disable grok-build-desktop ``` For repository-scoped tracing, see the [daemon configuration guide](https://github.com/braintrustdata/braintrust-coding-agent-plugins/blob/main/bt-daemon/README.md#project-scoped-tracing). diff --git a/src/plugins/cursor/content/package.json b/src/plugins/cursor/content/package.json index f4125ef8..31f5e2fa 100644 --- a/src/plugins/cursor/content/package.json +++ b/src/plugins/cursor/content/package.json @@ -1,7 +1,7 @@ { "name": "braintrust", "displayName": "Braintrust", - "description": "Connect Cursor to Braintrust for AI-powered access to your projects, experiments, and logs", + "description": "Connect Grok Build desktop or Cursor to Braintrust for AI-powered access to your projects, experiments, and logs", "version": "0.5.3", "publisher": "braintrustdata", "license": "MIT", @@ -21,7 +21,8 @@ "braintrust", "mcp", "ai", - "cursor" + "cursor", + "grok build" ], "activationEvents": [ "onStartupFinished" diff --git a/src/plugins/cursor/content/src/extension.ts b/src/plugins/cursor/content/src/extension.ts index a34c5b91..ef07f7ca 100644 --- a/src/plugins/cursor/content/src/extension.ts +++ b/src/plugins/cursor/content/src/extension.ts @@ -43,7 +43,7 @@ export function activate(_context: vscode.ExtensionContext): void { const apiKey = getApiKey(); if (!apiKey) { vscode.window.showWarningMessage( - `Braintrust MCP: ${ENV_VAR_NAME} is not set. Set it in your environment and restart Cursor.` + `Braintrust MCP: ${ENV_VAR_NAME} is not set. Set it in your environment and restart the app.` ); return; } diff --git a/src/plugins/grok/content/.grok-plugin/plugin.json b/src/plugins/grok/content/.grok-plugin/plugin.json index 51bdbf95..634f18ae 100644 --- a/src/plugins/grok/content/.grok-plugin/plugin.json +++ b/src/plugins/grok/content/.grok-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "trace-grok", - "description": "Beta Braintrust tracing for Grok sessions with transcript-reconstructed LLM and tool spans.", + "description": "Trace Grok Build TUI and legacy Grok CLI sessions in Braintrust.", "version": "0.0.7", "author": { "name": "Braintrust" diff --git a/src/plugins/grok/content/README.md b/src/plugins/grok/content/README.md index f28dbab5..8d703553 100644 --- a/src/plugins/grok/content/README.md +++ b/src/plugins/grok/content/README.md @@ -1,24 +1,25 @@ -# Braintrust tracing for Grok +# Braintrust tracing for the Grok Build TUI > **This repository is generated.** It is built from > [braintrustdata/braintrust-coding-agent-plugins](https://github.com/braintrustdata/braintrust-coding-agent-plugins). > Don't edit files here — make changes and file issues in that repository, and they > will be rebuilt into this one. -Trace Grok coding sessions in Braintrust. +Trace coding sessions from the Grok Build TUI or legacy Grok CLI in Braintrust. +For the desktop app, use the [Grok Build desktop integration](https://github.com/braintrustdata/braintrust-cursor-extension). ## Quickstart Prerequisites: -- The [Grok CLI](https://grok.com/build) +- The [Grok Build TUI (`grok`)](https://docs.grok.com/build/overview) - The [Braintrust CLI (`bt`)](https://docs.braintrust.dev/reference/cli/quickstart) Install: ```bash bt login -bt trace install grok --project my-coding-agent +bt trace install grok-build --project my-coding-agent ``` Setup installs and enables the published plugin and saves non-secret routing @@ -32,7 +33,12 @@ for details. ## What is captured -Each traced session includes: +The unified Grok Build TUI records sessions, prompts, final assistant responses, +and tool calls and results from its hooks. Trace capture starts once the TUI +reports its conversation transcript path. The TUI hooks do not provide model +call boundaries or usage metrics. + +Legacy Grok reconstructs traces from its stream transcripts. Each traced session includes: - a root span for the Grok session; - a turn span for each user request and visible assistant response; @@ -44,14 +50,12 @@ Each traced session includes: - session metadata such as Grok and plugin versions, working directory, workspace, and native session ID. -The plugin invokes the installed `bt` CLI directly for each event. `bt` owns -credentials, daemon startup, and trace delivery. It records the installed -plugin and Grok versions dynamically; no release-specific hook edits are -needed. +The plugin invokes `bt` for each event. `bt` handles credentials, daemon startup, +and trace delivery, and records the plugin and agent versions when available. ## Caveats -Grok's hooks and transcripts do not expose the complete provider request or +Legacy Grok's hooks and transcripts do not expose the complete provider request or native boundaries for every model call. As a result: - token and usage totals are accurate at the **turn** level, but are not @@ -62,17 +66,20 @@ native boundaries for every model call. As a result: - LLM boundaries are reconstructed from Grok stream timing and may not match provider-side spans exactly; - permission, compaction, and subagent activity do not receive dedicated span - hierarchies, and web or MCP operations may appear as generic tools; -- managed `bt trace run grok` and historical `bt trace import grok` workflows - are not currently supported. + hierarchies, and web or MCP operations may appear as generic tools. + +Managed runs and historical imports are unavailable for the TUI integration. Grok keeps running if tracing fails. ## Manage tracing +`grok` remains an alias for `grok-build` in setup and management commands. +Both use `~/.grok/braintrust.json`. + ```bash -bt trace doctor grok +bt trace doctor grok-build bt trace status -bt trace update grok -bt trace disable grok +bt trace update grok-build +bt trace disable grok-build ``` From 6ac99473282952fbb388f4661b570389b966e2b2 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 19:15:07 +0800 Subject: [PATCH 2/6] Handle partial Grok Build hooks and preserve session duration --- bt-daemon/src/translate/grok.rs | 19 +++- bt-daemon/src/translate/grok/agent_host.rs | 28 +++-- bt-daemon/tests/grok_translator.rs | 121 ++++++++++++++++++--- 3 files changed, 137 insertions(+), 31 deletions(-) diff --git a/bt-daemon/src/translate/grok.rs b/bt-daemon/src/translate/grok.rs index 4df241e4..49e0a368 100644 --- a/bt-daemon/src/translate/grok.rs +++ b/bt-daemon/src/translate/grok.rs @@ -510,10 +510,21 @@ impl GrokTranslator { let Some(kind) = update.session_update.as_deref() else { return; }; - if matches!( - kind, - "user_message_chunk" | "agent_thought_chunk" | "agent_message_chunk" - ) { + // Each listener notification is a complete prompt. Without a native + // ID, identical text can be submitted in separate turns. + let unidentified_hook_prompt = self.agent_host + && kind == "user_message_chunk" + && update + .meta + .as_ref() + .and_then(|meta| meta.prompt_id.as_ref()) + .is_none(); + if !unidentified_hook_prompt + && matches!( + kind, + "user_message_chunk" | "agent_thought_chunk" | "agent_message_chunk" + ) + { if kind != "user_message_chunk" && self.current_turn.is_none() { return; } diff --git a/bt-daemon/src/translate/grok/agent_host.rs b/bt-daemon/src/translate/grok/agent_host.rs index 1246b751..efc63804 100644 --- a/bt-daemon/src/translate/grok/agent_host.rs +++ b/bt-daemon/src/translate/grok/agent_host.rs @@ -25,15 +25,15 @@ impl PendingPrompt { #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct Prompt { - prompt_id: String, - prompt: String, + prompt_id: Option, + prompt: Option, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct Tool { - tool_use_id: String, - tool_name: String, + tool_use_id: Option, + tool_name: Option, // Arguments and results are tool-defined JSON. tool_input: Option, tool_result: Option, @@ -120,8 +120,8 @@ impl GrokTranslator { event.ts_ms, NativeUpdate { session_update: Some("tool_call".into()), - tool_call_id: Some(tool.tool_use_id), - title: Some(tool.tool_name), + tool_call_id: tool.tool_use_id, + title: tool.tool_name, raw_input: tool.tool_input, ..Default::default() }, @@ -137,8 +137,8 @@ impl GrokTranslator { event.ts_ms, NativeUpdate { session_update: Some("tool_call_update".into()), - tool_call_id: Some(tool.tool_use_id), - title: Some(tool.tool_name), + tool_call_id: tool.tool_use_id, + title: tool.tool_name, raw_input: tool.tool_input, raw_output: tool.tool_result, content: error.map(Value::String), @@ -150,12 +150,18 @@ impl GrokTranslator { } Hook::Stop(stop) => { if let Some(turn) = self.current_turn.as_mut().filter(|turn| { - stop.reason.as_deref() == Some("end_turn") && turn.prompt_id == stop.prompt_id + stop.reason.as_deref() == Some("end_turn") + && turn + .prompt_id + .as_ref() + .zip(stop.prompt_id.as_ref()) + .is_none_or(|(active, stopped)| active == stopped) }) { if let Some(text) = stop.last_assistant_message { turn.assistant_output .push(json!({"type": "text", "text": text})); } + self.last_ts_ms = self.last_ts_ms.max(event.ts_ms); self.close_turn( event.ts_ms, "end_turn", @@ -186,10 +192,10 @@ impl GrokTranslator { NativeUpdate { session_update: Some("user_message_chunk".into()), meta: Some(NativeMeta { - prompt_id: Some(prompt.fields.prompt_id), + prompt_id: prompt.fields.prompt_id, ..Default::default() }), - content: Some(Value::String(prompt.fields.prompt)), + content: prompt.fields.prompt.map(Value::String), ..Default::default() }, ops, diff --git a/bt-daemon/tests/grok_translator.rs b/bt-daemon/tests/grok_translator.rs index debeae4f..f1b3cf48 100644 --- a/bt-daemon/tests/grok_translator.rs +++ b/bt-daemon/tests/grok_translator.rs @@ -132,22 +132,8 @@ fn unified_grok_uses_native_hooks_after_the_transcript_layout_is_known() { ]; let mut translator = Registry::default_agents().create("grok", "unified-session"); let mut ops = Vec::new(); - for (index, (name, mut payload)) in hooks.into_iter().enumerate() { - // The unified CLI omits transcriptPath on UserPromptSubmit and sends - // both spellings once it creates the conversation transcript. - if index > 0 { - let path = "/grok/agent-host/projects/work/agent-transcripts/unified-session/unified-session.jsonl"; - payload["transcriptPath"] = json!(path); - payload["transcript_path"] = json!(path); - } - let event = Envelope { - source: "grok".into(), - event: name.into(), - session_id: "unified-session".into(), - ts_ms: 1000 + index as i64, - payload, - ..envelope(0, 0) - }; + for (index, (name, payload)) in hooks.into_iter().enumerate() { + let event = unified_hook(name, 1000 + index as i64, payload); let batch = handle(translator.as_mut(), &event); if index == 0 || index == 5 { assert!(batch.is_empty()); @@ -179,6 +165,109 @@ fn unified_grok_uses_native_hooks_after_the_transcript_layout_is_known() { if row.span_id == root.span_id && row.end_ms == Some(1004)))); } +fn unified_hook(name: &str, ts_ms: i64, mut payload: serde_json::Value) -> Envelope { + // The first prompt arrives before the CLI creates the transcript. Later + // hooks carry both spellings of its path. + if name != "user_prompt_submit" { + let path = "/grok/agent-host/projects/work/agent-transcripts/unified-session/unified-session.jsonl"; + payload["transcriptPath"] = json!(path); + payload["transcript_path"] = json!(path); + } + Envelope { + event: name.into(), + session_id: "unified-session".into(), + ts_ms, + payload, + ..envelope(0, 0) + } +} + +#[test] +fn unified_grok_finalizes_at_the_last_reply_without_session_end() { + let mut translator = Registry::default_agents().create("grok", "unified-session"); + let prompt = unified_hook( + "user_prompt_submit", + 1000, + json!({"promptId":"first", "prompt":"hello"}), + ); + assert!(handle(translator.as_mut(), &prompt).is_empty()); + let stop = unified_hook( + "stop", + 5000, + json!({"reason":"end_turn", "lastAssistantMessage":"Hi"}), + ); + let ops = handle(translator.as_mut(), &stop); + let root = ops + .iter() + .find_map(|op| match op { + SpanOp::Insert(row) if row.span_id == row.root_span_id => Some(row), + _ => None, + }) + .unwrap(); + assert_eq!(root.start_ms, Some(1000)); + assert!(ops.iter().any(|op| matches!(op, SpanOp::Merge(row) + if row.output == Some(json!([{"type":"text", "text":"Hi"}])) && row.end_ms == Some(5000)))); + let final_ops = translator.finalize(&ctx()).unwrap(); + assert!(matches!(final_ops.as_slice(), [SpanOp::Merge(row)] + if row.span_id == root.span_id && row.end_ms == Some(5000))); +} + +#[test] +fn unified_grok_handles_null_and_missing_prompt_and_tool_fields() { + let mut translator = Registry::default_agents().create("grok", "unified-session"); + for (index, input) in [json!({"promptId":null, "prompt":null}), json!({})] + .into_iter() + .enumerate() + { + let ts_ms = 1000 + index as i64 * 100; + let prompt = handle( + translator.as_mut(), + &unified_hook("user_prompt_submit", ts_ms, input), + ); + let pre = handle( + translator.as_mut(), + &unified_hook( + "pre_tool_use", + ts_ms + 1, + json!({"toolUseId":null, "toolName":"unknown tool"}), + ), + ); + let turn = prompt + .iter() + .chain(&pre) + .find_map(|op| match op { + SpanOp::Insert(row) if row.is_turn => Some(row), + _ => None, + }) + .unwrap(); + assert_eq!(turn.start_ms, Some(ts_ms)); + assert!(turn.input.is_none()); + assert!(pre + .iter() + .all(|op| !matches!(op, SpanOp::Insert(row) if row.span_type == SpanType::Tool))); + let post = handle( + translator.as_mut(), + &unified_hook( + "post_tool_use", + ts_ms + 2, + json!({"toolUseId":format!("call-{index}"), "toolName":null, "toolResult":{"text":"tool result"}}), + ), + ); + assert!(post.iter().any(|op| matches!(op, SpanOp::Insert(row) + if row.span_type == SpanType::Tool && row.name == "Tool" && row.parent_span_ids == [turn.span_id.clone()]))); + let stop = handle( + translator.as_mut(), + &unified_hook( + "stop", + ts_ms + 3, + json!({"promptId":"reported-only-at-stop", "reason":"end_turn"}), + ), + ); + assert!(stop.iter().any(|op| matches!(op, SpanOp::Merge(row) + if row.span_id == turn.span_id && row.end_ms == Some(ts_ms + 3)))); + } +} + #[test] fn grok_spans_under_a_turn_carry_its_turn_span_id() { let updates = std::fs::metadata(fixture("updates.jsonl")).unwrap().len(); From c4250480060156c8020885150f7991b61abf2898 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 19:21:13 +0800 Subject: [PATCH 3/6] Test legacy and unified Grok tracing in PR CI --- .github/scripts/run-grok-smoke.py | 178 ++++++++++++++++++++++++++++++ .github/workflows/ci.yml | 27 +++++ 2 files changed, 205 insertions(+) create mode 100644 .github/scripts/run-grok-smoke.py diff --git a/.github/scripts/run-grok-smoke.py b/.github/scripts/run-grok-smoke.py new file mode 100644 index 00000000..b60c5119 --- /dev/null +++ b/.github/scripts/run-grok-smoke.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Exercise an installed Grok plugin with loopback inference and a debug sink.""" + +import argparse +import json +import os +import shutil +import subprocess +import tempfile +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +MODEL = "grok-4.1-fast" +PROMPT = "Reply with the Grok tracing smoke marker." +ANSWER = "Grok tracing smoke passed." + + +class Inference(BaseHTTPRequestHandler): + def do_GET(self): + data = json.dumps({"object": "list", "data": [ + {"id": MODEL, "object": "model", "owned_by": "xai"}, + ]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(data) + + def do_POST(self): + self.rfile.read(int(self.headers["Content-Length"])) + if self.path not in ("/v1/responses", "/v1/chat/completions"): + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + if self.path == "/v1/responses": + self.send_responses_stream() + else: + self.send_chat_stream() + self.wfile.write(b"data: [DONE]\n\n") + + def send_responses_stream(self): + message = { + "id": "msg_test", "type": "message", "role": "assistant", "status": "completed", + "content": [{"type": "output_text", "text": ANSWER, "annotations": []}], + } + response = { + "id": "resp_test", "object": "response", "created_at": 1, + "model": MODEL, "status": "completed", "output": [message], + "usage": {"input_tokens": 2, "output_tokens": 1, "total_tokens": 3, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}}, + } + events = [ + ("response.created", {"response": {**response, "status": "in_progress", "output": []}}), + ("response.output_item.added", {"output_index": 0, "item": { + **message, "status": "in_progress", "content": [], + }}), + ("response.output_text.delta", {"output_index": 0, "content_index": 0, + "item_id": "msg_test", "delta": ANSWER}), + ("response.output_item.done", {"output_index": 0, "item": message}), + ("response.completed", {"response": response}), + ] + for index, (event, fields) in enumerate(events): + chunk = {"type": event, "sequence_number": index, **fields} + self.wfile.write(f"event: {event}\ndata: {json.dumps(chunk)}\n\n".encode()) + + def send_chat_stream(self): + for delta, reason in [({"role": "assistant", "content": ANSWER}, None), ({}, "stop")]: + chunk = { + "id": "chatcmpl-test", "object": "chat.completion.chunk", "created": 1, + "model": MODEL, "choices": [{"delta": delta, "index": 0, "finish_reason": reason}], + } + self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode()) + + +def wait_for_trace(data_dir, trace_source): + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + rows = [next(iter(json.loads(line).values())) + for path in (data_dir / "spans").glob("*.ndjson") + for line in path.read_text().split("\n")[:-1]] + span_by_id = {} + for row in rows: + span = span_by_id.setdefault(row["span_id"], {}) + span.update(row) + # The debug sink emits sparse merges. Find the original root and turn + # rows for metadata and use any later merge for their completion. + root = next((row for row in rows + if row.get("metadata", {}).get("trace_source") == trace_source + and row["span_id"] == row["root_span_id"]), None) + turn = next((row for row in rows + if row.get("name", "").startswith("Turn ") and PROMPT in str(row.get("input"))), None) + if root and turn and turn["parent_span_ids"] == [root["span_id"]]: + completed_root = span_by_id[root["span_id"]] + completed_turn = span_by_id[turn["span_id"]] + has_llm = any(row.get("span_type") == "llm" for row in rows) + if (completed_root.get("end_ms") is not None + and completed_turn.get("end_ms") is not None + and completed_root["end_ms"] >= completed_turn["end_ms"] + and ANSWER in json.dumps(completed_turn.get("output")) + and has_llm == (trace_source == "session_transcript")): + print(f"Verified completed {trace_source} session and turn spans") + return + time.sleep(0.1) + raise RuntimeError(f"Expected a completed {trace_source} trace, saw {len(rows)} span operations") + + +def smoke(args, home, endpoint): + work = home / "work" + work.mkdir() + bin_dir = home / "bin" + bin_dir.mkdir() + socket = home / "bt.sock" + data_dir = home / "data" + wrapper = Path(__file__).resolve().parents[2] / "src/plugins/cursor/test/bt-standalone-wrapper.sh" + shutil.copy2(wrapper, bin_dir / "bt") + env = { + "HOME": str(home), "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "XAI_API_KEY": "mock-inference-key", "GROK_XAI_API_BASE_URL": endpoint, + "GROK_MODELS_BASE_URL": endpoint, "BT_DAEMON_BIN": str(args.daemon.resolve()), + "BRAINTRUST_DAEMON_SOCKET": str(socket), + } + grok = str(args.grok.resolve()) + version = subprocess.check_output([grok, "--version"], env=env, text=True, timeout=15).strip() + print(version, flush=True) + if version.split()[:2] != ["grok", args.version]: + raise RuntimeError(f"Expected Grok {args.version}, got {version}") + for command in [["install", str(args.plugin.resolve()), "--trust"], ["enable", "trace-grok"]]: + subprocess.run([grok, "plugin", *command], cwd=work, env=env, check=True, timeout=30) + (home / ".grok/braintrust.json").write_text(json.dumps({ + "trace_to_braintrust": True, + "route": {"auth": {"source": "environment", "org_name": "grok-smoke"}, + "destination": {"type": "project_logs", "project_name": "grok-smoke"}}, + })) + with subprocess.Popen([env["BT_DAEMON_BIN"], "serve", "--socket", str(socket), + "--data-dir", str(data_dir), "--debug-sink"], env=env) as daemon: + try: + deadline = time.monotonic() + 10 + while not socket.exists(): + if daemon.poll() is not None or time.monotonic() >= deadline: + raise RuntimeError("The tracing daemon did not start") + time.sleep(0.05) + subprocess.run([grok, "-m", MODEL, "--no-memory", "-p", PROMPT], + cwd=work, env=env, check=True, timeout=90) + wait_for_trace(data_dir, args.trace_source) + finally: + daemon.terminate() + try: + daemon.wait(timeout=10) + except subprocess.TimeoutExpired: + daemon.kill() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--grok", type=Path, required=True) + parser.add_argument("--daemon", type=Path, required=True) + parser.add_argument("--plugin", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--trace-source", choices=("session_transcript", "hook"), required=True) + args = parser.parse_args() + # Keep the daemon socket below the platform's Unix socket path limit. + with tempfile.TemporaryDirectory(prefix="grok-smoke-", dir="/tmp") as temp: + with ThreadingHTTPServer(("127.0.0.1", 0), Inference) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + smoke(args, Path(temp), f"http://127.0.0.1:{server.server_port}/v1") + finally: + server.shutdown() + thread.join() + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88cf73de..8ca42505 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -440,6 +440,33 @@ jobs: run: cargo build --manifest-path bt-daemon/Cargo.toml --all-features --locked - name: Test daemon run: cargo test --manifest-path bt-daemon/Cargo.toml --all-features --locked + - name: Test legacy Grok and Grok Build TUI with mock inference + if: runner.os == 'macOS' + shell: bash + run: | + set -euo pipefail + make validate-grok + download_dir="$(mktemp -d "$RUNNER_TEMP/grok-compatibility.XXXXXX")" + trap 'rm -rf "$download_dir"' EXIT + test_grok() { + local version="$1" artifact="$2" sha="$3" trace_source="$4" + local target="$download_dir/$version" + mkdir "$target" && + curl --fail --silent --show-error --location --retry 3 \ + "https://x.ai/cli/$artifact.gz" -o "$target/grok.gz" && + gzip -dc "$target/grok.gz" > "$target/grok" && + printf '%s %s\n' "$sha" "$target/grok" | shasum -a 256 -c && + chmod 755 "$target/grok" && + python3 .github/scripts/run-grok-smoke.py \ + --grok "$target/grok" --daemon bt-daemon/target/debug/bt-daemon \ + --plugin dist/grok --version "$version" --trace-source "$trace_source" + } + failed=0 + test_grok 1.0.97 grok-1.0.97-macos-aarch64 \ + 0b42371fb80db63b310a90cfef4ddcdab960dcaaae8ee6a7d23e7d18e190ecd1 session_transcript || failed=1 + test_grok 2.0.6 unified/agent-host-2.0.6-macos-aarch64 \ + 32e4ea936bfbe4465b8bc8dc663e8c48c10f80b0496afb54bc323d15aaf1c2cd hook || failed=1 + exit "$failed" # `bt trace install/update codex` activation against the latest Codex, # in an isolated CODEX_HOME. Needs no credentials. - name: Check Codex hook activation contract From 9fcaf2bb80c512d8249c02ef63081432cb5fd53a Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 20:36:15 +0800 Subject: [PATCH 4/6] Run Grok compatibility through the Rust test harness --- .github/scripts/run-grok-smoke.py | 178 -------------------- .github/workflows/ci.yml | 13 +- bt-daemon/tests/grok_integration.rs | 133 +++++++++++++++ bt-daemon/tests/support/inference/openai.rs | 34 +++- 4 files changed, 167 insertions(+), 191 deletions(-) delete mode 100644 .github/scripts/run-grok-smoke.py create mode 100644 bt-daemon/tests/grok_integration.rs diff --git a/.github/scripts/run-grok-smoke.py b/.github/scripts/run-grok-smoke.py deleted file mode 100644 index b60c5119..00000000 --- a/.github/scripts/run-grok-smoke.py +++ /dev/null @@ -1,178 +0,0 @@ -#!/usr/bin/env python3 -"""Exercise an installed Grok plugin with loopback inference and a debug sink.""" - -import argparse -import json -import os -import shutil -import subprocess -import tempfile -import threading -import time -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path - -MODEL = "grok-4.1-fast" -PROMPT = "Reply with the Grok tracing smoke marker." -ANSWER = "Grok tracing smoke passed." - - -class Inference(BaseHTTPRequestHandler): - def do_GET(self): - data = json.dumps({"object": "list", "data": [ - {"id": MODEL, "object": "model", "owned_by": "xai"}, - ]}).encode() - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.end_headers() - self.wfile.write(data) - - def do_POST(self): - self.rfile.read(int(self.headers["Content-Length"])) - if self.path not in ("/v1/responses", "/v1/chat/completions"): - self.send_error(404) - return - self.send_response(200) - self.send_header("Content-Type", "text/event-stream") - self.end_headers() - if self.path == "/v1/responses": - self.send_responses_stream() - else: - self.send_chat_stream() - self.wfile.write(b"data: [DONE]\n\n") - - def send_responses_stream(self): - message = { - "id": "msg_test", "type": "message", "role": "assistant", "status": "completed", - "content": [{"type": "output_text", "text": ANSWER, "annotations": []}], - } - response = { - "id": "resp_test", "object": "response", "created_at": 1, - "model": MODEL, "status": "completed", "output": [message], - "usage": {"input_tokens": 2, "output_tokens": 1, "total_tokens": 3, - "input_tokens_details": {"cached_tokens": 0}, - "output_tokens_details": {"reasoning_tokens": 0}}, - } - events = [ - ("response.created", {"response": {**response, "status": "in_progress", "output": []}}), - ("response.output_item.added", {"output_index": 0, "item": { - **message, "status": "in_progress", "content": [], - }}), - ("response.output_text.delta", {"output_index": 0, "content_index": 0, - "item_id": "msg_test", "delta": ANSWER}), - ("response.output_item.done", {"output_index": 0, "item": message}), - ("response.completed", {"response": response}), - ] - for index, (event, fields) in enumerate(events): - chunk = {"type": event, "sequence_number": index, **fields} - self.wfile.write(f"event: {event}\ndata: {json.dumps(chunk)}\n\n".encode()) - - def send_chat_stream(self): - for delta, reason in [({"role": "assistant", "content": ANSWER}, None), ({}, "stop")]: - chunk = { - "id": "chatcmpl-test", "object": "chat.completion.chunk", "created": 1, - "model": MODEL, "choices": [{"delta": delta, "index": 0, "finish_reason": reason}], - } - self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode()) - - -def wait_for_trace(data_dir, trace_source): - deadline = time.monotonic() + 15 - while time.monotonic() < deadline: - rows = [next(iter(json.loads(line).values())) - for path in (data_dir / "spans").glob("*.ndjson") - for line in path.read_text().split("\n")[:-1]] - span_by_id = {} - for row in rows: - span = span_by_id.setdefault(row["span_id"], {}) - span.update(row) - # The debug sink emits sparse merges. Find the original root and turn - # rows for metadata and use any later merge for their completion. - root = next((row for row in rows - if row.get("metadata", {}).get("trace_source") == trace_source - and row["span_id"] == row["root_span_id"]), None) - turn = next((row for row in rows - if row.get("name", "").startswith("Turn ") and PROMPT in str(row.get("input"))), None) - if root and turn and turn["parent_span_ids"] == [root["span_id"]]: - completed_root = span_by_id[root["span_id"]] - completed_turn = span_by_id[turn["span_id"]] - has_llm = any(row.get("span_type") == "llm" for row in rows) - if (completed_root.get("end_ms") is not None - and completed_turn.get("end_ms") is not None - and completed_root["end_ms"] >= completed_turn["end_ms"] - and ANSWER in json.dumps(completed_turn.get("output")) - and has_llm == (trace_source == "session_transcript")): - print(f"Verified completed {trace_source} session and turn spans") - return - time.sleep(0.1) - raise RuntimeError(f"Expected a completed {trace_source} trace, saw {len(rows)} span operations") - - -def smoke(args, home, endpoint): - work = home / "work" - work.mkdir() - bin_dir = home / "bin" - bin_dir.mkdir() - socket = home / "bt.sock" - data_dir = home / "data" - wrapper = Path(__file__).resolve().parents[2] / "src/plugins/cursor/test/bt-standalone-wrapper.sh" - shutil.copy2(wrapper, bin_dir / "bt") - env = { - "HOME": str(home), "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", - "XAI_API_KEY": "mock-inference-key", "GROK_XAI_API_BASE_URL": endpoint, - "GROK_MODELS_BASE_URL": endpoint, "BT_DAEMON_BIN": str(args.daemon.resolve()), - "BRAINTRUST_DAEMON_SOCKET": str(socket), - } - grok = str(args.grok.resolve()) - version = subprocess.check_output([grok, "--version"], env=env, text=True, timeout=15).strip() - print(version, flush=True) - if version.split()[:2] != ["grok", args.version]: - raise RuntimeError(f"Expected Grok {args.version}, got {version}") - for command in [["install", str(args.plugin.resolve()), "--trust"], ["enable", "trace-grok"]]: - subprocess.run([grok, "plugin", *command], cwd=work, env=env, check=True, timeout=30) - (home / ".grok/braintrust.json").write_text(json.dumps({ - "trace_to_braintrust": True, - "route": {"auth": {"source": "environment", "org_name": "grok-smoke"}, - "destination": {"type": "project_logs", "project_name": "grok-smoke"}}, - })) - with subprocess.Popen([env["BT_DAEMON_BIN"], "serve", "--socket", str(socket), - "--data-dir", str(data_dir), "--debug-sink"], env=env) as daemon: - try: - deadline = time.monotonic() + 10 - while not socket.exists(): - if daemon.poll() is not None or time.monotonic() >= deadline: - raise RuntimeError("The tracing daemon did not start") - time.sleep(0.05) - subprocess.run([grok, "-m", MODEL, "--no-memory", "-p", PROMPT], - cwd=work, env=env, check=True, timeout=90) - wait_for_trace(data_dir, args.trace_source) - finally: - daemon.terminate() - try: - daemon.wait(timeout=10) - except subprocess.TimeoutExpired: - daemon.kill() - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--grok", type=Path, required=True) - parser.add_argument("--daemon", type=Path, required=True) - parser.add_argument("--plugin", type=Path, required=True) - parser.add_argument("--version", required=True) - parser.add_argument("--trace-source", choices=("session_transcript", "hook"), required=True) - args = parser.parse_args() - # Keep the daemon socket below the platform's Unix socket path limit. - with tempfile.TemporaryDirectory(prefix="grok-smoke-", dir="/tmp") as temp: - with ThreadingHTTPServer(("127.0.0.1", 0), Inference) as server: - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - smoke(args, Path(temp), f"http://127.0.0.1:{server.server_port}/v1") - finally: - server.shutdown() - thread.join() - - -if __name__ == "__main__": - main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8ca42505..360d1cda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -449,7 +449,7 @@ jobs: download_dir="$(mktemp -d "$RUNNER_TEMP/grok-compatibility.XXXXXX")" trap 'rm -rf "$download_dir"' EXIT test_grok() { - local version="$1" artifact="$2" sha="$3" trace_source="$4" + local version="$1" artifact="$2" sha="$3" local target="$download_dir/$version" mkdir "$target" && curl --fail --silent --show-error --location --retry 3 \ @@ -457,15 +457,16 @@ jobs: gzip -dc "$target/grok.gz" > "$target/grok" && printf '%s %s\n' "$sha" "$target/grok" | shasum -a 256 -c && chmod 755 "$target/grok" && - python3 .github/scripts/run-grok-smoke.py \ - --grok "$target/grok" --daemon bt-daemon/target/debug/bt-daemon \ - --plugin dist/grok --version "$version" --trace-source "$trace_source" + BT_AGENT_INFERENCE_MODE=mock BT_AGENT_INGEST_MODE=mock \ + GROK_BIN="$target/grok" GROK_TEST_VERSION="$version" GROK_TEST_PLUGIN_DIR="$PWD/dist/grok" \ + cargo test --manifest-path bt-daemon/Cargo.toml --all-features --locked \ + --test grok_integration -- --ignored --nocapture --exact grok_session_emits_traces } failed=0 test_grok 1.0.97 grok-1.0.97-macos-aarch64 \ - 0b42371fb80db63b310a90cfef4ddcdab960dcaaae8ee6a7d23e7d18e190ecd1 session_transcript || failed=1 + 0b42371fb80db63b310a90cfef4ddcdab960dcaaae8ee6a7d23e7d18e190ecd1 || failed=1 test_grok 2.0.6 unified/agent-host-2.0.6-macos-aarch64 \ - 32e4ea936bfbe4465b8bc8dc663e8c48c10f80b0496afb54bc323d15aaf1c2cd hook || failed=1 + 32e4ea936bfbe4465b8bc8dc663e8c48c10f80b0496afb54bc323d15aaf1c2cd || failed=1 exit "$failed" # `bt trace install/update codex` activation against the latest Codex, # in an isolated CODEX_HOME. Needs no credentials. diff --git a/bt-daemon/tests/grok_integration.rs b/bt-daemon/tests/grok_integration.rs new file mode 100644 index 00000000..21fa7dea --- /dev/null +++ b/bt-daemon/tests/grok_integration.rs @@ -0,0 +1,133 @@ +//! Live Grok CLI compatibility test using the packaged hooks and mock backends. +#![cfg(all(unix, feature = "cli"))] +#![allow( + clippy::unwrap_used, + clippy::expect_used, + reason = "Integration test assertions" +)] + +mod support; + +use serde_json::Value; +use std::path::PathBuf; +use support::agent_process::{command, AgentTestWorld}; +use support::agents::AgentOutput; +use support::inference::{MockReply, OpenAiMock, OpenAiTurn}; +use support::server::TestServer; + +const PROMPT: &str = "Reply with the Grok tracing smoke marker."; +const ANSWER: &str = "Grok tracing smoke passed."; + +#[tokio::test] +#[ignore = "requires a real Grok binary and the built tracing plugin"] +async fn grok_session_emits_traces() { + let binary = std::env::var_os("GROK_BIN").expect("set GROK_BIN"); + let version = std::env::var("GROK_TEST_VERSION").expect("set GROK_TEST_VERSION"); + let plugin = + PathBuf::from(std::env::var_os("GROK_TEST_PLUGIN_DIR").expect("set GROK_TEST_PLUGIN_DIR")) + .canonicalize() + .expect("locate built Grok plugin"); + let trace_source = match version.split('.').next() { + Some("1") => "session_transcript", + Some("2") => "hook", + _ => panic!("unsupported Grok test version {version}"), + }; + let world = AgentTestWorld::start().await; + assert!(world.uses_mock_inference() && world.uses_mock_ingest()); + let inference = OpenAiMock::new(|_, _| MockReply::response(OpenAiTurn::text(ANSWER))); + let server = TestServer::start(inference.grok_router()).await; + let endpoint = format!("{}/v1", server.uri()); + let home = world.temp_path("home"); + std::fs::create_dir(&home).expect("create isolated Grok home"); + let workspace = world.workspace(); + let grok = || { + let mut process = command(&binary); + process + .env_clear() + .current_dir(&workspace) + .env("HOME", &home) + .env("XAI_API_KEY", "mock-inference-key") + .env("GROK_XAI_API_BASE_URL", &endpoint) + .env("GROK_MODELS_BASE_URL", &endpoint); + world.configure(&mut process); + process + }; + let reported = world.output(grok().arg("--version")).await; + let reported_stdout = String::from_utf8_lossy(&reported.stdout); + eprintln!("{reported_stdout}"); + assert!(reported.status.success()); + assert_eq!( + reported_stdout.split_whitespace().nth(1), + Some(version.as_str()) + ); + + AgentOutput::from( + world + .output( + grok() + .args(["plugin", "install"]) + .arg(plugin) + .arg("--trust"), + ) + .await, + ) + .assert_success(); + AgentOutput::from( + world + .output(grok().args(["plugin", "enable", "trace-grok"])) + .await, + ) + .assert_success(); + let session = AgentOutput::from( + world + .output(grok().args(["-m", "grok-4.1-fast", "--no-memory", "-p", PROMPT])) + .await, + ); + session.assert_success(); + session.assert_contains(ANSWER); + + let rows = world + .wait_for_trace_rows_matching(|rows| completed_trace(rows, trace_source)) + .await; + assert_eq!( + rows.iter() + .any(|row| row["span_attributes"]["type"] == "llm"), + trace_source == "session_transcript" + ); +} + +fn completed_trace(rows: &[Value], trace_source: &str) -> bool { + let Some(root) = rows.iter().find(|row| { + row["metadata"]["source"] == "grok" + && row["metadata"]["trace_source"] == trace_source + && row["span_id"] == row["root_span_id"] + }) else { + return false; + }; + let Some(turn) = rows.iter().find(|row| { + row["span_attributes"]["name"] + .as_str() + .is_some_and(|name| name.starts_with("Turn ")) + && row["input"] + .as_str() + .is_some_and(|input| input.contains(PROMPT)) + && row["span_parents"] + .as_array() + .is_some_and(|parents| parents == &[root["span_id"].clone()]) + }) else { + return false; + }; + let turn_end = rows.iter().find_map(|row| { + (row["span_id"] == turn["span_id"] && row["output"].to_string().contains(ANSWER)) + .then(|| row["metrics"]["end"].as_f64()) + .flatten() + }); + turn_end.is_some_and(|end| { + rows.iter().any(|row| { + row["span_id"] == root["span_id"] + && row["metrics"]["end"] + .as_f64() + .is_some_and(|root_end| root_end >= end) + }) + }) +} diff --git a/bt-daemon/tests/support/inference/openai.rs b/bt-daemon/tests/support/inference/openai.rs index 1bdff75d..a13e16f8 100644 --- a/bt-daemon/tests/support/inference/openai.rs +++ b/bt-daemon/tests/support/inference/openai.rs @@ -251,14 +251,27 @@ impl OpenAiMock { } pub fn router(&self) -> Router { - Router::new() + Self::inference_routes() .route("/v1/models", get(models)) - .route("/muse-code/models", get(models)) - .route("/responses", post(muse_responses)) .route("/v1/responses", post(responses)) + .with_state(Arc::clone(&self.state)) + } + + pub fn grok_router(&self) -> Router { + Self::inference_routes() + .route("/", get(grok_models)) + .route("/v1/api-key", get(grok_models)) + .route("/v1/models", get(grok_models)) + .route("/v1/responses", post(complete_responses)) + .with_state(Arc::clone(&self.state)) + } + + fn inference_routes() -> Router> { + Router::new() + .route("/muse-code/models", get(models)) + .route("/responses", post(complete_responses)) .route("/v1/chat/completions", post(chat_completions)) .route("/backend-api/plugins/featured", get(featured_plugins)) - .with_state(Arc::clone(&self.state)) } pub fn requests(&self) -> Vec { @@ -275,13 +288,20 @@ async fn models() -> axum::Json { })) } +async fn grok_models() -> axum::Json { + axum::Json(json!({ + "object": "list", + "data": [{"id": "grok-4.1-fast", "object": "model", "owned_by": "xai"}] + })) +} + async fn featured_plugins() -> axum::Json { axum::Json(json!([])) } -// Muse validates the complete Responses envelope, including sequence numbers. -// Other agents intentionally also exercise the sparse mock response path. -async fn muse_responses( +// Muse and Grok use the complete Responses envelope, including sequence numbers. +// The default router still exercises the sparse response path. +async fn complete_responses( State(state): State>, headers: HeaderMap, body: Bytes, From 0e210aee50b4cd17f1b849ecce69fae952cba17c Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 20:44:32 +0800 Subject: [PATCH 5/6] Avoid writable executable fixtures in Linux hook tests --- bt-daemon/src/hook_executable.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/bt-daemon/src/hook_executable.rs b/bt-daemon/src/hook_executable.rs index 3af8aa14..ec80bf76 100644 --- a/bt-daemon/src/hook_executable.rs +++ b/bt-daemon/src/hook_executable.rs @@ -107,11 +107,21 @@ mod tests { #[test] fn delegation_preserves_input_arguments_streams_and_status() { + let current = std::env::current_exe().unwrap(); + // On Linux, another test's concurrent fork can briefly inherit the + // write handle used by copy and cause exec to fail with ETXTBSY. + // Hard-link the built harness on the same filesystem to avoid a writer. + #[cfg(target_os = "linux")] + let tmp = tempfile::tempdir_in(current.parent().unwrap()).unwrap(); + #[cfg(not(target_os = "linux"))] let tmp = tempfile::tempdir().unwrap(); let target = tmp .path() .join(format!("selected bt{}", std::env::consts::EXE_SUFFIX)); - std::fs::copy(std::env::current_exe().unwrap(), &target).unwrap(); + #[cfg(target_os = "linux")] + std::fs::hard_link(¤t, &target).unwrap(); + #[cfg(not(target_os = "linux"))] + std::fs::copy(¤t, &target).unwrap(); let output = child(&target, false); assert_eq!(output.status.code(), Some(23), "{output:?}"); let stdout = String::from_utf8_lossy(&output.stdout); From 0eb5fcec8b6ee9a8b228e6c29e837c7cf394551e Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 20:52:14 +0800 Subject: [PATCH 6/6] Keep Linux hook fixtures out of build directories --- bt-daemon/src/hook_executable.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/bt-daemon/src/hook_executable.rs b/bt-daemon/src/hook_executable.rs index ec80bf76..8e95c40b 100644 --- a/bt-daemon/src/hook_executable.rs +++ b/bt-daemon/src/hook_executable.rs @@ -108,18 +108,25 @@ mod tests { #[test] fn delegation_preserves_input_arguments_streams_and_status() { let current = std::env::current_exe().unwrap(); - // On Linux, another test's concurrent fork can briefly inherit the - // write handle used by copy and cause exec to fail with ETXTBSY. - // Hard-link the built harness on the same filesystem to avoid a writer. - #[cfg(target_os = "linux")] - let tmp = tempfile::tempdir_in(current.parent().unwrap()).unwrap(); - #[cfg(not(target_os = "linux"))] let tmp = tempfile::tempdir().unwrap(); let target = tmp .path() .join(format!("selected bt{}", std::env::consts::EXE_SUFFIX)); #[cfg(target_os = "linux")] - std::fs::hard_link(¤t, &target).unwrap(); + { + // A concurrent test's fork can inherit a write handle opened in + // this process and cause exec to fail with ETXTBSY. Let cp own the + // handle and wait for it to exit before launching the fixture. + let output = crate::subprocess::background_command("cp") + .arg("--") + .arg(¤t) + .arg(&target) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + std::fs::set_permissions(&target, std::fs::metadata(¤t).unwrap().permissions()) + .unwrap(); + } #[cfg(not(target_os = "linux"))] std::fs::copy(¤t, &target).unwrap(); let output = child(&target, false);