Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat(trace): add trace log analysis module (#503)

Maximilian Roosacce1423d4c4
diff --git a/Cargo.toml b/Cargo.toml
index 848e879a1..763c32790 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -60,6 +60,10 @@ name = "git-wt"
path = "src/git_wt.rs"
required-features = ["git-wt"]
+# Trace log analyzer for performance debugging
+[[bin]]
+name = "analyze-trace"
+path = "src/bin/analyze-trace.rs"
[dependencies]
anyhow = "1.0"
diff --git a/src/bin/analyze-trace.rs b/src/bin/analyze-trace.rs
new file mode 100644
index 000000000..62c09efc2
--- /dev/null
+++ b/src/bin/analyze-trace.rs
@@ -0,0 +1,71 @@
+//! Analyze wt-trace logs to understand command performance.
+//!
+//! # Usage
+//!
+//! ```bash
+//! # Analyze from file
+//! analyze-trace /path/to/trace.log
+//!
+//! # Analyze from stdin
+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace
+//!
+//! # Capture and analyze
+//! RUST_LOG=debug wt list --branches 2>&1 | grep wt-trace > trace.log
+//! analyze-trace trace.log
+//! ```
+
+use std::io::{IsTerminal, Read};
+use std::path::PathBuf;
+use worktrunk::trace;
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+
+ 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);
+ }
+ }
+ }
+ _ => {
+ // Read from stdin
+ if std::io::stdin().is_terminal() {
+ eprintln!("Usage: analyze-trace <file> | analyze-trace < input");
+ 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);
+ }
+
+ let mut content = String::new();
+ std::io::stdin()
+ .lock()
+ .read_to_string(&mut content)
+ .expect("Failed to read stdin");
+ content
+ }
+ };
+
+ let entries = trace::parse_lines(&input);
+
+ if entries.is_empty() {
+ 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!();
+ 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));
+}
diff --git a/src/lib.rs b/src/lib.rs
index 1c77bc131..26b72bed4 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -5,6 +5,7 @@ pub mod shell;
pub mod shell_exec;
pub mod styling;
pub mod sync;
+pub mod trace;
pub mod utils;
// Re-export HookType for convenience
diff --git a/src/trace/analyze.rs b/src/trace/analyze.rs
new file mode 100644
index 000000000..2f409f5b4
--- /dev/null
+++ b/src/trace/analyze.rs
@@ -0,0 +1,292 @@
+//! 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/display.rs b/src/trace/display.rs
new file mode 100644
index 000000000..7da8403be
--- /dev/null
+++ b/src/trace/display.rs
@@ -0,0 +1,169 @@
+//! 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.rs
new file mode 100644
index 000000000..4f7df4ebf
--- /dev/null
+++ b/src/trace/mod.rs
@@ -0,0 +1,29 @@
+//! Trace log parsing and performance analysis.
+//!
+//! 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.
+//!
+//! 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).
+//!
+//! # Usage
+//!
+//! ```ignore
+//! use worktrunk::trace::{parse, analyze, display};
+//!
+//! let entries = parse::parse_lines(&log_output);
+//! let analysis = analyze::analyze(&entries);
+//! println!("{}", display::render(&analysis));
+//! ```
+
+pub mod analyze;
+pub mod display;
+pub mod parse;
+
+// Re-export main types for convenience
+pub use analyze::{CommandStats, TraceAnalysis, analyze};
+pub use display::render;
+pub use parse::{TraceEntry, TraceResult, parse_line, parse_lines};
diff --git a/src/trace/parse.rs b/src/trace/parse.rs
new file mode 100644
index 000000000..ba064d41f
--- /dev/null
+++ b/src/trace/parse.rs
@@ -0,0 +1,238 @@
+//! Parse wt-trace log lines into structured entries.
+//!
+//! 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: ..."
+//! ```
+
+use std::time::Duration;
+
+/// A parsed trace entry from a wt-trace log line.
+#[derive(Debug, Clone, PartialEq)]
+pub struct TraceEntry {
+ /// Optional context (typically worktree name for git commands)
+ pub context: Option<String>,
+ /// Full command string (e.g., "git status --porcelain")
+ pub command: String,
+ /// Command duration
+ pub duration: Duration,
+ /// Command result
+ pub result: TraceResult,
+}
+
+/// Result of a traced command.
+#[derive(Debug, Clone, PartialEq)]
+pub enum TraceResult {
+ /// Command completed (ok=true or ok=false)
+ Completed { success: bool },
+ /// Command failed with error (err="...")
+ Error { message: String },
+}
+
+impl TraceEntry {
+ /// Extract the program name (first word of command).
+ pub fn program(&self) -> &str {
+ self.command.split_whitespace().next().unwrap_or("")
+ }
+
+ /// Extract git subcommand if this is a git command.
+ /// Returns None if not a git command.
+ pub fn git_subcommand(&self) -> Option<&str> {
+ let mut parts = self.command.split_whitespace();
+ let program = parts.next()?;
+ if program == "git" { parts.next() } else { None }
+ }
+
+ /// Returns true if the command succeeded.
+ pub fn is_success(&self) -> bool {
+ matches!(self.result, TraceResult::Completed { success: true })
+ }
+}
+
+/// Parse a single trace line.
+///
+/// Returns `None` if the line doesn't match the expected format.
+/// The `[wt-trace]` marker can appear anywhere in the line (to handle log prefixes).
+pub fn parse_line(line: &str) -> Option<TraceEntry> {
+ // Find the [wt-trace] marker anywhere in the line
+ let marker = "[wt-trace] ";
+ let marker_pos = line.find(marker)?;
+ let rest = &line[marker_pos + marker.len()..];
+
+ // Parse key=value pairs
+ let mut context = None;
+ let mut command = None;
+ let mut duration = None;
+ let mut result = None;
+
+ let mut remaining = rest;
+
+ while !remaining.is_empty() {
+ remaining = remaining.trim_start();
+ if remaining.is_empty() {
+ break;
+ }
+
+ // Find key=
+ let eq_pos = remaining.find('=')?;
+ let key = &remaining[..eq_pos];
+ remaining = &remaining[eq_pos + 1..];
+
+ // Parse value (quoted or unquoted)
+ let value = if remaining.starts_with('"') {
+ // Quoted value - find closing quote
+ remaining = &remaining[1..];
+ let end_quote = remaining.find('"')?;
+ let val = &remaining[..end_quote];
+ remaining = &remaining[end_quote + 1..];
+ val
+ } else {
+ // Unquoted value - ends at space or end
+ let end = remaining.find(' ').unwrap_or(remaining.len());
+ let val = &remaining[..end];
+ remaining = &remaining[end..];
+ val
+ };
+
+ match key {
+ "context" => context = Some(value.to_string()),
+ "cmd" => command = Some(value.to_string()),
+ "dur" => {
+ // Parse "123.4ms"
+ let ms_str = value.strip_suffix("ms")?;
+ let ms: f64 = ms_str.parse().ok()?;
+ duration = Some(Duration::from_secs_f64(ms / 1000.0));
+ }
+ "ok" => {
+ let success = value == "true";
+ result = Some(TraceResult::Completed { success });
+ }
+ "err" => {
+ result = Some(TraceResult::Error {
+ message: value.to_string(),
+ });
+ }
+ _ => {} // Ignore unknown keys for forward compatibility
+ }
+ }
+
+ Some(TraceEntry {
+ context,
+ command: command?,
+ duration: duration?,
+ result: result?,
+ })
+}
+
+/// Parse multiple lines, filtering to only valid trace entries.
+pub fn parse_lines(input: &str) -> Vec<TraceEntry> {
+ input.lines().filter_map(parse_line).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_parse_basic() {
+ let line = r#"[wt-trace] cmd="git status" dur=12.3ms ok=true"#;
+ let entry = parse_line(line).unwrap();
+
+ assert_eq!(entry.context, None);
+ assert_eq!(entry.command, "git status");
+ assert_eq!(entry.duration, Duration::from_secs_f64(0.0123));
+ assert!(entry.is_success());
+ }
+
+ #[test]
+ fn test_parse_with_context() {
+ let line =
+ r#"[wt-trace] context=main cmd="git merge-base HEAD origin/main" dur=45.2ms ok=true"#;
+ let entry = parse_line(line).unwrap();
+
+ assert_eq!(entry.context, Some("main".to_string()));
+ assert_eq!(entry.command, "git merge-base HEAD origin/main");
+ assert_eq!(entry.git_subcommand(), Some("merge-base"));
+ }
+
+ #[test]
+ fn test_parse_error() {
+ let line = r#"[wt-trace] cmd="git rev-list" dur=100.0ms err="fatal: bad revision""#;
+ let entry = parse_line(line).unwrap();
+
+ assert!(!entry.is_success());
+ assert!(matches!(
+ entry.result,
+ TraceResult::Error { message } if message == "fatal: bad revision"
+ ));
+ }
+
+ #[test]
+ fn test_parse_ok_false() {
+ let line = r#"[wt-trace] cmd="git diff" dur=5.0ms ok=false"#;
+ let entry = parse_line(line).unwrap();
+
+ assert!(!entry.is_success());
+ assert!(matches!(
+ entry.result,
+ TraceResult::Completed { success: false }
+ ));
+ }
+
+ #[test]
+ fn test_program_extraction() {
+ let line = r#"[wt-trace] cmd="gh pr list --limit 10" dur=200.0ms ok=true"#;
+ let entry = parse_line(line).unwrap();
+
+ assert_eq!(entry.program(), "gh");
+ assert_eq!(entry.git_subcommand(), None);
+ }
+
+ #[test]
+ fn test_parse_non_trace_line() {
+ assert!(parse_line("some random log line").is_none());
+ assert!(parse_line("[other-tag] something").is_none());
+ }
+
+ #[test]
+ fn test_parse_with_log_prefix() {
+ // Real output has thread ID prefix like "[a] "
+ let line = r#"[a] [wt-trace] cmd="git status" dur=5.0ms ok=true"#;
+ let entry = parse_line(line).unwrap();
+ assert_eq!(entry.command, "git status");
+ }
+
+ #[test]
+ fn test_parse_unknown_keys_ignored() {
+ // Unknown keys should be ignored for forward compatibility
+ let line =
+ r#"[wt-trace] future_field=xyz cmd="git status" dur=5.0ms ok=true extra=ignored"#;
+ let entry = parse_line(line).unwrap();
+ assert_eq!(entry.command, "git status");
+ assert!(entry.is_success());
+ }
+
+ #[test]
+ fn test_parse_trailing_whitespace() {
+ // Trailing whitespace should be handled (exercises trim_start + break)
+ let line = "[wt-trace] cmd=\"git status\" dur=5.0ms ok=true ";
+ let entry = parse_line(line).unwrap();
+ assert_eq!(entry.command, "git status");
+ }
+
+ #[test]
+ fn test_parse_lines() {
+ let input = r#"
+DEBUG some other log
+[wt-trace] cmd="git status" dur=10.0ms ok=true
+more noise
+[wt-trace] cmd="git diff" dur=20.0ms ok=true
+"#;
+ let entries = parse_lines(input);
+ assert_eq!(entries.len(), 2);
+ assert_eq!(entries[0].command, "git status");
+ assert_eq!(entries[1].command, "git diff");
+ }
+}
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.snap
new file mode 100644
index 000000000..9a8866408
--- /dev/null
+++ b/src/trace/snapshots/worktrunk__trace__display__tests__render_sample_log.snap
@@ -0,0 +1,59 @@
+---
+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 HEAD
diff --git a/src/trace/testdata/sample.log b/src/trace/testdata/sample.log
new file mode 100644
index 000000000..f9a7ddd70
--- /dev/null
+++ b/src/trace/testdata/sample.log
@@ -0,0 +1,148 @@
+[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=true
diff --git a/tests/integration_tests/analyze_trace.rs b/tests/integration_tests/analyze_trace.rs
new file mode 100644
index 000000000..7e70193b6
--- /dev/null
+++ b/tests/integration_tests/analyze_trace.rs
@@ -0,0 +1,119 @@
+//! Integration tests for the analyze-trace binary.
+
+use std::io::Write;
+use std::process::{Command, Stdio};
+
+/// Test that the binary produces expected output 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 mut child = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("Failed to spawn analyze-trace");
+
+ child
+ .stdin
+ .take()
+ .unwrap()
+ .write_all(sample_trace.as_bytes())
+ .expect("Failed to write to stdin");
+
+ let output = child.wait_with_output().expect("Failed to read output");
+
+ assert!(output.status.success(), "analyze-trace should succeed");
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ // Check key elements of the output
+ assert!(
+ stdout.contains("TRACE PERFORMANCE ANALYSIS"),
+ "Should have header"
+ );
+ assert!(
+ stdout.contains("git merge-base"),
+ "Should show git merge-base"
+ );
+ assert!(stdout.contains("git status"), "Should show git status");
+ assert!(stdout.contains("TOTAL"), "Should show total row");
+}
+
+/// 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
+ let output = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
+ .arg("/nonexistent/path/to/file.log")
+ .output()
+ .expect("Failed to run analyze-trace");
+
+ assert!(
+ !output.status.success(),
+ "Should fail with non-existent file"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Error reading"),
+ "Should show error message"
+ );
+}
+
+/// Test that the binary handles empty trace input.
+#[test]
+fn test_analyze_trace_empty_input() {
+ let mut child = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("Failed to spawn analyze-trace");
+
+ // Write empty input and close stdin
+ child.stdin.take().unwrap();
+
+ let output = child.wait_with_output().expect("Failed to read output");
+
+ assert!(
+ !output.status.success(),
+ "Should fail with no trace entries"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("No trace entries found"),
+ "Should indicate no trace entries"
+ );
+}
+
+/// 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");
+
+ let output = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
+ .arg(sample_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");
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index c74cddec5..4ef3fcf70 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -4,6 +4,7 @@
//
// Windows path differences are handled by snapshot filters in setup_snapshot_settings().
+pub mod analyze_trace;
// column_alignment merged into spacing_edge_cases
pub mod approval_pty;