Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add Chrome Trace Format export for concurrency visualization (#552)
Maximilian Roos989d183e645b
diff --git a/src/bin/analyze-trace.rs b/src/bin/analyze-trace.rsindex 62c09efc2..e6a1a39a0 100644--- a/src/bin/analyze-trace.rs+++ b/src/bin/analyze-trace.rs@@ -1,47 +1,60 @@-//! Analyze wt-trace logs to understand command performance.+//! Analyze wt-trace logs for concurrency visualization.//!//! # Usage//!//! ```bash-//! # Analyze from file-//! analyze-trace /path/to/trace.log+//! # Generate Chrome Trace Format for visualization+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace > trace.json//!-//! # Analyze from stdin-//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace+//! # Visualize: open trace.json in chrome://tracing or https://ui.perfetto.dev//!-//! # Capture and analyze-//! RUST_LOG=debug wt list --branches 2>&1 | grep wt-trace > trace.log-//! analyze-trace trace.log+//! # Analyze with SQL (requires: curl -LO https://get.perfetto.dev/trace_processor)+//! trace_processor trace.json -Q 'SELECT COUNT(*), SUM(dur)/1e6 as cpu_ms FROM slice'+//! trace_processor trace.json -Q 'SELECT name, COUNT(*) as n, SUM(dur)/1e6 as ms FROM slice GROUP BY name ORDER BY ms DESC'//! ```use std::io::{IsTerminal, Read};use std::path::PathBuf;++use clap::Parser;use worktrunk::trace;+/// Analyze wt-trace logs for concurrency visualization+#[derive(Parser)]+#[command(name = "analyze-trace")]+#[command(about = "Convert wt-trace logs to Chrome Trace Format for visualization")]+#[command(after_long_help = r#"EXAMPLES:+ # Generate trace from wt command+ RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace > trace.json++ # Then either:+ # - Open trace.json in chrome://tracing or https://ui.perfetto.dev+ # - Query with: trace_processor trace.json -Q 'SELECT * FROM slice LIMIT 10'++ # Install trace_processor for SQL analysis:+ curl -LO https://get.perfetto.dev/trace_processor && chmod +x trace_processor+"#)]+struct Args {+ /// Path to trace log file (reads from stdin if omitted)+ file: Option<PathBuf>,+}+fn main() {- let args: Vec<String> = std::env::args().collect();+ let args = Args::parse();- let input = match args.get(1) {- Some(path) if path != "-" => {- // Read from file- let path = PathBuf::from(path);- match std::fs::read_to_string(&path) {- Ok(content) => content,- Err(e) => {- eprintln!("Error reading {}: {}", path.display(), e);- std::process::exit(1);- }+ let input = match args.file {+ Some(path) if path.as_os_str() != "-" => match std::fs::read_to_string(&path) {+ Ok(content) => content,+ Err(e) => {+ eprintln!("Error reading {}: {}", path.display(), e);+ std::process::exit(1);}- }+ },_ => {- // Read from stdinif std::io::stdin().is_terminal() {- eprintln!("Usage: analyze-trace <file> | analyze-trace < input");+ eprintln!("Reading from stdin... (pipe trace data or use Ctrl+D to end)");eprintln!();- eprintln!("Examples:");- eprintln!(" analyze-trace /tmp/trace.log");- eprintln!(" RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace");- std::process::exit(1);+ eprintln!("Hint: RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace");}let mut content = String::new();@@ -59,13 +72,12 @@ fn main() {eprintln!("No trace entries found in input.");eprintln!();eprintln!("Trace lines should look like:");- eprintln!(" [wt-trace] cmd=\"git status\" dur=12.3ms ok=true");+ eprintln!(" [wt-trace] ts=1234567890 tid=3 cmd=\"git status\" dur=12.3ms ok=true");eprintln!();eprintln!("To capture traces, run with RUST_LOG=debug:");eprintln!(" RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace");std::process::exit(1);}- let analysis = trace::analyze(&entries);- println!("{}", trace::render(&analysis));+ println!("{}", trace::to_chrome_trace(&entries));}diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 2e3efe097..1388c8796 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -206,6 +206,18 @@ pub fn run(cmd: &mut Command, context: Option<&str>) -> std::io::Result<std::prorun_with_timeout(cmd, context, timeout)}+/// Extract numeric thread ID from ThreadId's debug format.+/// ThreadId debug format is "ThreadId(N)" where N is the numeric ID.+fn thread_id_number() -> u64 {+ let thread_id = std::thread::current().id();+ let debug_str = format!("{:?}", thread_id);+ debug_str+ .strip_prefix("ThreadId(")+ .and_then(|s| s.strip_suffix(")"))+ .and_then(|s| s.parse().ok())+ .unwrap_or(0)+}+/// Execute a command with an optional timeout.////// Like `run()`, but allows specifying a timeout. If the command doesn't complete within@@ -217,7 +229,7 @@ pub fn run_with_timeout(context: Option<&str>,timeout: Option<std::time::Duration>,) -> std::io::Result<std::process::Output> {- use std::time::Instant;+ use std::time::{Instant, SystemTime, UNIX_EPOCH};// Remove WORKTRUNK_DIRECTIVE_FILE to prevent hooks from writing to itcmd.env_remove(DIRECTIVE_FILE_ENV_VAR);@@ -241,6 +253,13 @@ pub fn run_with_timeout(// RAII guard ensures release even on paniclet _guard = get_semaphore().acquire();+ // Capture timestamp and thread ID for Chrome Trace Format support+ let start_time_us = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_micros() as u64)+ .unwrap_or(0);+ let tid = thread_id_number();+let t0 = Instant::now();// Execute with or without timeout@@ -251,11 +270,13 @@ pub fn run_with_timeout(let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;- // Log trace with timing+ // Log trace with timing, timestamp, and thread ID for concurrency analysismatch (&result, context) {(Ok(output), Some(ctx)) => {log::debug!(- "[wt-trace] context={} cmd=\"{}\" dur={:.1}ms ok={}",+ "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur={:.1}ms ok={}",+ start_time_us,+ tid,ctx,cmd_str,duration_ms,@@ -264,7 +285,9 @@ pub fn run_with_timeout(}(Ok(output), None) => {log::debug!(- "[wt-trace] cmd=\"{}\" dur={:.1}ms ok={}",+ "[wt-trace] ts={} tid={} cmd=\"{}\" dur={:.1}ms ok={}",+ start_time_us,+ tid,cmd_str,duration_ms,output.status.success()@@ -272,7 +295,9 @@ pub fn run_with_timeout(}(Err(e), Some(ctx)) => {log::debug!(- "[wt-trace] context={} cmd=\"{}\" dur={:.1}ms err=\"{}\"",+ "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur={:.1}ms err=\"{}\"",+ start_time_us,+ tid,ctx,cmd_str,duration_ms,@@ -281,7 +306,9 @@ pub fn run_with_timeout(}(Err(e), None) => {log::debug!(- "[wt-trace] cmd=\"{}\" dur={:.1}ms err=\"{}\"",+ "[wt-trace] ts={} tid={} cmd=\"{}\" dur={:.1}ms err=\"{}\"",+ start_time_us,+ tid,cmd_str,duration_ms,ediff --git a/src/trace/analyze.rs b/src/trace/analyze.rsdeleted file mode 100644index 2f409f5b4..000000000--- a/src/trace/analyze.rs+++ /dev/null@@ -1,292 +0,0 @@-//! Analyze trace entries to produce performance summaries.--use super::parse::TraceEntry;-use std::collections::HashMap;-use std::time::Duration;--/// Summary statistics for a group of commands.-#[derive(Debug, Clone)]-pub struct CommandStats {- pub name: String,- pub count: usize,- pub total: Duration,- pub p50: Duration,- pub p90: Duration,- pub max: Duration,-}--/// A bucket in the duration histogram.-#[derive(Debug, Clone)]-pub struct HistogramBucket {- pub label: String,- pub threshold_ms: Option<u64>, // None for the overflow bucket- pub count: usize,-}--/// Impact of applying a timeout threshold.-#[derive(Debug, Clone)]-pub struct TimeoutImpact {- pub threshold: Duration,- pub killed_count: usize,- pub saved_duration: Duration,- pub percent_of_total: f64,-}--/// Complete analysis of trace entries.-#[derive(Debug)]-pub struct TraceAnalysis {- /// Stats grouped by command type (git subcommand or program)- pub command_stats: Vec<CommandStats>,- /// Total duration across all commands- pub total_duration: Duration,- /// Duration histogram- pub histogram: Vec<HistogramBucket>,- /// Timeout impact analysis at various thresholds- pub timeout_impacts: Vec<TimeoutImpact>,- /// Slowest individual commands- pub slowest_commands: Vec<(Duration, String)>,-}--/// Analyze trace entries and produce a complete summary.-pub fn analyze(entries: &[TraceEntry]) -> TraceAnalysis {- let command_stats = compute_command_stats(entries);- let total_duration = entries.iter().map(|e| e.duration).sum();- let histogram = compute_histogram(entries);- let timeout_impacts = compute_timeout_impacts(entries, total_duration);- let slowest_commands = compute_slowest(entries, 10);-- TraceAnalysis {- command_stats,- total_duration,- histogram,- timeout_impacts,- slowest_commands,- }-}--/// Group commands and compute statistics for each group.-fn compute_command_stats(entries: &[TraceEntry]) -> Vec<CommandStats> {- // Group by command type (git subcommand or program name)- let mut groups: HashMap<String, Vec<Duration>> = HashMap::new();-- for entry in entries {- let name = if let Some(subcmd) = entry.git_subcommand() {- format!("git {}", subcmd)- } else {- entry.program().to_string()- };-- groups.entry(name).or_default().push(entry.duration);- }-- // Compute stats for each group- let mut stats: Vec<CommandStats> = groups- .into_iter()- .map(|(name, mut durations)| {- durations.sort();- let count = durations.len();- let total: Duration = durations.iter().sum();- let p50 = percentile(&durations, 50);- let p90 = percentile(&durations, 90);- let max = durations.last().copied().unwrap_or(Duration::ZERO);-- CommandStats {- name,- count,- total,- p50,- p90,- max,- }- })- .collect();-- // Sort by total time descending- stats.sort_by(|a, b| b.total.cmp(&a.total));- stats-}--/// Compute a percentile from sorted durations.-fn percentile(sorted: &[Duration], pct: usize) -> Duration {- if sorted.is_empty() {- return Duration::ZERO;- }- let idx = (sorted.len() * pct / 100).min(sorted.len() - 1);- sorted[idx]-}--/// Compute duration histogram with standard buckets.-fn compute_histogram(entries: &[TraceEntry]) -> Vec<HistogramBucket> {- let thresholds_ms = [10, 50, 100, 200, 500, 1000, 2000, 5000];- let mut counts = vec![0usize; thresholds_ms.len() + 1];-- for entry in entries {- let ms = entry.duration.as_millis() as u64;- let bucket = thresholds_ms- .iter()- .position(|&t| ms <= t)- .unwrap_or(thresholds_ms.len());- counts[bucket] += 1;- }-- let mut buckets = Vec::with_capacity(thresholds_ms.len() + 1);- for (i, &threshold) in thresholds_ms.iter().enumerate() {- buckets.push(HistogramBucket {- label: format!("<{}ms", threshold),- threshold_ms: Some(threshold),- count: counts[i],- });- }- buckets.push(HistogramBucket {- label: ">5s".to_string(),- threshold_ms: None,- count: counts[thresholds_ms.len()],- });-- buckets-}--/// Compute impact of various timeout thresholds.-fn compute_timeout_impacts(entries: &[TraceEntry], total: Duration) -> Vec<TimeoutImpact> {- let thresholds = [100, 200, 500, 1000];- let total_ms = total.as_millis() as f64;-- thresholds- .iter()- .map(|&threshold_ms| {- let threshold = Duration::from_millis(threshold_ms);- let (killed_count, saved_duration) =- entries.iter().fold((0, Duration::ZERO), |acc, e| {- if e.duration > threshold {- (acc.0 + 1, acc.1 + e.duration)- } else {- acc- }- });-- let percent = if total_ms > 0.0 {- saved_duration.as_millis() as f64 / total_ms * 100.0- } else {- 0.0- };-- TimeoutImpact {- threshold,- killed_count,- saved_duration,- percent_of_total: percent,- }- })- .collect()-}--/// Get the N slowest commands.-fn compute_slowest(entries: &[TraceEntry], n: usize) -> Vec<(Duration, String)> {- let mut sorted: Vec<_> = entries- .iter()- .map(|e| (e.duration, e.command.clone()))- .collect();- sorted.sort_by(|a, b| b.0.cmp(&a.0));- sorted.truncate(n);- sorted-}--#[cfg(test)]-mod tests {- use super::*;- use crate::trace::parse::parse_lines;-- #[test]- fn test_percentile_empty() {- // Edge case: percentile of empty slice returns ZERO- assert_eq!(percentile(&[], 50), Duration::ZERO);- }-- fn sample_trace() -> &'static str {- r#"[wt-trace] cmd="git status" dur=10.0ms ok=true-[wt-trace] cmd="git status" dur=15.0ms ok=true-[wt-trace] cmd="git diff" dur=100.0ms ok=true-[wt-trace] cmd="git merge-base HEAD main" dur=500.0ms ok=true-[wt-trace] cmd="gh pr list" dur=200.0ms ok=true"#- }-- #[test]- fn test_command_stats() {- let entries = parse_lines(sample_trace());- let stats = compute_command_stats(&entries);-- // Should have 3 groups: git merge-base, gh, git diff, git status- assert_eq!(stats.len(), 4);-- // First should be git merge-base (highest total)- assert_eq!(stats[0].name, "git merge-base");- assert_eq!(stats[0].count, 1);-- // git status should have count 2- let status_stats = stats.iter().find(|s| s.name == "git status").unwrap();- assert_eq!(status_stats.count, 2);- }-- #[test]- fn test_histogram() {- let entries = parse_lines(sample_trace());- let histogram = compute_histogram(&entries);-- // Buckets use <= threshold:- // 10ms -> <10ms bucket (10 <= 10)- // 15ms -> <50ms bucket- // 100ms -> <100ms bucket (100 <= 100)- // 200ms -> <200ms bucket (200 <= 200)- // 500ms -> <500ms bucket (500 <= 500)- let bucket_10 = histogram.iter().find(|b| b.label == "<10ms").unwrap();- assert_eq!(bucket_10.count, 1); // 10ms-- let bucket_50 = histogram.iter().find(|b| b.label == "<50ms").unwrap();- assert_eq!(bucket_50.count, 1); // 15ms- }-- #[test]- fn test_timeout_impact() {- let entries = parse_lines(sample_trace());- let total: Duration = entries.iter().map(|e| e.duration).sum();- let impacts = compute_timeout_impacts(&entries, total);-- // Timeout kills commands > threshold (not >=)- // At 100ms threshold: gh (200ms) and merge-base (500ms) would be killed- // diff (100ms) is NOT killed since 100 is not > 100- let impact_100 = impacts- .iter()- .find(|i| i.threshold.as_millis() == 100)- .unwrap();- assert_eq!(impact_100.killed_count, 2);- }-- #[test]- fn test_slowest() {- let entries = parse_lines(sample_trace());- let slowest = compute_slowest(&entries, 3);-- assert_eq!(slowest.len(), 3);- assert_eq!(slowest[0].0, Duration::from_millis(500));- assert!(slowest[0].1.contains("merge-base"));- }-- #[test]- fn test_empty_entries() {- let entries: Vec<TraceEntry> = vec![];- let analysis = super::analyze(&entries);-- assert!(analysis.command_stats.is_empty());- assert_eq!(analysis.total_duration, Duration::ZERO);- assert!(analysis.slowest_commands.is_empty());- // Histogram buckets exist but all have 0 count- assert!(analysis.histogram.iter().all(|b| b.count == 0));- // Timeout impacts have 0% saved- assert!(- analysis- .timeout_impacts- .iter()- .all(|i| i.percent_of_total == 0.0)- );- }-}diff --git a/src/trace/chrome.rs b/src/trace/chrome.rsnew file mode 100644index 000000000..f5baed8b7--- /dev/null+++ b/src/trace/chrome.rs@@ -0,0 +1,222 @@+//! Chrome Trace Format output for concurrency visualization.+//!+//! Converts trace entries to Chrome Trace Event Format JSON, which can be+//! visualized in chrome://tracing or <https://ui.perfetto.dev>.+//!+//! # Usage+//!+//! ```bash+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace > trace.json+//! # Then open trace.json in chrome://tracing or https://ui.perfetto.dev+//! ```+//!+//! # Format Reference+//!+//! - [Trace Event Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/)+//! - [Perfetto UI](https://ui.perfetto.dev)++use serde::Serialize;++use super::TraceEntry;++/// A Chrome Trace Event in the Trace Event Format.+#[derive(Debug, Serialize)]+struct TraceEvent {+ /// Event name (displayed in the UI)+ name: String,+ /// Phase: "X" for complete events (with duration)+ ph: &'static str,+ /// Timestamp in microseconds since epoch+ ts: u64,+ /// Duration in microseconds (for "X" phase events)+ dur: u64,+ /// Process ID (we use 1 for all events since wt is single-process)+ pid: u32,+ /// Thread ID+ tid: u64,+ /// Category (optional, for filtering in the UI)+ #[serde(skip_serializing_if = "Option::is_none")]+ cat: Option<String>,+ /// Custom arguments (shown when event is selected in UI)+ args: TraceEventArgs,+}++/// Custom arguments attached to trace events.+#[derive(Debug, Serialize)]+struct TraceEventArgs {+ /// Worktree context (if any)+ #[serde(skip_serializing_if = "Option::is_none")]+ context: Option<String>,+ /// Whether the command succeeded+ success: bool,+ /// Duration in milliseconds (human-readable)+ #[serde(rename = "duration_ms")]+ duration_ms: f64,+}++/// The top-level Chrome Trace Format structure.+#[derive(Debug, Serialize)]+struct ChromeTrace {+ /// Array of trace events+ #[serde(rename = "traceEvents")]+ trace_events: Vec<TraceEvent>,+ /// Display time unit preference+ #[serde(rename = "displayTimeUnit")]+ display_time_unit: &'static str,+ /// Metadata: tool that generated the trace+ #[serde(rename = "meta_generator")]+ meta_generator: &'static str,+}++/// Convert trace entries to Chrome Trace Format JSON.+///+/// Returns pretty-printed JSON suitable for chrome://tracing or Perfetto.+/// Entries without timestamp/thread data use 0 as fallback.+pub fn to_chrome_trace(entries: &[TraceEntry]) -> String {+ let trace_events: Vec<TraceEvent> = entries+ .iter()+ .map(|entry| {+ let ts = entry.start_time_us.unwrap_or(0);+ let tid = entry.thread_id.unwrap_or(0);+ let dur = entry.duration.as_micros() as u64;++ // Categorize by program type+ let cat = if entry.command.starts_with("git ") {+ Some("git".to_string())+ } else if entry.command.starts_with("gh ") || entry.command.starts_with("glab ") {+ Some("network".to_string())+ } else {+ None+ };++ TraceEvent {+ name: entry.command.clone(),+ ph: "X", // Complete event (has duration)+ ts,+ dur,+ pid: 1, // Single process+ tid,+ cat,+ args: TraceEventArgs {+ context: entry.context.clone(),+ success: entry.is_success(),+ duration_ms: entry.duration.as_secs_f64() * 1000.0,+ },+ }+ })+ .collect();++ let chrome_trace = ChromeTrace {+ trace_events,+ display_time_unit: "ms",+ meta_generator: "worktrunk analyze-trace",+ };++ serde_json::to_string_pretty(&chrome_trace).expect("Failed to serialize trace to JSON")+}++#[cfg(test)]+mod tests {+ use std::time::Duration;++ use super::*;+ use crate::trace::{TraceEntry, TraceResult};++ fn make_entry(+ command: &str,+ duration_ms: u64,+ start_time_us: Option<u64>,+ thread_id: Option<u64>,+ ) -> TraceEntry {+ TraceEntry {+ context: Some("feature".to_string()),+ command: command.to_string(),+ duration: Duration::from_millis(duration_ms),+ result: TraceResult::Completed { success: true },+ start_time_us,+ thread_id,+ }+ }++ #[test]+ fn test_to_chrome_trace_with_timestamps() {+ let entries = vec![+ make_entry("git status", 10, Some(1000000), Some(1)),+ make_entry("git diff", 20, Some(1000000), Some(2)),+ make_entry("git log", 15, Some(1010000), Some(1)),+ ];++ let json = to_chrome_trace(&entries);+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();++ assert_eq!(parsed["displayTimeUnit"], "ms");+ assert_eq!(parsed["meta_generator"], "worktrunk analyze-trace");++ let events = parsed["traceEvents"].as_array().unwrap();+ assert_eq!(events.len(), 3);++ // First event+ assert_eq!(events[0]["name"], "git status");+ assert_eq!(events[0]["ph"], "X");+ assert_eq!(events[0]["ts"], 1000000);+ assert_eq!(events[0]["dur"], 10000); // 10ms = 10000µs+ assert_eq!(events[0]["tid"], 1);+ assert_eq!(events[0]["cat"], "git");++ // Second event (parallel on thread 2)+ assert_eq!(events[1]["tid"], 2);+ assert_eq!(events[1]["ts"], 1000000); // Same start time = parallel+ }++ #[test]+ fn test_to_chrome_trace_without_timestamps() {+ // Old format entries without ts/tid get 0 as fallback+ let entries = vec![+ make_entry("git status", 10, None, None),+ make_entry("git diff", 20, None, None),+ ];++ let json = to_chrome_trace(&entries);+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();++ let events = parsed["traceEvents"].as_array().unwrap();++ // Fallback: both get ts=0 and tid=0+ assert_eq!(events[0]["ts"], 0);+ assert_eq!(events[1]["ts"], 0);+ assert_eq!(events[0]["tid"], 0);+ assert_eq!(events[1]["tid"], 0);+ }++ #[test]+ fn test_category_assignment() {+ let entries = vec![+ make_entry("git status", 10, Some(0), Some(1)),+ make_entry("gh pr list", 100, Some(0), Some(2)),+ make_entry("glab mr list", 100, Some(0), Some(3)),+ make_entry("echo hello", 1, Some(0), Some(4)),+ ];++ let json = to_chrome_trace(&entries);+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();+ let events = parsed["traceEvents"].as_array().unwrap();++ assert_eq!(events[0]["cat"], "git");+ assert_eq!(events[1]["cat"], "network");+ assert_eq!(events[2]["cat"], "network");+ assert!(events[3]["cat"].is_null()); // No category for other commands+ }++ #[test]+ fn test_args_include_context() {+ let entries = vec![make_entry("git status", 10, Some(0), Some(1))];++ let json = to_chrome_trace(&entries);+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();+ let events = parsed["traceEvents"].as_array().unwrap();++ assert_eq!(events[0]["args"]["context"], "feature");+ assert_eq!(events[0]["args"]["success"], true);+ assert_eq!(events[0]["args"]["duration_ms"], 10.0);+ }+}diff --git a/src/trace/display.rs b/src/trace/display.rsdeleted file mode 100644index 7da8403be..000000000--- a/src/trace/display.rs+++ /dev/null@@ -1,169 +0,0 @@-//! Display formatting for trace analysis output.--use super::analyze::TraceAnalysis;-use std::fmt::Write as _;--/// Render the complete analysis to a string.-pub fn render(analysis: &TraceAnalysis) -> String {- let mut out = String::new();-- render_header(&mut out);- render_command_breakdown(&mut out, analysis);- render_histogram(&mut out, analysis);- render_timeout_impact(&mut out, analysis);- render_slowest(&mut out, analysis);-- out-}--fn render_header(out: &mut String) {- out.push_str("============================================================\n");- out.push_str(" TRACE PERFORMANCE ANALYSIS\n");- out.push_str("============================================================\n");-}--fn render_command_breakdown(out: &mut String, analysis: &TraceAnalysis) {- out.push_str("\nCOMMAND TYPE BREAKDOWN\n");- out.push_str("----------------------\n");- writeln!(- out,- "{:<15} {:>6} {:>9} {:>8} {:>8} {:>8}",- "Command", "Count", "Total(s)", "p50(ms)", "p90(ms)", "Max(ms)"- )- .unwrap();- writeln!(- out,- "{:<15} {:>6} {:>9} {:>8} {:>8} {:>8}",- "---------------", "------", "---------", "--------", "--------", "--------"- )- .unwrap();-- for stat in &analysis.command_stats {- writeln!(- out,- "{:<15} {:>6} {:>9.1} {:>8.0} {:>8.0} {:>8.0}",- truncate(&stat.name, 15),- stat.count,- stat.total.as_secs_f64(),- stat.p50.as_secs_f64() * 1000.0,- stat.p90.as_secs_f64() * 1000.0,- stat.max.as_secs_f64() * 1000.0,- )- .unwrap();- }-- writeln!(- out,- "{:<15} {:>6} {:>9} {:>8} {:>8} {:>8}",- "---------------", "------", "---------", "--------", "--------", "--------"- )- .unwrap();- writeln!(- out,- "{:<15} {:>6} {:>9.1}",- "TOTAL",- "",- analysis.total_duration.as_secs_f64()- )- .unwrap();-}--fn render_histogram(out: &mut String, analysis: &TraceAnalysis) {- out.push_str("\nDURATION HISTOGRAM\n");- out.push_str("------------------\n");-- let max_count = analysis- .histogram- .iter()- .map(|b| b.count)- .max()- .unwrap_or(1)- .max(1);-- for bucket in &analysis.histogram {- let bar_len = (bucket.count as f64 / max_count as f64 * 30.0) as usize;- let bar: String = "#".repeat(bar_len);-- let annotation = match bucket.label.as_str() {- "<100ms" => " <-- 100ms",- "<500ms" => " <-- 500ms",- _ => "",- };-- writeln!(- out,- "{:<10} |{:<30}| {:>4}{}",- bucket.label, bar, bucket.count, annotation- )- .unwrap();- }-}--fn render_timeout_impact(out: &mut String, analysis: &TraceAnalysis) {- out.push_str("\nTIMEOUT IMPACT\n");- out.push_str("--------------\n");- writeln!(- out,- "{:<12} {:>8} {:>10} {:>10}",- "Threshold", "Killed", "Saved(s)", "% Total"- )- .unwrap();- writeln!(- out,- "{:<12} {:>8} {:>10} {:>10}",- "------------", "--------", "----------", "----------"- )- .unwrap();-- for impact in &analysis.timeout_impacts {- writeln!(- out,- "{:<12} {:>8} {:>9.1}s {:>9.0}%",- format!(">{}ms", impact.threshold.as_millis()),- impact.killed_count,- impact.saved_duration.as_secs_f64(),- impact.percent_of_total- )- .unwrap();- }-}--fn render_slowest(out: &mut String, analysis: &TraceAnalysis) {- out.push_str("\nTOP 10 SLOWEST COMMANDS\n");- out.push_str("-----------------------\n");-- for (duration, command) in &analysis.slowest_commands {- let cmd_display = truncate(command, 60);- writeln!(- out,- "{:>7.0}ms {}",- duration.as_secs_f64() * 1000.0,- cmd_display- )- .unwrap();- }-}--fn truncate(s: &str, max_len: usize) -> String {- if s.len() <= max_len {- s.to_string()- } else {- format!("{}...", &s[..max_len.saturating_sub(3)])- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::trace::{analyze::analyze, parse::parse_lines};-- #[test]- fn test_render_sample_log() {- let sample = include_str!("testdata/sample.log");- let entries = parse_lines(sample);- let analysis = analyze(&entries);- let output = render(&analysis);-- insta::assert_snapshot!(output);- }-}diff --git a/src/trace/mod.rs b/src/trace/mod.rsindex 4f7df4ebf..246b10a77 100644--- a/src/trace/mod.rs+++ b/src/trace/mod.rs@@ -1,29 +1,29 @@-//! Trace log parsing and performance analysis.+//! Trace log parsing and Chrome Trace Format export.//!//! This module provides tools for analyzing `wt-trace` log output to understand//! where time is spent during command execution.//!-//! **Note:** This module is new and minimal. We're very open to adding more-//! metrics, visualizations, or analysis capabilities as needs emerge.+//! # Features//!-//! To support wall-time analysis, thread utilization, or concurrency visualization,-//! we'd need to add timestamps to the trace log format (currently only duration is logged).+//! - **Trace parsing**: Parse `wt-trace` log lines into structured entries+//! - **Chrome Trace Format**: Export for chrome://tracing or Perfetto visualization+//! - **SQL analysis**: Use Perfetto's trace_processor for queries//!//! # Usage//!-//! ```ignore-//! use worktrunk::trace::{parse, analyze, display};+//! ```bash+//! # Generate Chrome Trace Format+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace --format=chrome > trace.json//!-//! let entries = parse::parse_lines(&log_output);-//! let analysis = analyze::analyze(&entries);-//! println!("{}", display::render(&analysis));+//! # Visualize: open trace.json in chrome://tracing or https://ui.perfetto.dev+//!+//! # Analyze with SQL (requires: curl -LO https://get.perfetto.dev/trace_processor)+//! trace_processor trace.json -Q 'SELECT name, COUNT(*), SUM(dur)/1e6 as ms FROM slice GROUP BY name'//! ```-pub mod analyze;-pub mod display;+pub mod chrome;pub mod parse;// Re-export main types for convenience-pub use analyze::{CommandStats, TraceAnalysis, analyze};-pub use display::render;+pub use chrome::to_chrome_trace;pub use parse::{TraceEntry, TraceResult, parse_line, parse_lines};diff --git a/src/trace/parse.rs b/src/trace/parse.rsindex ba064d41f..c6cb7f562 100644--- a/src/trace/parse.rs+++ b/src/trace/parse.rs@@ -2,10 +2,14 @@//!//! Trace lines are emitted by `shell_exec::run()` with this format://! ```text-//! [wt-trace] context=worktree cmd="git status" dur=12.3ms ok=true-//! [wt-trace] cmd="gh pr list" dur=45.2ms ok=false-//! [wt-trace] context=main cmd="git merge-base" dur=100.0ms err="fatal: ..."+//! [wt-trace] ts=1234567890 tid=3 context=worktree cmd="git status" dur=12.3ms ok=true+//! [wt-trace] ts=1234567890 tid=3 cmd="gh pr list" dur=45.2ms ok=false+//! [wt-trace] ts=1234567890 tid=3 context=main cmd="git merge-base" dur=100.0ms err="fatal: ..."//! ```+//!+//! The `ts` (timestamp in microseconds since epoch) and `tid` (thread ID) fields+//! enable concurrency analysis and Chrome Trace Format export for visualizing+//! thread utilization in tools like chrome://tracing or Perfetto.use std::time::Duration;@@ -20,6 +24,10 @@ pub struct TraceEntry {pub duration: Duration,/// Command resultpub result: TraceResult,+ /// Start timestamp in microseconds since Unix epoch (for Chrome Trace Format)+ pub start_time_us: Option<u64>,+ /// Thread ID that executed this command (for concurrency analysis)+ pub thread_id: Option<u64>,}/// Result of a traced command.@@ -66,6 +74,8 @@ pub fn parse_line(line: &str) -> Option<TraceEntry> {let mut command = None;let mut duration = None;let mut result = None;+ let mut start_time_us = None;+ let mut thread_id = None;let mut remaining = rest;@@ -114,6 +124,12 @@ pub fn parse_line(line: &str) -> Option<TraceEntry> {message: value.to_string(),});}+ "ts" => {+ start_time_us = value.parse().ok();+ }+ "tid" => {+ thread_id = value.parse().ok();+ }_ => {} // Ignore unknown keys for forward compatibility}}@@ -123,6 +139,8 @@ pub fn parse_line(line: &str) -> Option<TraceEntry> {command: command?,duration: duration?,result: result?,+ start_time_us,+ thread_id,})}@@ -235,4 +253,37 @@ more noiseassert_eq!(entries[0].command, "git status");assert_eq!(entries[1].command, "git diff");}++ #[test]+ fn test_parse_with_timestamp_and_thread_id() {+ let line = r#"[wt-trace] ts=1736600000000000 tid=5 context=feature cmd="git status" dur=12.3ms ok=true"#;+ let entry = parse_line(line).unwrap();++ assert_eq!(entry.start_time_us, Some(1736600000000000));+ assert_eq!(entry.thread_id, Some(5));+ assert_eq!(entry.context, Some("feature".to_string()));+ assert_eq!(entry.command, "git status");+ assert!(entry.is_success());+ }++ #[test]+ fn test_parse_without_timestamp_and_thread_id() {+ // Old format traces (without ts/tid) should still parse with None values+ let line = r#"[wt-trace] cmd="git status" dur=12.3ms ok=true"#;+ let entry = parse_line(line).unwrap();++ assert_eq!(entry.start_time_us, None);+ assert_eq!(entry.thread_id, None);+ assert_eq!(entry.command, "git status");+ }++ #[test]+ fn test_parse_partial_new_fields() {+ // Only ts provided, no tid+ let line = r#"[wt-trace] ts=1736600000000000 cmd="git status" dur=12.3ms ok=true"#;+ let entry = parse_line(line).unwrap();++ assert_eq!(entry.start_time_us, Some(1736600000000000));+ assert_eq!(entry.thread_id, None);+ }}diff --git a/src/trace/snapshots/worktrunk__trace__display__tests__render_sample_log.snap b/src/trace/snapshots/worktrunk__trace__display__tests__render_sample_log.snapdeleted file mode 100644index 9a8866408..000000000--- a/src/trace/snapshots/worktrunk__trace__display__tests__render_sample_log.snap+++ /dev/null@@ -1,59 +0,0 @@-----source: src/trace/display.rs-expression: output-----============================================================- TRACE PERFORMANCE ANALYSIS-============================================================--COMMAND TYPE BREAKDOWN------------------------Command Count Total(s) p50(ms) p90(ms) Max(ms)---------------- ------ --------- -------- -------- ---------git rev-parse 52 0.8 15 25 42-git show 17 0.3 16 37 38-git diff 14 0.3 18 38 41-git merge-tree 16 0.3 15 24 27-git status 8 0.2 28 34 34-git rev-list 11 0.2 14 20 20-git config 12 0.2 14 24 38-git merge-base 8 0.1 16 38 38-git fsmonito... 8 0.0 5 6 6-git worktree 1 0.0 9 9 9-git for-each... 1 0.0 7 7 7---------------- ------ --------- -------- -------- ---------TOTAL 2.5--DURATION HISTOGRAM--------------------<10ms |######## | 32-<50ms |##############################| 116-<100ms | | 0 <-- 100ms-<200ms | | 0-<500ms | | 0 <-- 500ms-<1000ms | | 0-<2000ms | | 0-<5000ms | | 0->5s | | 0--TIMEOUT IMPACT----------------Threshold Killed Saved(s) % Total------------- -------- ---------- ----------->100ms 0 0.0s 0%->200ms 0 0.0s 0%->500ms 0 0.0s 0%->1000ms 0 0.0s 0%--TOP 10 SLOWEST COMMANDS------------------------- 42ms git rev-parse main^{tree}- 41ms git diff --numstat main- 38ms git diff --name-only main...461- 38ms git show -s --format=%s 4d95ed9d94d4c9d6848d5f7261aebd61d...- 38ms git merge-base --is-ancestor 45521479ea0dd4442f4e10943944...- 38ms git config --get worktrunk.state.tmux.marker- 37ms git show -s --format=%s d4698b1abec3cc27d7791b06422f49543...- 34ms git status --porcelain- 34ms git status --porcelain- 33ms git diff --numstat HEADdiff --git a/src/trace/testdata/sample.log b/src/trace/testdata/sample.logdeleted file mode 100644index f9a7ddd70..000000000--- a/src/trace/testdata/sample.log+++ /dev/null@@ -1,148 +0,0 @@-[a] [wt-trace] context=. cmd="git worktree list --porcelain" dur=8.7ms ok=true-[c] [wt-trace] context=. cmd="git config --bool core.bare" dur=6.2ms ok=true-[b] [wt-trace] context=. cmd="git config --get worktrunk.default-branch" dur=6.2ms ok=true-[e] [wt-trace] context=. cmd="git for-each-ref --format=%(refname:lstrip=2) %(objectname) refs/heads/" dur=7.2ms ok=true-[a] [wt-trace] context=. cmd="git show -s --format=%H %ct d4698b1abec3cc27d7791b06422f4954316177fb 45521479ea0dd4442f4e1094394493989e635593 d4698b1abec3cc27d7791b06422f4954316177fb b521bbe6955f2be4aa51d0979bb4f77afaa7ef1f b6f88689b20ee1c5899f64010834b5d51a80de72 4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c c792ae28ab73d4d8b6405fb550fd45b526b8e1ae d4698b1abec3cc27d7791b06422f4954316177fb" dur=9.4ms ok=true-[a] [wt-trace] context=. cmd="git rev-parse --show-toplevel" dur=6.7ms ok=true-[a] [wt-trace] context=. cmd="git rev-parse --git-common-dir" dur=6.2ms ok=true-[a] [wt-trace] context=. cmd="git config --get worktrunk.history" dur=4.9ms ok=true-[a] [wt-trace] context=. cmd="git rev-parse --abbrev-ref main@{u}" dur=5.6ms ok=true-[a] [wt-trace] context=. cmd="git rev-parse main origin/main" dur=5.1ms ok=true-[a] [wt-trace] context=worktrunk cmd="git config --get core.fsmonitor" dur=5.0ms ok=true-[a] [wt-trace] context=worktrunk.command-attribution cmd="git fsmonitor--daemon start" dur=5.5ms ok=false-[a] [wt-trace] context=worktrunk cmd="git fsmonitor--daemon start" dur=5.6ms ok=false-[a] [wt-trace] context=worktrunk.461-skip cmd="git fsmonitor--daemon start" dur=5.3ms ok=false-[a] [wt-trace] context=worktrunk.tmux cmd="git fsmonitor--daemon start" dur=4.9ms ok=false-[a] [wt-trace] context=worktrunk.sanitize-db cmd="git fsmonitor--daemon start" dur=5.2ms ok=false-[a] [wt-trace] context=worktrunk.461 cmd="git fsmonitor--daemon start" dur=5.2ms ok=false-[a] [wt-trace] context=worktrunk.461-timeout cmd="git fsmonitor--daemon start" dur=5.2ms ok=false-[a] [wt-trace] context=worktrunk.plugin cmd="git fsmonitor--daemon start" dur=5.0ms ok=false-[G] [wt-trace] context=worktrunk.command-attribution cmd="git merge-tree --write-tree main command-attribution" dur=9.4ms ok=true-[b] [wt-trace] context=worktrunk.command-attribution cmd="git show -s --format=%ct b6f88689b20ee1c5899f64010834b5d51a80de72" dur=10.0ms ok=true-[e] [wt-trace] context=worktrunk cmd="git rev-list --left-right --count main...d4698b1abec3cc27d7791b06422f4954316177fb" dur=10.1ms ok=true-[C] [wt-trace] context=worktrunk.461-timeout cmd="git show -s --format=%ct b521bbe6955f2be4aa51d0979bb4f77afaa7ef1f" dur=9.9ms ok=true-[s] [wt-trace] context=worktrunk.461 cmd="git config --get worktrunk.state.461.marker" dur=9.3ms ok=true-[u] [wt-trace] context=worktrunk.command-attribution cmd="git rev-parse --abbrev-ref command-attribution@{u}" dur=10.2ms ok=false-[f] [wt-trace] context=worktrunk.command-attribution cmd="git diff --name-only main...command-attribution" dur=11.9ms ok=true-[l] [wt-trace] context=worktrunk cmd="git rev-parse --git-dir" dur=11.5ms ok=true-[c] [wt-trace] context=worktrunk.sanitize-db cmd="git merge-base --is-ancestor c792ae28ab73d4d8b6405fb550fd45b526b8e1ae main" dur=13.6ms ok=false-[d] [wt-trace] context=worktrunk.461-skip cmd="git rev-parse d4698b1abec3cc27d7791b06422f4954316177fb^{tree} main^{tree}" dur=14.2ms ok=true-[n] [wt-trace] context=worktrunk cmd="git rev-parse d4698b1abec3cc27d7791b06422f4954316177fb^{tree} main^{tree}" dur=14.3ms ok=true-[y] [wt-trace] context=worktrunk.command-attribution cmd="git rev-parse --git-dir" dur=14.4ms ok=true-[h] [wt-trace] context=worktrunk.tmux cmd="git diff --name-only main...tmux" dur=14.6ms ok=true-[B] [wt-trace] context=worktrunk.461-skip cmd="git rev-parse --abbrev-ref 461-skip@{u}" dur=14.7ms ok=false-[i] [wt-trace] context=worktrunk.461-skip cmd="git config --get worktrunk.state.461-skip.marker" dur=14.9ms ok=true-[t] [wt-trace] context=worktrunk.tmux cmd="git merge-tree --write-tree main d4698b1abec3cc27d7791b06422f4954316177fb" dur=15.1ms ok=true-[k] [wt-trace] context=worktrunk.command-attribution cmd="git rev-list --left-right --count main...b6f88689b20ee1c5899f64010834b5d51a80de72" dur=15.3ms ok=true-[q] [wt-trace] context=worktrunk.461 cmd="git rev-parse --abbrev-ref 461@{u}" dur=15.6ms ok=false-[D] [wt-trace] context=worktrunk.command-attribution cmd="git config --get worktrunk.state.command-attribution.marker" dur=15.0ms ok=true-[x] [wt-trace] context=worktrunk.command-attribution cmd="git merge-tree --write-tree main b6f88689b20ee1c5899f64010834b5d51a80de72" dur=15.8ms ok=true-[E] [wt-trace] context=worktrunk.461-timeout cmd="git merge-tree --write-tree main b521bbe6955f2be4aa51d0979bb4f77afaa7ef1f" dur=16.8ms ok=true-[m] [wt-trace] context=worktrunk cmd="git merge-base --is-ancestor d4698b1abec3cc27d7791b06422f4954316177fb main" dur=16.3ms ok=true-[F] [wt-trace] context=worktrunk cmd="git rev-parse --abbrev-ref main@{u}" dur=15.2ms ok=true-[p] [wt-trace] context=worktrunk.command-attribution cmd="git merge-base --is-ancestor b6f88689b20ee1c5899f64010834b5d51a80de72 main" dur=18.2ms ok=true-[z] [wt-trace] context=worktrunk.plugin cmd="git rev-parse --git-dir" dur=17.2ms ok=true-[o] [wt-trace] context=worktrunk.command-attribution cmd="git rev-parse b6f88689b20ee1c5899f64010834b5d51a80de72^{tree} main^{tree}" dur=18.7ms ok=true-[w] [wt-trace] context=worktrunk.tmux cmd="git show -s --format=%ct d4698b1abec3cc27d7791b06422f4954316177fb" dur=18.0ms ok=true-[A] [wt-trace] context=worktrunk.plugin cmd="git rev-list --left-right --count main...4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c" dur=17.6ms ok=true-[l] [wt-trace] context=worktrunk cmd="git rev-parse --git-dir" dur=10.0ms ok=true-[G] [wt-trace] context=worktrunk.command-attribution cmd="git rev-parse main^{tree}" dur=12.4ms ok=true-[f] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-parse --git-dir" dur=10.5ms ok=true-[v] [wt-trace] context=worktrunk.plugin cmd="git merge-tree --write-tree main plugin" dur=22.7ms ok=true-[s] [wt-trace] context=worktrunk.461 cmd="git merge-tree --write-tree main 45521479ea0dd4442f4e1094394493989e635593" dur=13.3ms ok=true-[C] [wt-trace] context=worktrunk.461-timeout cmd="git show -s --format=%s b521bbe6955f2be4aa51d0979bb4f77afaa7ef1f" dur=14.1ms ok=true-[b] [wt-trace] context=worktrunk.command-attribution cmd="git show -s --format=%s b6f88689b20ee1c5899f64010834b5d51a80de72" dur=14.4ms ok=true-[c] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-parse --abbrev-ref sanitize-db@{u}" dur=9.9ms ok=true-[E] [wt-trace] context=worktrunk.461-timeout cmd="git merge-tree --write-tree main 461-timeout" dur=8.5ms ok=true-[r] [wt-trace] context=worktrunk.tmux cmd="git status --porcelain" dur=25.0ms ok=true-[d] [wt-trace] context=worktrunk.461-skip cmd="git diff --name-only main...461-skip" dur=12.5ms ok=true-[h] [wt-trace] context=worktrunk.tmux cmd="git merge-base --is-ancestor d4698b1abec3cc27d7791b06422f4954316177fb main" dur=12.3ms ok=true-[i] [wt-trace] context=worktrunk.461-skip cmd="git merge-tree --write-tree main d4698b1abec3cc27d7791b06422f4954316177fb" dur=12.0ms ok=true-[D] [wt-trace] context=worktrunk.461-skip cmd="git rev-parse --git-dir" dur=12.5ms ok=true-[g] [wt-trace] context=worktrunk.command-attribution cmd="git status --porcelain" dur=28.2ms ok=true-[e] [wt-trace] context=worktrunk cmd="git show -s --format=%ct d4698b1abec3cc27d7791b06422f4954316177fb" dur=19.1ms ok=true-[n] [wt-trace] context=worktrunk cmd="git diff --name-only main...main" dur=15.0ms ok=true-[y] [wt-trace] context=worktrunk.command-attribution cmd="git rev-parse --git-dir" dur=17.4ms ok=true-[A] [wt-trace] context=worktrunk.plugin cmd="git rev-parse 4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c^{tree} main^{tree}" dur=14.0ms ok=true-[p] [wt-trace] context=worktrunk.tmux cmd="git rev-parse --git-dir" dur=15.5ms ok=true-[G] [wt-trace] context=worktrunk.461-skip cmd="git merge-base --is-ancestor d4698b1abec3cc27d7791b06422f4954316177fb main" dur=12.3ms ok=true-[u] [wt-trace] context=worktrunk.sanitize-db cmd="git merge-tree --write-tree main sanitize-db" dur=23.9ms ok=true-[j] [wt-trace] context=worktrunk.461-timeout cmd="git status --porcelain" dur=34.0ms ok=true-[l] [wt-trace] context=worktrunk cmd="git config --get worktrunk.state.main.marker" dur=13.6ms ok=true-[B] [wt-trace] context=worktrunk.461-skip cmd="git status --porcelain" dur=21.5ms ok=true-[E] [wt-trace] context=worktrunk.461-timeout cmd="git rev-parse main^{tree}" dur=12.0ms ok=true-[x] [wt-trace] context=worktrunk.461 cmd="git rev-parse --git-dir" dur=20.9ms ok=true-[F] [wt-trace] context=worktrunk cmd="git rev-list --left-right --count origin/main...d4698b1abec3cc27d7791b06422f4954316177fb" dur=20.5ms ok=true-[o] [wt-trace] context=worktrunk.plugin cmd="git merge-tree --write-tree main 4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c" dur=19.5ms ok=true-[C] [wt-trace] context=worktrunk.461-timeout cmd="git rev-list --left-right --count main...b521bbe6955f2be4aa51d0979bb4f77afaa7ef1f" dur=14.2ms ok=true-[k] [wt-trace] context=worktrunk.plugin cmd="git config --get worktrunk.state.plugin.marker" dur=23.5ms ok=false-[n] [wt-trace] context=worktrunk.461-timeout cmd="git rev-parse --git-dir" dur=10.4ms ok=true-[i] [wt-trace] context=worktrunk.461-skip cmd="git merge-tree --write-tree main 461-skip" dur=12.1ms ok=true-[D] [wt-trace] context=worktrunk.461-skip cmd="git rev-parse --git-dir" dur=11.5ms ok=true-[c] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-list --left-right --count origin/sanitize-db...c792ae28ab73d4d8b6405fb550fd45b526b8e1ae" dur=15.4ms ok=true-[w] [wt-trace] context=worktrunk.tmux cmd="git show -s --format=%s d4698b1abec3cc27d7791b06422f4954316177fb" dur=21.7ms ok=true-[d] [wt-trace] context=worktrunk.plugin cmd="git merge-base --is-ancestor 4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c main" dur=13.8ms ok=false-[f] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-parse --git-dir" dur=19.3ms ok=true-[h] [wt-trace] context=worktrunk.tmux cmd="git rev-parse --abbrev-ref tmux@{u}" dur=16.1ms ok=false-[z] [wt-trace] context=worktrunk.plugin cmd="git rev-parse --git-dir" dur=25.1ms ok=true-[b] [wt-trace] context=worktrunk.tmux cmd="git rev-list --left-right --count main...d4698b1abec3cc27d7791b06422f4954316177fb" dur=20.1ms ok=true-[y] [wt-trace] context=worktrunk.sanitize-db cmd="git config --get worktrunk.state.sanitize-db.marker" dur=12.6ms ok=true-[e] [wt-trace] context=worktrunk cmd="git show -s --format=%s d4698b1abec3cc27d7791b06422f4954316177fb" dur=15.9ms ok=true-[t] [wt-trace] context=worktrunk.tmux cmd="git merge-tree --write-tree main tmux" dur=27.3ms ok=true-[q] [wt-trace] context=worktrunk.461 cmd="git status --porcelain" dur=29.9ms ok=true-[s] [wt-trace] context=worktrunk.461 cmd="git merge-tree --write-tree main 461" dur=22.3ms ok=true-[x] [wt-trace] context=worktrunk.461 cmd="git rev-parse --git-dir" dur=10.7ms ok=true-[v] [wt-trace] context=worktrunk.plugin cmd="git rev-parse main^{tree}" dur=25.3ms ok=true-[B] [wt-trace] context=worktrunk.461-skip cmd="git rev-parse HEAD^{tree} main^{tree}" dur=12.7ms ok=true-[l] [wt-trace] context=worktrunk cmd="git merge-tree --write-tree main d4698b1abec3cc27d7791b06422f4954316177fb" dur=13.3ms ok=true-[r] [wt-trace] context=worktrunk.tmux cmd="git diff --numstat HEAD" dur=24.2ms ok=true-[G] [wt-trace] context=worktrunk.461-timeout cmd="git diff --name-only main...461-timeout" dur=15.6ms ok=true-[A] [wt-trace] context=worktrunk.plugin cmd="git diff --name-only main...plugin" dur=18.1ms ok=true-[m] [wt-trace] context=worktrunk.sanitize-db cmd="git status --porcelain" dur=33.8ms ok=true-[d] [wt-trace] context=worktrunk.plugin cmd="git rev-parse --abbrev-ref plugin@{u}" dur=11.0ms ok=true-[o] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-list --left-right --count main...c792ae28ab73d4d8b6405fb550fd45b526b8e1ae" dur=14.0ms ok=true-[i] [wt-trace] context=worktrunk.461-skip cmd="git rev-parse main^{tree}" dur=13.0ms ok=true-[E] [wt-trace] context=worktrunk.plugin cmd="git show -s --format=%ct 4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c" dur=15.8ms ok=true-[c] [wt-trace] context=worktrunk.461-timeout cmd="git rev-parse --abbrev-ref 461-timeout@{u}" dur=13.9ms ok=false-[C] [wt-trace] context=worktrunk.461-timeout cmd="git rev-parse b521bbe6955f2be4aa51d0979bb4f77afaa7ef1f^{tree} main^{tree}" dur=15.9ms ok=true-[f] [wt-trace] context=worktrunk cmd="git merge-tree --write-tree main main" dur=13.9ms ok=true-[b] [wt-trace] context=worktrunk.461-skip cmd="git show -s --format=%ct d4698b1abec3cc27d7791b06422f4954316177fb" dur=11.3ms ok=true-[w] [wt-trace] context=worktrunk.tmux cmd="git rev-parse d4698b1abec3cc27d7791b06422f4954316177fb^{tree} main^{tree}" dur=15.7ms ok=true-[y] [wt-trace] context=worktrunk.461-skip cmd="git rev-list --left-right --count main...d4698b1abec3cc27d7791b06422f4954316177fb" dur=14.2ms ok=true-[z] [wt-trace] context=worktrunk.sanitize-db cmd="git merge-tree --write-tree main c792ae28ab73d4d8b6405fb550fd45b526b8e1ae" dur=15.3ms ok=true-[t] [wt-trace] context=worktrunk.tmux cmd="git rev-parse main^{tree}" dur=14.9ms ok=true-[j] [wt-trace] context=worktrunk.461-timeout cmd="git diff --numstat HEAD" dur=25.1ms ok=true-[F] [wt-trace] context=worktrunk cmd="git status --porcelain" dur=22.8ms ok=true-[e] [wt-trace] context=worktrunk.461-timeout cmd="git config --get worktrunk.state.461-timeout.marker" dur=15.7ms ok=true-[h] [wt-trace] context=worktrunk.plugin cmd="git status --porcelain" dur=17.9ms ok=true-[l] [wt-trace] context=worktrunk.sanitize-db cmd="git diff --name-only main...sanitize-db" dur=12.3ms ok=true-[G] [wt-trace] context=worktrunk.461 cmd="git show -s --format=%ct 45521479ea0dd4442f4e1094394493989e635593" dur=11.3ms ok=true-[n] [wt-trace] context=worktrunk.461-timeout cmd="git rev-parse --git-dir" dur=21.7ms ok=true-[D] [wt-trace] context=worktrunk.461-timeout cmd="git merge-base --is-ancestor b521bbe6955f2be4aa51d0979bb4f77afaa7ef1f main" dur=21.6ms ok=false-[r] [wt-trace] context=worktrunk.tmux cmd="git rev-parse HEAD^{tree} main^{tree}" dur=12.1ms ok=true-[g] [wt-trace] context=worktrunk.command-attribution cmd="git diff --numstat HEAD" dur=33.0ms ok=true-[d] [wt-trace] context=worktrunk.plugin cmd="git rev-list --left-right --count origin/plugin...4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c" dur=10.4ms ok=true-[q] [wt-trace] context=worktrunk.461 cmd="git diff --numstat HEAD" dur=16.5ms ok=true-[v] [wt-trace] context=worktrunk.461 cmd="git rev-parse 45521479ea0dd4442f4e1094394493989e635593^{tree} main^{tree}" dur=12.6ms ok=true-[p] [wt-trace] context=worktrunk.tmux cmd="git rev-parse --git-dir" dur=28.4ms ok=true-[B] [wt-trace] context=worktrunk.sanitize-db cmd="git show -s --format=%ct c792ae28ab73d4d8b6405fb550fd45b526b8e1ae" dur=13.9ms ok=true-[x] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-parse c792ae28ab73d4d8b6405fb550fd45b526b8e1ae^{tree} main^{tree}" dur=14.7ms ok=true-[s] [wt-trace] context=worktrunk.461 cmd="git rev-parse main^{tree}" dur=17.6ms ok=true-[A] [wt-trace] context=worktrunk.461 cmd="git rev-list --left-right --count main...45521479ea0dd4442f4e1094394493989e635593" dur=12.9ms ok=true-[m] [wt-trace] context=worktrunk.sanitize-db cmd="git diff --numstat HEAD" dur=18.8ms ok=true-[k] [wt-trace] context=worktrunk.tmux cmd="git config --get worktrunk.state.tmux.marker" dur=37.6ms ok=true-[u] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-parse main^{tree}" dur=42.2ms ok=true-[f] [wt-trace] context=worktrunk cmd="git rev-parse main^{tree}" dur=21.2ms ok=true-[F] [wt-trace] context=worktrunk cmd="git rev-parse HEAD^{tree} main^{tree}" dur=23.4ms ok=true-[h] [wt-trace] context=worktrunk.plugin cmd="git rev-parse HEAD^{tree} main^{tree}" dur=26.3ms ok=true-[q] [wt-trace] context=worktrunk.461 cmd="git rev-parse HEAD^{tree} main^{tree}" dur=25.4ms ok=true-[g] [wt-trace] context=worktrunk.command-attribution cmd="git rev-parse HEAD^{tree} main^{tree}" dur=25.6ms ok=true-[o] [wt-trace] context=worktrunk.461 cmd="git diff --name-only main...461" dur=38.5ms ok=true-[i] [wt-trace] context=worktrunk.461 cmd="git merge-base --is-ancestor 45521479ea0dd4442f4e1094394493989e635593 main" dur=37.9ms ok=true-[j] [wt-trace] context=worktrunk.461-timeout cmd="git rev-parse HEAD^{tree} main^{tree}" dur=30.6ms ok=true-[E] [wt-trace] context=worktrunk.plugin cmd="git show -s --format=%s 4d95ed9d94d4c9d6848d5f7261aebd61d327cc5c" dur=38.0ms ok=true-[m] [wt-trace] context=worktrunk.sanitize-db cmd="git rev-parse HEAD^{tree} main^{tree}" dur=21.8ms ok=true-[G] [wt-trace] context=worktrunk.461 cmd="git show -s --format=%s 45521479ea0dd4442f4e1094394493989e635593" dur=31.7ms ok=true-[b] [wt-trace] context=worktrunk.461-skip cmd="git show -s --format=%s d4698b1abec3cc27d7791b06422f4954316177fb" dur=37.2ms ok=true-[B] [wt-trace] context=worktrunk.sanitize-db cmd="git show -s --format=%s c792ae28ab73d4d8b6405fb550fd45b526b8e1ae" dur=30.7ms ok=true-[r] [wt-trace] context=worktrunk.tmux cmd="git diff --numstat main" dur=41.1ms ok=truediff --git a/tests/integration_tests/analyze_trace.rs b/tests/integration_tests/analyze_trace.rsindex 7e70193b6..f1acc8003 100644--- a/tests/integration_tests/analyze_trace.rs+++ b/tests/integration_tests/analyze_trace.rs@@ -3,14 +3,14 @@use std::io::Write;use std::process::{Command, Stdio};-/// Test that the binary produces expected output for sample trace input.+/// Test that the binary produces Chrome Trace Format JSON for sample trace input.#[test]fn test_analyze_trace_from_stdin() {- let sample_trace = r#"[wt-trace] cmd="git status" dur=10.0ms ok=true-[wt-trace] cmd="git status" dur=15.0ms ok=true-[wt-trace] cmd="git diff" dur=100.0ms ok=true-[wt-trace] cmd="git merge-base HEAD main" dur=500.0ms ok=true-[wt-trace] cmd="gh pr list" dur=200.0ms ok=true"#;+ let sample_trace = r#"[wt-trace] ts=1000000 tid=1 cmd="git status" dur=10.0ms ok=true+[wt-trace] ts=1000000 tid=2 cmd="git status" dur=15.0ms ok=true+[wt-trace] ts=1010000 tid=1 cmd="git diff" dur=100.0ms ok=true+[wt-trace] ts=1020000 tid=2 cmd="git merge-base HEAD main" dur=500.0ms ok=true+[wt-trace] ts=1030000 tid=1 cmd="gh pr list" dur=200.0ms ok=true"#;let mut child = Command::new(env!("CARGO_BIN_EXE_analyze-trace")).stdin(Stdio::piped())@@ -31,24 +31,35 @@ fn test_analyze_trace_from_stdin() {assert!(output.status.success(), "analyze-trace should succeed");let stdout = String::from_utf8_lossy(&output.stdout);- // Check key elements of the output++ // Should be valid JSON with Chrome Trace Format structure+ let parsed: serde_json::Value =+ serde_json::from_str(&stdout).expect("Output should be valid JSON");+assert!(- stdout.contains("TRACE PERFORMANCE ANALYSIS"),- "Should have header"+ parsed["traceEvents"].is_array(),+ "Should have traceEvents array");- assert!(- stdout.contains("git merge-base"),- "Should show git merge-base"+ assert_eq!(+ parsed["displayTimeUnit"], "ms",+ "Should have displayTimeUnit");- assert!(stdout.contains("git status"), "Should show git status");- assert!(stdout.contains("TOTAL"), "Should show total row");++ let events = parsed["traceEvents"].as_array().unwrap();+ assert_eq!(events.len(), 5, "Should have 5 trace events");++ // Check first event structure+ assert_eq!(events[0]["name"], "git status");+ assert_eq!(events[0]["ph"], "X"); // Complete event+ assert_eq!(events[0]["ts"], 1000000);+ assert_eq!(events[0]["tid"], 1);+ assert_eq!(events[0]["cat"], "git");}/// Test that the binary shows usage when run interactively without input.#[test]fn test_analyze_trace_no_input_shows_usage() {- // Use --help to test non-interactive path without hanging- // The binary doesn't have --help, so we test by passing a non-existent file+ // Test by passing a non-existent filelet output = Command::new(env!("CARGO_BIN_EXE_analyze-trace")).arg("/nonexistent/path/to/file.log").output()@@ -96,24 +107,30 @@ fn test_analyze_trace_empty_input() {/// Test reading from a file.#[test]fn test_analyze_trace_from_file() {- // Use the sample log file from the testdata directory- let sample_log_path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/trace/testdata/sample.log");+ // Create a temporary file with trace data+ let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");+ let log_path = temp_dir.path().join("trace.log");++ let sample_trace = r#"[wt-trace] ts=1000000 tid=1 cmd="git rev-parse" dur=5.0ms ok=true+[wt-trace] ts=1005000 tid=1 cmd="git status" dur=10.0ms ok=true+[wt-trace] ts=1015000 tid=2 cmd="git diff" dur=20.0ms ok=true"#;++ std::fs::write(&log_path, sample_trace).expect("Failed to write temp file");let output = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))- .arg(sample_log_path)+ .arg(&log_path).output().expect("Failed to run analyze-trace");assert!(output.status.success(), "Should succeed with sample log");let stdout = String::from_utf8_lossy(&output.stdout);- assert!(- stdout.contains("TRACE PERFORMANCE ANALYSIS"),- "Should have header"- );- assert!(- stdout.contains("git rev-parse"),- "Should show git rev-parse (most common in sample)"- );- assert!(stdout.contains("TOTAL"), "Should show total row");++ // Should be valid Chrome Trace Format JSON+ let parsed: serde_json::Value =+ serde_json::from_str(&stdout).expect("Output should be valid JSON");++ let events = parsed["traceEvents"].as_array().unwrap();+ assert_eq!(events.len(), 3, "Should have 3 trace events");+ assert_eq!(events[0]["name"], "git rev-parse");}