Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(trace): don't flag stdin-driven commands as cache duplicates (#3296)
Maximilian Roosbfdb22b88906
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rsindex a7d1bd711..e98899ac4 100644--- a/src/commands/run_pipeline.rs+++ b/src/commands/run_pipeline.rs@@ -160,8 +160,10 @@ fn spawn_shell_command(.try_clone().context("failed to clone log file handle")?;// Start the trace just before spawning; the caller resolves it once the- // child is waited on (see `wait_resolving`).- let mut trace = CommandTrace::new(None, expanded);+ // child is waited on (see `wait_resolving`). The step is fed its own+ // `context_json` on stdin, so mark it stdin-reading — the same command+ // across worktrees isn't a duplicate (different per-worktree input).+ let mut trace = CommandTrace::new(None, expanded).reads_stdin(true);let mut child = match shell.command(expanded).current_dir(worktree_path)diff --git a/src/logging.rs b/src/logging.rsindex 9f92a4f06..fe0b62ade 100644--- a/src/logging.rs+++ b/src/logging.rs@@ -214,6 +214,9 @@ struct WtTraceFields {seq: Option<u64>,dur_us: Option<u64>,ok: Option<bool>,+ /// `true` when the command consumed stdin uncaptured by `cmd`; rendered as a+ /// trailing `stdin=true` only when true (omitted otherwise, like `context`).+ stdin: Option<bool>,context: Option<String>,cmd: Option<String>,err: Option<String>,@@ -233,8 +236,10 @@ impl tracing::field::Visit for WtTraceFields {}fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {- if field.name() == "ok" {- self.ok = Some(value);+ match field.name() {+ "ok" => self.ok = Some(value),+ "stdin" => self.stdin = Some(value),+ _ => {}}}@@ -289,13 +294,20 @@ fn format_wt_trace(f: &WtTraceFields) -> String {let cmd = f.cmd.as_deref().unwrap_or("");let dur_us = f.dur_us.unwrap_or(0);let ok = f.ok.unwrap_or(false);+ // Only commands that read stdin carry the marker; omit it otherwise+ // so the overwhelmingly common no-stdin record stays lean.+ let stdin = if f.stdin == Some(true) {+ " stdin=true"+ } else {+ ""+ };match &f.context {Some(ctx) => format!(- r#"[wt-trace] ts={ts} tid={tid} seq={seq} context={ctx} cmd="{cmd}" dur_us={dur_us} ok={ok}"#+ r#"[wt-trace] ts={ts} tid={tid} seq={seq} context={ctx} cmd="{cmd}" dur_us={dur_us} ok={ok}{stdin}"#),None => {format!(- r#"[wt-trace] ts={ts} tid={tid} seq={seq} cmd="{cmd}" dur_us={dur_us} ok={ok}"#+ r#"[wt-trace] ts={ts} tid={tid} seq={seq} cmd="{cmd}" dur_us={dur_us} ok={ok}{stdin}"#)}}@@ -305,12 +317,17 @@ fn format_wt_trace(f: &WtTraceFields) -> String {let cmd = f.cmd.as_deref().unwrap_or("");let dur_us = f.dur_us.unwrap_or(0);let err = f.err.as_deref().unwrap_or("");+ let stdin = if f.stdin == Some(true) {+ " stdin=true"+ } else {+ ""+ };match &f.context {Some(ctx) => format!(- r#"[wt-trace] ts={ts} tid={tid} seq={seq} context={ctx} cmd="{cmd}" dur_us={dur_us} err="{err}""#+ r#"[wt-trace] ts={ts} tid={tid} seq={seq} context={ctx} cmd="{cmd}" dur_us={dur_us} err="{err}"{stdin}"#),None => format!(- r#"[wt-trace] ts={ts} tid={tid} seq={seq} cmd="{cmd}" dur_us={dur_us} err="{err}""#+ r#"[wt-trace] ts={ts} tid={tid} seq={seq} cmd="{cmd}" dur_us={dur_us} err="{err}"{stdin}"#),}}@@ -965,6 +982,42 @@ mod tests {r#"[wt-trace] ts=100 tid=3 seq=4 cmd="gh pr list" dur_us=1000 err="network down""#);+ // cmd_completed reading stdin — `stdin=true` trails the record; a+ // stdin-less record (stdin None/Some(false)) omits the field entirely,+ // as every fixture above shows.+ let f = WtTraceFields {+ kind: Some("cmd_completed".into()),+ ts: Some(100),+ tid: Some(3),+ seq: Some(5),+ cmd: Some("git patch-id --verbatim".into()),+ dur_us: Some(640),+ ok: Some(true),+ stdin: Some(true),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 seq=5 cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true"#+ );++ // cmd_errored reading stdin — `stdin=true` trails the err field.+ let f = WtTraceFields {+ kind: Some("cmd_errored".into()),+ ts: Some(100),+ tid: Some(3),+ seq: Some(6),+ cmd: Some("claude -p".into()),+ dur_us: Some(900),+ err: Some("boom".into()),+ stdin: Some(true),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 seq=6 cmd="claude -p" dur_us=900 err="boom" stdin=true"#+ );+// instantlet f = WtTraceFields {kind: Some("instant".into()),diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex 6d3d01aac..55e579a70 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -320,7 +320,9 @@ fn spawn_child(// Start the trace just before spawning so its duration brackets the real// spawn → wait span (the child keeps running while we drain its output).- let mut trace = CommandTrace::new(None, cmd.expanded);+ // Each child is fed its own `context_json` on stdin, so mark it stdin-reading+ // — the same command across worktrees isn't a duplicate (different input).+ let mut trace = CommandTrace::new(None, cmd.expanded).reads_stdin(true);let mut child = match command.spawn() {Ok(child) => child,Err(e) => {diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 8dd03f7ad..7b619417a 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -1223,7 +1223,8 @@ impl Cmd {// Acquire semaphore to limit concurrent commandslet _guard = semaphore().acquire();- let mut trace = CommandTrace::new(self.context.as_deref(), &cmd_str);+ let mut trace = CommandTrace::new(self.context.as_deref(), &cmd_str)+ .reads_stdin(self.stdin_data.is_some());if let Err(e) = self.check_spawn_preconditions() {trace.fail(&e);@@ -1346,11 +1347,19 @@ impl Cmd {// yet, so a precondition failure emits a one-shot failed record rather// than holding a guard across an execution that never happens.if let Err(e) = self.check_spawn_preconditions() {- CommandTrace::record_failed(self.context.as_deref(), &first_cmd_str, &e);+ // stdin_data is still owned here (taken below), so it reflects+ // whether the source would have read a buffer; the sink always reads+ // the upstream pipe.+ CommandTrace::record_failed(+ self.context.as_deref(),+ &first_cmd_str,+ self.stdin_data.is_some(),+ &e,+ );return Err(e);}if let Err(e) = next.check_spawn_preconditions() {- CommandTrace::record_failed(next.context.as_deref(), &second_cmd_str, &e);+ CommandTrace::record_failed(next.context.as_deref(), &second_cmd_str, true, &e);return Err(e);}@@ -1368,8 +1377,10 @@ impl Cmd {.stderr(Stdio::piped());// Trace each command from just before its own spawn so the duration- // brackets the real spawn → wait span.- let mut first_trace = CommandTrace::new(self.context.as_deref(), &first_cmd_str);+ // brackets the real spawn → wait span. The source reads stdin only when+ // fed a buffer; the sink always reads it (the source's piped stdout).+ let mut first_trace = CommandTrace::new(self.context.as_deref(), &first_cmd_str)+ .reads_stdin(source_stdin.is_some());let mut first_child = match first.spawn() {Ok(child) => child,Err(e) => {@@ -1401,7 +1412,8 @@ impl Cmd {// Spawn `next` before waiting on either child so `self`'s stdout keeps// flowing through the pipe (otherwise a full pipe buffer would wedge// `self`). If the spawn itself fails, clean up `self` before returning.- let mut second_trace = CommandTrace::new(next.context.as_deref(), &second_cmd_str);+ let mut second_trace =+ CommandTrace::new(next.context.as_deref(), &second_cmd_str).reads_stdin(true);let second_child = match second.spawn() {Ok(child) => child,Err(e) => {@@ -1532,7 +1544,12 @@ impl Cmd {if let Err(e) = self.check_spawn_preconditions() {// Nothing spawned yet — emit a one-shot failed record (the trace// guard is constructed just before spawn, below).- CommandTrace::record_failed(self.context.as_deref(), &cmd_str, &e);+ CommandTrace::record_failed(+ self.context.as_deref(),+ &cmd_str,+ self.stdin_data.is_some(),+ &e,+ );return Err(anyhow::Error::from(GitError::Other {message: format!("Failed to execute command ({}): {}", exec_mode, e),}));@@ -1584,7 +1601,8 @@ impl Cmd {// Start the trace immediately before spawn, after the fallible// signal-handler install — so a pre-spawn early return can't drop the// guard unresolved, and the duration brackets the child.- let mut trace = CommandTrace::new(self.context.as_deref(), &cmd_str);+ let mut trace = CommandTrace::new(self.context.as_deref(), &cmd_str)+ .reads_stdin(self.stdin_data.is_some());let mut child = match cmd.spawn() {Ok(child) => child,Err(e) => {diff --git a/src/trace/chrome.rs b/src/trace/chrome.rsindex 081bbae2d..1494d48ed 100644--- a/src/trace/chrome.rs+++ b/src/trace/chrome.rs@@ -187,6 +187,7 @@ mod tests {command: command.to_string(),duration: Duration::from_millis(duration_ms),result: TraceResult::Completed { success: true },+ reads_stdin: false,},start_time_us,thread_id,diff --git a/src/trace/emit.rs b/src/trace/emit.rsindex b0e4039bf..7d700f02c 100644--- a/src/trace/emit.rs+++ b/src/trace/emit.rs@@ -12,10 +12,15 @@//! [wt-trace] ts=1234567 tid=3 seq=1 context=worktree cmd="git status" dur_us=12300 ok=true//! [wt-trace] ts=1234567 tid=3 seq=2 cmd="gh pr list" dur_us=45200 ok=false//! [wt-trace] ts=1234567 tid=3 seq=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ..."+//! [wt-trace] ts=1234567 tid=3 seq=4 cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true//! [wt-trace] ts=1234567 tid=3 event="Showed skeleton"//! [wt-trace] ts=1234567 tid=3 span="build_hook_context" dur_us=8200//! ```//!+//! `stdin=true` (command records only) marks a command that consumed stdin not+//! captured in `cmd`; it trails `ok`/`err` and is omitted when false. See+//! [`CommandTrace::reads_stdin`].+//!//! `seq` is a process-global monotonic command counter (command records only).//! The same value is printed into the per-command header in `subprocess.log`,//! so a raw output block there joins back to its command record here.@@ -125,19 +130,16 @@ static CMD_SEQ: AtomicU64 = AtomicU64::new(1);/// Emit a completed-command record (`ok=true`/`ok=false`).///-/// Private: the sole caller is [`CommandTrace::complete`]. Keeping the writer-/// module-private makes [`CommandTrace`] the only way to emit a command-/// record — see the module-level "subprocess chokepoint" note.-fn command_completed(- context: Option<&str>,- cmd: &str,- ts: u64,- tid: u64,- seq: u64,- dur_us: u64,- ok: bool,-) {- match context {+/// Private and taking `&CommandTrace`: every per-command field but the+/// resolution-time `dur_us`/`ok` already lives on the guard, so the writer reads+/// them off it rather than restating the grammar's columns as parameters. The+/// sole caller is [`CommandTrace::complete`]; keeping the writer module-private+/// makes [`CommandTrace`] the only way to emit a command record — see the+/// module-level "subprocess chokepoint" note.+fn command_completed(trace: &CommandTrace, dur_us: u64, ok: bool) {+ let cmd = trace.cmd.as_str();+ let (ts, tid, seq, stdin) = (trace.start_ts_us, trace.tid, trace.seq, trace.reads_stdin);+ match trace.context.as_deref() {Some(ctx) => tracing::debug!(target: WT_TRACE_TARGET,kind = "cmd_completed",@@ -148,6 +150,7 @@ fn command_completed(cmd,dur_us,ok,+ stdin,),None => tracing::debug!(target: WT_TRACE_TARGET,@@ -158,24 +161,20 @@ fn command_completed(cmd,dur_us,ok,+ stdin,),}}/// Emit a failed-command record (the command didn't run to completion).///-/// Private: the sole caller is [`CommandTrace::fail`]. See [`command_completed`].-fn command_errored(- context: Option<&str>,- cmd: &str,- ts: u64,- tid: u64,- seq: u64,- dur_us: u64,- err: impl Display,-) {+/// Takes `&CommandTrace` for the same reason as [`command_completed`]. The sole+/// caller is [`CommandTrace::fail`].+fn command_errored(trace: &CommandTrace, dur_us: u64, err: impl Display) {let err = err.to_string();- match context {+ let cmd = trace.cmd.as_str();+ let (ts, tid, seq, stdin) = (trace.start_ts_us, trace.tid, trace.seq, trace.reads_stdin);+ match trace.context.as_deref() {Some(ctx) => tracing::debug!(target: WT_TRACE_TARGET,kind = "cmd_errored",@@ -186,6 +185,7 @@ fn command_errored(cmd,dur_us,err = %err,+ stdin,),None => tracing::debug!(target: WT_TRACE_TARGET,@@ -196,6 +196,7 @@ fn command_errored(cmd,dur_us,err = %err,+ stdin,),}}@@ -235,6 +236,11 @@ pub struct CommandTrace {start: Instant,tid: u64,seq: u64,+ /// Whether the command consumed stdin not captured in its command string+ /// (a `stdin_bytes` buffer or an upstream pipe). Marks the record so the+ /// cache analysis never treats it as a duplicate — its real input isn't in+ /// `cmd`, so two runs with identical `cmd` may be entirely different work.+ reads_stdin: bool,resolved: bool,}@@ -249,10 +255,20 @@ impl CommandTrace {start: Instant::now(),tid: thread_id(),seq: CMD_SEQ.fetch_add(1, Ordering::Relaxed),+ reads_stdin: false,resolved: false,}}+ /// Mark this command as consuming stdin not captured in its command string.+ /// Set by spawn sites that feed a `stdin_bytes` buffer or pipe an upstream+ /// command's output in — the record then carries `stdin=true`, and the+ /// cache analysis excludes it from duplicate detection.+ pub fn reads_stdin(mut self, yes: bool) -> Self {+ self.reads_stdin = yes;+ self+ }+/// The command's monotonic sequence number — the key shared by this/// command's `[wt-trace]` record (`trace.log`) and its raw output block/// (`subprocess.log`).@@ -279,23 +295,17 @@ impl CommandTrace {/// `ok=true`/`ok=false` record with the elapsed duration.pub fn complete(&mut self, success: bool) {let dur_us = self.start.elapsed().as_micros() as u64;- command_completed(- self.context.as_deref(),- &self.cmd,- self.start_ts_us,- self.tid,- self.seq,- dur_us,- success,- );+ command_completed(self, dur_us, success);self.resolved = true;}/// Emit a failed record for a command that never produced a child to hold/// a guard against — a precondition failure before spawn, where there is/// nothing to time. Equivalent to `new` immediately followed by `fail`.- pub fn record_failed(context: Option<&str>, cmd: &str, err: impl Display) {- let mut trace = Self::new(context, cmd);+ /// `reads_stdin` records the same stdin shape a successful run would have, so+ /// a precondition-failed stdin command is excluded from dedup like any other.+ pub fn record_failed(context: Option<&str>, cmd: &str, reads_stdin: bool, err: impl Display) {+ let mut trace = Self::new(context, cmd).reads_stdin(reads_stdin);trace.fail(err);}@@ -303,15 +313,7 @@ impl CommandTrace {/// Emits an `err=…` record with the elapsed duration.pub fn fail(&mut self, err: impl Display) {let dur_us = self.start.elapsed().as_micros() as u64;- command_errored(- self.context.as_deref(),- &self.cmd,- self.start_ts_us,- self.tid,- self.seq,- dur_us,- err,- );+ command_errored(self, dur_us, err);self.resolved = true;}}@@ -422,7 +424,7 @@ mod tests {failed.fail(std::io::Error::other("boom"));drop(failed);- CommandTrace::record_failed(None, "git nope", "precondition");+ CommandTrace::record_failed(None, "git nope", false, "precondition");}// A guard that reaches drop without complete()/fail() is a spawn site thatdiff --git a/src/trace/parse.rs b/src/trace/parse.rsindex 51901ab8b..0291c440d 100644--- a/src/trace/parse.rs+++ b/src/trace/parse.rs@@ -5,8 +5,15 @@//! [wt-trace] ts=1234567 tid=3 seq=1 context=worktree cmd="git status" dur_us=12300 ok=true//! [wt-trace] ts=1234567 tid=3 seq=2 cmd="gh pr list" dur_us=45200 ok=false//! [wt-trace] ts=1234567 tid=3 seq=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ..."+//! [wt-trace] ts=1234567 tid=3 seq=4 cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true//! ```//!+//! `stdin=true` (command records only) flags a command that consumed stdin not+//! captured in `cmd` — a `stdin_bytes` buffer or an upstream pipe. It trails the+//! `ok`/`err` field and is omitted entirely when false, so older records parse+//! as `reads_stdin: false`. The cache analysis uses it to skip dedup for+//! commands whose real input the command string doesn't show.+//!//! `seq` (a per-command counter, command records only) is parsed leniently —//! it's dropped as an unknown key, since no consumer needs it; it correlates a//! `trace.log` record with its raw output block in `subprocess.log`.@@ -35,6 +42,11 @@ pub enum TraceEntryKind {duration: Duration,/// Command resultresult: TraceResult,+ /// Whether the command consumed stdin not captured in `command` (a+ /// `stdin_bytes` buffer or an upstream pipe). `false` for older records+ /// without the `stdin` field. The cache analysis treats a stdin-reading+ /// command as inherently unique — its real input isn't in `command`.+ reads_stdin: bool,},/// An instant event (milestone marker with no duration)Instant {@@ -113,6 +125,7 @@ fn parse_line(line: &str) -> Option<TraceEntry> {let mut result = None;let mut start_time_us = None;let mut thread_id = None;+ let mut reads_stdin = false;let mut remaining = rest;@@ -167,6 +180,9 @@ fn parse_line(line: &str) -> Option<TraceEntry> {"tid" => {thread_id = value.parse().ok();}+ "stdin" => {+ reads_stdin = value == "true";+ }_ => {} // Ignore unknown keys for forward compatibility}}@@ -187,6 +203,7 @@ fn parse_line(line: &str) -> Option<TraceEntry> {command: command?,duration: duration?,result: result?,+ reads_stdin,}};@@ -281,6 +298,23 @@ mod tests {));}+ #[test]+ fn test_parse_stdin_marker() {+ // `stdin=true` marks a command whose input came via stdin; its absence+ // (older records, stdin-less commands) parses as `reads_stdin: false`.+ let with = r#"[wt-trace] cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true"#;+ let TraceEntryKind::Command { reads_stdin, .. } = parse_line(with).unwrap().kind else {+ panic!("expected command");+ };+ assert!(reads_stdin);++ let without = r#"[wt-trace] cmd="git status" dur_us=5000 ok=true"#;+ let TraceEntryKind::Command { reads_stdin, .. } = parse_line(without).unwrap().kind else {+ panic!("expected command");+ };+ assert!(!reads_stdin);+ }+#[test]fn test_parse_unknown_keys_ignored() {// Unknown keys should be ignored for forward compatibilitydiff --git a/src/trace/profile.rs b/src/trace/profile.rsindex b98147515..4b044cb44 100644--- a/src/trace/profile.rs+++ b/src/trace/profile.rs@@ -12,7 +12,9 @@//! 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).+//! same context (a cache miss that should have been a hit). Commands that read+//! stdin are excluded — their real input isn't in the command string, so+//! identical command lines aren't necessarily identical work.//!//! The analysis ([`Profile::from_entries`], [`CacheReport::from_entries`]) is pure//! data over `&[TraceEntry]` and carries no styling, so it compiles without the@@ -181,11 +183,22 @@ pub struct Phase {/// 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.+///+/// The duplicate fields (`unique_commands`, `duplicated_commands`,+/// `extra_calls`, `same_context_*`) only consider commands whose work is fully+/// determined by `(command, context)`. A command that reads stdin+/// (`stdin=true`: a `claude -p` prompt, a diff piped to `git patch-id`) carries+/// input the command string doesn't capture, so two runs with identical+/// `(command, context)` may be entirely different work — it's counted in+/// `total_commands`/`total_time`/`contexts` but never reported as a duplicate.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct CacheReport {+ /// Every command record, including stdin-reading ones.pub total_commands: usize,+ /// Distinct dedupable command strings (stdin-reading commands excluded).pub unique_commands: usize,pub contexts: usize,+ /// Σ of every command duration, including stdin-reading ones.#[serde(rename = "total_time_us", serialize_with = "ser_dur_us")]pub total_time: Duration,/// Distinct commands run more than once (in any context).@@ -324,6 +337,7 @@ impl Profile {command,duration,result,+ ..} => {let dur_us = duration.as_micros() as u64;command_count += 1;@@ -612,6 +626,7 @@ 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 total_time_us = 0u64;let mut cmd_counts: HashMap<&str, usize> = HashMap::new();let mut contexts: HashSet<&str> = HashSet::new();// (command, context) → durations of every run, in microseconds.@@ -619,17 +634,32 @@ impl CacheReport {for entry in entries {if let TraceEntryKind::Command {- command, duration, ..+ command,+ duration,+ reads_stdin,+ ..} = &entry.kind{let ctx = entry.context.as_deref().unwrap_or("(none)");+ let dur_us = duration.as_micros() as u64;+ total_commands += 1;+ total_time_us += dur_us;+ contexts.insert(ctx);+ // Duplicate analysis assumes (command, context) fully determines+ // a command's work. A command that reads stdin carries input the+ // command string doesn't capture, so two runs with identical+ // (command, context) may be entirely different work (a different+ // prompt piped to `claude -p`, a different diff to `git+ // patch-id`). Count it in the totals above, but never let it+ // form — or join — a duplicate bucket.+ if *reads_stdin {+ continue;+ }*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;+ .push(dur_us);}}@@ -687,7 +717,6 @@ impl CacheReport {.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();@@ -822,12 +851,29 @@ mod tests {command: command.to_string(),duration: Duration::from_micros(dur_us),result: TraceResult::Completed { success: ok },+ reads_stdin: false,},start_time_us: Some(ts_us),thread_id: Some(tid),}}+ /// A successful command that consumed stdin uncaptured by its command+ /// string (the `stdin=true` shape: `claude -p`, `git patch-id`).+ fn cmd_stdin(command: &str, ctx: Option<&str>, dur_us: u64) -> 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: true },+ reads_stdin: true,+ },+ start_time_us: None,+ thread_id: None,+ }+ }+fn span(name: &str, ts_us: u64, dur_us: u64) -> TraceEntry {TraceEntry {context: None,@@ -941,6 +987,38 @@ mod tests {assert_eq!(cache.same_context_duplicates[0].max_per_context, 3);}+ #[test]+ fn cache_report_excludes_stdin_reading_commands() {+ // Three identical `claude -p` lines in one context differ only by the+ // prompt piped to stdin (not in the command string), so they're real+ // distinct work, not a cache miss. A plain `git status` repeated in the+ // same context is the genuine duplicate the report should still catch.+ let claude = "sh -c claude -p";+ let entries = vec![+ cmd_stdin(claude, Some("main"), 5_000),+ cmd_stdin(claude, Some("main"), 4_000),+ cmd_stdin(claude, Some("main"), 3_000),+ cmd("git status", Some("main"), 0, 2_000, 1, true),+ cmd("git status", Some("main"), 6_000, 1_000, 1, true),+ ];+ let cache = CacheReport::from_entries(&entries);++ // The stdin-reading commands are not duplicates …+ assert_eq!(cache.same_context_duplicates.len(), 1);+ assert_eq!(cache.same_context_duplicates[0].command, "git status");+ assert_eq!(cache.same_context_extra_calls, 1);+ assert_eq!(cache.same_context_extra, Duration::from_millis(1));+ // … nor counted in the cross-context duplicate tallies.+ assert_eq!(cache.duplicated_commands, 1);+ assert_eq!(cache.extra_calls, 1);+ assert_eq!(cache.unique_commands, 1); // only `git status` is dedupable++ // … but they still count toward the totals (real commands, real time).+ assert_eq!(cache.total_commands, 5);+ assert_eq!(cache.total_time, Duration::from_millis(15));+ assert_eq!(cache.contexts, 1);+ }+#[test]fn renders_full_report() {let entries = vec![@@ -1085,6 +1163,7 @@ mod tests {result: TraceResult::Error {message: message.to_string(),},+ reads_stdin: false,},start_time_us: None,thread_id: None,@@ -1095,6 +1174,7 @@ mod tests {command: command.to_string(),duration: Duration::from_micros(dur_us),result: TraceResult::Completed { success: true },+ reads_stdin: false,},start_time_us: None,thread_id: None,@@ -1120,6 +1200,7 @@ mod tests {command: command.to_string(),duration: Duration::from_micros(dur_us),result: TraceResult::Completed { success: true },+ reads_stdin: false,},start_time_us: None,thread_id: None,diff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rsindex 1ad8516f4..589579df3 100644--- a/tests/helpers/wt-perf/src/main.rs+++ b/tests/helpers/wt-perf/src/main.rs@@ -396,6 +396,7 @@ fn describe(e: &TraceEntry) -> (&'static str, Duration, String) {command,duration,result,+ ..} => {let mut label = match e.context.as_deref() {Some(c) => format!("{command} [{c}]"),@@ -470,7 +471,9 @@ fn read_trace_entries(file: Option<&std::path::Path>) -> Vec<worktrunk::trace::T/// `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.+/// summed over all but the slowest (likely cold) run per context. Commands that+/// read stdin (`stdin=true`) are excluded — their input isn't in the command+/// string, so identical lines aren't necessarily redundant.fn cache_check(entries: &[worktrunk::trace::TraceEntry]) {let report = worktrunk::trace::CacheReport::from_entries(entries);println!("{}", serde_json::to_string_pretty(&report).unwrap());@@ -506,6 +509,7 @@ mod tests {command: cmd.to_string(),duration: Duration::from_micros(dur_us),result: TraceResult::Completed { success: ok },+ reads_stdin: false,},start_time_us: Some(ts_us),thread_id: Some(tid),