Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(trace): emit wt-trace as structured fields, render in layer (#2907)
Maximilian Roos007df1725063
diff --git a/src/logging.rs b/src/logging.rsindex 2bc0b8de1..a6030a427 100644--- a/src/logging.rs+++ b/src/logging.rs@@ -26,6 +26,7 @@ use tracing_subscriber::registry::LookupSpan;use tracing_subscriber::util::SubscriberInitExt;use worktrunk::shell_exec::SUBPROCESS_FULL_TARGET;use worktrunk::styling::{eprintln, info_message};+use worktrunk::trace::WT_TRACE_TARGET;use crate::log_files::{self, OutputMakeWriter, TraceMakeWriter};use crate::output;@@ -119,13 +120,35 @@ wheremut writer: Writer<'_>,event: &Event<'_>,) -> fmt::Result {- let line = style_stderr_line(thread_label(), &event_message(event));+ let msg = render_event_message(event);+ let line = style_stderr_line(thread_label(), &msg);writeln!(writer, "{line}")}}+/// Render an event to its single-line text payload — `[wt-trace]` grammar+/// for events under [`WT_TRACE_TARGET`], the raw `message` field for+/// everything else. Shared between the stderr and `trace.log` formatters so+/// `[wt-trace]` records appear in both routes (`-vv` writes to the file;+/// `RUST_LOG=debug -v` surfaces them on stderr).+fn render_event_message(event: &Event<'_>) -> String {+ if event.metadata().target() == WT_TRACE_TARGET {+ let mut fields = WtTraceFields::default();+ event.record(&mut fields);+ format_wt_trace(&fields)+ } else {+ event_message(event)+ }+}+/// `trace.log` formatter: plain `[<thread>] <message>`, no ANSI, one line/// per event. Matches the on-disk layout pre-migration.+///+/// Events under [`WT_TRACE_TARGET`] are rendered via the dedicated+/// `[wt-trace] key=value` grammar in [`format_wt_trace`]; everything else+/// falls through to the legacy message-prefix shape. This is the only place+/// the `[wt-trace]` text format lives — emit sites in `trace::emit` carry+/// structured fields, not pre-formatted strings.struct TraceFileFormat;impl<S, N> FormatEvent<S, N> for TraceFileFormat@@ -140,11 +163,136 @@ whereevent: &Event<'_>,) -> fmt::Result {let thread_num = thread_label();- let msg = event_message(event);+ let msg = render_event_message(event);writeln!(writer, "[{thread_num}] {msg}")}}+/// Captured fields from a single `WT_TRACE_TARGET` event. The visitor reads+/// each field by name and stores its value typed — the layer renderer then+/// composes the final `[wt-trace] …` line in the exact field order+/// downstream parsers expect.+///+/// Unknown fields are dropped; the wt-trace grammar is closed (every key+/// has a fixed meaning).+#[derive(Default)]+struct WtTraceFields {+ kind: Option<String>,+ ts: Option<u64>,+ tid: Option<u64>,+ dur_us: Option<u64>,+ ok: Option<bool>,+ context: Option<String>,+ cmd: Option<String>,+ err: Option<String>,+ event: Option<String>,+ span: Option<String>,+}++impl tracing::field::Visit for WtTraceFields {+ fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {+ match field.name() {+ "ts" => self.ts = Some(value),+ "tid" => self.tid = Some(value),+ "dur_us" => self.dur_us = Some(value),+ _ => {}+ }+ }++ fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {+ if field.name() == "ok" {+ self.ok = Some(value);+ }+ }++ fn record_str(&mut self, field: &tracing::field::Field, value: &str) {+ self.record_string(field.name(), value);+ }++ fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {+ // `tracing::debug!(field = %expr)` routes Display-formatted values+ // through here via a `DisplayValue` wrapper whose `Debug` impl calls+ // `Display` (bare text, no `"…"` quoting). Capture the rendered+ // string verbatim — the wire grammar adds its own quotes when it+ // composes the line.+ let mut buf = String::new();+ let _ = write!(&mut buf, "{value:?}");+ self.record_string(field.name(), &buf);+ }+}++impl WtTraceFields {+ fn record_string(&mut self, name: &str, value: &str) {+ match name {+ "kind" => self.kind = Some(value.to_owned()),+ "context" => self.context = Some(value.to_owned()),+ "cmd" => self.cmd = Some(value.to_owned()),+ "err" => self.err = Some(value.to_owned()),+ "event" => self.event = Some(value.to_owned()),+ "span" => self.span = Some(value.to_owned()),+ _ => {}+ }+ }+}++/// Render structured fields as the `[wt-trace] key=value …` text wt-perf+/// and the integration tests parse. The field order per `kind` is the+/// contract; see `src/trace/parse.rs` for the consumer.+///+/// A malformed event (missing required fields, unknown `kind`) renders the+/// best-effort string `[wt-trace] kind=<…> <repr>` so a future-added kind+/// produces a noticeable but parseable line rather than silently vanishing.+fn format_wt_trace(f: &WtTraceFields) -> String {+ // `ts` and `tid` are required for every kind; default to 0 to keep the+ // line shape valid if a future emit site forgets one — the parser will+ // still accept it, and the missing field shows up as `0` in the+ // timeline rather than disappearing.+ let ts = f.ts.unwrap_or(0);+ let tid = f.tid.unwrap_or(0);++ match f.kind.as_deref() {+ Some("cmd_completed") => {+ let cmd = f.cmd.as_deref().unwrap_or("");+ let dur_us = f.dur_us.unwrap_or(0);+ let ok = f.ok.unwrap_or(false);+ match &f.context {+ Some(ctx) => format!(+ r#"[wt-trace] ts={ts} tid={tid} context={ctx} cmd="{cmd}" dur_us={dur_us} ok={ok}"#+ ),+ None => {+ format!(r#"[wt-trace] ts={ts} tid={tid} cmd="{cmd}" dur_us={dur_us} ok={ok}"#)+ }+ }+ }+ Some("cmd_errored") => {+ 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("");+ match &f.context {+ Some(ctx) => format!(+ r#"[wt-trace] ts={ts} tid={tid} context={ctx} cmd="{cmd}" dur_us={dur_us} err="{err}""#+ ),+ None => format!(+ r#"[wt-trace] ts={ts} tid={tid} cmd="{cmd}" dur_us={dur_us} err="{err}""#+ ),+ }+ }+ Some("instant") => {+ let event = f.event.as_deref().unwrap_or("");+ format!(r#"[wt-trace] ts={ts} tid={tid} event="{event}""#)+ }+ Some("span") => {+ let name = f.span.as_deref().unwrap_or("");+ let dur_us = f.dur_us.unwrap_or(0);+ format!(r#"[wt-trace] ts={ts} tid={tid} span="{name}" dur_us={dur_us}"#)+ }+ other => format!(+ r#"[wt-trace] ts={ts} tid={tid} kind={kind:?}"#,+ kind = other.unwrap_or("<unknown>")+ ),+ }+}+/// `output.log` formatter: the message verbatim. Subprocess bodies are/// already prefixed (` …` / ` ! …`) by `shell_exec::format_stream_full`.struct OutputFileFormat;@@ -363,7 +511,10 @@ fn announce_trace_destination() {mod tests {use ansi_str::AnsiStr;- use super::{effective_log_max_level, label_for_thread_index, style_stderr_line};+ use super::{+ WT_TRACE_TARGET, WtTraceFields, effective_log_max_level, format_wt_trace,+ label_for_thread_index, style_stderr_line,+ };/// Branch coverage for `label_for_thread_index` — `thread_label` never/// hands it `n == 0` or `n > 52` in practice (Rust's `ThreadId`@@ -410,6 +561,175 @@ mod tests {assert_eq!(plain, "[d] hello");}+ /// Drive `WtTraceFields::Visit` end-to-end via a temporary subscriber:+ /// emit one event per field-type variant under [`WT_TRACE_TARGET`],+ /// capture the visitor output, and assert the field landed in the+ /// expected slot. Covers `record_debug` (`err = %display`) — the+ /// production path nothing else exercises — plus the unknown-name `_`+ /// arms in `record_u64` / `record_str`.+ #[test]+ fn wt_trace_fields_visit_records_every_type() {+ use std::sync::{Arc, Mutex};++ use tracing::Subscriber;+ use tracing_subscriber::Registry;+ use tracing_subscriber::layer::{Context, Layer, SubscriberExt};++ struct Capture(Arc<Mutex<Vec<WtTraceFields>>>);+ impl<S: Subscriber> Layer<S> for Capture {+ fn on_event(&self, event: &tracing::Event<'_>, _: Context<'_, S>) {+ if event.metadata().target() != WT_TRACE_TARGET {+ return;+ }+ let mut fields = WtTraceFields::default();+ event.record(&mut fields);+ self.0.lock().unwrap().push(fields);+ }+ }+ let events: Arc<Mutex<Vec<WtTraceFields>>> = Arc::new(Mutex::new(Vec::new()));+ let subscriber = Registry::default().with(Capture(events.clone()));+ tracing::subscriber::with_default(subscriber, || {+ // u64 (ts/tid/dur_us) + unknown_u64 → `_` arm in record_u64+ tracing::debug!(+ target: WT_TRACE_TARGET,+ ts = 7u64,+ tid = 3u64,+ unknown_u64 = 42u64,+ );+ // bool (ok)+ tracing::debug!(target: WT_TRACE_TARGET, ok = true);+ // str (cmd) + unknown_str → `_` arm in record_string+ tracing::debug!(+ target: WT_TRACE_TARGET,+ cmd = "git status",+ unknown_str = "ignored",+ );+ // Display-formatted value (err = %expr) → record_debug+ let msg = "fatal: bad ref".to_string();+ tracing::debug!(target: WT_TRACE_TARGET, err = %msg);+ });++ let captured = events.lock().unwrap();+ assert_eq!(captured[0].ts, Some(7));+ assert_eq!(captured[0].tid, Some(3));+ assert_eq!(captured[1].ok, Some(true));+ assert_eq!(captured[2].cmd.as_deref(), Some("git status"));+ assert_eq!(captured[3].err.as_deref(), Some("fatal: bad ref"));+ }++ /// Lock the `[wt-trace]` wire grammar produced by `format_wt_trace`.+ /// wt-perf and the integration suite parse these lines; any drift here+ /// breaks downstream tooling, so each `kind` gets a fixture assertion.+ #[test]+ fn format_wt_trace_renders_each_kind() {+ // cmd_completed with context+ let f = WtTraceFields {+ kind: Some("cmd_completed".into()),+ ts: Some(100),+ tid: Some(3),+ context: Some("worktree".into()),+ cmd: Some("git status".into()),+ dur_us: Some(12300),+ ok: Some(true),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 context=worktree cmd="git status" dur_us=12300 ok=true"#+ );++ // cmd_completed without context+ let f = WtTraceFields {+ kind: Some("cmd_completed".into()),+ ts: Some(100),+ tid: Some(3),+ cmd: Some("gh pr list".into()),+ dur_us: Some(45200),+ ok: Some(false),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 cmd="gh pr list" dur_us=45200 ok=false"#+ );++ // cmd_errored with context+ let f = WtTraceFields {+ kind: Some("cmd_errored".into()),+ ts: Some(100),+ tid: Some(3),+ context: Some("main".into()),+ cmd: Some("git merge-base".into()),+ dur_us: Some(100000),+ err: Some("fatal: ...".into()),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ...""#+ );++ // cmd_errored without context (standalone tools like gh)+ let f = WtTraceFields {+ kind: Some("cmd_errored".into()),+ ts: Some(100),+ tid: Some(3),+ cmd: Some("gh pr list".into()),+ dur_us: Some(1000),+ err: Some("network down".into()),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 cmd="gh pr list" dur_us=1000 err="network down""#+ );++ // instant+ let f = WtTraceFields {+ kind: Some("instant".into()),+ ts: Some(100),+ tid: Some(3),+ event: Some("Showed skeleton".into()),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 event="Showed skeleton""#+ );++ // span+ let f = WtTraceFields {+ kind: Some("span".into()),+ ts: Some(100),+ tid: Some(3),+ span: Some("build_hook_context".into()),+ dur_us: Some(8200),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 span="build_hook_context" dur_us=8200"#+ );++ // Defensive fallback: a future kind not yet known to the renderer+ // emits a parseable record rather than silently vanishing.+ let f = WtTraceFields {+ kind: Some("future_kind".into()),+ ts: Some(100),+ tid: Some(3),+ ..Default::default()+ };+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=100 tid=3 kind="future_kind""#+ );+ let f = WtTraceFields::default();+ assert_eq!(+ format_wt_trace(&f),+ r#"[wt-trace] ts=0 tid=0 kind="<unknown>""#+ );+ }+/// `effective_log_max_level` mirrors the layer filters: env wins when/// set, else the verbosity baseline. Driving it as a pure function/// lets us cover the env-set branch without mutating the process envdiff --git a/src/trace/emit.rs b/src/trace/emit.rsindex 2e5100bc3..e27db60e6 100644--- a/src/trace/emit.rs+++ b/src/trace/emit.rs@@ -16,23 +16,50 @@//! [wt-trace] ts=1234567 tid=3 span="build_hook_context" dur_us=8200//! ```//!+//! # Emission model+//!+//! Records emit as `tracing` events under [`WT_TRACE_TARGET`] with typed+//! structured fields (`kind`, `ts`, `tid`, `cmd`, `dur_us`, `ok`, `err`,+//! `event`, `span`, `context`). The text grammar is produced downstream by+//! the `trace.log` layer's `FormatEvent` impl in+//! `src/logging.rs::TraceFileFormat`, which reads the structured fields+//! and renders the exact `[wt-trace] key=value …` lines wt-perf and the+//! integration suite parse.+//!+//! This split — structured fields at the emission site, grammar rendering+//! at the layer — means the wire format lives in one place+//! (`logging.rs`) and emit sites carry no string-formatting noise.+//!+//! # Timing+//!//! In-process spans (everything that isn't a subprocess) use [`Span`], an//! RAII guard that captures `ts` at construction and emits the completed//! record on drop with the elapsed duration. Use it to attribute time spent//! in code paths subprocess records can't see (config load, repo open,//! template render).//!-//! Records are emitted at `tracing::DEBUG`, so `-vv` or `RUST_LOG=debug` makes-//! them visible. Subprocess stdout/stderr continuations are emitted via-//! separate targets: the full output goes to `output.log`, and a bounded-//! preview shares the routing of all other records — `trace.log` at `-vv`,-//! stderr otherwise — so raw bodies don't spam `-vv`.+//! Subprocess emission lives in `shell_exec::WtTraceLog`, which captures+//! `Instant::now()` at `Cmd::run` entry — `tracing` spans can't carry this+//! across the sync subprocess wait, so the timing stays manual.+//!+//! # Routing+//!+//! Events emit at `tracing::DEBUG`, so `-vv` or `RUST_LOG=debug` makes them+//! visible. Subprocess stdout/stderr continuations route through separate+//! targets: the full output goes to `output.log`, and a bounded preview+//! shares the routing of all other records — `trace.log` at `-vv`, stderr+//! otherwise — so raw bodies don't spam `-vv`.use std::borrow::Cow;use std::fmt::Display;use std::sync::OnceLock;use std::time::Instant;+/// Tracing target the `trace.log` layer keys on to render the `[wt-trace]`+/// grammar. Events under any other target fall through to the layer's+/// default message-passing format.+pub const WT_TRACE_TARGET: &str = "worktrunk::wt_trace";+/// Monotonic epoch for trace timestamps. All `ts` fields are microseconds/// since this point. `Instant` is monotonic even if the system clock steps.static TRACE_EPOCH: OnceLock<Instant> = OnceLock::new();@@ -70,21 +97,23 @@ pub fn command_completed() {match context {Some(ctx) => tracing::debug!(- r#"[wt-trace] ts={} tid={} context={} cmd="{}" dur_us={} ok={}"#,+ target: WT_TRACE_TARGET,+ kind = "cmd_completed",ts,tid,- ctx,+ context = ctx,cmd,dur_us,- ok+ ok,),None => tracing::debug!(- r#"[wt-trace] ts={} tid={} cmd="{}" dur_us={} ok={}"#,+ target: WT_TRACE_TARGET,+ kind = "cmd_completed",ts,tid,cmd,dur_us,- ok+ ok,),}}@@ -98,23 +127,26 @@ pub fn command_errored(dur_us: u64,err: impl Display,) {+ let err = err.to_string();match context {Some(ctx) => tracing::debug!(- r#"[wt-trace] ts={} tid={} context={} cmd="{}" dur_us={} err="{}""#,+ target: WT_TRACE_TARGET,+ kind = "cmd_errored",ts,tid,- ctx,+ context = ctx,cmd,dur_us,- err+ err = %err,),None => tracing::debug!(- r#"[wt-trace] ts={} tid={} cmd="{}" dur_us={} err="{}""#,+ target: WT_TRACE_TARGET,+ kind = "cmd_errored",ts,tid,cmd,dur_us,- err+ err = %err,),}}@@ -126,10 +158,11 @@ pub fn command_errored(/// (chrome://tracing, Perfetto).pub fn instant(event: &str) {tracing::debug!(- r#"[wt-trace] ts={} tid={} event="{}""#,- now_us(),- thread_id(),- event+ target: WT_TRACE_TARGET,+ kind = "instant",+ ts = now_us(),+ tid = thread_id(),+ event,);}@@ -140,11 +173,12 @@ pub fn instant(event: &str) {/// around them (config load, repo open, template render, etc.).pub fn span_completed(name: &str, ts: u64, tid: u64, dur_us: u64) {tracing::debug!(- r#"[wt-trace] ts={} tid={} span="{}" dur_us={}"#,+ target: WT_TRACE_TARGET,+ kind = "span",ts,tid,- name,- dur_us+ span = name,+ dur_us,);}diff --git a/src/trace/mod.rs b/src/trace/mod.rsindex 4149685ae..343bfcb8a 100644--- a/src/trace/mod.rs+++ b/src/trace/mod.rs@@ -43,5 +43,5 @@ pub mod parse;// Re-export main types for conveniencepub use chrome::to_chrome_trace;-pub use emit::{Span, instant};+pub use emit::{Span, WT_TRACE_TARGET, instant};pub use parse::{TraceEntry, TraceEntryKind, TraceResult, parse_lines};