Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add diagnostic report generation for GitHub issues (#439)
Maximilian Roos1181f05255d7
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 723ba0cae..8c282f86f 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -52,6 +52,7 @@ use worktrunk::git::{LineDiff, Repository, Worktree};use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, warning_message};use crate::commands::is_worktree_at_expected_path_with;+use crate::diagnostic::DiagnosticReport;use super::ci_status::PrStatus;use super::model::{@@ -1091,10 +1092,14 @@ pub fn collect(}diag.push_str(- "\n\nThis likely indicates a git command hung. Run with RUST_LOG=debug for details.",+ "\n\nThis likely indicates a git command hung. Run with --verbose for details.",);- crate::output::print(warning_message(diag))?;+ crate::output::print(warning_message(&diag))?;++ // Show issue reporting hint (writes diagnostic file if --verbose was used)+ let report = DiagnosticReport::collect(repo, diag);+ crate::output::print(worktrunk::styling::hint_message(report.issue_hint(repo)))?;}// Compute status symbols for prunable worktrees (skipped during task spawning).@@ -1174,7 +1179,11 @@ pub fn collect("Some git operations failed:\n{}",format_with_gutter(&error_lines.join("\n"), None));- crate::output::print(warning_message(warning))?;+ crate::output::print(warning_message(&warning))?;++ // Show issue reporting hint (writes diagnostic file if --verbose was used)+ let report = DiagnosticReport::collect(repo, warning);+ crate::output::print(worktrunk::styling::hint_message(report.issue_hint(repo)))?;}// Populate display fields for all items (used by JSON output and statusline)diff --git a/src/diagnostic.rs b/src/diagnostic.rsnew file mode 100644index 000000000..d67b27a9a--- /dev/null+++ b/src/diagnostic.rs@@ -0,0 +1,271 @@+//! 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.+//!+//! # When Diagnostics Are Generated+//!+//! Diagnostic files are only written when `--verbose` is passed. Without verbose+//! logging, the hint simply tells users to re-run with `--verbose`. This ensures+//! the diagnostic file contains useful debug information.+//!+//! # Report Format+//!+//! The report is a markdown file designed for easy pasting into GitHub issues:+//!+//! 1. **Header** — Timestamp and context describing the issue+//! 2. **Diagnostic data** — Collapsed `<details>` block with:+//! - wt version, OS, architecture+//! - git version+//! - Shell integration status+//! - Raw `git worktree list --porcelain` output+//! 3. **Verbose log** — Debug log output, truncated to ~50KB if large+//!+//! # Privacy+//!+//! The report explicitly documents what IS and ISN'T included:+//!+//! **Included:** worktree paths, branch names, worktree status (prunable, locked),+//! verbose logs, commit messages (in verbose logs)+//!+//! **Not included:** file contents, credentials+//!+//! # File Location+//!+//! Reports are written to `.git/wt-logs/diagnostic.md` in the main worktree.+//! Verbose logs go to `.git/wt-logs/verbose.log`.+//!+//! # Usage+//!+//! ```rust,ignore+//! use crate::diagnostic::DiagnosticReport;+//!+//! // Show hint (writes diagnostic file only if --verbose was used)+//! let report = DiagnosticReport::collect(&repo, "Some git operations failed".into());+//! output::print(hint_message(report.issue_hint(&repo)))?;+//! ```+//!+use std::path::PathBuf;+use std::process::{Command, Stdio};++use anyhow::Context;+use color_print::cformat;+use minijinja::{Environment, context};+use worktrunk::git::Repository;+use worktrunk::path::format_path_for_display;+use worktrunk::shell_exec::run;++use crate::cli::version_str;+use crate::output;++/// Markdown template for the diagnostic report.+///+/// This template makes the report structure immediately visible.+/// Variables are filled in by `format_report()`.+const REPORT_TEMPLATE: &str = r#"## Diagnostic Report++**Generated:** {{ timestamp }}+**Context:** {{ context }}++### What's included++- wt version, OS, git version+- Worktree paths and branch names+- Worktree status (prunable, locked, etc.)+- Shell integration status+- Verbose logs (if run with --verbose)+- Commit messages (in verbose logs)++Does NOT contain: file contents, credentials.++<details>+<summary>Diagnostic data</summary>++```+wt {{ version }} ({{ os }} {{ arch }})+git {{ git_version }}+Shell integration: {{ shell_integration }}++--- git worktree list --porcelain ---+{{ worktree_list }}+```+</details>+{% if verbose_log %}+<details>+<summary>Verbose log</summary>++```+{{ verbose_log }}+```+</details>+{% endif %}+"#;++/// Collected diagnostic information for issue reporting.+pub struct DiagnosticReport {+ /// Formatted markdown content+ content: String,+}++impl DiagnosticReport {+ /// Collect diagnostic information from the current environment.+ ///+ /// # Arguments+ /// * `repo` - Repository to collect worktree info from+ /// * `context` - Context describing the issue (error message, affected item)+ pub fn collect(repo: &Repository, context: String) -> Self {+ let content = Self::format_report(repo, &context);+ Self { content }+ }++ /// Format the complete diagnostic report as markdown using minijinja template.+ fn format_report(repo: &Repository, context: &str) -> String {+ // Strip ANSI codes from context - the diagnostic is a markdown file for GitHub+ let context = strip_ansi_codes(context);++ // Collect data for template+ let timestamp = worktrunk::utils::now_iso8601();+ let version = version_str();+ let os = std::env::consts::OS;+ let arch = std::env::consts::ARCH;+ let git_version = get_git_version().unwrap_or_else(|_| "(unknown)".to_string());+ let shell_integration = if output::is_shell_integration_active() {+ "active"+ } else {+ "inactive"+ };+ let worktree_list = repo+ .run_command(&["worktree", "list", "--porcelain"])+ .map(|s| s.trim_end().to_string())+ .unwrap_or_else(|_| "(failed to get worktree list)".to_string());++ // Get verbose log content (if available)+ let verbose_log = crate::verbose_log::log_file_path()+ .and_then(|path| std::fs::read_to_string(&path).ok())+ .map(|content| truncate_log(content.trim()))+ .filter(|s| !s.is_empty());++ // Render template+ let env = Environment::new();+ let tmpl = env.template_from_str(REPORT_TEMPLATE).unwrap();+ tmpl.render(context! {+ timestamp,+ context,+ version,+ os,+ arch,+ git_version,+ shell_integration,+ worktree_list,+ verbose_log,+ })+ .unwrap()+ }++ /// Write diagnostic file (if verbose) and return issue reporting hint.+ ///+ /// If verbose logging is active: writes diagnostic file, returns hint with gh command.+ /// Otherwise: returns hint to re-run with --verbose (no file written).+ pub fn issue_hint(&self, repo: &Repository) -> String {+ if !crate::verbose_log::is_active() {+ return cformat!("To create a diagnostic file, re-run with <bright-black>--verbose</>");+ }++ // Write the diagnostic file+ let Some(path) = self.write_file(repo) else {+ return "Failed to write diagnostic file".to_string();+ };++ let path_display = format_path_for_display(&path);+ let mut hint = format!("Diagnostic saved: {path_display}");++ if is_gh_installed() {+ // Escape single quotes for shell: 'it'\''s' -> it's+ let path_str = path.to_string_lossy().replace('\'', "'\\''");+ hint.push_str(&cformat!(+ "\n <bright-black>gh issue create -R max-sixty/worktrunk -t 'Bug report' --body-file '{path_str}'</>"+ ));+ }++ hint+ }++ /// Write the diagnostic report to a file.+ fn write_file(&self, repo: &Repository) -> Option<PathBuf> {+ let log_dir = repo.wt_logs_dir().ok()?;+ std::fs::create_dir_all(&log_dir).ok()?;++ let path = log_dir.join("diagnostic.md");+ std::fs::write(&path, &self.content).ok()?;++ Some(path)+ }+}++/// Check if the GitHub CLI (gh) is installed.+fn is_gh_installed() -> bool {+ let mut cmd = Command::new("gh");+ cmd.args(["--version"]);+ cmd.stdin(Stdio::null());++ run(&mut cmd, None)+ .map(|o| o.status.success())+ .unwrap_or(false)+}++/// Strip ANSI escape codes from a string.+///+/// Used to clean terminal-formatted text for markdown output.+fn strip_ansi_codes(s: &str) -> String {+ // Match SGR (Select Graphic Rendition) sequences: ESC [ <params> m+ // This covers colors, bold, dim, etc.+ let re = regex::Regex::new(r"\x1b\[[0-9;]*m").unwrap();+ re.replace_all(s, "").into_owned()+}++/// Truncate verbose log to ~50KB if it's too large.+///+/// Keeps the last ~50KB of the log, cutting at a line boundary.+fn truncate_log(content: &str) -> String {+ const MAX_LOG_SIZE: usize = 50 * 1024;+ if content.len() <= MAX_LOG_SIZE {+ return content.to_string();+ }++ let start = content.len() - MAX_LOG_SIZE;+ // Find the next newline to avoid cutting mid-line+ let start = content[start..]+ .find('\n')+ .map(|i| start + i + 1)+ .unwrap_or(start);++ format!("(log truncated to last ~50KB)\n{}", &content[start..])+}++/// Get git version string.+fn get_git_version() -> anyhow::Result<String> {+ let mut cmd = Command::new("git");+ cmd.args(["--version"]);+ cmd.stdin(Stdio::null());++ let output = run(&mut cmd, None).context("Failed to run git --version")?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ let version = stdout+ .trim()+ .strip_prefix("git version ")+ .unwrap_or(stdout.trim())+ .to_string();++ Ok(version)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_is_gh_installed_returns_bool() {+ // Just verify it doesn't panic and returns a bool+ let _ = is_gh_installed();+ }+}diff --git a/src/main.rs b/src/main.rsindex d5be8146b..d5ce97d97 100644--- a/src/main.rs+++ b/src/main.rs@@ -15,12 +15,14 @@ use worktrunk::styling::{mod cli;mod commands;mod completion;+mod diagnostic;mod display;pub(crate) mod help_pager;mod llm;mod md_help;mod output;mod pager;+mod verbose_log;pub use crate::cli::OutputFormat;@@ -741,58 +743,76 @@ fn main() {}// Configure logging based on --verbose flag or RUST_LOG env var- env_logger::Builder::from_env(- env_logger::Env::default().default_filter_or(if cli.verbose { "debug" } else { "off" }),- )- .format(|buf, record| {- use std::io::Write;-- let msg = record.args().to_string();-- // Map thread ID to a single character (a-z, then A-Z)- let thread_id = format!("{:?}", std::thread::current().id());- let thread_num = thread_id- .strip_prefix("ThreadId(")- .and_then(|s| s.strip_suffix(")"))- .and_then(|s| s.parse::<usize>().ok())- .map(|n| {- if n <= 26 {- char::from(b'a' + (n - 1) as u8)- } else if n <= 52 {- char::from(b'A' + (n - 27) as u8)+ // When --verbose is set, also write logs to .git/wt-logs/verbose.log+ if cli.verbose {+ verbose_log::init();+ }++ // --verbose takes precedence over RUST_LOG: use Builder::new() to ignore env var+ // Otherwise, respect RUST_LOG (defaulting to off)+ let mut builder = if cli.verbose {+ let mut b = env_logger::Builder::new();+ b.filter_level(log::LevelFilter::Debug);+ b+ } else {+ env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("off"))+ };++ builder+ .format(|buf, record| {+ use std::io::Write;++ let msg = record.args().to_string();++ // Map thread ID to a single character (a-z, then A-Z)+ let thread_id = format!("{:?}", std::thread::current().id());+ let thread_num = thread_id+ .strip_prefix("ThreadId(")+ .and_then(|s| s.strip_suffix(")"))+ .and_then(|s| s.parse::<usize>().ok())+ .map(|n| {+ if n == 0 {+ '0'+ } else if n <= 26 {+ char::from(b'a' + (n - 1) as u8)+ } else if n <= 52 {+ char::from(b'A' + (n - 27) as u8)+ } else {+ '?'+ }+ })+ .unwrap_or('?');++ // Write plain text to log file (no ANSI codes)+ verbose_log::write_line(&format!("[{thread_num}] {msg}"));++ // 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}</>")+ )}- })- .unwrap_or('?');-- // 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 if msg.starts_with(" ! ") {+ // Error output - show in red+ writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> <red>{msg}</>"))} else {- writeln!(- buf,- "{}",- cformat!("<dim>[{thread_num}]</> $ <bold>{rest}</>")- )+ // 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();+ })+ .init();let Some(command) = cli.command else {// No subcommand provided - print help to stderr (stdout is eval'd by shell wrapper)diff --git a/src/utils.rs b/src/utils.rsindex f45ba5475..b9fe5e25e 100644--- a/src/utils.rs+++ b/src/utils.rs@@ -2,6 +2,24 @@use std::time::{SystemTime, UNIX_EPOCH};+/// 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.+pub fn format_timestamp_iso8601(timestamp: u64) -> String {+ let timestamp = timestamp as i64;+ chrono::DateTime::from_timestamp(timestamp, 0)+ .unwrap_or_else(chrono::Utc::now)+ .format("%Y-%m-%dT%H:%M:%SZ")+ .to_string()+}++/// Format the current time as ISO 8601 string, respecting `SOURCE_DATE_EPOCH`.+///+/// Convenience function combining `get_now()` and `format_timestamp_iso8601()`.+pub fn now_iso8601() -> String {+ format_timestamp_iso8601(get_now())+}+/// Get current Unix timestamp in seconds, respecting `SOURCE_DATE_EPOCH`.////// When `SOURCE_DATE_EPOCH` environment variable is set, returns that valuediff --git a/src/verbose_log.rs b/src/verbose_log.rsnew file mode 100644index 000000000..50ea2fdc8--- /dev/null+++ b/src/verbose_log.rs@@ -0,0 +1,101 @@+//! Verbose log file management for diagnostics.+//!+//! When `--verbose` is passed, logs are written to both stderr AND+//! `.git/wt-logs/verbose.log`. This file can be included in diagnostic+//! reports to help debug issues.+//!+//! # Usage+//!+//! 1. Call `init()` early in main() after parsing CLI args but before logging+//! 2. Call `write_line()` from the log format function+//! 3. The diagnostic module reads the log file via `log_file_path()`++use std::fs::{File, OpenOptions};+use std::io::Write;+use std::path::PathBuf;+use std::sync::{Mutex, OnceLock};++/// Global state for verbose logging to file.+static VERBOSE_LOG: OnceLock<Mutex<Option<VerboseLog>>> = OnceLock::new();++struct VerboseLog {+ path: PathBuf,+ file: File,+}++/// Initialize verbose log file writing.+///+/// Should be called early in main() when `--verbose` is set.+/// Tries to find a git repo and create the log file.+pub fn init() {+ let mutex = VERBOSE_LOG.get_or_init(|| Mutex::new(None));+ let Ok(mut guard) = mutex.lock() else { return };++ // Try to find the repo and create the log file+ if let Some((path, file)) = try_create_log_file() {+ *guard = Some(VerboseLog { path, file });+ }+}++/// Write a line to the verbose log file (if initialized).+///+/// Call this from the log format function. The line should be+/// plain text (no ANSI codes) for readability in issue reports.+pub fn write_line(line: &str) {+ if let Some(mutex) = VERBOSE_LOG.get()+ && let Ok(mut guard) = mutex.lock()+ && let Some(log) = guard.as_mut()+ {+ // Ignore write errors - logging shouldn't break the command+ let _ = writeln!(log.file, "{}", line);+ let _ = log.file.flush();+ }+}++/// Get the path to the verbose log file, if it was created.+///+/// Used by the diagnostic module to include log contents.+pub fn log_file_path() -> Option<PathBuf> {+ VERBOSE_LOG.get().and_then(|mutex| {+ mutex+ .lock()+ .ok()+ .and_then(|guard| guard.as_ref().map(|log| log.path.clone()))+ })+}++/// Try to create the verbose log file in the repo's wt-logs directory.+///+/// TODO: This uses current_dir() which ignores the `-C` flag. If a user runs+/// `wt -C /other/repo list --verbose` from outside the repo, the log file+/// will be created in the wrong location (or not at all). To fix this,+/// verbose_log::init() would need to run after set_base_path(), or accept+/// a repository parameter.+fn try_create_log_file() -> Option<(PathBuf, File)> {+ // Find the git repo from current directory+ let cwd = std::env::current_dir().ok()?;+ let repo = worktrunk::git::Repository::at(cwd);++ // Get the wt-logs directory (creates it if needed)+ let log_dir = repo.wt_logs_dir().ok()?;+ std::fs::create_dir_all(&log_dir).ok()?;++ let path = log_dir.join("verbose.log");++ // Truncate/create the file+ let file = OpenOptions::new()+ .write(true)+ .create(true)+ .truncate(true)+ .open(&path)+ .ok()?;++ Some((path, file))+}++/// Check if verbose logging to file is active.+pub fn is_active() -> bool {+ VERBOSE_LOG+ .get()+ .is_some_and(|mutex| mutex.lock().is_ok_and(|g| g.is_some()))+}diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rsnew file mode 100644index 000000000..5d64726bb--- /dev/null+++ b/tests/integration_tests/diagnostic.rs@@ -0,0 +1,454 @@+//! Tests for diagnostic report generation.+//!+//! These tests verify the markdown structure and content of diagnostic reports+//! to ensure they're suitable for GitHub issue filing.+//!+//! # Test Coverage+//!+//! - `test_diagnostic_report_file_format`: Snapshot of full diagnostic structure+//! - `test_diagnostic_not_created_without_verbose`: No file without --verbose+//! - `test_diagnostic_hint_without_verbose`: Hint tells user to use --verbose+//! - `test_diagnostic_contains_required_sections`: All sections present+//! - `test_diagnostic_context_has_no_ansi_codes`: ANSI stripped for GitHub+//! - `test_diagnostic_verbose_log_contains_git_commands`: Log has useful data+//! - `test_diagnostic_shows_gh_command_hint`: gh CLI suggestion when available+//! - `test_diagnostic_written_to_correct_location`: File in .git/wt-logs/++use std::fs;+use std::path::PathBuf;++use insta::assert_snapshot;+use rstest::rstest;++use crate::common::{TestRepo, repo, setup_snapshot_settings};++/// Helper to corrupt a worktree's HEAD file to trigger git errors.+fn corrupt_worktree_head(repo: &TestRepo, worktree_name: &str) -> PathBuf {+ let feature_path = repo.worktrees.get(worktree_name).unwrap();+ let git_dir = feature_path.join(".git");+ let git_content = fs::read_to_string(&git_dir).unwrap();+ let actual_git_dir = git_content+ .strip_prefix("gitdir: ")+ .unwrap()+ .trim()+ .to_string();+ let head_path = PathBuf::from(&actual_git_dir).join("HEAD");+ fs::write(&head_path, "invalid").unwrap();+ head_path+}++/// Snapshot the diagnostic report file generated on git errors with --verbose.+///+/// This test triggers a git error (invalid HEAD) which causes `wt list --verbose`+/// to generate a diagnostic report file. We then read and snapshot the file+/// to verify its structure.+///+/// Note: Diagnostic files are only generated when --verbose is used.+#[rstest]+fn test_diagnostic_report_file_format(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ let output = repo+ .wt_command()+ .args(["list", "--verbose"])+ .output()+ .unwrap();++ let diagnostic_path = repo+ .root_path()+ .join(".git")+ .join("wt-logs")+ .join("diagnostic.md");+ assert!(+ diagnostic_path.exists(),+ "Diagnostic file should be generated at {:?}",+ diagnostic_path+ );++ let content = fs::read_to_string(&diagnostic_path).unwrap();++ // Verify verbose log section is present (requires --verbose)+ assert!(+ content.contains("<summary>Verbose log</summary>"),+ "Diagnostic should include verbose log section when run with --verbose"+ );++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ assert_snapshot!("diagnostic_file_format", normalize_report(&content));+ });++ // Verify the stderr mentions the diagnostic was saved+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Diagnostic saved"),+ "Output should mention diagnostic was saved. stderr: {}",+ stderr+ );+}++/// Without --verbose, no diagnostic file should be created.+///+/// The diagnostic file is only useful with verbose logs, so we don't create+/// an empty/minimal diagnostic when --verbose is not used.+#[rstest]+fn test_diagnostic_not_created_without_verbose(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ // Run WITHOUT --verbose+ repo.wt_command().args(["list"]).output().unwrap();++ // Diagnostic file should NOT exist+ let diagnostic_path = repo+ .root_path()+ .join(".git")+ .join("wt-logs")+ .join("diagnostic.md");+ assert!(+ !diagnostic_path.exists(),+ "Diagnostic file should NOT be created without --verbose"+ );+}++/// Without --verbose, the hint should tell users to re-run with --verbose.+#[rstest]+fn test_diagnostic_hint_without_verbose(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ let output = repo.wt_command().args(["list"]).output().unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("To create a diagnostic file, re-run with"),+ "Should hint to use --verbose. stderr: {}",+ stderr+ );+ assert!(+ stderr.contains("--verbose"),+ "Hint should mention --verbose flag. stderr: {}",+ stderr+ );+}++/// Diagnostic file must contain all required sections for GitHub issues.+#[rstest]+fn test_diagnostic_contains_required_sections(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ repo.wt_command()+ .args(["list", "--verbose"])+ .output()+ .unwrap();++ let content = fs::read_to_string(+ repo.root_path()+ .join(".git")+ .join("wt-logs")+ .join("diagnostic.md"),+ )+ .unwrap();++ // Header section+ assert!(+ content.contains("## Diagnostic Report"),+ "Should have header"+ );+ assert!(content.contains("**Generated:**"), "Should have timestamp");+ assert!(content.contains("**Context:**"), "Should have context");++ // Privacy notice+ assert!(+ content.contains("### What's included"),+ "Should have privacy section"+ );+ assert!(+ content.contains("Commit messages"),+ "Should mention commit messages are included"+ );+ assert!(+ content.contains("Does NOT contain:"),+ "Should clarify what's excluded"+ );+ assert!(+ content.contains("file contents"),+ "Should clarify file contents are excluded"+ );++ // Diagnostic data section+ assert!(+ content.contains("<summary>Diagnostic data</summary>"),+ "Should have diagnostic data section"+ );+ assert!(content.contains("wt v"), "Should have wt version");+ assert!(content.contains("git "), "Should have git version");+ assert!(+ content.contains("Shell integration:"),+ "Should have shell integration status"+ );+ assert!(+ content.contains("git worktree list --porcelain"),+ "Should have worktree list output"+ );++ // Verbose log section+ assert!(+ content.contains("<summary>Verbose log</summary>"),+ "Should have verbose log section"+ );+}++/// The context field should have ANSI codes stripped for clean GitHub display.+#[rstest]+fn test_diagnostic_context_has_no_ansi_codes(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ repo.wt_command()+ .args(["list", "--verbose"])+ .output()+ .unwrap();++ let content = fs::read_to_string(+ repo.root_path()+ .join(".git")+ .join("wt-logs")+ .join("diagnostic.md"),+ )+ .unwrap();++ // ANSI escape codes start with \x1b[ or \033[+ assert!(+ !content.contains("\x1b["),+ "Diagnostic file should not contain ANSI escape codes"+ );+ assert!(+ !content.contains("\u{001b}"),+ "Diagnostic file should not contain ANSI escape codes (unicode)"+ );+}++/// Verbose log should contain git command traces for debugging.+#[rstest]+fn test_diagnostic_verbose_log_contains_git_commands(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ repo.wt_command()+ .args(["list", "--verbose"])+ .output()+ .unwrap();++ let content = fs::read_to_string(+ repo.root_path()+ .join(".git")+ .join("wt-logs")+ .join("diagnostic.md"),+ )+ .unwrap();++ // Extract verbose log section+ let verbose_start = content+ .find("<summary>Verbose log</summary>")+ .expect("Should have verbose log");+ let verbose_section = &content[verbose_start..];++ // Should contain git command traces+ assert!(+ verbose_section.contains("git worktree list"),+ "Verbose log should contain git worktree list command"+ );+ assert!(+ verbose_section.contains("[wt-trace]"),+ "Verbose log should contain wt-trace entries"+ );+ assert!(+ verbose_section.contains("dur="),+ "Verbose log should contain command durations"+ );+ assert!(+ verbose_section.contains("ok="),+ "Verbose log should contain success/failure indicators"+ );+}++/// When gh CLI is available, should show command to create issue.+#[rstest]+fn test_diagnostic_shows_gh_command_hint(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ let output = repo+ .wt_command()+ .args(["list", "--verbose"])+ .output()+ .unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr);++ // Check if gh is installed (the hint varies based on this)+ let gh_available = std::process::Command::new("gh")+ .arg("--version")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false);++ if gh_available {+ assert!(+ stderr.contains("gh issue create"),+ "Should show gh command when gh CLI is available. stderr: {}",+ stderr+ );+ assert!(+ stderr.contains("--body-file"),+ "gh command should use --body-file. stderr: {}",+ stderr+ );+ }+ // If gh is not available, just verify diagnostic was saved+ assert!(+ stderr.contains("Diagnostic saved"),+ "Should always mention diagnostic was saved. stderr: {}",+ stderr+ );+}++/// Diagnostic file should be written to .git/wt-logs/diagnostic.md+#[rstest]+fn test_diagnostic_written_to_correct_location(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ repo.wt_command()+ .args(["list", "--verbose"])+ .output()+ .unwrap();++ // Should be in .git/wt-logs/ directory+ let wt_logs_dir = repo.root_path().join(".git").join("wt-logs");+ assert!(wt_logs_dir.exists(), "wt-logs directory should exist");++ let diagnostic_path = wt_logs_dir.join("diagnostic.md");+ assert!(+ diagnostic_path.exists(),+ "diagnostic.md should be in wt-logs"+ );++ // Should be a markdown file+ let content = fs::read_to_string(&diagnostic_path).unwrap();+ assert!(+ content.starts_with("## "),+ "Should be a markdown file starting with header"+ );+}++/// Verbose log file should also be created alongside diagnostic.+#[rstest]+fn test_verbose_log_file_created(mut repo: TestRepo) {+ repo.add_worktree("feature");+ corrupt_worktree_head(&repo, "feature");++ repo.wt_command()+ .args(["list", "--verbose"])+ .output()+ .unwrap();++ let verbose_log_path = repo+ .root_path()+ .join(".git")+ .join("wt-logs")+ .join("verbose.log");+ assert!(+ verbose_log_path.exists(),+ "verbose.log should be created with --verbose"+ );++ let content = fs::read_to_string(&verbose_log_path).unwrap();+ assert!(!content.is_empty(), "verbose.log should not be empty");+ assert!(+ content.contains("[wt-trace]"),+ "verbose.log should contain trace entries"+ );+}++/// Normalize the report for snapshot comparison.+///+/// Replaces variable content (versions, paths, timestamps) with placeholders.+fn normalize_report(content: &str) -> String {+ let mut result = content.to_string();++ // Normalize timestamp (e.g., "2025-01-01T00:00:00Z" -> "[TIMESTAMP]")+ result = regex::Regex::new(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")+ .unwrap()+ .replace_all(&result, "[TIMESTAMP]")+ .to_string();++ // Normalize wt version line (e.g., "wt v0.9.3-dirty (macos aarch64)" or "wt be89089 (linux x86_64)")+ // CI builds use commit hashes instead of version numbers+ result = regex::Regex::new(r"wt [^ ]+ \([^)]+\)")+ .unwrap()+ .replace_all(&result, "wt [VERSION] ([OS] [ARCH])")+ .to_string();++ // Normalize git version line+ result = regex::Regex::new(r"git \d+\.\d+[^\n]*")+ .unwrap()+ .replace_all(&result, "git [GIT_VERSION]")+ .to_string();++ // Normalize worktree paths in porcelain output (Unix and Windows absolute paths)+ result = regex::Regex::new(r"worktree (?:/|[A-Za-z]:)[^\n]+")+ .unwrap()+ .replace_all(&result, "worktree [PATH]")+ .to_string();++ // Normalize commit hashes (40 hex chars) - in "HEAD xxx" format+ result = regex::Regex::new(r"HEAD [a-f0-9]{40}")+ .unwrap()+ .replace_all(&result, "HEAD [COMMIT]")+ .to_string();++ // Normalize all other commit hashes (40 hex chars standalone)+ result = regex::Regex::new(r"\b[a-f0-9]{40}\b")+ .unwrap()+ .replace_all(&result, "[HASH]")+ .to_string();++ // Normalize temp paths in context (repo paths) - handles both Unix and Windows paths+ // Unix: /var/folders/.../repo.xxx or /tmp/.../repo.xxx+ // Windows: D:\a\worktrunk\worktrunk\... or C:\Users\...\repo.xxx+ // Match Windows paths first (drive letter + colon + any path chars)+ result = regex::Regex::new(r"([A-Z]:[^\s)]+|/[^\s)]+/repo\.[^\s)]+)")+ .unwrap()+ .replace_all(&result, "[REPO_PATH]")+ .to_string();++ // Normalize line breaks in git error messages (cross-platform consistency)+ // Some platforms wrap "fatal: not a git repository:\n /path" on two lines,+ // others keep it on one line. Normalize to single-line format.+ result = regex::Regex::new(r"(fatal: not a git repository:)\s*\n\s*(\[REPO_PATH\])")+ .unwrap()+ .replace_all(&result, "$1 $2")+ .to_string();++ // Truncate verbose log section - it has parallel git commands that interleave+ // in different orders, making exact snapshot comparison flaky.+ // We verify the section exists separately in the test.+ if let Some(start) = result.find("<summary>Verbose log</summary>") {+ // Find the closing </details> after this point+ if let Some(end_offset) = result[start..].find("</details>") {+ let end = start + end_offset + "</details>".len();+ let before = &result[..start];+ let after = &result[end..];+ result = format!(+ "{}<summary>Verbose log</summary>\n\n[VERBOSE_LOG_CONTENT]\n</details>{}",+ before, after+ );+ }+ }++ result+}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex 9728a51ca..27c4e260f 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -21,6 +21,7 @@ pub mod config_show_theme;pub mod config_state;pub mod configure_shell;pub mod default_branch;+pub mod diagnostic;pub mod directives;pub mod doc_templates;pub mod e2e_shell;diff --git a/tests/snapshots/integration__integration_tests__diagnostic__diagnostic_file_format.snap b/tests/snapshots/integration__integration_tests__diagnostic__diagnostic_file_format.snapnew file mode 100644index 000000000..e4bb5c792--- /dev/null+++ b/tests/snapshots/integration__integration_tests__diagnostic__diagnostic_file_format.snap@@ -0,0 +1,47 @@+---+source: tests/integration_tests/diagnostic.rs+expression: normalize_report(&content)+---+## Diagnostic Report++**Generated:** [TIMESTAMP]+**Context:** Some git operations failed:+ (detached): commit-details (fatal: not a git repository: [REPO_PATH])+ (detached): ahead-behind (fatal: not a git repository: [REPO_PATH])+ (detached): committed-trees-match (fatal: not a git repository: [REPO_PATH])+ (detached): working-tree-diff (fatal: not a git repository: [REPO_PATH])++### What's included++- wt version, OS, git version+- Worktree paths and branch names+- Worktree status (prunable, locked, etc.)+- Shell integration status+- Verbose logs (if run with --verbose)+- Commit messages (in verbose logs)++Does NOT contain: file contents, credentials.++<details>+<summary>Diagnostic data</summary>++```+wt [VERSION] ([OS] [ARCH])+git [GIT_VERSION]+Shell integration: inactive++--- git worktree list --porcelain ---+worktree [PATH]+HEAD [COMMIT]+branch refs/heads/main++worktree [PATH]+HEAD [COMMIT]+```+</details>++<details>+<summary>Verbose log</summary>++[VERBOSE_LOG_CONTENT]+</details>diff --git a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snapindex ccec5f6a0..20cc804c2 100644--- a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap+++ b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap@@ -20,6 +20,7 @@ info:PATH: "[PATH]"RUST_LOG: warnSOURCE_DATE_EPOCH: "1735776000"+ TERM: alacrittyUSERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -42,3 +43,4 @@ exit_code: 0[107m [0m working tree.)[107m [0m [1mfeature[22m: has-file-changes (fatal: Invalid symmetric difference expression main...feature)[107m [0m [1mfeature[22m: working-tree-diff (fatal: bad object HEAD)[39m+[2m↳[22m [2mTo create a diagnostic file, re-run with [90m--verbose[39m[22m