Skip to content

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

refactor(log): route -vv log pipeline to trace.log instead of stderr (#2892)

Maximilian Roosa50785f70a5c
diff --git a/.typos.toml b/.typos.toml
index d03285d17..911fb0147 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -1,5 +1,5 @@
[files]
-extend-exclude = ["docs/demos/vhs-keystrokes/", "*.snap", "vendor/"]
+extend-exclude = ["docs/demos/vhs-keystrokes/", "*.snap", "vendor/", "*.log"]
[default.extend-words]
# Git commit hashes that typos flags as potential typos
diff --git a/docs/content/config.md b/docs/content/config.md
index 0d769e9d7..6efac7c9c 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -929,9 +929,9 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
|------|-------------|
| `trace.log` | Running with `-vv` |
| `output.log` | Running with `-vv` |
-| `diagnostic.md` | Running with `-vv` when warnings occur |
+| `diagnostic.md` | Running with `-vv` |
-`trace.log` mirrors stderr (commands, `[wt-trace]` records, bounded subprocess previews). `output.log` holds the raw uncapped subprocess stdout/stderr bodies. Both are overwritten on each `-vv` run. `diagnostic.md` is a markdown report for pasting into GitHub issues — written only when warnings occur, and inlines `trace.log` (never `output.log`, which can be multi-MB).
+`trace.log` receives the noisy `log::*` pipeline at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews — so stderr stays readable (user-facing status messages still print as normal). `output.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown report for pasting into GitHub issues; it inlines `trace.log` but not `output.log`, which can be multi-MB. All three are overwritten on each `-vv` run.
### Location
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 0fe35d267..181324ffa 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -122,9 +122,9 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) |
| `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
-| `.git/wt/logs/trace.log` | Debug log (mirrors stderr) for issue reporting | Running with `-vv` |
+| `.git/wt/logs/trace.log` | Debug log for issue reporting (captures the `log::*` pipeline that `-vv` would otherwise put on stderr) | Running with `-vv` |
| `.git/wt/logs/output.log` | Raw uncapped subprocess stdout/stderr (may be multi-MB) | Running with `-vv` |
-| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` when warnings occur |
+| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` |
| `.git/wt/trash/<name>-<timestamp>` | Staged worktree contents pending background deletion | `wt remove` |
None of this is tracked by git or pushed to remotes.
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 74eaf8cda..73a07f062 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -959,9 +959,9 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
|------|-------------|
| `trace.log` | Running with `-vv` |
| `output.log` | Running with `-vv` |
-| `diagnostic.md` | Running with `-vv` when warnings occur |
+| `diagnostic.md` | Running with `-vv` |
-`trace.log` mirrors stderr (commands, `[wt-trace]` records, bounded subprocess previews). `output.log` holds the raw uncapped subprocess stdout/stderr bodies. Both are overwritten on each `-vv` run. `diagnostic.md` is a markdown report for pasting into GitHub issues — written only when warnings occur, and inlines `trace.log` (never `output.log`, which can be multi-MB).
+`trace.log` receives the noisy `log::*` pipeline at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews — so stderr stays readable (user-facing status messages still print as normal). `output.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown report for pasting into GitHub issues; it inlines `trace.log` but not `output.log`, which can be multi-MB. All three are overwritten on each `-vv` run.
### Location
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 2bd0a1f84..ee715d17b 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -115,9 +115,9 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) |
| `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
-| `.git/wt/logs/trace.log` | Debug log (mirrors stderr) for issue reporting | Running with `-vv` |
+| `.git/wt/logs/trace.log` | Debug log for issue reporting (captures the `log::*` pipeline that `-vv` would otherwise put on stderr) | Running with `-vv` |
| `.git/wt/logs/output.log` | Raw uncapped subprocess stdout/stderr (may be multi-MB) | Running with `-vv` |
-| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` when warnings occur |
+| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` |
| `.git/wt/trash/<name>-<timestamp>` | Staged worktree contents pending background deletion | `wt remove` |
None of this is tracked by git or pushed to remotes.
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 47aa7203c..6e11698ef 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -785,9 +785,9 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
|------|-------------|
| `trace.log` | Running with `-vv` |
| `output.log` | Running with `-vv` |
-| `diagnostic.md` | Running with `-vv` when warnings occur |
+| `diagnostic.md` | Running with `-vv` |
-`trace.log` mirrors stderr (commands, `[wt-trace]` records, bounded subprocess previews). `output.log` holds the raw uncapped subprocess stdout/stderr bodies. Both are overwritten on each `-vv` run. `diagnostic.md` is a markdown report for pasting into GitHub issues — written only when warnings occur, and inlines `trace.log` (never `output.log`, which can be multi-MB).
+`trace.log` receives the noisy `log::*` pipeline at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews — so stderr stays readable (user-facing status messages still print as normal). `output.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown report for pasting into GitHub issues; it inlines `trace.log` but not `output.log`, which can be multi-MB. All three are overwritten on each `-vv` run.
## Location
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index 6e8fcf39f..773b7b239 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -1,13 +1,15 @@
//! Diagnostic report generation for issue reporting.
//!
-//! When unexpected warnings occur (timeouts, git errors, etc.), this module
-//! can generate a diagnostic file that users attach to GitHub issues.
+//! This module generates a markdown file users can attach to GitHub issues —
+//! command line, environment, worktree state, config, and the captured trace
+//! log.
//!
//! # When Diagnostics Are Generated
//!
-//! Diagnostic files are written when `-vv` is passed. Without `-vv`, the hint
-//! simply tells users to run with `-vv`. This ensures the diagnostic file
-//! contains useful debug information.
+//! Diagnostic files are written on every `-vv` run (one file per command,
+//! overwritten each time). Without `-vv`, the hint simply tells users to
+//! rerun with `-vv`. This ensures the diagnostic file contains the trace
+//! the report inlines.
//!
//! # Report Format
//!
@@ -155,7 +157,7 @@ impl DiagnosticReport {
// Get config show output (if available)
let config_show = config_show_output(repo);
- // Inline the trace log (bounded; mirrors stderr). The raw subprocess
+ // Inline the trace log (bounded). The raw subprocess
// output log is only *referenced* by path — it can be multi-MB and
// would drown out the trace records that matter in a bug report.
let trace_log = crate::log_files::TRACE
diff --git a/src/log_files.rs b/src/log_files.rs
index 22d057735..ca040d706 100644
--- a/src/log_files.rs
+++ b/src/log_files.rs
@@ -2,14 +2,17 @@
//!
//! At `-vv`, two files are written in the repo's `.git/wt/logs/` directory:
//!
-//! - [`TRACE`] → `trace.log`: mirrors stderr. Structured records,
-//! `$ cmd [context]` headers, and bounded subprocess previews (same
-//! elision markers the user sees on stderr). High-signal, bounded size —
+//! - [`TRACE`] → `trace.log`: structured records, `$ cmd [context]`
+//! headers, and bounded subprocess previews. High-signal, bounded size —
//! safe to embed in `diagnostic.md` bug reports.
//! - [`OUTPUT`] → `output.log`: raw, uncapped subprocess stdout/stderr
//! bodies captured by `shell_exec::Cmd`. Potentially multi-MB (full
//! `git log -p` / patch-id output); opt-in for deep dives.
//!
+//! Direct user-facing output (`info_message` / `eprintln!` from command
+//! code) is unaffected — it goes to stderr at every verbosity level. This
+//! module governs only the `log::*` macro pipeline.
+//!
//! # Routing
//!
//! [`route`] is the single source of truth for which sink a log record
@@ -17,11 +20,12 @@
//!
//! - `SUBPROCESS_FULL_TARGET` records never reach stderr — raw bodies
//! don't flood terminals. They go to `output.log` if active, else
-//! drop. The bounded preview (`SUBPROCESS_TERMINAL_TARGET`) still
-//! reaches stderr, so users always see a capped view.
-//! - `SUBPROCESS_TERMINAL_TARGET` records always reach stderr.
-//! - All other records always reach stderr.
-//! - Stderr records are mirrored to `trace.log` when it's active.
+//! drop.
+//! - All other log records go to `trace.log` when it's active (`-vv`),
+//! and to stderr otherwise (e.g. `-v`, or `RUST_LOG=debug` without
+//! `-vv`). At `-vv` the `log::*` pipeline is silent on stderr — the
+//! user-facing `eprintln!` output stays, but the noisy `$ cmd`
+//! headers and subprocess previews land in the file.
use std::fs::{File, OpenOptions};
use std::io::Write;
@@ -92,7 +96,11 @@ pub(crate) fn init() {
TRACE.init();
OUTPUT.init();
// Let shell_exec phrase the elision marker to match reality — points at
- // output.log when it exists, else suggests rerunning with -vv.
+ // output.log when it exists, else suggests rerunning with -vv. The
+ // false case at -vv (open failed asymmetrically) is benign here: the
+ // user already got a "(output.log unavailable)" warning from the
+ // startup pointer, so the marker's "rerun with -vv" text is just
+ // redundant rather than misleading.
worktrunk::shell_exec::set_output_log_available(OUTPUT.is_active());
}
@@ -100,8 +108,8 @@ pub(crate) fn init() {
pub(crate) enum Route {
/// Append to this sink; skip stderr.
File(&'static LogSink),
- /// Emit to stderr with normal formatting. Callers also mirror the line
- /// to [`TRACE`] (no-op when inactive).
+ /// Emit to stderr with normal formatting. Chosen when TRACE is
+ /// inactive — the `-vv` path takes `File(&TRACE)` instead.
Stderr,
/// Drop the record entirely.
Drop,
@@ -117,8 +125,13 @@ pub(crate) fn route(target: &str) -> Route {
} else {
Route::Drop
}
+ } else if TRACE.is_active() {
+ // -vv: send the noisy log pipeline to trace.log instead of stderr
+ // so the user's terminal stays readable.
+ Route::File(&TRACE)
} else {
- // `SUBPROCESS_TERMINAL_TARGET` and all other targets share this path.
+ // -v, or RUST_LOG=debug without -vv. `SUBPROCESS_BOUNDED_TARGET`
+ // and all other targets share this path.
Route::Stderr
}
}
diff --git a/src/main.rs b/src/main.rs
index d1593f6ec..35cb1b23f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1247,17 +1247,39 @@ fn thread_label() -> char {
fn init_logging(verbose_level: u8) {
// Configure logging based on --verbose flag or RUST_LOG env var.
- // Level map: -v → Info, -vv+ → Debug (stderr, with subprocess output
- // capped). At -vv, `.git/wt/logs/trace.log` mirrors stderr and
- // `.git/wt/logs/output.log` receives the uncapped subprocess bodies
- // routed via `shell_exec::SUBPROCESS_FULL_TARGET`.
+ // Level map: -v → Info on stderr (no file), -vv+ → Debug routed to
+ // `.git/wt/logs/trace.log` instead of stderr, plus uncapped subprocess
+ // bodies in `.git/wt/logs/output.log` (via `SUBPROCESS_FULL_TARGET`).
//
- // env_logger registers the logger via `.init()` at the bottom of this
- // function. `log_files::init()` runs after that so the
- // `Repository::current()` it triggers (cold cache: 4ms `git rev-parse
- // --git-common-dir`) is visible in `[wt-trace]` output.
+ // At -vv the `log::*` pipeline is silent on stderr — user-facing
+ // `eprintln!` output (template expansions, status, hints) is
+ // unaffected. A one-line pointer below tells the user where the
+ // trace went.
output::set_verbosity(verbose_level);
+ // Prime `GIT_COMMON_DIR_CACHE` BEFORE env_logger registers, so any
+ // log records emitted while building the cache go nowhere (no logger
+ // installed yet) and the later `Repository::current()` triggered by
+ // `log_files::init` is a memory-cache hit with no fresh git call.
+ // Without this, those records would fire while `TRACE.is_active()`
+ // is still false (we're inside the call that sets the file) and
+ // route to stderr — exactly the noise -vv is supposed to keep off
+ // the terminal. Running before `.init()` also keeps the priming
+ // robust if `Repository::current()` grows new log emissions later:
+ // a not-yet-installed logger drops them harmlessly.
+ //
+ // Caveat: if priming itself fails (Ctrl-C during the ~5ms rev-parse
+ // fork; transient fork error), the cache stays empty and the later
+ // `log_files::init` re-runs the git call, which logs onto the
+ // now-installed logger and leaks one `$ git rev-parse` line to
+ // stderr. Rare and minor (one line, not 15K), so we don't engineer
+ // around it; closing it cleanly requires resolving the log-dir path
+ // without going through `shell_exec::Cmd`, which violates the
+ // command-execution-through-Cmd invariant in CLAUDE.md.
+ if verbose_level >= 2 {
+ let _ = worktrunk::git::Repository::current();
+ }
+
let mut builder = match verbose_level {
0 => env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("off")),
1 => {
@@ -1275,58 +1297,75 @@ fn init_logging(verbose_level: u8) {
builder
.format(|buf, record| {
let route = log_files::route(record.target());
- if matches!(route, log_files::Route::Drop) {
- return Ok(());
- }
-
let thread_num = thread_label();
let msg = record.args().to_string();
- let file_line = format!("[{thread_num}] {msg}");
- if let log_files::Route::File(sink) = route {
- sink.write_line(&file_line);
- return Ok(());
- }
- // Route::Stderr: mirror to trace.log (no-op when inactive), then
- // write the ANSI-formatted version to stderr below.
- log_files::TRACE.write_line(&file_line);
-
- // Commands start with $, make only the command bold (not $ or [worktree])
- if let Some(rest) = msg.strip_prefix("$ ") {
- // Split: "git command [worktree]" -> ("git command", " [worktree]")
- if let Some(bracket_pos) = rest.find(" [") {
- let command = &rest[..bracket_pos];
- let worktree = &rest[bracket_pos..];
- writeln!(
- buf,
- "{}",
- cformat!("<dim>[{thread_num}]</> $ <bold>{command}</>{worktree}")
- )
- } else {
- writeln!(
- buf,
- "{}",
- cformat!("<dim>[{thread_num}]</> $ <bold>{rest}</>")
- )
+ match route {
+ log_files::Route::Drop => Ok(()),
+ log_files::Route::File(sink) => {
+ sink.write_line(&format!("[{thread_num}] {msg}"));
+ Ok(())
+ }
+ log_files::Route::Stderr => {
+ // Commands start with $, make only the command bold (not $ or [worktree])
+ if let Some(rest) = msg.strip_prefix("$ ") {
+ // Split: "git command [worktree]" -> ("git command", " [worktree]")
+ // Standalone tools (gh, glab) emit no `[ctx]` suffix.
+ let (command, worktree) = match rest.find(" [") {
+ Some(pos) => (&rest[..pos], &rest[pos..]),
+ None => (rest, ""),
+ };
+ writeln!(
+ buf,
+ "{}",
+ cformat!("<dim>[{thread_num}]</> $ <bold>{command}</>{worktree}")
+ )
+ } else if msg.starts_with(" ! ") {
+ // Error output - show in red
+ writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> <red>{msg}</>"))
+ } else {
+ // Regular output with thread ID
+ writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> {msg}"))
+ }
}
- } else if msg.starts_with(" ! ") {
- // Error output - show in red
- writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> <red>{msg}</>"))
- } else {
- // Regular output with thread ID
- writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> {msg}"))
}
})
.init();
// Open per-file log sinks AFTER env_logger is registered so the
// `Repository::current()` rev-parse fired by `try_create` is captured
- // in the trace.
+ // in the trace. The startup pointer below uses the path resolved here.
if verbose_level >= 2 {
log_files::init();
+ announce_trace_destination();
}
}
+/// Print a one-line stderr pointer at `-vv` so users know where the noisy
+/// `log::*` output went. Silent if `trace.log` couldn't be opened (outside
+/// a git repo, permission error) — there's nothing meaningful to point at.
+fn announce_trace_destination() {
+ // TRACE and OUTPUT open independently — `LogSink::init` succeeds per
+ // file. The (Some, None) case (trace.log open, output.log failed) is
+ // rare but real (path-type mismatch, fs quota); the reverse is
+ // possible too but `output.log` alone has no `$ cmd` context, so we
+ // stay silent there.
+ let Some(trace_path) = log_files::TRACE.path() else {
+ return;
+ };
+ let trace_display = worktrunk::path::format_path_for_display(&trace_path);
+ let msg = match log_files::OUTPUT.path() {
+ Some(output_path) => {
+ let output_display = worktrunk::path::format_path_for_display(&output_path);
+ cformat!(
+ "Tracing to <underline>{trace_display}</> (raw subprocess output @ <underline>{output_display}</>)"
+ )
+ }
+ None => cformat!("Tracing to <underline>{trace_display}</> (output.log unavailable)"),
+ };
+ eprintln!("{}", info_message(msg));
+}
+
fn handle_merge_command(args: MergeArgs, yes: bool) -> anyhow::Result<()> {
if args.no_verify {
warn_no_verify_deprecated();
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 974559155..d84ad11ed 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -452,38 +452,48 @@ pub fn set_command_timeout(timeout: Option<Duration>) {
COMMAND_TIMEOUT.with(|t| t.set(timeout));
}
-/// Maximum lines of captured stdout/stderr emitted to stderr per stream.
-/// Exceeded content is elided with a `… (N more lines, M bytes elided)` marker;
-/// the full output is still written to `output.log` via
+/// Maximum lines of the bounded subprocess preview per stream. Exceeded
+/// content is elided with a `… (N more lines, M bytes elided)` marker; the
+/// full output is still written to `output.log` via
/// [`SUBPROCESS_FULL_TARGET`].
const LOG_OUTPUT_MAX_LINES: usize = 200;
-/// Maximum bytes of captured stdout/stderr emitted to stderr per stream.
-/// Applied in addition to [`LOG_OUTPUT_MAX_LINES`].
+/// Maximum bytes of the bounded subprocess preview per stream. Applied in
+/// addition to [`LOG_OUTPUT_MAX_LINES`].
const LOG_OUTPUT_MAX_BYTES: usize = 64 * 1024;
-/// Log target used for *full* subprocess stdout/stderr. The format closure in
-/// `main.rs` routes records on this target to `output.log` only, so raw
-/// subprocess bodies (diffs, `git log -p`, patch-id pipelines) don't spam
-/// stderr or drown out trace records in `trace.log`.
+/// Log target used for *full* subprocess stdout/stderr. The router in
+/// `log_files::route` sends records on this target to `output.log` only,
+/// so raw subprocess bodies (diffs, `git log -p`, patch-id pipelines)
+/// never reach stderr.
pub const SUBPROCESS_FULL_TARGET: &str = "worktrunk::subprocess_full";
-/// Log target used for the *bounded* (stderr-safe) preview of subprocess
-/// output. The format closure in `main.rs` routes records on this target to
-/// stderr and mirrors to `trace.log` — the uncapped version is captured via
-/// [`SUBPROCESS_FULL_TARGET`].
-pub const SUBPROCESS_TERMINAL_TARGET: &str = "worktrunk::subprocess_terminal";
+/// Log target used for the *bounded* preview of subprocess output (capped
+/// at `LOG_OUTPUT_MAX_LINES` / `LOG_OUTPUT_MAX_BYTES` with an elision
+/// marker). Shares the routing of all non-full records: stderr at `-v`
+/// (or `RUST_LOG=debug` without `-vv`), `trace.log` at `-vv`. The
+/// uncapped version is captured via [`SUBPROCESS_FULL_TARGET`].
+pub const SUBPROCESS_BOUNDED_TARGET: &str = "worktrunk::subprocess_bounded";
-/// Whether the full subprocess output is being captured somewhere (e.g.
-/// `output.log` at `-vv`). Gates the phrasing of the elision marker so it
-/// doesn't promise a file that wasn't created.
+/// Whether the full subprocess output is being captured to `output.log` at
+/// `-vv`. Gates the phrasing of the elision marker so it doesn't promise a
+/// file that wasn't created.
+///
+/// The two-state split (available / not) intentionally collapses two
+/// situations: (a) the user didn't run with `-vv` at all, and (b) the user
+/// did but `output.log` failed to open (rare: path-type mismatch, FD
+/// exhaustion). In (b), `announce_trace_destination` already warns at
+/// startup; the elision marker text is allowed to lag — saying "rerun with
+/// -vv" is harmless because the user's startup warning is the
+/// authoritative signal.
///
/// Set by the binary's log-file init; stays `false` under `RUST_LOG=debug`
/// without `-vv`, where the full records are dropped by design.
static OUTPUT_LOG_AVAILABLE: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
-/// Called from the binary once the `output.log` sink has been created.
+/// Called from the binary once `log_files::init` has attempted to open
+/// `output.log` — `yes` reflects whether that attempt succeeded.
pub fn set_output_log_available(yes: bool) {
OUTPUT_LOG_AVAILABLE.store(yes, std::sync::atomic::Ordering::Relaxed);
}
@@ -491,11 +501,11 @@ pub fn set_output_log_available(yes: bool) {
/// Log captured stdout/stderr of a finished command.
///
/// At `log::debug!` (`-vv`) each stream is emitted twice via separate log
-/// targets, and the format closure in `main.rs` routes them:
+/// targets, and `log_files::route` directs them:
/// - [`SUBPROCESS_FULL_TARGET`]: uncapped, line-per-record, `output.log` only.
-/// - [`SUBPROCESS_TERMINAL_TARGET`]: capped at [`LOG_OUTPUT_MAX_LINES`] and
-/// [`LOG_OUTPUT_MAX_BYTES`] per stream with an elision marker, stderr +
-/// `trace.log`.
+/// - [`SUBPROCESS_BOUNDED_TARGET`]: capped at [`LOG_OUTPUT_MAX_LINES`] and
+/// [`LOG_OUTPUT_MAX_BYTES`] per stream with an elision marker, then
+/// routed to `trace.log` at `-vv` or stderr otherwise.
///
/// Below `log::debug!` both targets are disabled and this is a no-op.
fn log_output(output: &std::process::Output) {
@@ -509,10 +519,10 @@ fn log_output(output: &std::process::Output) {
log::debug!(target: SUBPROCESS_FULL_TARGET, "{}", line);
}
for line in format_stream_bounded(&output.stdout, " ") {
- log::debug!(target: SUBPROCESS_TERMINAL_TARGET, "{}", line);
+ log::debug!(target: SUBPROCESS_BOUNDED_TARGET, "{}", line);
}
for line in format_stream_bounded(&output.stderr, " ! ") {
- log::debug!(target: SUBPROCESS_TERMINAL_TARGET, "{}", line);
+ log::debug!(target: SUBPROCESS_BOUNDED_TARGET, "{}", line);
}
}
diff --git a/src/trace/emit.rs b/src/trace/emit.rs
index d3d5f9025..6f2f9008d 100644
--- a/src/trace/emit.rs
+++ b/src/trace/emit.rs
@@ -25,7 +25,8 @@
//! Records are emitted at `log::debug!`, so `-vv` or `RUST_LOG=debug` makes
//! them visible. Subprocess stdout/stderr continuations are emitted via
//! separate log targets: the full output goes to `output.log`, and a bounded
-//! preview goes to stderr + `trace.log` — so raw bodies don't spam `-vv`.
+//! preview shares the routing of all other log records — `trace.log` at `-vv`,
+//! stderr otherwise — so raw bodies don't spam `-vv`.
use std::borrow::Cow;
use std::fmt::Display;
diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rs
index a21788d77..adac0af41 100644
--- a/tests/integration_tests/diagnostic.rs
+++ b/tests/integration_tests/diagnostic.rs
@@ -353,17 +353,20 @@ fn test_vv_splits_full_and_bounded_output(repo: TestRepo) {
);
}
-/// At `-vv`, when a single subprocess produces more than the line cap, stderr
-/// and `trace.log` must show the elision marker while `output.log` holds the
-/// full body without any elision. This guards the bounded-stderr invariant —
-/// a regression that routed full output to stderr would silently fail to
-/// elide.
+/// At `-vv`, the `log::*` pipeline is silent on stderr — the bounded
+/// preview lands in `trace.log` (not stderr), and `output.log` still holds
+/// the unbounded body. Guards against a regression that re-routes the
+/// debug stream to stderr and floods the terminal. (Direct stderr writes
+/// from command code — the "Tracing to ..." pointer, "Diagnostic saved",
+/// bug-report hint — are not part of the `log::*` pipeline and DO appear
+/// on stderr; those are asserted at the end of this test.)
#[rstest]
-fn test_vv_bounded_on_stderr_full_in_output_log(repo: TestRepo) {
+fn test_vv_log_pipeline_silent_on_stderr(repo: TestRepo) {
// `wt list` runs `git for-each-ref refs/heads/` (captured via `Cmd::run`),
// so its output flows through `log_output` and exercises the split.
// Populate packed-refs with 250 fake branches pointing at HEAD — far more
- // than LOG_OUTPUT_MAX_LINES (200), which guarantees elision on stderr.
+ // than LOG_OUTPUT_MAX_LINES (200), which would have tripped elision on
+ // stderr under the old routing.
let head_out = repo
.git_command()
.args(["rev-parse", "HEAD"])
@@ -388,25 +391,26 @@ fn test_vv_bounded_on_stderr_full_in_output_log(repo: TestRepo) {
.expect("wt list");
let stderr = String::from_utf8_lossy(&output.stderr);
- // Elision marker appears on stderr (bounded preview) and in trace.log.
- let marker = "more lines, ";
- assert!(
- stderr.contains(marker),
- "stderr should contain elision marker for >200-line subprocess output: {stderr}"
- );
-
let logs_dir = repo.root_path().join(".git").join("wt/logs");
let trace = fs::read_to_string(logs_dir.join("trace.log")).unwrap();
let raw = fs::read_to_string(logs_dir.join("output.log")).unwrap();
+ // Elision marker belongs to the bounded preview, which now lives in
+ // trace.log only — never on stderr.
+ let marker = "more lines, ";
assert!(
trace.contains(marker),
- "trace.log mirrors stderr and should include the elision marker"
+ "trace.log should hold the bounded preview's elision marker"
+ );
+ assert!(
+ !stderr.contains(marker),
+ "stderr must not receive the bounded preview at -vv: {stderr}"
);
assert!(
!raw.contains(marker),
"output.log holds full output and must not contain an elision marker"
);
+
// The tail refs only appear in the full log.
let tail_ref = "many-branch-249";
assert!(
@@ -415,17 +419,36 @@ fn test_vv_bounded_on_stderr_full_in_output_log(repo: TestRepo) {
);
assert!(
!stderr.contains(tail_ref),
- "stderr preview should be bounded before the last ref"
+ "stderr must not see the per-line subprocess output at -vv"
);
assert!(
!trace.contains(tail_ref),
- "trace.log mirrors stderr and should be bounded too"
+ "trace.log holds the bounded preview, which is capped before the last ref"
+ );
+
+ // The full subprocess stdout still lands in output.log, and trace.log
+ // still captures the `$ cmd` / `[wt-trace]` records — confirm both so a
+ // regression that disables the file sinks fails loudly here too.
+ assert!(
+ raw.lines().any(|l| l.contains("refs/heads/many-branch-")),
+ "output.log should contain the captured for-each-ref stdout"
+ );
+ assert!(
+ trace.contains("[wt-trace]"),
+ "trace.log should contain [wt-trace] records at -vv"
+ );
+
+ // Stderr at -vv should contain the new pointer line (and the existing
+ // diagnostic line), so the user knows where the trace went.
+ assert!(
+ stderr.contains("Tracing to") && stderr.contains("trace.log"),
+ "stderr should announce the trace destination at -vv: {stderr}"
);
}
/// `RUST_LOG=debug` at `-v 0` activates Debug logging without creating the
/// on-disk log files. Stderr receives the **bounded** preview
-/// (`SUBPROCESS_TERMINAL_TARGET`); the uncapped `SUBPROCESS_FULL_TARGET`
+/// (`SUBPROCESS_BOUNDED_TARGET`); the uncapped `SUBPROCESS_FULL_TARGET`
/// records are dropped so raw bodies don't flood the terminal.
#[rstest]
fn test_rust_log_debug_fallback_without_vv(repo: TestRepo) {
@@ -532,6 +555,39 @@ fn test_vv_writes_diagnostic_on_error(mut repo: TestRepo) {
);
}
+/// If one of the `-vv` log files can't be opened (here: pre-existing path
+/// of the wrong type), the user still gets a "Tracing to ..." pointer for
+/// the one that opened, and the elision marker reflects the asymmetric
+/// state instead of telling a `-vv` user to "rerun with -vv".
+#[rstest]
+fn test_vv_pointer_handles_split_init(repo: TestRepo) {
+ let logs_dir = repo.root_path().join(".git").join("wt/logs");
+ std::fs::create_dir_all(&logs_dir).unwrap();
+ // Block output.log open by occupying the path with a directory.
+ std::fs::create_dir(logs_dir.join("output.log")).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["list", "-vv"])
+ .env("NO_COLOR", "1")
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ stderr.contains("Tracing to") && stderr.contains("trace.log"),
+ "stderr should point at trace.log even when output.log can't open: {stderr}"
+ );
+ assert!(
+ stderr.contains("output.log unavailable"),
+ "stderr should note output.log is unavailable: {stderr}"
+ );
+ assert!(
+ logs_dir.join("trace.log").exists(),
+ "trace.log should still be created"
+ );
+}
+
/// With just -v, info-level logging goes to stderr but no log files are written.
/// `-vv` is the threshold for `trace.log`, `output.log`, and `diagnostic.md`.
#[rstest]
@@ -551,7 +607,9 @@ fn test_v_does_not_write_log_files(repo: TestRepo) {
}
}
-/// With -vv outside a git repo, command should still work (no crash).
+/// With -vv outside a git repo, command should still work (no crash), no
+/// log files are written, and `announce_trace_destination` takes its silent
+/// early-return path (TRACE.path() is None).
#[test]
fn test_vv_outside_repo_no_crash() {
use crate::common::wt_command;
@@ -559,13 +617,21 @@ fn test_vv_outside_repo_no_crash() {
// Create a temp directory that is NOT a git repo
let temp_dir = tempfile::tempdir().unwrap();
+ // Use `list` (not `--version`) so `init_logging` actually runs — clap
+ // short-circuits `--version` before logging is set up, which would
+ // skip the announce_trace_destination path this test exists to cover.
let output = wt_command()
- .args(["--version", "-vv"])
+ .args(["list", "-vv"])
.current_dir(temp_dir.path())
.output()
.unwrap();
- assert!(output.status.success(), "Command should succeed");
+ // `wt list` exits non-zero outside a git repo, but that's fine —
+ // init_logging still ran before the command failed.
+ assert!(
+ !output.status.success(),
+ "wt list outside a repo should fail"
+ );
// No diagnostic file should be created (not in a git repo)
let diagnostic_path = temp_dir
@@ -577,6 +643,14 @@ fn test_vv_outside_repo_no_crash() {
!diagnostic_path.exists(),
"Diagnostic file should NOT be created outside a git repo"
);
+
+ // Startup pointer should NOT appear: TRACE failed to open, so
+ // announce_trace_destination took its early-return path.
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !stderr.contains("Tracing to"),
+ "no startup pointer when trace.log can't open: {stderr}"
+ );
}
/// When gh is installed, the hint should show gist creation and issue URL.
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
index d7b0058e6..3c5e96107 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
@@ -102,13 +102,13 @@ All post-* hooks (post-start, post-switch, post-commit, post-merge) run
Diagnostic files
- File Created when
- ───────────── ────────────────────────────────────
- trace.log Running with -vv
- output.log Running with -vv
- diagnostic.md Running with -vv when warnings occur
+ File Created when
+ ───────────── ────────────────
+ trace.log Running with -vv
+ output.log Running with -vv
+ diagnostic.md Running with -vv
-trace.log mirrors stderr (commands, [wt-trace] records, bounded subprocess previews). output.log holds the raw uncapped subprocess stdout/stderr bodies. Both are overwritten on each -vv run. diagnostic.md is a markdown report for pasting into GitHub issues — written only when warnings occur, and inlines trace.log (never output.log, which can be multi-MB).
+trace.log receives the noisy log::* pipeline at -vv — commands, [wt-trace] records, bounded subprocess previews — so stderr stays readable (user-facing status messages still print as normal). output.log holds the raw uncapped subprocess stdout/stderr bodies. diagnostic.md is a markdown report for pasting into GitHub issues; it inlines trace.log but not output.log, which can be multi-MB. All three are overwritten on each -vv run.
Location