Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add `wt config state logs profile` performance profiler (#3184)
Maximilian Roos9425a22bd0b6
diff --git a/docs/content/config.md b/docs/content/config.mdindex 218120daf..9aaa80dcd 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -1086,7 +1086,7 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the| `subprocess.log` | Running with `-vv` || `diagnostic.md` | Running with `-vv` |-`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log`; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.+`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `wt config state logs profile` summarizes one into a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log`; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.### Location@@ -1121,8 +1121,9 @@ wt config state logs - Operation and debug logsUsage: <b><span class=c>wt config state logs</span></b> <span class=c>[OPTIONS]</span> <span class=c>[COMMAND]</span><b><span class=g>Commands:</span></b>- <b><span class=c>get</span></b> List all log file paths- <b><span class=c>clear</span></b> Clear all log files+ <b><span class=c>get</span></b> List all log file paths+ <b><span class=c>profile</span></b> Performance profile from a trace log+ <b><span class=c>clear</span></b> Clear all log files<b><span class=g>Options:</span></b><b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex 02cbf7645..965d70f3d 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -1121,7 +1121,7 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the| `subprocess.log` | Running with `-vv` || `diagnostic.md` | Running with `-vv` |-`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log`; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.+`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `wt config state logs profile` summarizes one into a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log`; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.### Location@@ -1166,8 +1166,9 @@ wt config state logs - Operation and debug logsUsage: wt config state logs [OPTIONS] [COMMAND]Commands:- get List all log file paths- clear Clear all log files+ get List all log file paths+ profile Performance profile from a trace log+ clear Clear all log filesOptions:-h, --helpdiff --git a/src/cli/config.rs b/src/cli/config.rsindex 4dfab084e..e41d04d5a 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -857,7 +857,7 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the| `subprocess.log` | Running with `-vv` || `diagnostic.md` | Running with `-vv` |-`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log`; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.+`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `wt config state logs profile` summarizes one into a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log`; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.## Location@@ -1301,6 +1301,38 @@ $ wt config state logs --format=json | jq '.hook_output[] | select(.branch | sta)]Get,+ /// Performance profile from a trace log+ #[command(+ after_long_help = r#"Summarize where a single `wt` invocation spent its time, reading the `[wt-trace]` records captured to `trace.log` by a `-vv` run.++Reads `.git/wt/logs/trace.log` by default, or a log file given as an argument (e.g. a CI artifact, or `-` for stdin). The report answers three questions: where time goes (subprocess time by command type, plus the slowest individual jobs), how parallel the run was (concurrency factor and peak concurrency), and where work was wasted (commands re-run with the same context). For a `wt list` capture it also shows derived latencies (time to skeleton, time to first result) and a timeline of collect milestones; the skeleton/first-result markers need a terminal (TTY) capture. `--format=json` emits the same data for scripting.++For an interactive timeline or a Perfetto trace, use the `wt-perf` helper (`cargo run -p wt-perf -- timeline`); both share the same trace parser.++## Examples++Profile the last `-vv` run in this repo:+```console+$ wt -vv list+$ wt config state logs profile+```++Profile a trace from elsewhere (e.g. a CI artifact), by path or on stdin:+```console+$ wt config state logs profile ci-run.log+$ wt config state logs profile - < ci-run.log+```++JSON for scripting:+```console+$ wt config state logs profile --format=json | jq '.by_type[0]'+```"#+ )]+ Profile {+ /// Trace log to read (defaults to `.git/wt/logs/trace.log`; `-` for stdin)+ file: Option<std::path::PathBuf>,+ },+/// Clear all log filesClear,}@@ -1390,7 +1422,7 @@ impl StateWrite for MarkerAction {impl StateWrite for LogsAction {fn write_verb(&self) -> Option<&'static str> {match self {- Self::Get => None,+ Self::Get | Self::Profile { .. } => None,Self::Clear => Some("clear"),}}diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rsindex 4e15b2498..344638451 100644--- a/src/commands/config/mod.rs+++ b/src/commands/config/mod.rs@@ -25,9 +25,9 @@ pub use plugins::{};pub use show::handle_config_show;pub use state::{- handle_cache_clear, handle_cache_get, handle_logs_list, handle_state_clear,- handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show,- handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set,+ handle_cache_clear, handle_cache_get, handle_logs_list, handle_logs_profile,+ handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,+ handle_state_show, handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set,};pub use update::handle_config_update;diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 1e0f87876..a5647b452 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -70,7 +70,7 @@//! under a single reserved subdirectory rather than adding sibling top-level dirs.use std::fmt::Write as _;-use std::path::Path;+use std::path::{Path, PathBuf};use anyhow::Context;use color_print::cformat;@@ -667,6 +667,56 @@ pub fn handle_logs_list(format: SwitchFormat) -> anyhow::Result<()> {Ok(())}+/// `wt config state logs profile [FILE]` — summarize where a `-vv` run spent its+/// time, from the `[wt-trace]` records in `trace.log` (or a given file / stdin).+pub fn handle_logs_profile(file: Option<PathBuf>, format: SwitchFormat) -> anyhow::Result<()> {+ let (input, source) = match file {+ Some(ref p) if p.as_os_str() == "-" => {+ let mut buf = String::new();+ std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)+ .context("read trace from stdin")?;+ (buf, "stdin".to_string())+ }+ Some(p) => {+ let content = std::fs::read_to_string(&p).with_context(|| {+ format!("Failed to read trace log {}", format_path_for_display(&p))+ })?;+ (content, format_path_for_display(&p).to_string())+ }+ None => {+ let repo = Repository::current().map_err(|_| {+ anyhow::anyhow!(cformat!(+ "Not inside a git repository, so there's no default <bold>.git/wt/logs/trace.log</> to read; pass a trace log path or <bold>-</> for stdin"+ ))+ })?;+ let path = repo.wt_logs_dir().join("trace.log");+ let content = std::fs::read_to_string(&path).map_err(|_| {+ anyhow::anyhow!(cformat!(+ "No trace log at <bold>{}</>; run a command with <bold>-vv</> to capture one",+ format_path_for_display(&path)+ ))+ })?;+ (content, format_path_for_display(&path).to_string())+ }+ };++ let entries = worktrunk::trace::parse_lines(&input);+ if entries.is_empty() {+ anyhow::bail!(cformat!(+ "No [wt-trace] records in {source}; run a command with <bold>-vv</> to capture a trace"+ ));+ }++ let profile = worktrunk::trace::Profile::from_entries(&entries);++ if format == SwitchFormat::Json {+ println!("{}", serde_json::to_string_pretty(&profile)?);+ } else {+ show_help_in_pager(&profile.render_text(&source), true);+ }+ Ok(())+}+// ==================== State Get/Set/Clear Commands ====================/// Handle the state get commanddiff --git a/src/commands/mod.rs b/src/commands/mod.rsindex d3086670b..906d5b6a2 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -40,9 +40,9 @@ pub(crate) use config::{handle_cache_get, handle_claude_install, handle_claude_install_statusline,handle_claude_uninstall, handle_codex_install, handle_codex_uninstall, handle_config_create,handle_config_show, handle_config_update, handle_hints_clear, handle_hints_get,- handle_logs_list, handle_opencode_install, handle_opencode_uninstall, handle_state_clear,- handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show,- handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set,+ handle_logs_list, handle_logs_profile, handle_opencode_install, handle_opencode_uninstall,+ handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,+ handle_state_show, handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set,};pub(crate) use configure_shell::{handle_configure_shell, handle_show_theme, handle_unconfigure_shell,diff --git a/src/diagnostic.rs b/src/diagnostic.rsindex cf1c0dc82..d4a6d2dcb 100644--- a/src/diagnostic.rs+++ b/src/diagnostic.rs@@ -19,7 +19,9 @@//! 2. **Environment** — wt version, OS, git version, shell integration//! 3. **Worktrees** — Raw `git worktree list --porcelain` output//! 4. **Config** — User and project config contents-//! 5. **Verbose log** — Debug log output, truncated to ~50KB if large+//! 5. **Performance profile** — Rendered view of `trace.log`: where time went,+//! parallelism, and same-context cache misses (omitted if no records)+//! 6. **Verbose log** — Debug log output, truncated to ~50KB if large//!//! # Privacy//!@@ -95,6 +97,16 @@ Shell integration: {{ shell_integration }}```</details>{%- endif %}+{%- if performance_profile %}++<details>+<summary>Performance profile</summary>++```+{{ performance_profile }}+```+</details>+{%- endif %}{%- if trace_log %}<details>@@ -157,14 +169,19 @@ impl DiagnosticReport {// Get config show output (if available)let config_show = config_show_output(repo);- // Inline the trace log (bounded). The raw subprocess- // output log is only *referenced* by path — it can be multi-MB and- // would drown out the trace records that matter in a bug report.- let trace_log = crate::log_files::TRACE+ // Read the trace once, then derive two views: a bounded raw inline (the+ // records themselves) and a rendered performance profile (the summary of+ // where time went). The raw subprocess output log is only *referenced* by+ // path — it can be multi-MB and would drown out the trace records that+ // matter in a bug report.+ let trace_content = crate::log_files::TRACE.path()- .and_then(|path| std::fs::read_to_string(&path).ok())+ .and_then(|path| std::fs::read_to_string(&path).ok());+ let trace_log = trace_content+ .as_deref().map(|content| truncate_log(content.trim())).filter(|s| !s.is_empty());+ let performance_profile = trace_content.as_deref().and_then(render_trace_profile);// Forward slashes on both platforms so the rendered markdown reads the// same in bug reports regardless of where it was produced.let subprocess_log_path = crate::log_files::SUBPROCESS@@ -186,6 +203,7 @@ impl DiagnosticReport {shell_integration,worktree_list,config_show,+ performance_profile,trace_log,subprocess_log_path,})@@ -298,6 +316,19 @@ fn is_gh_installed() -> bool {.unwrap_or(false)}+/// Render the captured trace as a human-readable performance profile for the+/// report — a derived view of `trace.log` (where time went, parallelism,+/// same-context cache misses), ANSI-stripped for the markdown bundle. `None`+/// when the capture has no `[wt-trace]` records, so the section is omitted.+fn render_trace_profile(trace_content: &str) -> Option<String> {+ let entries = worktrunk::trace::parse_lines(trace_content);+ if entries.is_empty() {+ return None;+ }+ let rendered = worktrunk::trace::Profile::from_entries(&entries).render_text("trace.log");+ Some(rendered.ansi_strip().to_string())+}+/// Truncate log content to ~50KB if it's too large.////// Keeps the last ~50KB of the log, cutting at a line boundary.@@ -442,6 +473,26 @@ mod tests {assert!(result.len() < 5000);}+ #[test]+ fn test_render_trace_profile_summarizes_records() {+ let trace = r#"[wt-trace] ts=1000 tid=1 context=main cmd="git status" dur_us=12000 ok=true+[wt-trace] ts=1000 tid=2 context=feature cmd="git status" dur_us=8000 ok=true+"#;+ let rendered = render_trace_profile(trace).expect("records present");+ assert!(rendered.contains("PERFORMANCE PROFILE"), "{rendered}");+ assert!(rendered.contains("BY COMMAND TYPE"), "{rendered}");+ // ANSI is stripped for the markdown bundle.+ assert!(+ !rendered.contains('\u{1b}'),+ "should be ANSI-free: {rendered}"+ );+ }++ #[test]+ fn test_render_trace_profile_none_without_records() {+ assert!(render_trace_profile("not a trace line\nanother line\n").is_none());+ }+#[test]fn test_truncate_log_small_content() {let content = "small log content";diff --git a/src/main.rs b/src/main.rsindex ce217ef26..e1cdd2500 100644--- a/src/main.rs+++ b/src/main.rs@@ -46,7 +46,7 @@ use commands::{handle_claude_uninstall, handle_codex_install, handle_codex_uninstall, handle_completions,handle_config_create, handle_config_show, handle_config_update, handle_configure_shell,handle_custom_command, handle_hints_clear, handle_hints_get, handle_hook_show, handle_init,- handle_list, handle_logs_list, handle_merge, handle_opencode_install,+ handle_list, handle_logs_list, handle_logs_profile, handle_merge, handle_opencode_install,handle_opencode_uninstall, handle_promote, handle_rebase, handle_remove_command,handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,handle_state_set, handle_state_show, handle_switch_command, handle_unconfigure_shell,@@ -509,6 +509,7 @@ fn handle_state_command(action: StateCommand, yes: bool) -> anyhow::Result<()> {}match action {Some(LogsAction::Get) | None => handle_logs_list(format),+ Some(LogsAction::Profile { file }) => handle_logs_profile(file, format),Some(LogsAction::Clear) => handle_state_clear("logs", None, false),}}diff --git a/src/trace/mod.rs b/src/trace/mod.rsindex 3b71b8c18..66e5dace4 100644--- a/src/trace/mod.rs+++ b/src/trace/mod.rs@@ -40,8 +40,10 @@pub mod chrome;pub mod emit;pub mod parse;+pub mod profile;// Re-export main types for conveniencepub use chrome::to_chrome_trace;pub use emit::{CommandTrace, Span, WT_TRACE_TARGET, instant};pub use parse::{TraceEntry, TraceEntryKind, TraceResult, parse_lines};+pub use profile::{CacheReport, Profile};diff --git a/src/trace/profile.rs b/src/trace/profile.rsnew file mode 100644index 000000000..fe3a8ec7b--- /dev/null+++ b/src/trace/profile.rs@@ -0,0 +1,1157 @@+//! Aggregate `[wt-trace]` records into a performance profile.+//!+//! Where [`parse`](super::parse) turns trace lines into [`TraceEntry`] values and+//! [`chrome`](super::chrome) exports them for Perfetto, this module answers the+//! three questions [`benches/CLAUDE.md`] poses about a single `wt` invocation+//! without leaving the terminal:+//!+//! - **Where does time go?** — [`Profile::by_type`] groups subprocesses by command+//! shape (`git status`, `git rev-list`, `gh pr list`) with count/total/max/avg,+//! and [`Profile::slowest`] lists the most expensive individual jobs.+//! - **How parallel are we?** — [`Profile::parallelism`] is Σ(subprocess time) ÷+//! their wall span; [`Profile::peak_concurrency`] is the most subprocesses in+//! flight at once.+//! - **Where is work wasted?** — [`CacheReport`] flags commands re-run with the+//! same context (a cache miss that should have been a hit).+//!+//! The analysis ([`Profile::from_entries`], [`CacheReport::from_entries`]) is pure+//! data over `&[TraceEntry]` and carries no styling, so it compiles without the+//! `cli` feature and is shared by both `wt config state logs profile` (which+//! renders via [`Profile::render_text`] or serializes the struct for `--format=json`)+//! and the `wt-perf` helper (which reuses [`CacheReport`] for its `cache-check`+//! output). The struct's `Serialize` impl is the single canonical JSON source.+//!+//! [`benches/CLAUDE.md`]: ../../../benches/CLAUDE.md++use std::collections::{BTreeMap, HashMap, HashSet};+use std::time::Duration;++use serde::Serialize;++use crate::styling::format_heading;++use super::{TraceEntry, TraceEntryKind, TraceResult};++/// How many individual calls [`Profile::slowest`] retains.+const SLOWEST_LIMIT: usize = 8;+/// How many cache offenders the text summary lists before collapsing the rest.+const CACHE_OFFENDER_LIMIT: usize = 3;++// Milestone event strings emitted by the `wt list` / picker collect pipeline+// (`src/commands/list/collect/mod.rs`). These literals must match the emit+// sites; a rename there is caught by the integration test+// `test_logs_profile_real_capture_has_key_intervals`.+//+// `List collect started`, `Parallel execution started`, `All results drained`,+// and `List collect complete` always fire on a collect run, so `collect_total`+// and `parallel_phase` are present in any capture. `Skeleton rendered` fires+// only for a progressive consumer — a TTY `wt list` or the picker — and+// `First result received` only for the progressive `wt list` table; both are+// absent from a piped capture, so the intervals built from them are too.+const M_COLLECT_STARTED: &str = "List collect started";+const M_SKELETON: &str = "Skeleton rendered";+const M_PARALLEL_STARTED: &str = "Parallel execution started";+const M_FIRST_RESULT: &str = "First result received";+const M_DRAINED: &str = "All results drained";+const M_COLLECT_COMPLETE: &str = "List collect complete";++/// Serialize a `Duration` as integer microseconds (the `dur_us` wire convention).+fn ser_dur_us<S: serde::Serializer>(d: &Duration, s: S) -> Result<S::Ok, S::Error> {+ s.serialize_u64(d.as_micros() as u64)+}++/// Serialize an optional `Duration` as nullable microseconds.+fn ser_opt_dur_us<S: serde::Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {+ match d {+ Some(d) => s.serialize_u64(d.as_micros() as u64),+ None => s.serialize_none(),+ }+}++/// A performance profile derived from a set of `[wt-trace]` records.+///+/// The struct IS the canonical result: `--format=json` serializes it directly+/// (durations as `*_us` microseconds), and [`Profile::render_text`] renders the+/// same fields, so the two views can't drift.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Profile {+ /// First → last record, across commands, spans, and instant events.+ #[serde(rename = "traced_us", serialize_with = "ser_dur_us")]+ pub traced: Duration,+ /// Number of subprocess (command) records.+ pub command_count: usize,+ /// Σ of every subprocess duration.+ #[serde(rename = "command_total_us", serialize_with = "ser_dur_us")]+ pub command_total: Duration,+ /// Σ of in-process span durations (config load, repo open, …).+ #[serde(rename = "span_total_us", serialize_with = "ser_dur_us")]+ pub span_total: Duration,+ /// Σ(timed subprocess time) ÷ (their wall span). `None` when no command+ /// carries a timestamp (e.g. a log captured before `ts`/`tid` existed) or+ /// the span is zero.+ pub parallelism: Option<f64>,+ /// Most subprocesses in flight simultaneously. `None` without timestamps.+ pub peak_concurrency: Option<usize>,+ /// Distinct thread IDs that ran subprocesses.+ pub thread_count: usize,+ /// Derived `wt list` latencies from the collect milestones.+ pub key_intervals: KeyIntervals,+ /// Subprocess time grouped by command shape, busiest first.+ pub by_type: Vec<TypeStat>,+ /// The most expensive individual jobs (commands and spans), slowest first.+ pub slowest: Vec<Slow>,+ /// Redundant same-context commands.+ pub cache: CacheReport,+ /// Milestone events with the gap since the previous milestone.+ pub phases: Vec<Phase>,+ /// Whether this capture is a `wt list`/picker collect run (the start anchor+ /// milestone is present). Drives the skeleton/first-result "not recorded"+ /// note; not serialized (derivable from `phases`).+ #[serde(skip)]+ pub collect_run: bool,+}++/// Derived latencies from the `wt list` collect milestones. Each is `None` when+/// an endpoint milestone is absent — `time_to_skeleton`/`time_to_first_result`+/// need a TTY/`--progressive` capture; `collect_total`/`parallel_phase` are+/// built from always-fire milestones and present in any collect capture.+// Field order matches the KEY INTERVALS render order so the text and JSON views+// agree (serde follows declaration order).+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct KeyIntervals {+ /// `Skeleton rendered` − `List collect started`: the headline perceived latency.+ #[serde(rename = "time_to_skeleton_us", serialize_with = "ser_opt_dur_us")]+ pub time_to_skeleton: Option<Duration>,+ /// `First result received` − `List collect started`.+ #[serde(rename = "time_to_first_result_us", serialize_with = "ser_opt_dur_us")]+ pub time_to_first_result: Option<Duration>,+ /// `All results drained` − `Parallel execution started`: the parallel fan-out.+ #[serde(rename = "parallel_phase_us", serialize_with = "ser_opt_dur_us")]+ pub parallel_phase: Option<Duration>,+ /// `List collect complete` − `List collect started`: whole collection.+ #[serde(rename = "collect_total_us", serialize_with = "ser_opt_dur_us")]+ pub collect_total: Option<Duration>,+}++impl KeyIntervals {+ /// True when no interval could be computed (not a collect capture).+ fn is_empty(&self) -> bool {+ self.time_to_skeleton.is_none()+ && self.time_to_first_result.is_none()+ && self.collect_total.is_none()+ && self.parallel_phase.is_none()+ }+}++/// Aggregated timing for one command shape (e.g. `git status`).+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct TypeStat {+ /// The command shape — program plus leading subcommand tokens.+ #[serde(rename = "command")]+ pub key: String,+ pub count: usize,+ #[serde(rename = "total_us", serialize_with = "ser_dur_us")]+ pub total: Duration,+ #[serde(rename = "max_us", serialize_with = "ser_dur_us")]+ pub max: Duration,+ #[serde(rename = "avg_us", serialize_with = "ser_dur_us")]+ pub avg: Duration,+}++/// One expensive job in [`Profile::slowest`].+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Slow {+ #[serde(rename = "dur_us", serialize_with = "ser_dur_us")]+ pub duration: Duration,+ /// Display label — `cmd [context]` (with a failure marker) or `span:name`.+ pub label: String,+}++/// A milestone event and the gap since the previous one.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Phase {+ pub name: String,+ /// Offset from the first record.+ #[serde(rename = "at_us", serialize_with = "ser_dur_us")]+ pub at: Duration,+ /// Gap since the previous milestone (`None` for the first).+ #[serde(rename = "delta_us", serialize_with = "ser_opt_dur_us")]+ pub delta: Option<Duration>,+}++/// Redundant-command analysis: the same `(command, context)` run more than once+/// in a single invocation is a cache that should have hit but didn't.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct CacheReport {+ pub total_commands: usize,+ pub unique_commands: usize,+ pub contexts: usize,+ #[serde(rename = "total_time_us", serialize_with = "ser_dur_us")]+ pub total_time: Duration,+ /// Distinct commands run more than once (in any context).+ pub duplicated_commands: usize,+ /// Extra runs beyond the first, regardless of context.+ pub extra_calls: usize,+ /// Commands re-run within the same context, worst waste first.+ pub same_context_duplicates: Vec<DuplicateCommand>,+ /// Extra same-context runs beyond the first.+ pub same_context_extra_calls: usize,+ /// Time spent on those extra same-context runs (slowest run per context kept).+ #[serde(rename = "same_context_extra_us", serialize_with = "ser_dur_us")]+ pub same_context_extra: Duration,+}++/// One command re-run within the same context.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct DuplicateCommand {+ pub command: String,+ /// Highest run-count across this command's contexts.+ pub max_per_context: usize,+ pub extra_calls: usize,+ #[serde(rename = "extra_us", serialize_with = "ser_dur_us")]+ pub extra: Duration,+ pub contexts: Vec<DuplicateContext>,+}++/// Per-context run counts for a [`DuplicateCommand`].+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct DuplicateContext {+ pub context: String,+ pub count: usize,+ #[serde(rename = "total_us", serialize_with = "ser_dur_us")]+ pub total: Duration,+}++/// The command shape used to group subprocesses: the program plus up to two+/// leading subcommand tokens.+///+/// Leading global flags before the subcommand are skipped (`git+/// --no-optional-locks status` → `git status`; `-c`/`-C` also consume their+/// value). A subcommand token is then lowercase letters and dashes only+/// (`status`, `for-each-ref`, `rev-list`, `pr`, `list`), so `git status+/// --porcelain` and `gh pr list --json …` collapse to `git status` and `gh pr+/// list`. The walk stops at the first flag, ref, range, path, or SHA.+///+/// The two-token allowance keeps real second-level subcommands distinct (`git+/// worktree list`, `gh pr list`), at the cost of a bare lowercase positional+/// operand also being absorbed — `git checkout main` and `git checkout feature`+/// land in separate buckets. worktrunk's hot commands (`status`, `rev-list`,+/// `merge-base`, …) take flags/refs/SHAs as their first operand, so this only+/// bites branch-name operands in a single invocation, which `wt list` doesn't+/// emit.+fn command_type(command: &str) -> String {+ let mut tokens = command.split_whitespace();+ let Some(program) = tokens.next() else {+ return String::new();+ };+ let mut parts = vec![program];++ let mut tokens = tokens.peekable();+ while let Some(tok) = tokens.peek() {+ if tok.starts_with('-') {+ let consumes_value = matches!(*tok, "-c" | "-C");+ tokens.next();+ if consumes_value {+ tokens.next();+ }+ } else {+ break;+ }+ }++ for tok in tokens {+ if parts.len() < 3+ && tok.starts_with(|c: char| c.is_ascii_lowercase())+ && tok.chars().all(|c| c.is_ascii_lowercase() || c == '-')+ {+ parts.push(tok);+ } else {+ break;+ }+ }+ parts.join(" ")+}++/// Display label for one slowest-list command.+fn command_label(command: &str, context: Option<&str>, result: &TraceResult) -> String {+ let mut label = match context {+ Some(c) => format!("{command} [{c}]"),+ None => command.to_string(),+ };+ match result {+ TraceResult::Completed { success: false } => label.push_str(" (ok=false)"),+ TraceResult::Error { message } => label.push_str(&format!(" (err: {message})")),+ TraceResult::Completed { success: true } => {}+ }+ label+}++/// Microseconds of an entry's duration (zero for instant events).+fn entry_dur_us(entry: &TraceEntry) -> u64 {+ match &entry.kind {+ TraceEntryKind::Command { duration, .. } | TraceEntryKind::Span { duration, .. } => {+ duration.as_micros() as u64+ }+ TraceEntryKind::Instant { .. } => 0,+ }+}++impl Profile {+ /// Build a profile from parsed trace entries.+ pub fn from_entries(entries: &[TraceEntry]) -> Self {+ let min_start = entries.iter().filter_map(|e| e.start_time_us).min();+ let max_end = entries+ .iter()+ .filter_map(|e| e.start_time_us.map(|s| s + entry_dur_us(e)))+ .max();+ let traced = match (min_start, max_end) {+ (Some(a), Some(b)) => Duration::from_micros(b.saturating_sub(a)),+ _ => Duration::ZERO,+ };++ let mut command_count = 0;+ let mut command_total_us = 0u64;+ let mut span_total_us = 0u64;+ let mut by_type_map: BTreeMap<String, (usize, u64, u64)> = BTreeMap::new();+ let mut threads: HashSet<u64> = HashSet::new();+ // (start, end) for timed subprocesses — drives parallelism & peak concurrency.+ let mut intervals: Vec<(u64, u64)> = Vec::new();+ let mut slowest: Vec<Slow> = Vec::new();++ for entry in entries {+ match &entry.kind {+ TraceEntryKind::Command {+ command,+ duration,+ result,+ } => {+ let dur_us = duration.as_micros() as u64;+ command_count += 1;+ command_total_us += dur_us;+ let stat = by_type_map.entry(command_type(command)).or_default();+ stat.0 += 1;+ stat.1 += dur_us;+ stat.2 = stat.2.max(dur_us);+ if let Some(tid) = entry.thread_id {+ threads.insert(tid);+ }+ if let Some(start) = entry.start_time_us {+ intervals.push((start, start + dur_us));+ }+ slowest.push(Slow {+ duration: *duration,+ label: command_label(command, entry.context.as_deref(), result),+ });+ }+ TraceEntryKind::Span { name, duration } => {+ span_total_us += duration.as_micros() as u64;+ slowest.push(Slow {+ duration: *duration,+ label: format!("span:{name}"),+ });+ }+ TraceEntryKind::Instant { .. } => {}+ }+ }++ let mut by_type: Vec<TypeStat> = by_type_map+ .into_iter()+ .map(|(key, (count, total, max))| TypeStat {+ key,+ count,+ total: Duration::from_micros(total),+ max: Duration::from_micros(max),+ avg: Duration::from_micros(total / count as u64),+ })+ .collect();+ by_type.sort_by(|a, b| b.total.cmp(&a.total).then_with(|| a.key.cmp(&b.key)));++ slowest.sort_by_key(|s| std::cmp::Reverse(s.duration));+ slowest.truncate(SLOWEST_LIMIT);++ let (parallelism, peak_concurrency) = concurrency(&intervals);++ let base = min_start.unwrap_or(0);+ let mut milestones: Vec<(&str, u64)> = entries+ .iter()+ .filter_map(|e| match &e.kind {+ TraceEntryKind::Instant { name } => e.start_time_us.map(|s| (name.as_str(), s)),+ _ => None,+ })+ .collect();+ milestones.sort_by_key(|(_, start)| *start);++ // Absolute timestamp of each milestone (first occurrence) for the+ // derived intervals. `Skeleton rendered` appears at most once per run.+ let mut milestone_at: BTreeMap<&str, u64> = BTreeMap::new();+ for (name, start) in &milestones {+ milestone_at.entry(name).or_insert(*start);+ }+ let interval = |from: &str, to: &str| match (milestone_at.get(from), milestone_at.get(to)) {+ (Some(&a), Some(&b)) if b >= a => Some(Duration::from_micros(b - a)),+ _ => None,+ };+ let key_intervals = KeyIntervals {+ time_to_skeleton: interval(M_COLLECT_STARTED, M_SKELETON),+ time_to_first_result: interval(M_COLLECT_STARTED, M_FIRST_RESULT),+ collect_total: interval(M_COLLECT_STARTED, M_COLLECT_COMPLETE),+ parallel_phase: interval(M_PARALLEL_STARTED, M_DRAINED),+ };+ let collect_run = milestone_at.contains_key(M_COLLECT_STARTED);++ let mut phases = Vec::with_capacity(milestones.len());+ let mut prev: Option<u64> = None;+ for (name, start) in milestones {+ let at = start.saturating_sub(base);+ phases.push(Phase {+ name: name.to_string(),+ at: Duration::from_micros(at),+ delta: prev.map(|p| Duration::from_micros(at.saturating_sub(p))),+ });+ prev = Some(at);+ }++ Profile {+ traced,+ command_count,+ command_total: Duration::from_micros(command_total_us),+ span_total: Duration::from_micros(span_total_us),+ parallelism,+ peak_concurrency,+ thread_count: threads.len(),+ key_intervals,+ by_type,+ slowest,+ cache: CacheReport::from_entries(entries),+ phases,+ collect_run,+ }+ }++ /// Render the profile as a human-readable report (ANSI styling auto-strips+ /// on a pipe). `source` labels where the records came from.+ pub fn render_text(&self, source: &str) -> String {+ let mut out = String::new();++ out.push_str(&format_heading(+ "PERFORMANCE PROFILE",+ Some(&format!("@ {source}")),+ ));+ out.push('\n');+ let parallelism = match self.parallelism {+ Some(p) => format!("parallelism {p:.1}×"),+ None => "parallelism n/a".to_string(),+ };+ let peak = match self.peak_concurrency {+ Some(p) => format!("peak {p}"),+ None => "peak n/a".to_string(),+ };+ // Build the summary from segments so the timestamp-derived fields+ // (thread count, traced wall span) drop out for a log without `ts`/`tid`+ // rather than rendering a confusing `0 threads · traced 0.00ms`.+ let mut segments = vec![+ format!(+ "{} subprocess{}",+ self.command_count,+ plural(self.command_count, "es")+ ),+ format!("{} subprocess time", fmt_dur(self.command_total)),+ parallelism,+ peak,+ ];+ if self.thread_count > 0 {+ segments.push(format!(+ "{} thread{}",+ self.thread_count,+ plural(self.thread_count, "s")+ ));+ }+ if !self.traced.is_zero() {+ segments.push(format!("traced {}", fmt_dur(self.traced)));+ }+ if !self.span_total.is_zero() {+ segments.push(format!("{} in-process", fmt_dur(self.span_total)));+ }+ out.push_str(" ");+ out.push_str(&segments.join(" · "));+ out.push('\n');++ if !self.by_type.is_empty() {+ out.push('\n');+ out.push_str(&format_heading("BY COMMAND TYPE", None));+ out.push('\n');+ let mut rows = vec![vec![+ "command".to_string(),+ "count".to_string(),+ "total".to_string(),+ "max".to_string(),+ "avg".to_string(),+ ]];+ for stat in &self.by_type {+ rows.push(vec![+ stat.key.clone(),+ stat.count.to_string(),+ fmt_dur(stat.total),+ fmt_dur(stat.max),+ fmt_dur(stat.avg),+ ]);+ }+ out.push_str(&render_table(+ &rows,+ &[+ Align::Left,+ Align::Right,+ Align::Right,+ Align::Right,+ Align::Right,+ ],+ ));+ }++ if !self.slowest.is_empty() {+ out.push('\n');+ out.push_str(&format_heading("SLOWEST CALLS", None));+ out.push('\n');+ let rows: Vec<Vec<String>> = self+ .slowest+ .iter()+ .map(|s| vec![fmt_dur(s.duration), s.label.clone()])+ .collect();+ out.push_str(&render_table(&rows, &[Align::Right, Align::Left]));+ }++ let cache = &self.cache;+ out.push('\n');+ out.push_str(&format_heading("CACHE", None));+ out.push('\n');+ if cache.same_context_extra_calls == 0 {+ out.push_str(" no commands re-run with the same context\n");+ } else {+ out.push_str(&format!(+ " {} duplicate call{} wasting ~{} (same context, slowest run kept)\n",+ cache.same_context_extra_calls,+ plural(cache.same_context_extra_calls, "s"),+ fmt_dur(cache.same_context_extra),+ ));+ let rows: Vec<Vec<String>> = cache+ .same_context_duplicates+ .iter()+ .take(CACHE_OFFENDER_LIMIT)+ .map(|dup| {+ vec![+ fmt_dur(dup.extra),+ format!("{} (×{})", dup.command, dup.max_per_context),+ ]+ })+ .collect();+ out.push_str(&render_table(&rows, &[Align::Right, Align::Left]));+ let remaining = cache+ .same_context_duplicates+ .len()+ .saturating_sub(CACHE_OFFENDER_LIMIT);+ if remaining > 0 {+ out.push_str(&format!(+ " … and {remaining} more command{}\n",+ plural(remaining, "s")+ ));+ }+ }++ let ki = &self.key_intervals;+ if !ki.is_empty() {+ out.push('\n');+ out.push_str(&format_heading("KEY INTERVALS", None));+ out.push('\n');+ let items = [+ ("time to skeleton", ki.time_to_skeleton),+ ("time to first result", ki.time_to_first_result),+ ("parallel phase", ki.parallel_phase),+ ("collect total", ki.collect_total),+ ];+ let rows: Vec<Vec<String>> = items+ .iter()+ .filter_map(|(label, d)| d.map(|d| vec![label.to_string(), fmt_dur(d)]))+ .collect();+ out.push_str(&render_table(&rows, &[Align::Left, Align::Right]));+ }+ if self.collect_run && ki.time_to_skeleton.is_none() {+ out.push_str(&color_print::cformat!(+ " <dim>skeleton/first-result not recorded — these need an interactive terminal; re-run in a terminal, or use wt-perf timeline -- list --progressive</>\n"+ ));+ }++ if !self.phases.is_empty() {+ out.push('\n');+ out.push_str(&format_heading("PHASES", None));+ out.push('\n');+ let rows: Vec<Vec<String>> = self+ .phases+ .iter()+ .map(|p| {+ let delta = match p.delta {+ Some(d) => format!("+{}", fmt_dur(d)),+ None => String::new(),+ };+ vec![fmt_dur(p.at), delta, p.name.clone()]+ })+ .collect();+ out.push_str(&render_table(+ &rows,+ &[Align::Right, Align::Right, Align::Left],+ ));+ }++ out+ }+}++impl CacheReport {+ /// Build a redundant-command report from parsed trace entries.+ pub fn from_entries(entries: &[TraceEntry]) -> Self {+ let mut total_commands = 0;+ let mut cmd_counts: HashMap<&str, usize> = HashMap::new();+ let mut contexts: HashSet<&str> = HashSet::new();+ // (command, context) → durations of every run, in microseconds.+ let mut pair_durations: HashMap<(&str, &str), Vec<u64>> = HashMap::new();++ for entry in entries {+ if let TraceEntryKind::Command {+ command, duration, ..+ } = &entry.kind+ {+ let ctx = entry.context.as_deref().unwrap_or("(none)");+ *cmd_counts.entry(command.as_str()).or_default() += 1;+ pair_durations+ .entry((command.as_str(), ctx))+ .or_default()+ .push(duration.as_micros() as u64);+ contexts.insert(ctx);+ total_commands += 1;+ }+ }++ // Group same-context repeats by command.+ let mut by_command: BTreeMap<&str, Vec<(&str, &Vec<u64>)>> = BTreeMap::new();+ for ((cmd, ctx), durations) in &pair_durations {+ if durations.len() > 1 {+ by_command.entry(cmd).or_default().push((ctx, durations));+ }+ }++ let mut same_context_duplicates = Vec::new();+ let mut same_context_extra_calls = 0usize;+ let mut same_context_extra_us = 0u64;+ for (cmd, ctx_list) in &by_command {+ let max_per_context = ctx_list.iter().map(|(_, d)| d.len()).max().unwrap_or(0);+ let extra_calls: usize = ctx_list.iter().map(|(_, d)| d.len() - 1).sum();+ same_context_extra_calls += extra_calls;+ // Wasted time: keep the slowest run per context (the likely cold+ // call), sum the rest.+ let extra_us: u64 = ctx_list+ .iter()+ .map(|(_, durations)| {+ let max = durations.iter().max().copied().unwrap_or(0);+ durations.iter().sum::<u64>() - max+ })+ .sum();+ same_context_extra_us += extra_us;++ let mut context_stats: Vec<DuplicateContext> = ctx_list+ .iter()+ .map(|(ctx, durations)| DuplicateContext {+ context: (*ctx).to_string(),+ count: durations.len(),+ total: Duration::from_micros(durations.iter().sum()),+ })+ .collect();+ context_stats.sort_by(|a, b| {+ b.total+ .cmp(&a.total)+ .then_with(|| a.context.cmp(&b.context))+ });++ same_context_duplicates.push(DuplicateCommand {+ command: (*cmd).to_string(),+ max_per_context,+ extra_calls,+ extra: Duration::from_micros(extra_us),+ contexts: context_stats,+ });+ }+ same_context_duplicates.sort_by(|a, b| {+ b.extra+ .cmp(&a.extra)+ .then_with(|| a.command.cmp(&b.command))+ });++ let total_time_us: u64 = pair_durations.values().flat_map(|d| d.iter()).sum();+ let duplicated_commands = cmd_counts.values().filter(|c| **c > 1).count();+ let extra_calls = cmd_counts.values().filter(|c| **c > 1).map(|c| c - 1).sum();++ CacheReport {+ total_commands,+ unique_commands: cmd_counts.len(),+ contexts: contexts.len(),+ total_time: Duration::from_micros(total_time_us),+ duplicated_commands,+ extra_calls,+ same_context_duplicates,+ same_context_extra_calls,+ same_context_extra: Duration::from_micros(same_context_extra_us),+ }+ }+}++/// Parallelism factor and peak concurrency from timed subprocess intervals.+///+/// Factor is Σ(durations) ÷ wall span: 1.0 is serial, 4.0 means four+/// subprocesses ran concurrently on average. Peak is the most intervals+/// overlapping at any instant (a half-open sweep, so back-to-back commands+/// don't count as concurrent).+fn concurrency(intervals: &[(u64, u64)]) -> (Option<f64>, Option<usize>) {+ if intervals.is_empty() {+ return (None, None);+ }+ let span = intervals.iter().map(|(_, e)| *e).max().unwrap()+ - intervals.iter().map(|(s, _)| *s).min().unwrap();+ let total: u64 = intervals.iter().map(|(s, e)| e - s).sum();+ let parallelism = (span > 0).then(|| total as f64 / span as f64);++ let mut events: Vec<(u64, i32)> = Vec::with_capacity(intervals.len() * 2);+ for &(start, end) in intervals {+ events.push((start, 1));+ events.push((end, -1));+ }+ // Closings before openings at the same instant so adjacency isn't overlap.+ events.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));+ let mut current = 0i32;+ let mut peak = 0i32;+ for (_, delta) in events {+ current += delta;+ peak = peak.max(current);+ }+ (parallelism, Some(peak as usize))+}++#[derive(Clone, Copy)]+enum Align {+ Left,+ Right,+}++/// Pad rows into aligned columns, two spaces between columns, two-space indent.+///+/// Widths use `char` count — trace command shapes and durations are ASCII;+/// only a `[context]` (a branch name) can carry wide characters, and it sits in+/// the final left-aligned column. Trailing whitespace is trimmed per line.+///+/// Durations all render in one unit ([`fmt_dur`]) with two decimals, so+/// right-aligning a duration column lines up both the decimal points and the+/// `ms` suffix — no decimal-specific alignment is needed.+fn render_table(rows: &[Vec<String>], aligns: &[Align]) -> String {+ let cols = aligns.len();+ let mut widths = vec![0usize; cols];+ for row in rows {+ for (i, cell) in row.iter().enumerate() {+ widths[i] = widths[i].max(cell.chars().count());+ }+ }++ let mut out = String::new();+ for row in rows {+ let mut line = String::from(" ");+ for (i, cell) in row.iter().enumerate() {+ let last = i + 1 == row.len();+ let pad = widths[i].saturating_sub(cell.chars().count());+ match aligns[i] {+ Align::Left => {+ line.push_str(cell);+ if !last {+ line.push_str(&" ".repeat(pad));+ }+ }+ Align::Right => {+ line.push_str(&" ".repeat(pad));+ line.push_str(cell);+ }+ }+ if !last {+ line.push_str(" ");+ }+ }+ out.push_str(line.trim_end());+ out.push('\n');+ }+ out+}++/// Format a duration in milliseconds with two decimals — one unit everywhere so+/// every duration column aligns (decimals and the `ms` suffix line up under+/// right-alignment) regardless of magnitude.+fn fmt_dur(d: Duration) -> String {+ format!("{:.2}ms", d.as_micros() as f64 / 1_000.0)+}++fn plural(n: usize, suffix: &str) -> &str {+ if n == 1 { "" } else { suffix }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Strip ANSI so the heading colors don't clutter the snapshot.+ fn plain(s: String) -> String {+ anstream::adapter::strip_str(&s).to_string()+ }++ fn cmd(+ command: &str,+ ctx: Option<&str>,+ ts_us: u64,+ dur_us: u64,+ tid: u64,+ ok: bool,+ ) -> TraceEntry {+ TraceEntry {+ context: ctx.map(str::to_string),+ kind: TraceEntryKind::Command {+ command: command.to_string(),+ duration: Duration::from_micros(dur_us),+ result: TraceResult::Completed { success: ok },+ },+ start_time_us: Some(ts_us),+ thread_id: Some(tid),+ }+ }++ fn span(name: &str, ts_us: u64, dur_us: u64) -> TraceEntry {+ TraceEntry {+ context: None,+ kind: TraceEntryKind::Span {+ name: name.to_string(),+ duration: Duration::from_micros(dur_us),+ },+ start_time_us: Some(ts_us),+ thread_id: Some(1),+ }+ }++ fn instant(name: &str, ts_us: u64) -> TraceEntry {+ TraceEntry {+ context: None,+ kind: TraceEntryKind::Instant {+ name: name.to_string(),+ },+ start_time_us: Some(ts_us),+ thread_id: Some(1),+ }+ }++ #[test]+ fn command_type_keeps_program_and_subcommands() {+ // Stops at flags, refs, ranges, paths, and SHAs.+ assert_eq!(command_type("git status --porcelain"), "git status");+ assert_eq!(+ command_type("git rev-list --count HEAD...origin/main"),+ "git rev-list"+ );+ assert_eq!(+ command_type("git for-each-ref --format=%(refname) refs/heads/"),+ "git for-each-ref"+ );+ assert_eq!(command_type("gh pr list --json number"), "gh pr list");+ assert_eq!(+ command_type("git merge-base abc123 def456"),+ "git merge-base"+ );+ assert_eq!(command_type("git diff main...HEAD --shortstat"), "git diff");+ assert_eq!(command_type("claude -p 'summarize'"), "claude");+ // Leading global flags are skipped to reach the subcommand.+ assert_eq!(+ command_type("git --no-optional-locks status --porcelain"),+ "git status"+ );+ assert_eq!(command_type("git -c foo.bar=baz diff --stat"), "git diff");+ // Empty command string yields an empty key.+ assert_eq!(command_type(""), "");+ }++ #[test]+ fn fmt_dur_is_milliseconds() {+ // One unit everywhere, two decimals — sub-millisecond and multi-second alike.+ assert_eq!(fmt_dur(Duration::from_micros(53)), "0.05ms");+ assert_eq!(fmt_dur(Duration::from_micros(1_500)), "1.50ms");+ assert_eq!(fmt_dur(Duration::from_millis(826)), "826.00ms");+ assert_eq!(fmt_dur(Duration::from_secs(3)), "3000.00ms");+ assert_eq!(fmt_dur(Duration::from_micros(999_999)), "1000.00ms");+ assert_eq!(fmt_dur(Duration::ZERO), "0.00ms");+ }++ /// A collect run with only milestones (no subprocesses) and no skeleton:+ /// KEY INTERVALS shows the always-fire intervals, the note explains the+ /// absent skeleton/first-result milestones, and the empty subprocess sections+ /// are omitted.+ #[test]+ fn renders_collect_run_without_skeleton() {+ let entries = vec![+ instant("List collect started", 1_000),+ instant("Parallel execution started", 2_000),+ instant("All results drained", 8_000),+ instant("List collect complete", 9_000),+ ];+ let profile = Profile::from_entries(&entries);+ assert_eq!(profile.key_intervals.time_to_skeleton, None);+ insta::assert_snapshot!(plain(profile.render_text("trace.log")));+ }++ #[test]+ fn parallelism_and_peak_from_overlap() {+ // Three 10ms commands: two overlap on threads 1 & 2 (0–10ms), the third+ // runs alone after (10–20ms). Σ=30ms over a 20ms span → 1.5×; peak 2.+ let entries = vec![+ cmd("git status", Some("a"), 0, 10_000, 1, true),+ cmd("git status", Some("b"), 0, 10_000, 2, true),+ cmd("git diff", Some("a"), 10_000, 10_000, 1, true),+ ];+ let profile = Profile::from_entries(&entries);+ assert_eq!(profile.parallelism, Some(1.5));+ assert_eq!(profile.peak_concurrency, Some(2));+ assert_eq!(profile.thread_count, 2);+ assert_eq!(profile.command_total, Duration::from_millis(30));+ }++ #[test]+ fn cache_report_counts_same_context_repeats() {+ // `git config` runs 3× in context "a" (2 extra) and once in "b".+ let entries = vec![+ cmd("git config", Some("a"), 0, 5_000, 1, true),+ cmd("git config", Some("a"), 6_000, 4_000, 1, true),+ cmd("git config", Some("a"), 11_000, 3_000, 1, true),+ cmd("git config", Some("b"), 0, 2_000, 2, true),+ ];+ let cache = CacheReport::from_entries(&entries);+ assert_eq!(cache.same_context_extra_calls, 2);+ // Context "a": keep slowest (5ms), waste 4ms+3ms = 7ms.+ assert_eq!(cache.same_context_extra, Duration::from_millis(7));+ assert_eq!(cache.same_context_duplicates.len(), 1);+ assert_eq!(cache.same_context_duplicates[0].max_per_context, 3);+ }++ #[test]+ fn renders_full_report() {+ let entries = vec![+ instant("List collect started", 0),+ cmd(+ "git status --porcelain",+ Some("main"),+ 1_000,+ 12_000,+ 1,+ true,+ ),+ cmd(+ "git status --porcelain",+ Some("feature"),+ 1_000,+ 8_000,+ 2,+ true,+ ),+ span("user_config_load", 500, 2_000),+ instant("Skeleton rendered", 13_000),+ cmd(+ "git diff --shortstat",+ Some("main"),+ 13_000,+ 5_000,+ 1,+ false,+ ),+ cmd("git config --list", Some("main"), 1_000, 4_000, 1, true),+ cmd("git config --list", Some("main"), 6_000, 3_000, 1, true),+ instant("All results drained", 18_000),+ ];+ let profile = Profile::from_entries(&entries);+ insta::assert_snapshot!(plain(profile.render_text("trace.log")));+ }++ /// The JSON form (direct serialization of the struct — the single canonical+ /// source) carries the same analysis with microsecond durations, including+ /// nullable key-interval keys.+ #[test]+ fn to_json_shape() {+ let entries = vec![+ instant("List collect started", 0),+ instant("Skeleton rendered", 3_000),+ cmd("git status", Some("main"), 0, 5_000, 1, true),+ cmd("git status", Some("main"), 6_000, 4_000, 1, true),+ instant("List collect complete", 12_000),+ ];+ let profile = Profile::from_entries(&entries);+ insta::assert_snapshot!(serde_json::to_string_pretty(&profile).unwrap(), @r#"+ {+ "traced_us": 12000,+ "command_count": 2,+ "command_total_us": 9000,+ "span_total_us": 0,+ "parallelism": 0.9,+ "peak_concurrency": 1,+ "thread_count": 1,+ "key_intervals": {+ "time_to_skeleton_us": 3000,+ "time_to_first_result_us": null,+ "parallel_phase_us": null,+ "collect_total_us": 12000+ },+ "by_type": [+ {+ "command": "git status",+ "count": 2,+ "total_us": 9000,+ "max_us": 5000,+ "avg_us": 4500+ }+ ],+ "slowest": [+ {+ "dur_us": 5000,+ "label": "git status [main]"+ },+ {+ "dur_us": 4000,+ "label": "git status [main]"+ }+ ],+ "cache": {+ "total_commands": 2,+ "unique_commands": 1,+ "contexts": 1,+ "total_time_us": 9000,+ "duplicated_commands": 1,+ "extra_calls": 1,+ "same_context_duplicates": [+ {+ "command": "git status",+ "max_per_context": 2,+ "extra_calls": 1,+ "extra_us": 4000,+ "contexts": [+ {+ "context": "main",+ "count": 2,+ "total_us": 9000+ }+ ]+ }+ ],+ "same_context_extra_calls": 1,+ "same_context_extra_us": 4000+ },+ "phases": [+ {+ "name": "List collect started",+ "at_us": 0,+ "delta_us": null+ },+ {+ "name": "Skeleton rendered",+ "at_us": 3000,+ "delta_us": 3000+ },+ {+ "name": "List collect complete",+ "at_us": 12000,+ "delta_us": 9000+ }+ ]+ }+ "#);+ }++ /// A failed command, no timestamps, no repeats, no milestones: exercises the+ /// `(err: …)` label, the `n/a` parallelism/peak fallbacks, the+ /// no-duplicates cache line, and the omitted PHASES/in-process sections.+ #[test]+ fn renders_minimal_report_without_timestamps() {+ let err = |command: &str, dur_us: u64, message: &str| TraceEntry {+ context: None,+ kind: TraceEntryKind::Command {+ command: command.to_string(),+ duration: Duration::from_micros(dur_us),+ result: TraceResult::Error {+ message: message.to_string(),+ },+ },+ start_time_us: None,+ thread_id: None,+ };+ let ok = |command: &str, dur_us: u64| TraceEntry {+ context: None,+ kind: TraceEntryKind::Command {+ command: command.to_string(),+ duration: Duration::from_micros(dur_us),+ result: TraceResult::Completed { success: true },+ },+ start_time_us: None,+ thread_id: None,+ };+ let entries = vec![+ ok("git status", 5_000),+ err("git rev-list", 3_000, "bad revision"),+ ];+ let profile = Profile::from_entries(&entries);+ assert_eq!(profile.parallelism, None);+ assert_eq!(profile.peak_concurrency, None);+ insta::assert_snapshot!(plain(profile.render_text("trace.log")));+ }++ /// Many slow calls and several duplicate commands (one across two contexts):+ /// exercises slowest-list truncation, the cache `… and N more` collapse, and+ /// the per-context sort.+ #[test]+ fn truncates_slowest_and_collapses_cache() {+ let dup = |command: &str, ctx: &str, dur_us: u64| TraceEntry {+ context: Some(ctx.to_string()),+ kind: TraceEntryKind::Command {+ command: command.to_string(),+ duration: Duration::from_micros(dur_us),+ result: TraceResult::Completed { success: true },+ },+ start_time_us: None,+ thread_id: None,+ };+ // Four duplicated commands (waste aaa>bbb>ccc>ddd); ddd spans two+ // contexts. Ten calls total, so the eight-deep slowest list truncates.+ let entries = vec![+ dup("git aaa", "w1", 9_000),+ dup("git aaa", "w1", 8_000),+ dup("git bbb", "w1", 7_000),+ dup("git bbb", "w1", 6_000),+ dup("git ccc", "w1", 5_000),+ dup("git ccc", "w1", 4_000),+ dup("git ddd", "w1", 3_000),+ dup("git ddd", "w1", 2_000),+ dup("git ddd", "w2", 1_500),+ dup("git ddd", "w2", 1_000),+ ];+ let profile = Profile::from_entries(&entries);+ assert_eq!(profile.slowest.len(), SLOWEST_LIMIT);+ assert_eq!(profile.cache.same_context_duplicates.len(), 4);+ // ddd's contexts sort by total time: w1 (5ms) before w2 (2.5ms).+ let ddd = profile+ .cache+ .same_context_duplicates+ .iter()+ .find(|d| d.command == "git ddd")+ .unwrap();+ assert_eq!(+ ddd.contexts+ .iter()+ .map(|c| c.context.as_str())+ .collect::<Vec<_>>(),+ ["w1", "w2"]+ );+ insta::assert_snapshot!(plain(profile.render_text("trace.log")));+ }+}diff --git a/src/trace/snapshots/worktrunk__trace__profile__tests__renders_collect_run_without_skeleton.snap b/src/trace/snapshots/worktrunk__trace__profile__tests__renders_collect_run_without_skeleton.snapnew file mode 100644index 000000000..bc12a42f7--- /dev/null+++ b/src/trace/snapshots/worktrunk__trace__profile__tests__renders_collect_run_without_skeleton.snap@@ -0,0 +1,20 @@+---+source: src/trace/profile.rs+expression: "plain(profile.render_text(\"trace.log\"))"+---+PERFORMANCE PROFILE @ trace.log+ 0 subprocesses · 0.00ms subprocess time · parallelism n/a · peak n/a · traced 8.00ms++CACHE+ no commands re-run with the same context++KEY INTERVALS+ parallel phase 6.00ms+ collect total 8.00ms+ skeleton/first-result not recorded — these need an interactive terminal; re-run in a terminal, or use wt-perf timeline -- list --progressive++PHASES+ 0.00ms List collect started+ 1.00ms +1.00ms Parallel execution started+ 7.00ms +6.00ms All results drained+ 8.00ms +1.00ms List collect completediff --git a/src/trace/snapshots/worktrunk__trace__profile__tests__renders_full_report.snap b/src/trace/snapshots/worktrunk__trace__profile__tests__renders_full_report.snapnew file mode 100644index 000000000..4cf2ebeee--- /dev/null+++ b/src/trace/snapshots/worktrunk__trace__profile__tests__renders_full_report.snap@@ -0,0 +1,32 @@+---+source: src/trace/profile.rs+expression: "plain(profile.render_text(\"trace.log\"))"+---+PERFORMANCE PROFILE @ trace.log+ 5 subprocesses · 32.00ms subprocess time · parallelism 1.9× · peak 3 · 2 threads · traced 18.00ms · 2.00ms in-process++BY COMMAND TYPE+ command count total max avg+ git status 2 20.00ms 12.00ms 10.00ms+ git config 2 7.00ms 4.00ms 3.50ms+ git diff 1 5.00ms 5.00ms 5.00ms++SLOWEST CALLS+ 12.00ms git status --porcelain [main]+ 8.00ms git status --porcelain [feature]+ 5.00ms git diff --shortstat [main] (ok=false)+ 4.00ms git config --list [main]+ 3.00ms git config --list [main]+ 2.00ms span:user_config_load++CACHE+ 1 duplicate call wasting ~3.00ms (same context, slowest run kept)+ 3.00ms git config --list (×2)++KEY INTERVALS+ time to skeleton 13.00ms++PHASES+ 0.00ms List collect started+ 13.00ms +13.00ms Skeleton rendered+ 18.00ms +5.00ms All results draineddiff --git a/src/trace/snapshots/worktrunk__trace__profile__tests__renders_minimal_report_without_timestamps.snap b/src/trace/snapshots/worktrunk__trace__profile__tests__renders_minimal_report_without_timestamps.snapnew file mode 100644index 000000000..35c6a8552--- /dev/null+++ b/src/trace/snapshots/worktrunk__trace__profile__tests__renders_minimal_report_without_timestamps.snap@@ -0,0 +1,18 @@+---+source: src/trace/profile.rs+expression: "plain(profile.render_text(\"trace.log\"))"+---+PERFORMANCE PROFILE @ trace.log+ 2 subprocesses · 8.00ms subprocess time · parallelism n/a · peak n/a++BY COMMAND TYPE+ command count total max avg+ git status 1 5.00ms 5.00ms 5.00ms+ git rev-list 1 3.00ms 3.00ms 3.00ms++SLOWEST CALLS+ 5.00ms git status+ 3.00ms git rev-list (err: bad revision)++CACHE+ no commands re-run with the same contextdiff --git a/src/trace/snapshots/worktrunk__trace__profile__tests__truncates_slowest_and_collapses_cache.snap b/src/trace/snapshots/worktrunk__trace__profile__tests__truncates_slowest_and_collapses_cache.snapnew file mode 100644index 000000000..30784132e--- /dev/null+++ b/src/trace/snapshots/worktrunk__trace__profile__tests__truncates_slowest_and_collapses_cache.snap@@ -0,0 +1,30 @@+---+source: src/trace/profile.rs+expression: "plain(profile.render_text(\"trace.log\"))"+---+PERFORMANCE PROFILE @ trace.log+ 10 subprocesses · 46.50ms subprocess time · parallelism n/a · peak n/a++BY COMMAND TYPE+ command count total max avg+ git aaa 2 17.00ms 9.00ms 8.50ms+ git bbb 2 13.00ms 7.00ms 6.50ms+ git ccc 2 9.00ms 5.00ms 4.50ms+ git ddd 4 7.50ms 3.00ms 1.88ms++SLOWEST CALLS+ 9.00ms git aaa [w1]+ 8.00ms git aaa [w1]+ 7.00ms git bbb [w1]+ 6.00ms git bbb [w1]+ 5.00ms git ccc [w1]+ 4.00ms git ccc [w1]+ 3.00ms git ddd [w1]+ 2.00ms git ddd [w1]++CACHE+ 5 duplicate calls wasting ~21.00ms (same context, slowest run kept)+ 8.00ms git aaa (×2)+ 6.00ms git bbb (×2)+ 4.00ms git ccc (×2)+ … and 1 more commanddiff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rsindex 56297094c..1ad8516f4 100644--- a/tests/helpers/wt-perf/src/main.rs+++ b/tests/helpers/wt-perf/src/main.rs@@ -466,101 +466,14 @@ fn read_trace_entries(file: Option<&std::path::Path>) -> Vec<worktrunk::trace::T/// Analyze trace entries for cache effectiveness.///-/// Outputs structured JSON to stdout, composable with jq.-///-/// For each (command, context) pair called N times, the first call is "necessary"-/// and the remaining N-1 are "extra". Wasted time is computed by keeping the-/// slowest call (likely a cache-miss/cold call) and summing the rest.+/// Outputs structured JSON to stdout, composable with jq. The analysis lives in+/// `worktrunk::trace::CacheReport` so `wt config state logs profile` and this+/// helper share one implementation: each `(command, context)` pair run N times+/// counts the first call as necessary and the rest as extra, with wasted time+/// summed over all but the slowest (likely cold) run per context.fn cache_check(entries: &[worktrunk::trace::TraceEntry]) {- use std::collections::{BTreeMap, HashMap, HashSet};- use worktrunk::trace::TraceEntryKind;-- let mut total_commands = 0;- let mut cmd_counts: HashMap<&str, usize> = HashMap::new();- let mut contexts: HashSet<&str> = HashSet::new();-- // Collect all durations per (command, context) pair- let mut pair_durations: HashMap<(&str, &str), Vec<u64>> = HashMap::new();-- for entry in entries {- if let TraceEntryKind::Command {- command, duration, ..- } = &entry.kind- {- let ctx = entry.context.as_deref().unwrap_or("(none)");- *cmd_counts.entry(command.as_str()).or_default() += 1;- pair_durations- .entry((command.as_str(), ctx))- .or_default()- .push(duration.as_micros() as u64);- contexts.insert(ctx);- total_commands += 1;- }- }-- // Build structured duplicates list: group by command- let mut cmd_ctx_info: BTreeMap<&str, Vec<(&str, &Vec<u64>)>> = BTreeMap::new();- for ((cmd, ctx), durations) in &pair_durations {- if durations.len() > 1 {- cmd_ctx_info.entry(cmd).or_default().push((ctx, durations));- }- }-- let mut duplicates = Vec::new();- let mut total_extra = 0usize;- let mut total_extra_us = 0u64;- for (cmd, ctx_list) in &cmd_ctx_info {- let max_count = ctx_list.iter().map(|(_, d)| d.len()).max().unwrap();- let extra: usize = ctx_list.iter().map(|(_, d)| d.len() - 1).sum();- total_extra += extra;-- // Wasted time: for each context, keep the slowest call, sum the rest- let extra_us: u64 = ctx_list- .iter()- .map(|(_, durations)| {- let max = durations.iter().max().unwrap();- durations.iter().sum::<u64>() - max- })- .sum();- total_extra_us += extra_us;-- let contexts: Vec<_> = ctx_list- .iter()- .map(|(ctx, durations)| {- let total_us: u64 = durations.iter().sum();- serde_json::json!({- "context": ctx,- "count": durations.len(),- "total_us": total_us,- })- })- .collect();- duplicates.push(serde_json::json!({- "command": cmd,- "max_per_context": max_count,- "extra_calls": extra,- "extra_us": extra_us,- "contexts": contexts,- }));- }- duplicates.sort_by(|a, b| b["extra_us"].as_u64().cmp(&a["extra_us"].as_u64()));-- let total_time_us: u64 = pair_durations.values().flat_map(|d| d.iter()).sum();- let dup_count = cmd_counts.values().filter(|c| **c > 1).count();- let dup_total: usize = cmd_counts.values().filter(|c| **c > 1).map(|c| c - 1).sum();-- let output = serde_json::json!({- "total_commands": total_commands,- "unique_commands": cmd_counts.len(),- "contexts": contexts.len(),- "total_time_us": total_time_us,- "duplicated_commands": dup_count,- "extra_calls": dup_total,- "same_context_duplicates": duplicates,- "same_context_extra_calls": total_extra,- "same_context_extra_us": total_extra_us,- });- println!("{}", serde_json::to_string_pretty(&output).unwrap());+ let report = worktrunk::trace::CacheReport::from_entries(entries);+ println!("{}", serde_json::to_string_pretty(&report).unwrap());}#[cfg(test)]diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 1f15b993a..7f88f0a8a 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -331,6 +331,298 @@ fn test_state_bare_logs(repo: TestRepo) {assert!(output.status.success());}+/// A synthetic `-vv` trace: two parallel `git status` runs, an in-process span,+/// a failed `git diff`, and a `git config` run twice in the same context (the+/// cache-miss the profile flags), bracketed by milestone events.+const PROFILE_FIXTURE_TRACE: &str = r#"[wt-trace] ts=1000 tid=1 event="List collect started"+[wt-trace] ts=1000 tid=1 context=main cmd="git status --porcelain" dur_us=12000 ok=true+[wt-trace] ts=1000 tid=2 context=feature cmd="git status --porcelain" dur_us=8000 ok=true+[wt-trace] ts=500 tid=1 span="user_config_load" dur_us=2000+[wt-trace] ts=13000 tid=1 event="Skeleton rendered"+[wt-trace] ts=13000 tid=1 context=main cmd="git diff --shortstat" dur_us=5000 ok=false+[wt-trace] ts=1000 tid=1 context=main cmd="git config --list" dur_us=4000 ok=true+[wt-trace] ts=6000 tid=1 context=main cmd="git config --list" dur_us=3000 ok=true+[wt-trace] ts=18000 tid=1 event="All results drained"+"#;++/// Run `wt config state logs profile <args>` with `input` on stdin.+fn profile_from_stdin(repo: &TestRepo, args: &[&str], input: &str) -> std::process::Output {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["config", "state", "logs", "profile"]);+ cmd.args(args);+ cmd.current_dir(repo.root_path());+ cmd.stdin(Stdio::piped());+ cmd.stdout(Stdio::piped());+ cmd.stderr(Stdio::piped());+ let mut child = cmd.spawn().unwrap();+ child+ .stdin+ .take()+ .unwrap()+ .write_all(input.as_bytes())+ .unwrap();+ child.wait_with_output().unwrap()+}++/// `wt config state logs profile -` reads a trace from stdin and reports where+/// time went, how parallel the run was, and any same-context cache misses.+#[rstest]+fn test_logs_profile_from_stdin(repo: TestRepo) {+ let output = profile_from_stdin(&repo, &["-"], PROFILE_FIXTURE_TRACE);+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));+}++/// `--format=json` emits the same analysis as machine-readable data.+#[rstest]+fn test_logs_profile_json(repo: TestRepo) {+ let output = profile_from_stdin(&repo, &["-", "--format=json"], PROFILE_FIXTURE_TRACE);+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"+ {+ "traced_us": 17500,+ "command_count": 5,+ "command_total_us": 32000,+ "span_total_us": 2000,+ "parallelism": 1.8823529411764706,+ "peak_concurrency": 3,+ "thread_count": 2,+ "key_intervals": {+ "time_to_skeleton_us": 12000,+ "time_to_first_result_us": null,+ "parallel_phase_us": null,+ "collect_total_us": null+ },+ "by_type": [+ {+ "command": "git status",+ "count": 2,+ "total_us": 20000,+ "max_us": 12000,+ "avg_us": 10000+ },+ {+ "command": "git config",+ "count": 2,+ "total_us": 7000,+ "max_us": 4000,+ "avg_us": 3500+ },+ {+ "command": "git diff",+ "count": 1,+ "total_us": 5000,+ "max_us": 5000,+ "avg_us": 5000+ }+ ],+ "slowest": [+ {+ "dur_us": 12000,+ "label": "git status --porcelain [main]"+ },+ {+ "dur_us": 8000,+ "label": "git status --porcelain [feature]"+ },+ {+ "dur_us": 5000,+ "label": "git diff --shortstat [main] (ok=false)"+ },+ {+ "dur_us": 4000,+ "label": "git config --list [main]"+ },+ {+ "dur_us": 3000,+ "label": "git config --list [main]"+ },+ {+ "dur_us": 2000,+ "label": "span:user_config_load"+ }+ ],+ "cache": {+ "total_commands": 5,+ "unique_commands": 3,+ "contexts": 2,+ "total_time_us": 32000,+ "duplicated_commands": 2,+ "extra_calls": 2,+ "same_context_duplicates": [+ {+ "command": "git config --list",+ "max_per_context": 2,+ "extra_calls": 1,+ "extra_us": 3000,+ "contexts": [+ {+ "context": "main",+ "count": 2,+ "total_us": 7000+ }+ ]+ }+ ],+ "same_context_extra_calls": 1,+ "same_context_extra_us": 3000+ },+ "phases": [+ {+ "name": "List collect started",+ "at_us": 500,+ "delta_us": null+ },+ {+ "name": "Skeleton rendered",+ "at_us": 12500,+ "delta_us": 12000+ },+ {+ "name": "All results drained",+ "at_us": 17500,+ "delta_us": 5000+ }+ ]+ }+ "#);+}++/// A trace log given as a path argument is read directly.+#[rstest]+fn test_logs_profile_from_file(repo: TestRepo) {+ let trace = repo.root_path().join("captured.log");+ std::fs::write(&trace, PROFILE_FIXTURE_TRACE).unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["config", "state", "logs", "profile"]);+ cmd.arg(&trace);+ cmd.current_dir(repo.root_path());+ let output = cmd.output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("PERFORMANCE PROFILE"), "stdout: {stdout}");+}++/// A missing path argument fails, naming the file it could not read.+#[rstest]+fn test_logs_profile_file_missing(repo: TestRepo) {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["config", "state", "logs", "profile", "no-such-trace.log"]);+ cmd.current_dir(repo.root_path());+ let output = cmd.output().unwrap();+ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Failed to read trace log"),+ "stderr: {stderr}"+ );+}++/// With no argument, the profile reads the repo's `.git/wt/logs/trace.log`.+#[rstest]+fn test_logs_profile_default_path(repo: TestRepo) {+ let logs_dir = repo.root_path().join(".git/wt/logs");+ std::fs::create_dir_all(&logs_dir).unwrap();+ std::fs::write(logs_dir.join("trace.log"), PROFILE_FIXTURE_TRACE).unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["config", "state", "logs", "profile"]);+ cmd.current_dir(repo.root_path());+ let output = cmd.output().unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("PERFORMANCE PROFILE"), "stdout: {stdout}");+ assert!(stdout.contains("BY COMMAND TYPE"), "stdout: {stdout}");+}++/// An input with no `[wt-trace]` records fails, pointing at `-vv`.+#[rstest]+fn test_logs_profile_no_records(repo: TestRepo) {+ let output = profile_from_stdin(&repo, &["-"], "not a trace line\nanother line\n");+ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(stderr.contains("No [wt-trace] records"), "stderr: {stderr}");+ assert!(stderr.contains("-vv"), "stderr: {stderr}");+}++/// End-to-end: a real `wt -vv list` capture must yield the always-fire key+/// intervals. Guards against a milestone-string rename at the emit sites in+/// `src/commands/list/collect/mod.rs` drifting from the `M_*` constants in+/// `src/trace/profile.rs` — only this test exercises the real emit→profile path.+#[rstest]+fn test_logs_profile_real_capture_has_key_intervals(repo: TestRepo) {+ // `-vv` writes the trace log. stdout is a pipe here, so the TTY-gated+ // skeleton/first-result milestones don't fire, but the four always-fire+ // collect milestones do.+ let mut list = wt_command();+ repo.configure_wt_cmd(&mut list);+ list.args(["-vv", "list"]);+ list.current_dir(repo.root_path());+ assert!(list.output().unwrap().status.success());++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["config", "state", "logs", "profile", "--format=json"]);+ cmd.current_dir(repo.root_path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let intervals = &json["key_intervals"];+ assert!(+ intervals["collect_total_us"].is_u64(),+ "collect_total missing — a collect milestone string likely drifted: {intervals}"+ );+ assert!(+ intervals["parallel_phase_us"].is_u64(),+ "parallel_phase missing — a collect milestone string likely drifted: {intervals}"+ );+}++/// Without a trace log, the error names the missing file and points at `-vv`.+#[rstest]+fn test_logs_profile_missing(repo: TestRepo) {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["config", "state", "logs", "profile"]);+ cmd.current_dir(repo.root_path());+ let output = cmd.output().unwrap();+ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(stderr.contains("No trace log at"), "stderr: {stderr}");+ assert!(stderr.contains("-vv"), "stderr: {stderr}");+}++/// With no FILE argument and no surrounding git repository, the error explains+/// the absent default trace log and points at the path / `-` (stdin)+/// alternatives, rather than surfacing a bare git "not a repository" error.+/// `wt_command()`'s default cwd is a process-scoped tempdir outside any repo.+#[rstest]+fn test_logs_profile_no_repo() {+ let output = wt_command()+ .args(["config", "state", "logs", "profile"])+ .output()+ .unwrap();+ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Not inside a git repository"),+ "stderr: {stderr}"+ );+ // The `-` is bold-wrapped (`\x1b[1m-\x1b[22m`), so assert on the surrounding+ // unstyled text rather than a substring that crosses the ANSI boundary.+ assert!(stderr.contains("pass a trace log path"), "stderr: {stderr}");+ assert!(stderr.contains("for stdin"), "stderr: {stderr}");+}+/// `wt config state hints` (no subcommand) defaults to `get`.#[rstest]fn test_state_bare_hints(repo: TestRepo) {diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rsindex cbf21375b..cb5a8b860 100644--- a/tests/integration_tests/diagnostic.rs+++ b/tests/integration_tests/diagnostic.rs@@ -75,6 +75,12 @@ fn test_diagnostic_report_file_format(mut repo: TestRepo) {"Diagnostic should include trace log section when run with -vv");+ // The rendered performance profile rides alongside the raw trace.+ assert!(+ content.contains("<summary>Performance profile</summary>"),+ "Diagnostic should include a performance profile section when run with -vv"+ );+let settings = setup_snapshot_settings(&repo);settings.bind(|| {assert_snapshot!("diagnostic_file_format", normalize_report(&content));@@ -997,6 +1003,22 @@ fn normalize_report(content: &str) -> String {.replace_all(&result, "$1 $2").to_string();+ // Truncate performance profile section - its durations and by-type/slowest+ // ordering depend on the run's real timing, so exact comparison is flaky.+ // We verify the section exists separately in the test.+ if let Some(start) = result.find("<summary>Performance profile</summary>") {+ // Find the closing </details> after this point+ if let Some(end_offset) = result[start..].find("</details>") {+ let end = start + end_offset + "</details>".len();+ let before = &result[..start];+ let after = &result[end..];+ result = format!(+ "{}<summary>Performance profile</summary>\n\n[PERFORMANCE_PROFILE_CONTENT]\n</details>{}",+ before, after+ );+ }+ }+// Truncate trace log section - it has parallel git commands that interleave// in different orders, making exact snapshot comparison flaky.// We verify the section exists separately in the test.diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rsindex b19bad9a7..7f0486287 100644--- a/tests/integration_tests/help.rs+++ b/tests/integration_tests/help.rs@@ -96,6 +96,7 @@ fn snapshot_help(test_name: &str, args: &[&str]) {#[case("help_config_state_ci_status", "config state ci-status --help")]#[case("help_config_state_marker", "config state marker --help")]#[case("help_config_state_logs", "config state logs --help")]+#[case("help_config_state_logs_profile", "config state logs profile --help")]#[case("help_config_state_get", "config state get --help")]#[case("help_config_state_clear", "config state clear --help")]#[case("help_config_approvals", "config approvals --help")]diff --git a/tests/snapshots/integration__integration_tests__config_state__logs_profile_from_stdin.snap b/tests/snapshots/integration__integration_tests__config_state__logs_profile_from_stdin.snapnew file mode 100644index 000000000..527694e47--- /dev/null+++ b/tests/snapshots/integration__integration_tests__config_state__logs_profile_from_stdin.snap@@ -0,0 +1,32 @@+---+source: tests/integration_tests/config_state.rs+expression: "String::from_utf8_lossy(&output.stdout)"+---+[36mPERFORMANCE PROFILE[39m @ stdin+ 5 subprocesses · 32.00ms subprocess time · parallelism 1.9× · peak 3 · 2 threads · traced 17.50ms · 2.00ms in-process++[36mBY COMMAND TYPE[39m+ command count total max avg+ git status 2 20.00ms 12.00ms 10.00ms+ git config 2 7.00ms 4.00ms 3.50ms+ git diff 1 5.00ms 5.00ms 5.00ms++[36mSLOWEST CALLS[39m+ 12.00ms git status --porcelain [main]+ 8.00ms git status --porcelain [feature]+ 5.00ms git diff --shortstat [main] (ok=false)+ 4.00ms git config --list [main]+ 3.00ms git config --list [main]+ 2.00ms span:user_config_load++[36mCACHE[39m+ 1 duplicate call wasting ~3.00ms (same context, slowest run kept)+ 3.00ms git config --list (×2)++[36mKEY INTERVALS[39m+ time to skeleton 12.00ms++[36mPHASES[39m+ 0.50ms List collect started+ 12.50ms +12.00ms Skeleton rendered+ 17.50ms +5.00ms All results draineddiff --git a/tests/snapshots/integration__integration_tests__diagnostic__diagnostic_file_format.snap b/tests/snapshots/integration__integration_tests__diagnostic__diagnostic_file_format.snapindex e984646d2..ab13625b6 100644--- a/tests/snapshots/integration__integration_tests__diagnostic__diagnostic_file_format.snap+++ b/tests/snapshots/integration__integration_tests__diagnostic__diagnostic_file_format.snap@@ -56,6 +56,12 @@ Project config: _REPO_/.config/wt.toml```</details>+<details>+<summary>Performance profile</summary>++[PERFORMANCE_PROFILE_CONTENT]+</details>+<details><summary>Trace log</summary>diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snapindex f180cf283..7fb04f29d 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap@@ -39,8 +39,9 @@ wt config state logs - Operation and debug logsUsage: [1m[36mwt config state logs[0m [36m[OPTIONS][0m [36m[COMMAND][0m[1m[32mCommands:[0m- [1m[36mget[0m List all log file paths- [1m[36mclear[0m Clear all log files+ [1m[36mget[0m List all log file paths+ [1m[36mprofile[0m Performance profile from a trace log+ [1m[36mclear[0m Clear all log files[1m[32mOptions:[0m[1m[36m-h[0m, [1m[36m--help[0m@@ -106,7 +107,7 @@ All [2mpost-*[0m hooks (post-start, post-switch, post-commit, post-merge) run[2msubprocess.log[0m Running with [2m-vv[0m[2mdiagnostic.md[0m Running with [2m-vv[0m-[2mtrace.log[0m captures debug-level records at [2m-vv[0m — commands, [2m[wt-trace][0m records, bounded subprocess previews. [2msubprocess.log[0m holds the raw uncapped subprocess stdout/stderr bodies. [2mdiagnostic.md[0m is a markdown bug-report bundle that inlines [2mtrace.log[0m; [2mwt[0m prints a [2mgh gist create[0m command pointing at it. All three are overwritten on each [2m-vv[0m run.+[2mtrace.log[0m captures debug-level records at [2m-vv[0m — commands, [2m[wt-trace][0m records, bounded subprocess previews. [2mwt config state logs profile[0m summarizes one into a performance report (where time went, parallelism, redundant commands). [2msubprocess.log[0m holds the raw uncapped subprocess stdout/stderr bodies. [2mdiagnostic.md[0m is a markdown bug-report bundle that inlines [2mtrace.log[0m; [2mwt[0m prints a [2mgh gist create[0m command pointing at it. All three are overwritten on each [2m-vv[0m run.[1m[32mLocation[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_logs_profile.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_logs_profile.snapnew file mode 100644index 000000000..ee1fb2c22--- /dev/null+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_logs_profile.snap@@ -0,0 +1,90 @@+---+source: tests/integration_tests/help.rs+info:+ program: wt+ args:+ - config+ - state+ - logs+ - profile+ - "--help"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ TERM: alacritty+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+---+success: true+exit_code: 0+----- stdout -----+wt config state logs profile - Performance profile from a trace log++Usage: [1m[36mwt config state logs profile[0m [36m[OPTIONS][0m [36m[FILE][0m++[1m[32mArguments:[0m+ [36m[FILE][0m+ Trace log to read (defaults to [1m.git/wt/logs/trace.log[0m; [1m-[0m for stdin)++[1m[32mOptions:[0m+ [1m[36m-h[0m, [1m[36m--help[0m+ Print help (see a summary with '-h')++[1m[32mOutput:[0m+ [1m[36m--format[0m[36m [0m[36m<FORMAT>[0m+ Output format (text, json) [default: text]++[1m[32mGlobal Options:[0m+ [1m[36m-C[0m[36m [0m[36m<path>[0m+ Working directory for this command++ [1m[36m--config[0m[36m [0m[36m<path>[0m+ User config file path++ [1m[36m--config-set[0m[36m [0m[36m<toml>[0m+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ [1m[36m-v[0m, [1m[36m--verbose[0m[36m...[0m+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to apply the same level everywhere — including shell completion, which no flag can reach++ [1m[36m-y[0m, [1m[36m--yes[0m+ Skip approval prompts++Summarize where a single [2mwt[0m invocation spent its time, reading the [2m[wt-trace][0m records captured to [2mtrace.log[0m by a [2m-vv[0m run.++Reads [2m.git/wt/logs/trace.log[0m by default, or a log file given as an argument (e.g. a CI artifact, or [2m-[0m for stdin). The report answers three questions: where time goes (subprocess time by command type, plus the slowest individual jobs), how parallel the run was (concurrency factor and peak concurrency), and where work was wasted (commands re-run with the same context). For a [2mwt list[0m capture it also shows derived latencies (time to skeleton, time to first result) and a timeline of collect+milestones; the skeleton/first-result markers need a terminal (TTY) capture. [2m--format=json[0m emits the same data for scripting.++For an interactive timeline or a Perfetto trace, use the [2mwt-perf[0m helper ([2mcargo run -p wt-perf -- timeline[0m); both share the same trace parser.++[1m[32mExamples[0m++Profile the last [2m-vv[0m run in this repo:+[107m [0m [2m[0m[2m[34mwt[0m[2m [0m[2m[36m-vv[0m[2m list[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m config state logs profile[0m++Profile a trace from elsewhere (e.g. a CI artifact), by path or on stdin:+[107m [0m [2m[0m[2m[34mwt[0m[2m config state logs profile ci-run.log[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m config state logs profile [0m[2m[36m-[0m[2m [0m[2m[36m<[0m[2m ci-run.log[0m++JSON for scripting:+[107m [0m [2m[0m[2m[34mwt[0m[2m config state logs profile [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[32m'.by_type[0]'[0m++----- stderr -----