Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add trace.jsonl structured-event sink and migrate logging to native tracing (#3232)
Maximilian Roosfdeddc879685
diff --git a/src/cache.rs b/src/cache.rsindex 9ede54b76..87815603b 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -56,7 +56,7 @@ pub fn read_json<T: DeserializeOwned>(path: &Path) -> Option<T> {match serde_json::from_str::<T>(&json) {Ok(value) => Some(value),Err(e) => {- log::debug!("cache: corrupt entry at {}: {}", path.display(), e);+ tracing::debug!(path = %path.display(), error = %e, "cache: corrupt entry at {}: {}", path.display(), e);None}}@@ -72,17 +72,17 @@ pub fn write_json<T: Serialize>(path: &Path, value: &T) {if let Some(parent) = path.parent()&& let Err(e) = fs::create_dir_all(parent){- log::debug!("cache: failed to create dir {}: {}", parent.display(), e);+ tracing::debug!(path = %parent.display(), error = %e, "cache: failed to create dir {}: {}", parent.display(), e);return;}let Ok(json) = serde_json::to_string(value) else {- log::debug!("cache: failed to serialize entry for {}", path.display());+ tracing::debug!(path = %path.display(), "cache: failed to serialize entry for {}", path.display());return;};if let Err(e) = fs::write(path, &json) {- log::debug!("cache: failed to write {}: {}", path.display(), e);+ tracing::debug!(path = %path.display(), error = %e, "cache: failed to write {}: {}", path.display(), e);}}@@ -153,7 +153,7 @@ pub fn sweep_lru(dir: &Path, max: usize) {for (path, _) in with_mtime.iter().take(excess) {let _ = fs::remove_file(path);}- log::debug!("cache: swept {} entries from {}", excess, dir.display());+ tracing::debug!(count = excess, dir = %dir.display(), "cache: swept {} entries from {}", excess, dir.display());}/// Remove a single cache entry.diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 6acc5b17e..7f4d9ae5b 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -1441,7 +1441,7 @@ fn render_version_check(out: &mut String) -> anyhow::Result<()> {match fetch_latest_version() {Ok(latest) => writeln!(out, "{}", format_version_status(&latest))?,Err(e) => {- log::debug!("Version check failed: {e}");+ tracing::debug!(error = %e, "Version check failed: {e}");writeln!(out, "{}", hint_message("Version check unavailable"))?;}}diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 0eca527e2..3515e8484 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -61,8 +61,8 @@//! # Log layout invariant//!//! Inside `wt_logs_dir()`, top-level *files* are shared logs (`commands.jsonl*`,-//! `internal-*.log`, `trace.log`, `subprocess.log`, `diagnostic.md`) and top-level-//! *directories* are per-branch log trees+//! `internal-*.log`, `trace.log`, `trace.jsonl`, `subprocess.log`,+//! `diagnostic.md`) and top-level *directories* are per-branch log trees//! (`{branch}/{source|internal}/{hook-type}/{name}.log`).//! Categorization//! relies on this file-vs-directory distinction: new top-level shared entries@@ -95,7 +95,12 @@ use crate::summary::CachedSummary;// ==================== Log Management ====================/// Top-level files created by `-vv` under `wt_logs_dir()`.-const DIAGNOSTIC_FILES: &[&str] = &["trace.log", "subprocess.log", "diagnostic.md"];+const DIAGNOSTIC_FILES: &[&str] = &[+ "trace.log",+ "trace.jsonl",+ "subprocess.log",+ "diagnostic.md",+];/// Whether a top-level file is a diagnostic log.///@@ -121,9 +126,13 @@ fn truncate_display(s: &str, max_chars: usize) -> String {format!("{truncated}...")}-/// Check if a top-level file belongs to the command audit log (`.jsonl` / `.jsonl.old`).+/// Check if a top-level file belongs to the command audit log+/// (`commands.jsonl`, rotated to `commands.jsonl.old`).+///+/// Matched by exact name, not a `.jsonl` suffix: `trace.jsonl` is a diagnostic+/// file (see [`DIAGNOSTIC_FILES`]), not part of the audit log.fn is_command_log_file(name: &str) -> bool {- name.ends_with(".jsonl") || name.ends_with(".jsonl.old")+ name == "commands.jsonl" || name == "commands.jsonl.old"}/// A hook-output log file discovered by walking the per-branch subtree.@@ -293,7 +302,7 @@ fn count_log_files_recursive(dir: &Path) -> anyhow::Result<usize> {////// Walks the two layers of log storage:///-/// 1. **Top-level files**: `commands.jsonl*`, `trace.log`, `subprocess.log`, `diagnostic.md`.+/// 1. **Top-level files**: `commands.jsonl*`, `trace.log`, `trace.jsonl`, `subprocess.log`, `diagnostic.md`./// Also sweeps any legacy flat `.log` files left over from the pre-nested/// layout so the transition is self-healing (no explicit migrator)./// 2. **Top-level directories**: per-branch log trees — counted recursivelydiff --git a/src/commands/list/ci_status/azure.rs b/src/commands/list/ci_status/azure.rsindex f3779bb79..d206bf61f 100644--- a/src/commands/list/ci_status/azure.rs+++ b/src/commands/list/ci_status/azure.rs@@ -93,7 +93,9 @@ pub(super) fn detect_azure_pr({Ok(output) => output,Err(e) => {- log::warn!(+ tracing::warn!(+ branch = %branch.full_name,+ error = %e,"az repos pr list failed to execute for branch {}: {}",branch.full_name,e@@ -182,7 +184,9 @@ pub(super) fn detect_azure_pipeline({Ok(output) => output,Err(e) => {- log::warn!(+ tracing::warn!(+ branch = %branch.full_name,+ error = %e,"az pipelines runs list failed to execute for branch {}: {}",branch.full_name,ediff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsindex 5a600b700..ee06c3a2a 100644--- a/src/commands/list/ci_status/github.rs+++ b/src/commands/list/ci_status/github.rs@@ -41,7 +41,8 @@ pub(super) fn detect_github(let branch_owner = branch_owner_repo(repo, branch).map(|(owner, _)| owner);let Some(branch_owner) = branch_owner else {- log::debug!(+ tracing::debug!(+ branch = %branch.full_name,"Branch {} has no resolvable push remote; skipping PR-based CI detection",branch.full_name);@@ -79,7 +80,9 @@ pub(super) fn detect_github({Ok(output) => output,Err(e) => {- log::warn!(+ tracing::warn!(+ branch = %branch.full_name,+ error = %e,"gh pr list failed to execute for branch {}: {}",branch.full_name,e@@ -105,7 +108,10 @@ pub(super) fn detect_github(.unwrap_or(true) // Missing owner field = potential match});if pr_info.is_none() && !pr_list.is_empty() {- log::debug!(+ tracing::debug!(+ count = %pr_list.len(),+ branch = %branch.full_name,+ owner = %branch_owner,"Found {} PRs for branch {} but none from owner {}",pr_list.len(),branch.full_name,@@ -176,7 +182,9 @@ pub(super) fn detect_github_commit_checks({Ok(output) => output,Err(e) => {- log::warn!(+ tracing::warn!(+ head = %local_head,+ error = %e,"gh api check-runs failed to execute for {}: {}",local_head,ediff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rsindex 7c63beb6e..231dac3a2 100644--- a/src/commands/list/ci_status/gitlab.rs+++ b/src/commands/list/ci_status/gitlab.rs@@ -78,7 +78,7 @@ pub(super) fn detect_gitlab(// Get current project ID for filteringlet project_id = gitlab_project_id(repo);if project_id.is_none() {- log::debug!("Could not determine GitLab project ID");+ tracing::debug!("Could not determine GitLab project ID");}// Fetch MRs with matching source branch.@@ -101,7 +101,9 @@ pub(super) fn detect_gitlab({Ok(output) => output,Err(e) => {- log::warn!(+ tracing::warn!(+ branch = %branch.full_name,+ error = %e,"glab mr list failed to execute for branch {}: {}",branch.full_name,e@@ -131,7 +133,10 @@ pub(super) fn detect_gitlab(.iter().find(|mr| mr.source_project_id == Some(proj_id));if matched.is_none() && !mr_list.is_empty() {- log::debug!(+ tracing::debug!(+ count = %mr_list.len(),+ branch = %branch.full_name,+ project_id = %proj_id,"Found {} MRs for branch {} but none from project ID {}",mr_list.len(),branch.full_name,@@ -148,7 +153,9 @@ pub(super) fn detect_gitlab(} else {// Multiple MRs exist but we can't determine which project we're in.// Don't guess - return None to avoid showing wrong project's CI status.- log::debug!(+ tracing::debug!(+ count = %mr_list.len(),+ branch = %branch.full_name,"Found {} MRs for branch {} but no project ID to filter - skipping to avoid ambiguity",mr_list.len(),branch.full_name@@ -178,7 +185,7 @@ pub(super) fn detect_gitlab(// (not NoCI, which would imply no MR exists). Carry the MR identity// already in hand: the ⚠ stays clickable and the iid still feeds the// CI column width ratchet.- log::debug!("Could not fetch MR details for !{}", mr_entry.iid);+ tracing::debug!(iid = %mr_entry.iid, "Could not fetch MR details for !{}", mr_entry.iid);return Some(PrStatus {ci_status: CiStatus::Error,source: CiSource::PullRequest,@@ -236,7 +243,9 @@ pub(super) fn detect_gitlab_pipeline({Ok(output) => output,Err(e) => {- log::warn!(+ tracing::warn!(+ branch = %branch,+ error = %e,"glab ci list failed to execute for branch {}: {}",branch,e@@ -371,7 +380,7 @@ fn fetch_mr_details(iid: u64, repo_root: &Path) -> Option<GitLabMrInfo> {.ok()?;if !output.status.success() {- log::debug!("glab mr view {} failed", iid);+ tracing::debug!(iid = %iid, "glab mr view {} failed", iid);return None;}diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex 177b2c4c4..f5c7e3429 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -130,7 +130,7 @@ pub(crate) fn tool_available(tool: &str, args: &[&str]) -> bool {/// Parse JSON output from CLI toolsfn parse_json<T: DeserializeOwned>(stdout: &[u8], command: &str, branch: &str) -> Option<T> {serde_json::from_slice(stdout)- .map_err(|e| log::warn!("Failed to parse {} JSON for {}: {}", command, branch, e))+ .map_err(|e| tracing::warn!(command = %command, branch = %branch, error = %e, "Failed to parse {} JSON for {}: {}", command, branch, e)).ok()}@@ -557,12 +557,20 @@ impl PrStatus {// Use full_name as cache key to distinguish local "feature" from remote "origin/feature"let now_secs = epoch_now();+ // `age` saturates: under a pinned test clock (or real clock skew)+ // `now_secs` can predate `checked_at`, so a raw subtraction would+ // underflow-panic when this `debug!` fires (its args build at `-vv`).+ // `saturating_sub` clamps to 0, matching `CachedCiStatus::is_valid`.let status = match CachedCiStatus::read(repo, &branch.full_name) {Some(cached) if cached.is_valid(local_head, now_secs, &repo_path) => {- log::debug!(+ tracing::debug!(+ branch = %branch.full_name,+ age = %(now_secs.saturating_sub(cached.checked_at)),+ ttl = %CachedCiStatus::ttl_for_repo(&repo_path),+ status = ?cached.status.as_ref().map(|s| &s.ci_status),"Using cached CI status for {} (age={}s, ttl={}s, status={:?})",branch.full_name,- now_secs - cached.checked_at,+ now_secs.saturating_sub(cached.checked_at),CachedCiStatus::ttl_for_repo(&repo_path),cached.status.as_ref().map(|s| &s.ci_status));@@ -570,10 +578,14 @@ impl PrStatus {}cached => {if let Some(cached) = cached {- log::debug!(+ tracing::debug!(+ branch = %branch.full_name,+ age = %(now_secs.saturating_sub(cached.checked_at)),+ ttl = %CachedCiStatus::ttl_for_repo(&repo_path),+ head_match = %(cached.head == local_head),"Cache expired for {} (age={}s, ttl={}s, head_match={})",branch.full_name,- now_secs - cached.checked_at,+ now_secs.saturating_sub(cached.checked_at),CachedCiStatus::ttl_for_repo(&repo_path),cached.head == local_head);@@ -621,7 +633,7 @@ impl PrStatus {Some(p) => platform::detect_ci(p, repo, branch, local_head, has_upstream),None => {// Unknown platform — user should set forge.platform in project config- log::debug!(+ tracing::debug!("Could not detect CI platform from remote URL; \set forge.platform in .config/wt.toml for CI status");diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 934fde900..ff33e888e 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -1674,7 +1674,7 @@ pub fn collect(s.table.update_row(item_idx, rendered.clone());if let Err(e) = s.table.flush() {- log::debug!("Progressive table flush failed: {}", e);+ tracing::debug!(error = %e, "Progressive table flush failed: {}", e);}}@@ -1692,7 +1692,7 @@ pub fn collect(s.table.update_row(idx, line.clone());}if let Err(e) = s.table.flush() {- log::debug!("Progressive table reveal flush failed: {}", e);+ tracing::debug!(error = %e, "Progressive table reveal flush failed: {}", e);}}@@ -1722,7 +1722,7 @@ pub fn collect(if s.table.update_footer(footer_msg)&& let Err(e) = s.table.flush(){- log::debug!("Progressive table flush failed: {}", e);+ tracing::debug!(error = %e, "Progressive table flush failed: {}", e);}}// Picker has no stall UI; per-update repaints keep it@@ -2103,7 +2103,8 @@ pub fn populate_item(// Handle timeout (silent for statusline - just log it)if let DrainOutcome::TimedOut { received_count, .. } = drain_outcome {- log::warn!(+ tracing::warn!(+ count = received_count,"populate_item timed out after {}s ({received_count} results received)",results::DRAIN_TIMEOUT.as_secs());@@ -2111,10 +2112,17 @@ pub fn populate_item(// Log errors silently (statusline shouldn't spam warnings)if !errors.is_empty() {- log::warn!("populate_item had {} task errors", errors.len());+ tracing::warn!(+ count = errors.len(),+ "populate_item had {} task errors",+ errors.len()+ );for error in &errors {let kind_str: &'static str = error.kind.into();- log::debug!(+ tracing::debug!(+ item = error.item_idx,+ kind = %kind_str,+ error = %error.message," - item {}: {} ({})",error.item_idx,kind_str,diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex 2257fa1da..9b16263a1 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -82,7 +82,7 @@ impl TaskContext {let sha = &self.branch_ref.commit_sha;let short_sha = &sha[..sha.len().min(8)];let branch = self.branch_ref.short_name().unwrap_or(short_sha);- log::debug!("Task {} timed out for {}", kind_str, branch);+ tracing::debug!(kind = %kind_str, branch = %branch, "Task {} timed out for {}", kind_str, branch);ErrorCause::Timeout} else {ErrorCause::Otherdiff --git a/src/commands/list/custom_columns.rs b/src/commands/list/custom_columns.rsindex 227315b2c..5e82254b0 100644--- a/src/commands/list/custom_columns.rs+++ b/src/commands/list/custom_columns.rs@@ -113,7 +113,7 @@ pub fn expand_custom_columns(|(column, name)| match env.template_from_named_str(name, &column.template) {Ok(template) => Some(template),Err(e) => {- log::debug!("[{name}] parse failed after validation: {e}");+ tracing::debug!(name = %name, error = %e, "[{name}] parse failed after validation: {e}");None}},@@ -174,7 +174,7 @@ pub fn expand_custom_columns(match template.render(&context) {Ok(value) => sanitize_cell(&value),Err(e) => {- log::debug!("[{name}] render failed for row {branch:?}: {e}");+ tracing::debug!(name = %name, branch = ?branch, error = %e, "[{name}] render failed for row {branch:?}: {e}");String::new()}}diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex d7d2bcb7c..0abc0398d 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -194,7 +194,11 @@ impl LayoutConfig {// Debug: Log if cell exceeds its allocated widthif cell_width > column.width {- log::debug!(+ tracing::debug!(+ column = ?column.kind,+ allocated = column.width,+ actual = cell_width,+ excess = cell_width - column.width,"Cell overflow: column={:?} allocated={} actual={} excess={}",column.kind,column.width,@@ -212,7 +216,7 @@ impl LayoutConfig {}let final_width = line.width();- log::debug!("Rendered line width: {}", final_width);+ tracing::debug!(width = final_width, "Rendered line width: {}", final_width);line}diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 56df4a829..50d90d9b7 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -380,7 +380,7 @@ impl PickerCollector {// this is a genuine `git branch -D` failure. The row is// restored anyway because the branch still exists (see// `removal_target_still_present`) — surface the cause.- log::warn!("picker: failed to delete branch '{branch_name}': {e:#}");+ tracing::warn!(branch = %branch_name, error = %e, "picker: failed to delete branch '{branch_name}': {e:#}");}}}@@ -458,7 +458,7 @@ impl PickerCollector {.name(format!("picker-remove-{selected_output}")).spawn(move || {if let Err(e) = Self::do_removal(&repo, &result, &approvals) {- log::warn!("picker: removal of '{selected_output}' errored: {e:#}");+ tracing::warn!(selected_output = %selected_output, error = %e, "picker: removal of '{selected_output}' errored: {e:#}");}if removal_target_still_present(&repo, &result)&& let Some((item, pos)) = removed@@ -763,7 +763,7 @@ fn removal_target_still_present(repo: &Repository, result: &RemoveResult) -> boo/// [`removal_will_remove_target`]), the row must reappear. This re-inserts it into/// `shared_items` at its original slot, stashes/// a `kept` warning (drained to stderr once skim releases the terminal; the full-/// error, if any, is in the `log::warn!` the caller emits), then reloads the+/// error, if any, is in the `tracing::warn!` the caller emits), then reloads the/// picker to re-stream the restored list and lands the cursor back on the row.////// The reload command is any string that is neither `remove <token>` nor the@@ -867,7 +867,7 @@ impl CommandCollector for PickerCollector {}}Err(e) => {- log::info!("picker: cannot remove '{selected_output}': {e:#}");+ tracing::info!(selected_output = %selected_output, error = %e, "picker: cannot remove '{selected_output}': {e:#}");}}}diff --git a/src/commands/picker/pager.rs b/src/commands/picker/pager.rsindex bcbe251bf..7139d3d1d 100644--- a/src/commands/picker/pager.rs+++ b/src/commands/picker/pager.rs@@ -80,7 +80,7 @@ pub(super) fn diff_pager() -> Option<&'static String> {/// Returns the paged output, or the original text if the pager fails or times out./// Sets `COLUMNS` environment variable for pagers like delta with side-by-side mode.pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> String {- log::debug!("Piping through pager: {}", pager_cmd);+ tracing::debug!(pager_cmd = %pager_cmd, "Piping through pager: {}", pager_cmd);// Spawn pager with stdin pipedlet mut cmd = Command::new("sh");@@ -94,7 +94,7 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> Slet mut child = match cmd.spawn() {Ok(child) => child,Err(e) => {- log::debug!("Failed to spawn pager: {}", e);+ tracing::debug!(error = %e, "Failed to spawn pager: {}", e);return text.to_string();}};@@ -131,17 +131,17 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S{return s;}- log::debug!("Pager exited with status: {}", status);+ tracing::debug!(status = %status, "Pager exited with status: {}", status);}Ok(None) => {// Timed out - kill pager and clean up- log::debug!("Pager timed out after {:?}", PAGER_TIMEOUT);+ tracing::debug!(timeout = ?PAGER_TIMEOUT, "Pager timed out after {:?}", PAGER_TIMEOUT);let _ = child.kill();let _ = child.wait();let _ = reader_thread.join();}Err(e) => {- log::debug!("Failed to wait for pager: {}", e);+ tracing::debug!(error = %e, "Failed to wait for pager: {}", e);let _ = child.kill();let _ = child.wait();let _ = reader_thread.join();diff --git a/src/commands/process.rs b/src/commands/process.rsindex 4fe24f8e9..0ad69504c 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -199,7 +199,8 @@ pub fn spawn_detached() -> anyhow::Result<std::path::PathBuf> {let (log_path, log_file) = create_detach_log(repo, branch, hook_log)?;- log::debug!(+ tracing::debug!(+ command = %command,"$ {} (detached, logging to {})",command,log_path.file_name().unwrap_or_default().to_string_lossy()@@ -356,7 +357,8 @@ pub fn spawn_detached_exec() -> anyhow::Result<std::path::PathBuf> {let (log_path, log_file) = create_detach_log(repo, branch, hook_log)?;- log::debug!(+ tracing::debug!(+ program = %program.display(),"$ {} {} (detached, logging to {})",program.display(),args.join(" "),@@ -539,7 +541,7 @@ pub fn sweep_stale_trash(repo: &Repository) {&HookLog::shared(InternalOp::TrashSweep),None,) {- log::debug!("Failed to spawn stale trash sweep: {e}");+ tracing::debug!(error = %e, "Failed to spawn stale trash sweep: {e}");}}diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex d700f8a98..af5fbe7c0 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -254,8 +254,8 @@ fn parse_rate_limits(v: &serde_json::Value) -> Vec<RateLimitReading> {// distinguishes "no rate_limits key" from "stdin context never parsed"// (which logs nothing at all).match v.get("rate_limits") {- Some(rl) => log::debug!("rate_limits input: {rl}"),- None => log::debug!("rate_limits input: absent"),+ Some(rl) => tracing::debug!(rate_limits = %rl, "rate_limits input: {rl}"),+ None => tracing::debug!("rate_limits input: absent"),}let mut out = Vec::new();for (key, window_secs, priors) in [@@ -620,7 +620,7 @@ fn select_binding_window(let t = elapsed.clamp(0.0, 1.0);let p = p_over(u, t, r.priors);let lockout = expected_lockout(u, t.max(0.001), r.priors);- log::debug!(+ tracing::debug!("rate-limit {} window: used={:.1}% elapsed={:.1}% pace={:.2}× P(over)={p:.3} lockout={lockout:.3} cost={:.3} (show threshold {RATE_LIMIT_P_THRESHOLD})",r.name,u * 100.0,@@ -1517,18 +1517,25 @@ mod tests {#[test]fn test_select_binding_window_logs_at_debug() {- // The per-window debug line's format args are lazily skipped at- // default verbosity; enabling Debug evaluates them. The- // not-yet-started window (negative elapsed, clamped to 0) is the- // case the `t.max(0.001)` division guard exists for.- log::set_max_level(log::LevelFilter::Debug);+ use tracing::Subscriber;+ use tracing_subscriber::Registry;+ use tracing_subscriber::layer::{Layer, SubscriberExt};++ // The per-window debug line's format args are lazily skipped unless a+ // DEBUG-level subscriber is active; installing one forces them to+ // evaluate. The not-yet-started window (negative elapsed, clamped to+ // 0) is the case the `t.max(0.001)` division guard exists for.+ struct Sink;+ impl<S: Subscriber> Layer<S> for Sink {}+let now = 1_700_000_000_i64;let readings = [make_reading(80.0, 0.60, &FIVE_HOUR_PRIORS, now, FIVE_HOUR_SECS),make_reading(5.0, -0.10, &SEVEN_DAY_PRIORS, now, SEVEN_DAY_SECS),];- let sel = select_binding_window(&readings, now);- log::set_max_level(log::LevelFilter::Off);+ let subscriber = Registry::default().with(Sink);+ let sel =+ tracing::subscriber::with_default(subscriber, || select_binding_window(&readings, now));assert_eq!(sel.unwrap().used_percentage, 80.0);}diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex 82db3db21..96a50323c 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -438,7 +438,7 @@ pub fn handle_no_ff_merge(worktrunk::path::format_path_for_display(wt_path))));- log::warn!("Failed to sync target worktree: {e}");+ tracing::warn!(error = %e, "Failed to sync target worktree: {e}");}}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 4bd7b42f1..46a15d602 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -274,7 +274,7 @@ fn resolve_fork_ref(let expected_remote = match remote_ref::find_remote(repo, info) {Ok(remote) => Some(remote),Err(e) => {- log::debug!("Could not resolve remote for {}: {e:#}", ref_type.name());+ tracing::debug!(name = %ref_type.name(), error = %e, "Could not resolve remote for {}: {e:#}", ref_type.name());None}};diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex cb6dab48d..28dfb4720 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -988,11 +988,12 @@ pub fn expand_template(// -vv: Full debug logging with vars// Redact credentials from values to prevent leaking tokens in logsif verbose >= 2 {- log::debug!("[template:{name}] template={template:?}");+ tracing::debug!(name = %name, template = ?template, "[template:{name}] template={template:?}");// Sort keys for deterministic output in testslet mut sorted_vars: Vec<_> = vars.iter().collect();sorted_vars.sort_by_key(|(k, _)| *k);- log::debug!(+ tracing::debug!(+ name = %name,"[template:{name}] vars={{{}}}",sorted_vars.iter()@@ -1033,7 +1034,7 @@ pub fn expand_template(// -vv: Full debug logging with result// Redact credentials from result to prevent leaking tokens in logsif verbose >= 2 {- log::debug!("[template:{name}] result={:?}", redact_credentials(&result));+ tracing::debug!(name = %name, "[template:{name}] result={:?}", redact_credentials(&result));}// -v: Nice styled output showing template expansion. The source templatediff --git a/src/copy.rs b/src/copy.rsindex 3a5428631..a6a618ab0 100644--- a/src/copy.rs+++ b/src/copy.rs@@ -180,7 +180,7 @@ pub fn copy_dir_recursive(dest: dest_path,});} else {- log::debug!("skipping non-regular file: {}", src_path.display());+ tracing::debug!(path = %src_path.display(), "skipping non-regular file: {}", src_path.display());}}}diff --git a/src/git/ci_platform.rs b/src/git/ci_platform.rsindex 116a4e57b..e66ed5cb2 100644--- a/src/git/ci_platform.rs+++ b/src/git/ci_platform.rs@@ -60,7 +60,7 @@ impl Repository {&& let Some(url) = self.effective_remote_url(remote)&& let Some(platform) = platform_from_url(&url){- log::debug!("Detected CI platform {platform} from remote '{remote}' (hint)");+ tracing::debug!(platform = %platform, remote = %remote, "Detected CI platform {platform} from remote '{remote}' (hint)");return Some(platform);}@@ -68,7 +68,7 @@ impl Repository {&& let Some(url) = self.effective_remote_url(&remote)&& let Some(platform) = platform_from_url(&url){- log::debug!("Detected CI platform {platform} from remote '{remote}'");+ tracing::debug!(platform = %platform, remote = %remote, "Detected CI platform {platform} from remote '{remote}'");return Some(platform);}@@ -90,11 +90,12 @@ impl Repository {.map(str::to_string)?;match raw.parse::<CiPlatform>() {Ok(platform) => {- log::debug!("Using CI platform from config: {platform}");+ tracing::debug!(platform = %platform, "Using CI platform from config: {platform}");Some(platform)}Err(_) => {- log::warn!(+ tracing::warn!(+ value = %raw,"Invalid CI platform in config: '{raw}'. Expected 'github', 'gitlab', 'gitea', or 'azure-devops'.");Nonediff --git a/src/git/fsmonitor.rs b/src/git/fsmonitor.rsindex a58e00574..2920d529a 100644--- a/src/git/fsmonitor.rs+++ b/src/git/fsmonitor.rs@@ -422,13 +422,16 @@ pub fn reap_orphan_fsmonitor_daemons(repo: &Repository) {return;}- log::debug!(+ tracing::debug!(+ count = orphans.len(),"Reaping {} orphaned fsmonitor daemon(s): {:?}",orphans.len(),orphans);let gone = escalate_terminate(&NixSignaller, &orphans, REAP_KILL_DEADLINE);- log::debug!(+ tracing::debug!(+ gone = %gone,+ count = orphans.len(),"Orphaned fsmonitor reap: {gone}/{} terminated",orphans.len());diff --git a/src/git/recover.rs b/src/git/recover.rsindex 294a52ecc..e7b03daea 100644--- a/src/git/recover.rs+++ b/src/git/recover.rs@@ -114,7 +114,9 @@ fn recover_from_path(deleted_path: &Path) -> Option<Repository> {let mut candidate = deleted_path.parent()?;loop {if candidate.is_dir() {- log::debug!(+ tracing::debug!(+ path = %deleted_path.display(),+ ancestor = %candidate.display(),"Deleted CWD recovery: path={}, checking ancestor={}",deleted_path.display(),candidate.display()diff --git a/src/git/remove.rs b/src/git/remove.rsindex ddc8f7869..1069fc039 100644--- a/src/git/remove.rs+++ b/src/git/remove.rs@@ -125,7 +125,7 @@ pub fn stop_fsmonitor_daemon(worktree: &WorkingTree) {let socket = match worktree.git_dir() {Ok(git_dir) => git_dir.join("fsmonitor--daemon.ipc"),Err(e) => {- log::debug!("fsmonitor: could not resolve git dir, skipping force-kill: {e}");+ tracing::debug!(error = %e, "fsmonitor: could not resolve git dir, skipping force-kill: {e}");return;}};@@ -159,7 +159,7 @@ fn force_kill_fsmonitor_via_socket(socket: &Path) {{Ok(output) => output,Err(e) => {- log::debug!("fsmonitor: lsof failed, cannot force-kill: {e}");+ tracing::debug!(error = %e, "fsmonitor: lsof failed, cannot force-kill: {e}");return;}};@@ -373,7 +373,7 @@ pub fn stage_worktree_removal(repo: &Repository, worktree_path: &Path) -> Optionif std::fs::rename(worktree_path, &staged_path).is_ok() {if let Err(e) = repo.prune_worktrees() {- log::debug!("Failed to prune worktrees after rename: {e}");+ tracing::debug!(error = %e, "Failed to prune worktrees after rename: {e}");}Some(staged_path)} else {diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex 0aae6e912..627da75e3 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -372,7 +372,7 @@ impl Repository {// Detect: try remote, then local inferencelet detected = self.detect_from_remote().or_else(|| {self.infer_default_branch_locally()- .inspect_err(|e| log::debug!("Local inference failed: {e}"))+ .inspect_err(|e| tracing::debug!(error = %e, "Local inference failed: {e}")).ok()});@@ -380,7 +380,7 @@ impl Repository {if let Some(ref branch) = detected&& let Err(e) = self.set_config_value("worktrunk.default-branch", branch){- log::debug!("Failed to persist default-branch cache: {e}");+ tracing::debug!(error = %e, "Failed to persist default-branch cache: {e}");}detecteddiff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 4a879ab97..6a2bfb11a 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -316,7 +316,10 @@ impl Repository {.parse().unwrap_or(0);if target_commit_count > PATCH_ID_SCAN_MAX_COMMITS {- log::debug!(+ tracing::debug!(+ target_commit_count,+ merge_base = %merge_base,+ target = %target,"skipping patch-id squash-merge check: {target_commit_count} commits in {merge_base}..{target} exceeds cap of {PATCH_ID_SCAN_MAX_COMMITS}");return Ok(false);diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex d4d18fd30..740c8187b 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1181,7 +1181,7 @@ impl Repository {pub fn start_fsmonitor_daemon_at(&self, path: &Path) {let context = path_to_logging_context(path);let cmd_str = "git fsmonitor--daemon start";- log::debug!("$ {cmd_str} [{context}]");+ tracing::debug!(cmd = cmd_str, context = %context, "$ {cmd_str} [{context}]");let mut cmd = std::process::Command::new("git");cmd.args(["fsmonitor--daemon", "start"]).current_dir(path)@@ -1198,12 +1198,12 @@ impl Repository {Ok(status) => {trace.complete(status.success());if !status.success() {- log::debug!("fsmonitor daemon start exited {status} (usually fine)");+ tracing::debug!(status = %status, "fsmonitor daemon start exited {status} (usually fine)");}}Err(e) => {trace.fail(&e);- log::debug!("fsmonitor daemon start failed (usually fine): {e}");+ tracing::debug!(error = %e, "fsmonitor daemon start failed (usually fine): {e}");}}}diff --git a/src/git/repository/ref_snapshot.rs b/src/git/repository/ref_snapshot.rsindex 5f7a2dbeb..d736ede5a 100644--- a/src/git/repository/ref_snapshot.rs+++ b/src/git/repository/ref_snapshot.rs@@ -516,7 +516,7 @@ fn scan_ahead_behind(let output = match repo.run_command(&args) {Ok(out) => out,Err(e) => {- log::debug!("RefSnapshot ahead/behind batch failed for base {base}: {e}");+ tracing::debug!(base = %base, error = %e, "RefSnapshot ahead/behind batch failed for base {base}: {e}");return HashMap::new();}};diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex 784f54d03..97027ccc2 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -168,7 +168,7 @@ impl Repository {None,/* force_hint */ true,)?;- log::debug!("Using --force for worktree removal due to initialized submodules");+ tracing::debug!("Using --force for worktree removal due to initialized submodules");}let mut args = vec!["worktree", "remove"];if use_force {diff --git a/src/help_pager.rs b/src/help_pager.rsindex e49f569d4..9f5fe3e50 100644--- a/src/help_pager.rs+++ b/src/help_pager.rs@@ -58,7 +58,7 @@ fn detect_help_pager() -> Option<String> {if shell.is_posix {Some("less".to_string())} else {- log::debug!("No POSIX shell available, skipping pager (less not available)");+ tracing::debug!("No POSIX shell available, skipping pager (less not available)");None}}@@ -84,13 +84,13 @@ fn detect_help_pager() -> Option<String> {pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) {// Short help (-h) never uses a pagerif !use_pager {- log::debug!("Short help (-h) requested, printing directly to stdout");+ tracing::debug!("Short help (-h) requested, printing directly to stdout");print!("{}", help_text);return;}let Some(pager_cmd) = detect_help_pager() else {- log::debug!("No pager configured, printing help directly to stdout");+ tracing::debug!("No pager configured, printing help directly to stdout");print!("{}", help_text);return;};@@ -98,14 +98,14 @@ pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) {// Only page when our output destination is a terminal.// If stdout is piped/redirected (e.g., `wt --help | grep foo`), print directly.if !std::io::stdout().is_terminal() {- log::debug!("stdout is not a TTY, skipping pager");+ tracing::debug!("stdout is not a TTY, skipping pager");print!("{}", help_text);return;}- log::debug!("Invoking pager: {}", pager_cmd);+ tracing::debug!(pager_cmd = %pager_cmd, "Invoking pager: {}", pager_cmd);if let Err(e) = pipe_through_pager(&pager_cmd, help_text) {- log::debug!("Pager failed, falling back to stdout: {}", e);+ tracing::debug!(error = %e, "Pager failed, falling back to stdout: {}", e);print!("{}", help_text);}}@@ -119,7 +119,7 @@ pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) {fn pipe_through_pager(pager_cmd: &str, help_text: &str) -> std::io::Result<()> {let less_flags = compute_less_flags(std::env::var("LESS").ok().as_deref());let shell = ShellConfig::get().map_err(std::io::Error::other)?;- log::debug!("$ {} (pager)", pager_cmd);+ tracing::debug!(pager_cmd = %pager_cmd, "$ {} (pager)", pager_cmd);let mut cmd = shell.command(pager_cmd);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);let mut child = cmd.stdin(Stdio::piped()).env("LESS", &less_flags).spawn()?;diff --git a/src/llm.rs b/src/llm.rsindex 4d547cb6a..e7e3c0602 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -235,7 +235,9 @@ pub(crate) fn prepare_diff(diff: String, stat: String) -> PreparedDiff {return PreparedDiff { diff, stat };}- log::debug!(+ tracing::debug!(+ count = diff.len(),+ threshold = DIFF_SIZE_THRESHOLD,"Diff size ({} chars) exceeds threshold ({}), filtering",diff.len(),DIFF_SIZE_THRESHOLD@@ -250,7 +252,11 @@ pub(crate) fn prepare_diff(diff: String, stat: String) -> PreparedDiff {let lock_files_removed = sections.len() - filtered_sections.len();if lock_files_removed > 0 {- log::debug!("Filtered out {} lock file(s)", lock_files_removed);+ tracing::debug!(+ count = lock_files_removed,+ "Filtered out {} lock file(s)",+ lock_files_removed+ );}let filtered_diff: String = filtered_sections@@ -267,7 +273,8 @@ pub(crate) fn prepare_diff(diff: String, stat: String) -> PreparedDiff {}// Step 2: Truncate each file and limit file count- log::debug!(+ tracing::debug!(+ count = filtered_diff.len(),"Still too large ({} chars), truncating to {} lines/file, {} files max",filtered_diff.len(),MAX_LINES_PER_FILE,diff --git a/src/log_files.rs b/src/log_files.rsindex 6178bc941..bdbf84a81 100644--- a/src/log_files.rs+++ b/src/log_files.rs@@ -1,10 +1,17 @@//! On-disk log file sinks for `-vv` debug output.//!-//! At `-vv`, two files are written in the repo's `.git/wt/logs/` directory:+//! At `-vv`, three files are written in the repo's `.git/wt/logs/` directory://!//! - [`TRACE`] → `trace.log`: structured records, `$ cmd [context]`//! headers, and bounded subprocess previews. High-signal, bounded size —//! safe to embed in `diagnostic.md` bug reports.+//! - [`TRACE_JSONL`] → `trace.jsonl`: the same event stream as `trace.log`+//! (minus the command output), but one JSON object per line instead of the+//! text grammar. Each event's fields serialize generically: a `[wt-trace]`+//! record comes through rich (`cmd`, `seq`, `dur_us`, …), a free-form+//! `log::*` line as `{"message":…}` until its call site is given fields.+//! Machine-first (agents, `jq`); written alongside `trace.log`, not in+//! place of it.//! - [`SUBPROCESS`] → `subprocess.log`: raw, uncapped subprocess//! stdout/stderr bodies captured by `shell_exec::Cmd`, each block//! introduced by a `$ cmd … [seq=N tid=T]` header whose `seq` joins it to@@ -98,6 +105,10 @@ pub(crate) static TRACE: LogSink = LogSink {file: OnceLock::new(),filename: "trace.log",};+pub(crate) static TRACE_JSONL: LogSink = LogSink {+ file: OnceLock::new(),+ filename: "trace.jsonl",+};pub(crate) static SUBPROCESS: LogSink = LogSink {file: OnceLock::new(),filename: "subprocess.log",@@ -111,6 +122,7 @@ pub(crate) static SUBPROCESS: LogSink = LogSink {/// here doesn't emit records to a half-built pipeline.pub(crate) fn init() {TRACE.init();+ TRACE_JSONL.init();SUBPROCESS.init();}@@ -159,6 +171,16 @@ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TraceMakeWriter {}}+/// `MakeWriter` for the trace.jsonl layer: always writes to `TRACE_JSONL`.+pub(crate) struct TraceJsonlMakeWriter;++impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TraceJsonlMakeWriter {+ type Writer = SinkWriter;+ fn make_writer(&'a self) -> SinkWriter {+ TRACE_JSONL.writer()+ }+}+/// `MakeWriter` for the subprocess.log layer: always writes to `SUBPROCESS`.pub(crate) struct SubprocessMakeWriter;diff --git a/src/logging.rs b/src/logging.rsindex fd78250a3..9f92a4f06 100644--- a/src/logging.rs+++ b/src/logging.rs@@ -1,6 +1,6 @@//! Tracing-subscriber setup for the `wt` binary.//!-//! Three layered subscribers cooperate to give each verbosity level the+//! Four layered subscribers cooperate to give each verbosity level the//! routing it needs. Filtering is structural (per-layer `Filter`), not done//! after-the-fact in a format closure://!@@ -8,12 +8,22 @@//! | ---------------- | --------------------------------------------------- | ----------------- |//! | stderr | `$RUST_LOG` or flag baseline (`Off`/`Info`/`Info`) | styled with ANSI |//! | `trace.log` | `-vv` only, excludes `SUBPROCESS_FULL_TARGET` | plain text |+//! | `trace.jsonl` | `-vv` only, excludes both subprocess targets | one JSON object per event |//! | `subprocess.log` | `-vv` only, includes only `SUBPROCESS_FULL_TARGET` | raw bodies + `$ cmd … seq=N` headers |//!//! At `-vv` the stderr layer keeps its Info baseline — `-vv` is a strict//! superset of `-v`, with Debug-level records (the noisy ones, including//! the bounded subprocess preview) routed to the file layers only.//!+//! Each layer's target filter carries an explicit TRACE `max_level_hint`+//! (see [`target_filter`]) so the `EnvFilter`'s level bound survives the+//! `Filter::and` and reaches the global `LevelFilter`. That keeps the native+//! `tracing::*` macros cheap: below the active verbosity a `debug!` is gated+//! out before it builds its fields, exactly as `log::debug!` short-circuits+//! on `log::max_level`. Without the hint, `And`'s `cmp::min` (where a `None`+//! hint sorts below any `Some`) would erase the bound, pin the global level+//! at TRACE, and force every `debug!` to format its args even at `-v0`.+//!//! The `log` crate calls (used throughout the codebase) are bridged into//! `tracing` by [`tracing_log::LogTracer::init`] — every layer above sees//! both native `tracing::*` events and forwarded `log::*` records.@@ -24,17 +34,17 @@ use std::fmt::{self, Write as _};use color_print::cformat;use tracing::{Event, Subscriber};use tracing_subscriber::Layer;-use tracing_subscriber::filter::{EnvFilter, FilterExt, LevelFilter, filter_fn};+use tracing_subscriber::filter::{EnvFilter, FilterExt, FilterFn, LevelFilter, filter_fn};use tracing_subscriber::fmt::{FmtContext, FormatEvent, FormatFields, format::Writer};use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::registry::LookupSpan;use tracing_subscriber::util::SubscriberInitExt;-use worktrunk::shell_exec::SUBPROCESS_FULL_TARGET;+use worktrunk::shell_exec::{SUBPROCESS_BOUNDED_TARGET, SUBPROCESS_FULL_TARGET};use worktrunk::styling::{eprintln, format_with_gutter, info_message};-use worktrunk::trace::WT_TRACE_TARGET;+use worktrunk::trace::{WT_TRACE_TARGET, now_us, thread_id};use worktrunk::utils::escape_controls;-use crate::log_files::{self, SubprocessMakeWriter, TraceMakeWriter};+use crate::log_files::{self, SubprocessMakeWriter, TraceJsonlMakeWriter, TraceMakeWriter};use crate::output;/// Single-character thread label (e.g. `a`, `b`, …, `A`, …) used to group@@ -320,6 +330,103 @@ fn format_wt_trace(f: &WtTraceFields) -> String {}}+/// Generic field collector for `trace.jsonl`: serializes whatever typed fields+/// an event carries into a JSON object, regardless of which fields they are.+///+/// This is the structured counterpart of [`event_message`] (which keeps only+/// the `message` field). A `[wt-trace]` event arrives with its full typed+/// grammar (`kind`, `ts`, `seq`, `cmd`, `dur_us`, `ok`, ...) and serializes+/// rich; a bridged `log::*` / bare `tracing::*` call arrives with just+/// `message` and serializes as `{"message":...}`. Nothing here is+/// `[wt-trace]`-specific, so a freshly-structured call site+/// (`tracing::warn!(branch = %b, "...")`) gains a queryable `branch` field with+/// no change to this layer.+///+/// serde_json owns all string escaping, so control bytes and embedded quotes in+/// any field are encoded losslessly -- the JSON path needs no `escape_controls`.+#[derive(Default)]+struct JsonFieldVisitor {+ map: serde_json::Map<String, serde_json::Value>,+}++impl tracing::field::Visit for JsonFieldVisitor {+ fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {+ self.map.insert(field.name().to_owned(), value.into());+ }++ fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {+ self.map.insert(field.name().to_owned(), value.into());+ }++ fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {+ self.map.insert(field.name().to_owned(), value.into());+ }++ fn record_str(&mut self, field: &tracing::field::Field, value: &str) {+ self.map.insert(field.name().to_owned(), value.into());+ }++ fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {+ // `message` (an `Arguments`) and `%`/`?`-formatted values arrive here;+ // store their rendered form as a JSON string.+ self.map+ .insert(field.name().to_owned(), format!("{value:?}").into());+ }+}++/// Render a single event as one line of `trace.jsonl`.+///+/// Collects the event's typed fields via [`JsonFieldVisitor`], then fills in+/// `ts`/`tid` from the runtime *only if the event did not carry them* (a+/// `[wt-trace]` record sets its own, captured at the precise event moment; a+/// bridged `log::*` line carries neither, so it gets the emission-time values),+/// and stamps the metadata `level`. Field order is serde_json's default+/// (sorted) -- irrelevant to a machine reader.+fn event_json(event: &Event<'_>) -> String {+ let mut visitor = JsonFieldVisitor::default();+ event.record(&mut visitor);+ let map = &mut visitor.map;+ map.entry("ts".to_owned())+ .or_insert_with(|| now_us().into());+ map.entry("tid".to_owned())+ .or_insert_with(|| thread_id().into());+ map.insert(+ "level".to_owned(),+ event+ .metadata()+ .level()+ .as_str()+ .to_ascii_lowercase()+ .into(),+ );+ serde_json::Value::Object(visitor.map).to_string()+}++/// `trace.jsonl` formatter: one JSON object per event, fields serialized+/// generically by [`event_json`].+///+/// The layer admits every event except the two subprocess-output targets (see+/// [`build_trace_jsonl_layer`]), so both structured `[wt-trace]` records and+/// free-form `log::*` messages arrive here. The former serialize rich (their+/// full typed grammar); the latter as `{"message":...}` until their call site+/// is given fields.+struct TraceJsonlFormat;++impl<S, N> FormatEvent<S, N> for TraceJsonlFormat+where+ S: Subscriber + for<'a> LookupSpan<'a>,+ N: for<'a> FormatFields<'a> + 'static,+{+ fn format_event(+ &self,+ _ctx: &FmtContext<'_, S, N>,+ mut writer: Writer<'_>,+ event: &Event<'_>,+ ) -> fmt::Result {+ writeln!(writer, "{}", event_json(event))+ }+}+/// `subprocess.log` formatter: the message verbatim. Body lines are already/// prefixed (` …` / ` ! …`) by `shell_exec::format_stream_full`, and each/// command's block is introduced by a `$ cmd … seq=N` header line emitted by@@ -353,7 +460,7 @@ where/// are dropped by the default no-op `log` logger, which is the right/// behavior — there's nothing meaningful to attribute the call to before/// the subscriber exists.-/// 3. Build three layered subscribers, each gated by both a verbosity check+/// 3. Build four layered subscribers, each gated by both a verbosity check/// and the relevant `LogSink::is_active()` so a failed file open turns/// its layer into a no-op rather than silently dropping records./// 4. Bridge `log::*` into tracing via `LogTracer`. Idempotent on@@ -371,6 +478,7 @@ pub(crate) fn init(verbose_level: u8) {// naturally with subscriber `.with(...)` calls.let stderr_layer = build_stderr_layer(verbose_level);let trace_layer = build_trace_layer(verbose_level);+ let trace_jsonl_layer = build_trace_jsonl_layer(verbose_level);let subprocess_layer = build_subprocess_layer(verbose_level);// `try_init` fails only if a subscriber is already installed (the@@ -380,6 +488,7 @@ pub(crate) fn init(verbose_level: u8) {let _ = tracing_subscriber::registry().with(stderr_layer).with(trace_layer)+ .with(trace_jsonl_layer).with(subprocess_layer).try_init();@@ -387,16 +496,20 @@ pub(crate) fn init(verbose_level: u8) {// init: `LogTracer::enabled` consults the tracing dispatcher.//// The builder's `with_max_level` caps `log::max_level()` — the static- // gate `log_enabled!` checks before format args are evaluated. Mirror- // the env-wins-when-set semantics the layer filters use (PR #2901):+ // gate `log_enabled!` checks before a `log::*` record evaluates its+ // format args. Worktrunk's own emit sites are native `tracing::*`, gated+ // by the global level hint the layer filters now expose (see+ // `target_filter`), so this cap is specifically for the two `log`-API+ // consumers that hint can't reach: the `log::*` records forwarded from+ // dependencies, and the `log::log_enabled!` deep-logging guard in+ // `shell_exec::log_output`.+ //+ // Mirror the env-wins-when-set semantics the layer filters use (PR #2901):// if `RUST_LOG` is set, its level wins; otherwise the verbosity flag// baseline applies. Without an explicit cap, the default// `LevelFilter::max()` would always pass the static check, forcing- // every `log::debug!(…)` site to evaluate its format args — exposing- // arithmetic that's safe today only because the macro short-circuits- // (e.g. `now_secs - cached.checked_at` in `list/ci_status` is fine- // under monotonic-ish clocks but panics when args are evaluated- // against a clock-skewed fixture).+ // every dependency `log::debug!(…)` to format its args even when no+ // sink is active.let _ = tracing_log::LogTracer::builder().with_max_level(effective_log_max_level(verbose_level, rust_log_level())).init();@@ -465,6 +578,25 @@ fn parse_verbose_level(raw: Option<&str>) -> u8 {raw.and_then(|v| v.trim().parse::<u8>().ok()).unwrap_or(0)}+/// Wrap a target predicate as a `Filter` that bounds by callsite *target*,+/// never by level — and says so via an explicit TRACE `max_level_hint`.+///+/// A bare [`filter_fn`] reports no hint (`None`). [`FilterExt::and`] returns+/// `None` if *either* side lacks one (`cmp::min`, and a `None` hint sorts+/// below any `Some`), so ANDing a hintless target filter onto an `EnvFilter`+/// erases its level bound. That `None` then propagates through the layered+/// subscriber's `pick_level_hint` up to the global `LevelFilter::current()`,+/// pinning it at TRACE — at which point the `tracing::*` macros stop+/// short-circuiting and build their fields at every verbosity, even `-v0`+/// where nothing records them. Tagging the target filter with TRACE (honest:+/// it really does pass all levels) lets the `EnvFilter`'s real bound survive.+fn target_filter<F>(predicate: F) -> FilterFn<F>+where+ F: Fn(&tracing::Metadata<'_>) -> bool,+{+ filter_fn(predicate).with_max_level_hint(LevelFilter::TRACE)+}+/// Stderr layer: the flag sets a baseline (`Off` / `Info` / `Info`) and/// `RUST_LOG`, when set, overrides via the standard directive grammar —/// matching the env-wins-when-set convention (see PR #2901). At `-vv`@@ -483,7 +615,7 @@ wherelet env_filter = EnvFilter::builder().with_default_directive(baseline.into()).from_env_lossy();- let exclude_full = filter_fn(|meta| meta.target() != SUBPROCESS_FULL_TARGET);+ let exclude_full = target_filter(|meta| meta.target() != SUBPROCESS_FULL_TARGET);let layer = tracing_subscriber::fmt::layer().with_writer(std::io::stderr).with_ansi(true)@@ -506,7 +638,7 @@ wherelet env_filter = EnvFilter::builder().with_default_directive(LevelFilter::DEBUG.into()).from_env_lossy();- let exclude_full = filter_fn(|meta| meta.target() != SUBPROCESS_FULL_TARGET);+ let exclude_full = target_filter(|meta| meta.target() != SUBPROCESS_FULL_TARGET);let layer = tracing_subscriber::fmt::layer().with_writer(TraceMakeWriter).with_ansi(false)@@ -515,6 +647,37 @@ whereSome(layer)}+/// `trace.jsonl` layer: every event *except* the two subprocess-output targets,+/// rendered one JSON object per line at the Debug baseline (`RUST_LOG`+/// overrides, matching `trace.log`). Active only when `-vv` opened the file.+///+/// The exclusions are the raw bodies (`SUBPROCESS_FULL_TARGET`, which belong in+/// `subprocess.log`) and the bounded preview (`SUBPROCESS_BOUNDED_TARGET`, the+/// capped gist of that same output) — `trace.jsonl` is the *event* stream, so+/// command output stays out and is reached via `seq` into `subprocess.log`.+/// Everything else flows in: `[wt-trace]` records serialize rich, and free-form+/// `log::*` lines serialize as `{"message":...}` until structured.+fn build_trace_jsonl_layer<S>(verbose_level: u8) -> Option<impl Layer<S>>+where+ S: Subscriber + for<'a> LookupSpan<'a>,+{+ if verbose_level < 2 || !log_files::TRACE_JSONL.is_active() {+ return None;+ }+ let env_filter = EnvFilter::builder()+ .with_default_directive(LevelFilter::DEBUG.into())+ .from_env_lossy();+ let exclude_output = target_filter(|meta| {+ meta.target() != SUBPROCESS_FULL_TARGET && meta.target() != SUBPROCESS_BOUNDED_TARGET+ });+ let layer = tracing_subscriber::fmt::layer()+ .with_writer(TraceJsonlMakeWriter)+ .with_ansi(false)+ .event_format(TraceJsonlFormat)+ .with_filter(env_filter.and(exclude_output));+ Some(layer)+}+/// `subprocess.log` layer: only `SUBPROCESS_FULL_TARGET` records (raw bodies/// and their `$ cmd … seq=N` headers), written through verbatim.fn build_subprocess_layer<S>(verbose_level: u8) -> Option<impl Layer<S>>@@ -524,7 +687,7 @@ whereif verbose_level < 2 || !log_files::SUBPROCESS.is_active() {return None;}- let only_full = filter_fn(|meta| meta.target() == SUBPROCESS_FULL_TARGET);+ let only_full = target_filter(|meta| meta.target() == SUBPROCESS_FULL_TARGET);let layer = tracing_subscriber::fmt::layer().with_writer(SubprocessMakeWriter).with_ansi(false)@@ -561,6 +724,9 @@ fn announce_trace_destination() {// Keeping the "unavailable" note in the header leaves the gutter a clean// list of live, copy-pasteable paths.let mut paths = vec![dir.join("trace.log")];+ if log_files::TRACE_JSONL.path().is_some() {+ paths.push(dir.join("trace.jsonl"));+ }let header = match log_files::SUBPROCESS.path() {Some(_) => {paths.push(dir.join("subprocess.log"));@@ -584,10 +750,49 @@ mod tests {use ansi_str::AnsiStr;use super::{- WT_TRACE_TARGET, WtTraceFields, effective_log_max_level, format_wt_trace,+ WT_TRACE_TARGET, WtTraceFields, effective_log_max_level, event_json, format_wt_trace,label_for_thread_index, parse_verbose_level, style_stderr_line,};+ /// The level-hint footgun this module's `target_filter` exists to dodge:+ /// a bare `filter_fn` reports no `max_level_hint`, and `Filter::and`+ /// collapses to `None` (its `cmp::min` sorts `None` below any `Some`),+ /// erasing the level bound. A `None` hint propagates to the global+ /// `LevelFilter`, pinning it at TRACE so every `tracing::debug!` builds+ /// its fields even at `-v0`. `target_filter` tags the predicate with a+ /// TRACE hint so the `LevelFilter`/`EnvFilter` side survives the `and`.+ #[test]+ fn target_filter_preserves_level_bound_through_and() {+ use tracing::level_filters::LevelFilter;+ use tracing_subscriber::Registry;+ use tracing_subscriber::filter::{FilterExt, filter_fn};+ use tracing_subscriber::layer::Filter;++ // The tagged target filter passes all levels (TRACE), but ANDing it+ // onto an `OFF` level filter keeps the `OFF` bound.+ let target = super::target_filter(|meta| meta.target() != "x");+ assert_eq!(+ Filter::<Registry>::max_level_hint(&target),+ Some(LevelFilter::TRACE)+ );+ let bounded = LevelFilter::OFF.and(target);+ assert_eq!(+ Filter::<Registry>::max_level_hint(&bounded),+ Some(LevelFilter::OFF),+ "the OFF bound must survive ANDing with the target filter"+ );++ // Regression guard: the bare `filter_fn` form collapses the AND hint+ // to `None` — the exact behavior that pinned the global level at TRACE.+ let bare = filter_fn(|meta| meta.target() != "x");+ let collapsed = LevelFilter::OFF.and(bare);+ assert_eq!(+ Filter::<Registry>::max_level_hint(&collapsed),+ None,+ "documents the footgun target_filter fixes"+ );+ }+/// Branch coverage for `label_for_thread_index` — `thread_label` never/// hands it `n == 0` or `n > 52` in practice (Rust's `ThreadId`/// numbering starts at 1 and the main process won't spawn 53+ threads@@ -806,6 +1011,79 @@ mod tests {);}+ /// `event_json` serializes whatever typed fields an event carries, then+ /// stamps `level` and fills `ts`/`tid` only when the event omitted them.+ /// Drives real events through a capture layer (the only way to obtain a+ /// `tracing::Event`). Keys land in serde_json's sorted order.+ #[test]+ fn event_json_serializes_structured_and_freeform_events() {+ use std::sync::{Arc, Mutex};++ use tracing::Subscriber;+ use tracing_subscriber::Registry;+ use tracing_subscriber::layer::{Context, Layer, SubscriberExt};++ struct Capture(Arc<Mutex<Vec<String>>>);+ impl<S: Subscriber> Layer<S> for Capture {+ fn on_event(&self, event: &tracing::Event<'_>, _: Context<'_, S>) {+ self.0.lock().unwrap().push(event_json(event));+ }+ }+ let lines: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));+ let subscriber = Registry::default().with(Capture(lines.clone()));+ tracing::subscriber::with_default(subscriber, || {+ // A full `[wt-trace]` cmd record: every field typed, ts/tid present.+ tracing::debug!(+ target: WT_TRACE_TARGET,+ kind = "cmd_completed",+ ts = 100u64,+ tid = 3u64,+ seq = 1u64,+ context = "worktree",+ cmd = "git status",+ dur_us = 12300u64,+ ok = true,+ );+ // The escaping win: a literal `"` in the command, where the+ // `key="value"` text grammar would truncate the parse. The+ // negative `exit` also drives `JsonFieldVisitor::record_i64`.+ tracing::debug!(+ target: WT_TRACE_TARGET,+ kind = "cmd_completed",+ ts = 100u64,+ tid = 3u64,+ seq = 5u64,+ exit = -1i64,+ cmd = r#"git commit -m "wip""#,+ dur_us = 1u64,+ ok = true,+ );+ // A free-form message with no fields and no ts/tid of its own.+ tracing::warn!("fsmonitor: skipping force-kill");+ });+ let lines = lines.lock().unwrap();++ // Structured record: rich, keys sorted, `level` stamped, ts/tid kept.+ assert_eq!(+ lines[0],+ r#"{"cmd":"git status","context":"worktree","dur_us":12300,"kind":"cmd_completed","level":"debug","ok":true,"seq":1,"tid":3,"ts":100}"#+ );++ // Embedded quote round-trips losslessly.+ let parsed: serde_json::Value = serde_json::from_str(&lines[1]).expect("valid JSON");+ assert_eq!(parsed["cmd"], r#"git commit -m "wip""#);+ assert_eq!(parsed["seq"], 5);+ assert_eq!(parsed["exit"], -1); // exercises record_i64++ // Free-form message: falls through as `{"message":...}`, with `level`+ // stamped and ts/tid injected from the runtime (so present, any value).+ let parsed: serde_json::Value = serde_json::from_str(&lines[2]).expect("valid JSON");+ assert_eq!(parsed["message"], "fsmonitor: skipping force-kill");+ assert_eq!(parsed["level"], "warn");+ assert!(parsed["ts"].is_u64() && parsed["tid"].is_u64());+ assert!(parsed.get("kind").is_none());+ }+/// `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/main.rs b/src/main.rsindex a87bf6168..415ba94d3 100644--- a/src/main.rs+++ b/src/main.rs@@ -975,7 +975,7 @@ fn format_command_error(error: &anyhow::Error) -> String {false,"Multiline error without CommandError or context: {msg}");- log::warn!("Multiline error without CommandError or context: {msg}");+ tracing::warn!("Multiline error without CommandError or context: {msg}");let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");let _ = writeln!(out, "{}", error_message("Command failed"));let _ = writeln!(out, "{}", format_with_gutter(&normalized, None));diff --git a/src/output/commit_generation.rs b/src/output/commit_generation.rsindex 02a63cda8..90869347f 100644--- a/src/output/commit_generation.rs+++ b/src/output/commit_generation.rs@@ -212,7 +212,7 @@ pub fn prompt_commit_generation(config: &mut UserConfig) -> anyhow::Result<bool>let save_result = require_config_path().and_then(|path| config.set_commit_generation_command(command.clone(), &path));if let Err(e) = save_result {- log::error!("Failed to save config: {}", e);+ tracing::error!(error = %e, "Failed to save config: {}", e);eprintln!("{}",hint_message(cformat!(diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex cfa27fa66..6d3d01aac 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -310,7 +310,9 @@ fn spawn_child(command.process_group(0);}- log::debug!(+ tracing::debug!(+ command = %cmd.expanded,+ shell = %shell.name,"$ {} (concurrent #{index}, shell: {})",cmd.expanded,shell.namediff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 7d0024175..b67926b59 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -183,7 +183,7 @@ fn execute_instant_removal_or_fallback()}){- log::debug!("Failed to delete branch {} synchronously: {}", branch, e);+ tracing::debug!(branch = %branch, error = %e, "Failed to delete branch {} synchronously: {}", branch, e);}if changed_directory {// Create an empty placeholder at the original path so the shell's working@@ -258,7 +258,7 @@ fn delete_branch_in_synchronous_fallback(deletion_mode.is_force(),)}) {- log::debug!("Failed to delete branch {branch} in synchronous fallback: {e}");+ tracing::debug!(branch = %branch, error = %e, "Failed to delete branch {branch} in synchronous fallback: {e}");}}diff --git a/src/shell/utils.rs b/src/shell/utils.rsindex c3b6eb72a..16d3361be 100644--- a/src/shell/utils.rs+++ b/src/shell/utils.rs@@ -127,7 +127,7 @@ pub fn detect_zsh_compinit() -> Option<bool> {let probe_cmd =r#"(( $+functions[compdef] )) && echo __WT_COMPINIT_YES__ || echo __WT_COMPINIT_NO__"#;- log::debug!("$ zsh -ic '{}' (probe)", probe_cmd);+ tracing::debug!(command = %probe_cmd, "$ zsh -ic '{}' (probe)", probe_cmd);let mut cmd = Command::new("zsh");cmd.arg("-ic")diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex ab1354179..8dd03f7ad 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -537,6 +537,15 @@ fn command_header(cmd: &str, context: Option<&str>) -> String {////// Below Debug both targets are disabled and this is a no-op.fn log_output(trace: &CommandTrace, stdin: Option<&[u8]>, output: Option<&std::process::Output>) {+ // `log::max_level` (held at the verbosity/`RUST_LOG` ceiling by the+ // `LogTracer` cap in `logging::init`) is the coarse "deep logging on at+ // all?" gate that skips building the full *and* bounded output strings+ // when nothing consumes them. It stays a `log::*` check on purpose: this+ // body feeds both `SUBPROCESS_FULL_TARGET` and `SUBPROCESS_BOUNDED_TARGET`,+ // so the gate must fire whenever *either* deep sink is live — exactly the+ // verbosity cap. A per-target `tracing::enabled!(SUBPROCESS_FULL_TARGET …)`+ // would wrongly skip the bounded preview in the rare case where `-vv`+ // opened `trace.log` but `subprocess.log` failed to open.if !log::log_enabled!(log::Level::Debug) {return;}@@ -547,7 +556,7 @@ fn log_output(trace: &CommandTrace, stdin: Option<&[u8]>, output: Option<&std::p.map(|o| (o.stdout.as_slice(), o.stderr.as_slice())).unwrap_or_default();if !stdin.is_empty() || !stdout.is_empty() || !stderr.is_empty() {- log::debug!(+ tracing::debug!(target: SUBPROCESS_FULL_TARGET,"{} [seq={} tid={}]",command_header(trace.cmd(), trace.context()),@@ -556,19 +565,19 @@ fn log_output(trace: &CommandTrace, stdin: Option<&[u8]>, output: Option<&std::p);}for line in format_stream_full(stdin, " < ") {- log::debug!(target: SUBPROCESS_FULL_TARGET, "{}", line);+ tracing::debug!(target: SUBPROCESS_FULL_TARGET, "{}", line);}for line in format_stream_full(stdout, " ") {- log::debug!(target: SUBPROCESS_FULL_TARGET, "{}", line);+ tracing::debug!(target: SUBPROCESS_FULL_TARGET, "{}", line);}for line in format_stream_full(stderr, " ! ") {- log::debug!(target: SUBPROCESS_FULL_TARGET, "{}", line);+ tracing::debug!(target: SUBPROCESS_FULL_TARGET, "{}", line);}for line in format_stream_bounded(stdout, " ") {- log::debug!(target: SUBPROCESS_BOUNDED_TARGET, "{}", line);+ tracing::debug!(target: SUBPROCESS_BOUNDED_TARGET, "{}", line);}for line in format_stream_bounded(stderr, " ! ") {- log::debug!(target: SUBPROCESS_BOUNDED_TARGET, "{}", line);+ tracing::debug!(target: SUBPROCESS_BOUNDED_TARGET, "{}", line);}}@@ -991,11 +1000,11 @@ impl Cmd {}fn log_run_start(&self, cmd_str: &str) {- log::debug!("{}", command_header(cmd_str, self.context.as_deref()));+ tracing::debug!("{}", command_header(cmd_str, self.context.as_deref()));}fn log_stream_start(&self, cmd_str: &str, exec_mode: &str) {- log::debug!(+ tracing::debug!("{} (streaming, {})",command_header(cmd_str, self.context.as_deref()),exec_mode@@ -1003,7 +1012,7 @@ impl Cmd {}fn log_delayed_stream_start(&self, cmd_str: &str, delay_ms: i64) {- log::debug!(+ tracing::debug!("{} (delayed stream, {}ms)",command_header(cmd_str, self.context.as_deref()),delay_msdiff --git a/src/trace/mod.rs b/src/trace/mod.rsindex 66e5dace4..f0a0d985b 100644--- a/src/trace/mod.rs+++ b/src/trace/mod.rs@@ -44,6 +44,6 @@ 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 emit::{CommandTrace, Span, WT_TRACE_TARGET, instant, now_us, thread_id};pub use parse::{TraceEntry, TraceEntryKind, TraceResult, parse_lines};pub use profile::{CacheReport, Profile};