Skip to content

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

fix(diagnostic): escape control bytes in subprocess preview so diagnostic.md uploads as a gist (#2991)

Worktrunk Bot7cb56c368bdb
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index a9fa0d4d6..cc367d027 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -174,21 +174,32 @@ impl DiagnosticReport {
// Render template
let env = Environment::new();
let tmpl = env.template_from_str(REPORT_TEMPLATE).unwrap();
- tmpl.render(context! {
- timestamp,
- command,
- context,
- version,
- os,
- arch,
- git_version,
- shell_integration,
- worktree_list,
- config_show,
- trace_log,
- subprocess_log_path,
- })
- .unwrap()
+ let rendered = tmpl
+ .render(context! {
+ timestamp,
+ command,
+ context,
+ version,
+ os,
+ arch,
+ git_version,
+ shell_integration,
+ worktree_list,
+ config_show,
+ trace_log,
+ subprocess_log_path,
+ })
+ .unwrap();
+
+ // Final sanitize at the upload boundary. This is the only place that
+ // covers *every* inlined source at once: `config_show` and
+ // `worktree_list` are spliced in directly, never through the
+ // already-escaped `trace.log`, so a control byte from either (or from
+ // the `context` error string) would still make `gh gist create` reject
+ // diagnostic.md as binary. `escape_controls` preserves tabs/newlines,
+ // so the markdown structure is intact, and is idempotent over the
+ // trace.log the formatter already cleaned.
+ worktrunk::utils::escape_controls(&rendered).into_owned()
}
/// Write the diagnostic report to a file.
diff --git a/src/logging.rs b/src/logging.rs
index 78a46a458..7c9555c16 100644
--- a/src/logging.rs
+++ b/src/logging.rs
@@ -18,6 +18,7 @@
//! `tracing` by [`tracing_log::LogTracer::init`] — every layer above sees
//! both native `tracing::*` events and forwarded `log::*` records.
+use std::borrow::Cow;
use std::fmt::{self, Write as _};
use color_print::cformat;
@@ -31,6 +32,7 @@ use tracing_subscriber::util::SubscriberInitExt;
use worktrunk::shell_exec::SUBPROCESS_FULL_TARGET;
use worktrunk::styling::{eprintln, info_message};
use worktrunk::trace::WT_TRACE_TARGET;
+use worktrunk::utils::escape_controls;
use crate::log_files::{self, SubprocessMakeWriter, TraceMakeWriter};
use crate::output;
@@ -135,13 +137,28 @@ where
/// everything else. Shared between the stderr and `trace.log` formatters so
/// `[wt-trace]` records appear in both routes (`-vv` writes to the file;
/// `RUST_LOG=debug -v` surfaces them on stderr).
+///
+/// Control bytes are escaped here ([`escape_controls`]) — this is the single
+/// chokepoint feeding both human-facing routes, so raw NUL/ESC from subprocess
+/// output (e.g. the bounded preview of `git … -z`, or a `cmd=`/`err=` field
+/// carrying captured bytes) can't ride into the terminal or `trace.log`, and
+/// thus can't break the gist upload of the `diagnostic.md` that inlines
+/// `trace.log`. `subprocess.log` keeps raw bytes verbatim: it renders via
+/// [`event_message`] directly, not this helper.
fn render_event_message(event: &Event<'_>) -> String {
- if event.metadata().target() == WT_TRACE_TARGET {
+ let rendered = if event.metadata().target() == WT_TRACE_TARGET {
let mut fields = WtTraceFields::default();
event.record(&mut fields);
format_wt_trace(&fields)
} else {
event_message(event)
+ };
+ // Reuse the owned `rendered` on the clean path — `escape_controls` borrows
+ // when nothing needs escaping, so `into_owned()` would otherwise re-clone an
+ // already-owned String on every log line. Only control-bearing lines allocate.
+ match escape_controls(&rendered) {
+ Cow::Borrowed(_) => rendered,
+ Cow::Owned(escaped) => escaped,
}
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 4605bb157..37be49df5 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -515,6 +515,13 @@ fn format_stream_full(bytes: &[u8], prefix: &str) -> Vec<String> {
/// `tracing::enabled!` against [`SUBPROCESS_FULL_TARGET`] — true iff the
/// `subprocess.log` layer is registered and accepting that target (`-vv` opened
/// the file successfully).
+///
+/// Preview lines are emitted raw here; control bytes (most commonly NUL from
+/// `-z`/`--null` git output) are escaped downstream at the single point that
+/// feeds both human-facing sinks — `render_event_message` in the binary's
+/// logging layer, which renders this target's records to stderr and `trace.log`.
+/// The uncapped [`SUBPROCESS_FULL_TARGET`] copy bypasses that escape and keeps
+/// the bytes verbatim in `subprocess.log`.
fn format_stream_bounded(bytes: &[u8], prefix: &str) -> Vec<String> {
if bytes.is_empty() {
return Vec::new();
diff --git a/src/utils.rs b/src/utils.rs
index f71ad7f22..4fc3b1f36 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -1,7 +1,43 @@
//! General utilities.
+use std::borrow::Cow;
use std::time::{SystemTime, UNIX_EPOCH};
+/// Replace C0/C1 control characters — other than tab and newline — with a
+/// visible escape so the text stays valid for plain-text and markdown sinks.
+///
+/// Raw subprocess output can carry control bytes, most commonly NUL from
+/// `-z`/`--null` git invocations (`git config --list -z`,
+/// `git for-each-ref --format=…%00…`). Left in place they ride into the
+/// human-facing `trace.log` and the `diagnostic.md` bug-report bundle, where
+/// the content-type sniffing behind `gh gist create` flags the file as binary
+/// ("binary file not supported") and refuses to upload it.
+///
+/// Tab and newline are preserved — they're legitimate text structure (git
+/// output is full of tabs; `trace.log` and `diagnostic.md` are multi-line).
+/// NUL renders as the compact `\0` rather than `escape_default`'s `\u{0}`
+/// because it's by far the most common byte here. The function is idempotent:
+/// its own output carries no control bytes, so a sink can re-sanitize content
+/// another sink already cleaned without doubling the escapes.
+///
+/// Borrows when there's nothing to escape (the common case), so the hot logging
+/// path allocates only for lines that actually carry control bytes.
+pub fn escape_controls(s: &str) -> Cow<'_, str> {
+ if !s.chars().any(|c| c.is_control() && c != '\t' && c != '\n') {
+ return Cow::Borrowed(s);
+ }
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '\t' | '\n' => out.push(c),
+ '\0' => out.push_str(r"\0"),
+ c if c.is_control() => out.extend(c.escape_default()),
+ c => out.push(c),
+ }
+ }
+ Cow::Owned(out)
+}
+
/// Format a Unix timestamp as ISO 8601 string (e.g., "2025-01-01T00:00:00Z").
///
/// Used for human-readable timestamps in diagnostic reports and logs.
@@ -85,4 +121,46 @@ mod tests {
let formatted = format_timestamp_iso8601(chrono_out_of_range);
assert!(formatted.starts_with("invalid-timestamp("));
}
+
+ #[test]
+ fn escape_controls_borrows_clean_text() {
+ // No control bytes (tab/newline aside) → borrowed, untouched.
+ let out = escape_controls("plain text");
+ assert!(matches!(out, Cow::Borrowed(_)));
+ assert_eq!(out, "plain text");
+ }
+
+ #[test]
+ fn escape_controls_preserves_tab_and_newline() {
+ // Tab and newline are legitimate structure and must survive verbatim
+ // (git output is full of tabs; trace.log / diagnostic.md are multi-line).
+ let out = escape_controls("a\tb\nc");
+ assert!(matches!(out, Cow::Borrowed(_)));
+ assert_eq!(out, "a\tb\nc");
+ }
+
+ #[test]
+ fn escape_controls_renders_nul_compactly() {
+ // NUL (the `-z`/`--null` record separator) → `\0`, not `\u{0}`.
+ assert_eq!(
+ escape_controls("core.bare\0false\0core.filemode\0true"),
+ r"core.bare\0false\0core.filemode\0true"
+ );
+ }
+
+ #[test]
+ fn escape_controls_escapes_other_control_bytes() {
+ // ESC (0x1b) and BEL (0x07) take the general `escape_default` arm.
+ assert_eq!(escape_controls("a\x1bb"), r"a\u{1b}b");
+ assert_eq!(escape_controls("a\x07b"), r"a\u{7}b");
+ }
+
+ #[test]
+ fn escape_controls_is_idempotent() {
+ // Re-escaping already-escaped text is a no-op: the escapes carry no
+ // control bytes, so diagnostic.md assembly can re-sanitize a trace.log
+ // the formatter already cleaned without doubling the backslashes.
+ let once = escape_controls("x\0y\x1bz").into_owned();
+ assert_eq!(escape_controls(&once), once);
+ }
}
diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rs
index ff98dbf72..ccaad2496 100644
--- a/tests/integration_tests/diagnostic.rs
+++ b/tests/integration_tests/diagnostic.rs
@@ -360,6 +360,43 @@ fn test_vv_splits_full_and_bounded_output(repo: TestRepo) {
);
}
+/// Control bytes in captured subprocess output must be escaped on the
+/// human-facing routes (stderr + `trace.log`) but kept verbatim in
+/// `subprocess.log`. `wt list` runs `git for-each-ref --format=…%00…`
+/// (`LOCAL_BRANCH_FORMAT`), so its captured stdout carries NUL bytes between
+/// fields — a real instance of the bytes that, left raw, make `diagnostic.md`
+/// sniff as binary and break its `gh gist create` upload (issue #2988).
+#[rstest]
+fn test_vv_escapes_control_bytes_in_trace_not_subprocess(repo: TestRepo) {
+ repo.wt_command().args(["list", "-vv"]).output().unwrap();
+
+ let logs_dir = repo.root_path().join(".git").join("wt/logs");
+ let trace = fs::read_to_string(logs_dir.join("trace.log")).unwrap();
+ let subprocess = fs::read_to_string(logs_dir.join("subprocess.log")).unwrap();
+ let diagnostic = fs::read_to_string(logs_dir.join("diagnostic.md")).unwrap();
+
+ // subprocess.log is the raw byte stream — NUL survives verbatim.
+ assert!(
+ subprocess.contains('\u{0}'),
+ "subprocess.log should keep raw NUL bytes from for-each-ref output"
+ );
+ // The bounded preview in trace.log is escaped: visible `\0`, no raw NUL.
+ assert!(
+ trace.contains(r"\0"),
+ "trace.log should render NUL as the escaped `\\0`"
+ );
+ assert!(
+ !trace.contains('\u{0}'),
+ "trace.log must not carry raw NUL bytes (would sniff as binary)"
+ );
+ // diagnostic.md inlines trace.log plus config / worktree list — the upload
+ // boundary must be free of raw control bytes so the gist upload succeeds.
+ assert!(
+ !diagnostic.contains('\u{0}'),
+ "diagnostic.md must not carry raw NUL bytes (binary file → gist upload fails)"
+ );
+}
+
/// At `-vv`, Debug-level records (the noisy ones) stay out of stderr —
/// the bounded subprocess preview lands in `trace.log` (not stderr), and
/// `subprocess.log` still holds the unbounded body. Info-level routing