Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Make wt config show a real diagnostic (#3999)
Maximilian Roos9f28b1267f85
diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.mdindex 5d63f8c8e..3b85274f2 100644--- a/docs/src/content/docs/config.md+++ b/docs/src/content/docs/config.md@@ -752,10 +752,9 @@ Global Options:Show configuration files & locations.-Shows location and contents of user config (`~/.config/worktrunk/config.toml`)-and project config (`.config/wt.toml`). Also shows system config if present.--If a config file doesn't exist, shows defaults that would be used.+Shows config sources and checks for invalid TOML or list columns, misplaced or+deprecated keys, and commands awaiting approval. It renders every section+before failing; warnings exit zero.### Full diagnostics@@ -824,8 +823,8 @@ instead of applying it in place. Use `-` for stdout. When both user and projectconfig need migration, stdout emits a labeled inspection artifact and fileoutput fails rather than combining the configs.-Output artifacts omit deprecated `approved-commands`; only in-place updates-move those entries to `approvals.toml`.+`--output` omits deprecated `approved-commands` with a stderr warning; only an+in-place update migrates them to `approvals.toml`.### Examplesdiff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex d8909ba5b..3c570027f 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -744,10 +744,9 @@ Global Options:Show configuration files & locations.-Shows location and contents of user config (`~/.config/worktrunk/config.toml`)-and project config (`.config/wt.toml`). Also shows system config if present.--If a config file doesn't exist, shows defaults that would be used.+Shows config sources and checks for invalid TOML or list columns, misplaced or+deprecated keys, and commands awaiting approval. It renders every section+before failing; warnings exit zero.### Full diagnostics@@ -816,8 +815,8 @@ instead of applying it in place. Use `-` for stdout. When both user and projectconfig need migration, stdout emits a labeled inspection artifact and fileoutput fails rather than combining the configs.-Output artifacts omit deprecated `approved-commands`; only in-place updates-move those entries to `approvals.toml`.+`--output` omits deprecated `approved-commands` with a stderr warning; only an+in-place update migrates them to `approvals.toml`.### Examplesdiff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex d8909ba5b..3c570027f 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -744,10 +744,9 @@ Global Options:Show configuration files & locations.-Shows location and contents of user config (`~/.config/worktrunk/config.toml`)-and project config (`.config/wt.toml`). Also shows system config if present.--If a config file doesn't exist, shows defaults that would be used.+Shows config sources and checks for invalid TOML or list columns, misplaced or+deprecated keys, and commands awaiting approval. It renders every section+before failing; warnings exit zero.### Full diagnostics@@ -816,8 +815,8 @@ instead of applying it in place. Use `-` for stdout. When both user and projectconfig need migration, stdout emits a labeled inspection artifact and fileoutput fails rather than combining the configs.-Output artifacts omit deprecated `approved-commands`; only in-place updates-move those entries to `approvals.toml`.+`--output` omits deprecated `approved-commands` with a stderr warning; only an+in-place update migrates them to `approvals.toml`.### Examplesdiff --git a/src/cli/config.rs b/src/cli/config.rsindex 04d935eba..45edae2f3 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -564,10 +564,9 @@ pub enum ConfigCommand {/// Show configuration files & locations#[command(- after_long_help = r#"Shows location and contents of user config (`~/.config/worktrunk/config.toml`)-and project config (`.config/wt.toml`). Also shows system config if present.--If a config file doesn't exist, shows defaults that would be used.+ after_long_help = r#"Shows config sources and checks for invalid TOML or list columns, misplaced or+deprecated keys, and commands awaiting approval. It renders every section+before failing; warnings exit zero.## Full diagnostics@@ -604,8 +603,8 @@ instead of applying it in place. Use `-` for stdout. When both user and projectconfig need migration, stdout emits a labeled inspection artifact and fileoutput fails rather than combining the configs.-Output artifacts omit deprecated `approved-commands`; only in-place updates-move those entries to `approvals.toml`.+`--output` omits deprecated `approved-commands` with a stderr warning; only an+in-place update migrates them to `approvals.toml`.## Examplesdiff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rsindex 87bb09ce4..540b5bec3 100644--- a/src/commands/config/approvals.rs+++ b/src/commands/config/approvals.rs@@ -28,7 +28,9 @@ use crate::output::print_json;/// Every approvable command a project config declares: hooks in lifecycle/// order, then aliases (alphabetical), then any commit-message guidance./// The shared collection behind `wt config approvals {list,add}`.-fn collect_approvable_commands(project_config: &ProjectConfig) -> Vec<ApprovableCommand> {+pub(super) fn collect_approvable_commands(+ project_config: &ProjectConfig,+) -> Vec<ApprovableCommand> {let all_hooks: Vec<_> = HookType::iter().collect();let mut commands = collect_commands_for_hooks(project_config, &all_hooks);commands.extend(collect_commands_for_aliases(project_config));diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex c2f2fe4d5..f3275f15d 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -9,11 +9,13 @@ use std::path::{Path, PathBuf};use anyhow::Context;use color_print::cformat;+use serde::{Serialize, de::DeserializeOwned};use worktrunk::config::{- ProjectConfig, UserConfig, default_system_config_path, require_config_path, system_config_path,+ LoadError, ProjectConfig, UserConfig, default_system_config_path, require_config_path,+ system_config_path,};use worktrunk::git::remote_ref::azure::azure_devops_extension_installed;-use worktrunk::git::{ErrorExt, ForgeKind, Repository};+use worktrunk::git::{ErrorExt, ForgeKind, Repository, WorktrunkError};use worktrunk::path::format_path_for_display;use worktrunk::shell::{FileDetectionResult, Shell, ZshStartupScope, probe_zsh_compdef, scan_for_detection_details,@@ -32,7 +34,7 @@ use crate::llm::test_commit_generation;use crate::output;use crate::output::print_json;-/// Handle the config show command+/// Render the full report, then exit non-zero if any section is invalid.pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()> {if format == SwitchFormat::Json {return handle_config_show_json();@@ -40,20 +42,32 @@ pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()// Build the complete output as a stringlet mut show_output = String::new();- // Render system config section (only when a system config file exists)- let has_system_config = render_system_config(&mut show_output)?;- if has_system_config {+ let repo = Repository::current().ok();++ let mut invalid = false;+ let has_system_config = if let Some(system_invalid) = render_system_config(&mut show_output) {+ invalid |= system_invalid;show_output.push('\n');- }+ true+ } else {+ false+ };// Render user config- render_user_config(&mut show_output, has_system_config)?;+ invalid |= render_user_config(&mut show_output, repo.as_ref(), has_system_config)?;show_output.push('\n');// Render project config if in a git repository- render_project_config(&mut show_output)?;+ invalid |= render_project_config(&mut show_output, repo.as_ref())?;show_output.push('\n');+ let mut approvals_output = String::new();+ invalid |= render_approvals(&mut approvals_output, repo.as_ref());+ if !approvals_output.is_empty() {+ show_output.push_str(&approvals_output);+ show_output.push('\n');+ }+// Render shell integration statusrender_shell_status(&mut show_output)?;@@ -100,48 +114,81 @@ pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()// Display through pager (config show is always long-form output)show_help_in_pager(&show_output, true);+ if invalid {+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());+ }+Ok(())}-/// JSON output for config show: paths, existence, and parsed config contents.+/// JSON retains the report on invalid input and signals failure by exit code.fn handle_config_show_json() -> anyhow::Result<()> {+ let repo = Repository::current().ok();+ let (merged_user_config, user_warnings) = UserConfig::load_with_warnings();+ let mut invalid = user_warnings+ .iter()+ .any(|warning| matches!(warning, LoadError::Validation(_)));let user_path = require_config_path()?;let user_exists = user_path.exists();let user_config = if user_exists {- let config = UserConfig::load().context("Failed to load config")?;- Some(serde_json::to_value(&config)?)+ match read_user_config(&user_path) {+ Some(_) => Some(serde_json::to_value(merged_user_config)?),+ None => {+ invalid = true;+ None+ }+ }} else {None};- let (project_path, project_config, project_identifier) = if let Ok(repo) = Repository::current()- {- let config = repo.load_project_config()?;- let on_disk = repo.project_config_path()?;- // When config resolved but not from an existing on-disk file, it came- // from the object-store fallback (bare repo, default branch checked out- // in no worktree — #3461). Surface that revision spec as the source so- // `path`/`exists`/`config` agree, instead of pointing `path` at a- // missing file while `config` is populated.- let path = match &on_disk {- Some(p) if p.exists() => on_disk.clone(),- _ if config.is_some() => repo- .default_branch_project_config_content()- .map(|(_, spec)| spec),- _ => on_disk.clone(),+ let (project_path, project_exists, project_config, project_identifier) =+ if let Some(repo) = repo.as_ref() {+ let on_disk = repo.project_config_path()?;+ let object_store = match &on_disk {+ Some(path) if path.exists() => None,+ _ => repo.default_branch_project_config_content(),+ };+ let object_store_exists = object_store.is_some();+ let (path, config) = match &on_disk {+ Some(path) if path.exists() => {+ let config = read_json_config::<ProjectConfig>(path)?;+ (on_disk.clone(), config)+ }+ _ => match object_store {+ Some((contents, spec)) => {+ let config = parse_json_config::<ProjectConfig>(&contents)?;+ (Some(spec), config)+ }+ None => (on_disk.clone(), None),+ },+ };+ if (on_disk.as_ref().is_some_and(|path| path.exists()) || object_store_exists)+ && config.is_none()+ {+ invalid = true;+ }+ let identifier = repo.project_identifier().ok();+ let exists = on_disk.as_ref().is_some_and(|path| path.exists()) || object_store_exists;+ (path, exists, config, identifier)+ } else {+ (None, false, None, None)};- let identifier = repo.project_identifier().ok();- (- path,- config.map(|c| serde_json::to_value(&c)).transpose()?,- identifier,- )- } else {- (None, None, None)- };let system_path = system_config_path().or_else(default_system_config_path);let system_exists = system_path.as_ref().is_some_and(|p| p.exists());+ let system_invalid = if let Some(path) = system_path.as_deref().filter(|_| system_exists) {+ match std::fs::read_to_string(path) {+ Ok(contents) => parse_user_config(&contents).is_err(),+ Err(_) => true,+ }+ } else {+ false+ };+ let approvals_invalid = matches!(+ approvals_diagnostic(repo.as_ref()),+ ApprovalsDiagnostic::Invalid(_)+ );let output = serde_json::json!({"user": {@@ -151,12 +198,10 @@ fn handle_config_show_json() -> anyhow::Result<()> {},"project": {"path": project_path,- // Config source resolved — an on-disk file or the object-store- // fallback — iff `config` is populated. Keying `exists` off the- // loaded config (not `path.exists()`) keeps it consistent with- // `config` in the object-store case, where `path` is a revision- // spec with no file on disk.- "exists": project_config.is_some(),+ // An invalid on-disk source still exists even though `config` is+ // null. The object-store fallback counts as existing too, though+ // its revision spec is not a filesystem path.+ "exists": project_exists,"identifier": project_identifier,"config": project_config,},@@ -165,10 +210,53 @@ fn handle_config_show_json() -> anyhow::Result<()> {"exists": system_exists,},});+ invalid |= system_invalid+ || approvals_invalid+ || repo+ .as_ref()+ .is_some_and(|repo| validate_column_selection(repo).is_err());print_json(&output)?;++ if invalid {+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());+ }+Ok(())}+fn read_json_config<C>(path: &Path) -> anyhow::Result<Option<serde_json::Value>>+where+ C: DeserializeOwned + Serialize,+{+ let Ok(contents) = std::fs::read_to_string(path) else {+ return Ok(None);+ };+ parse_json_config::<C>(&contents)+}++fn read_user_config(path: &Path) -> Option<UserConfig> {+ let contents = std::fs::read_to_string(path).ok()?;+ parse_user_config(&contents).ok()+}++fn parse_user_config(contents: &str) -> Result<UserConfig, String> {+ let migrated = worktrunk::config::migrate_content(contents);+ let config = toml::from_str::<UserConfig>(&migrated).map_err(|err| err.to_string())?;+ config.validate().map_err(|err| err.to_string())?;+ Ok(config)+}++fn parse_json_config<C>(contents: &str) -> anyhow::Result<Option<serde_json::Value>>+where+ C: DeserializeOwned + Serialize,+{+ let migrated = worktrunk::config::migrate_content(contents);+ toml::from_str::<C>(&migrated)+ .ok()+ .map(|config| serde_json::to_value(config).map_err(Into::into))+ .transpose()+}+// ==================== Helper Functions ====================/// Check if Claude Code CLI is available@@ -641,45 +729,46 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {Ok(())}-/// Render the SYSTEM CONFIG section. Returns true if a system config file was found.-fn render_system_config(out: &mut String) -> anyhow::Result<bool> {- let Some(system_path) = system_config_path() else {- return Ok(false);- };+/// Render system config when present, returning whether it is invalid.+fn render_system_config(out: &mut String) -> Option<bool> {+ let system_path = system_config_path()?;- writeln!(+ let _ = writeln!(out,"{}",format_heading("SYSTEM CONFIG",Some(&format!("@ {}", format_path_for_display(&system_path))))- )?;+ );- // Read and display the file contents- let contents =- std::fs::read_to_string(&system_path).context("Failed to read system config file")?;+ let contents = match std::fs::read_to_string(&system_path) {+ Ok(contents) => contents,+ Err(err) => {+ render_config_read_error(out, &err);+ return Some(true);+ }+ };if contents.trim().is_empty() {- writeln!(out, "{}", hint_message("Empty file (no system defaults)"))?;- return Ok(true);+ let _ = writeln!(out, "{}", hint_message("Empty file (no system defaults)"));+ return Some(false);}- // Validate config (syntax + schema) and warn if invalid- if let Err(e) = toml::from_str::<UserConfig>(&contents) {- writeln!(out, "{}", error_message("Invalid config"))?;- writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;- } else {- out.push_str(&warn_unknown_keys::<UserConfig>(&contents));- }+ let invalid = render_user_config_diagnostics(out, &contents);// Display TOML with syntax highlighting- writeln!(out, "{}", format_toml(&contents))?;+ let _ = writeln!(out, "{}", format_toml(&contents));- Ok(true)+ Some(invalid)}-fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Result<()> {+/// Render the USER CONFIG section. Returns true if the config is invalid.+fn render_user_config(+ out: &mut String,+ repo: Option<&Repository>,+ has_system_config: bool,+) -> anyhow::Result<bool> {let config_path = require_config_path()?;writeln!(@@ -700,16 +789,25 @@ fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Resu"Not found; to create one, run <underline>wt config create</>")))?;- return Ok(());+ // A `[list] columns` selection can still arrive from the system layer,+ // the environment, or `--config-set`, so the check runs either way.+ return render_column_selection(out, repo);}- // Read and display the file contents- let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;+ let contents = match std::fs::read_to_string(&config_path) {+ Ok(contents) => contents,+ Err(err) => {+ render_config_read_error(out, &err);+ render_column_selection(out, repo)?;+ return Ok(true);+ }+ };// Check for deprecations with emit_inline_warnings=false (silent mode)// User config is global, not tied to any repository// Deprecated patterns supersede the TOML dump below because their diff// covers the file.+ let mut invalid = false;let skip_dump = match worktrunk::config::check_and_migrate(&config_path,&contents,@@ -729,6 +827,7 @@ fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Resu}}Err(err) => {+ invalid = true;writeln!(out, "{}", error_message(err.to_string()))?;false}@@ -736,17 +835,10 @@ fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Resuif contents.trim().is_empty() {writeln!(out, "{}", hint_message("Empty file (using defaults)"))?;- return Ok(());+ return Ok(invalid | render_column_selection(out, repo)?);}- // Validate config (syntax + schema) and warn if invalid- if let Err(e) = toml::from_str::<UserConfig>(&contents) {- // Use gutter for error details to avoid markup interpretation of user content- writeln!(out, "{}", error_message("Invalid config"))?;- writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;- } else {- out.push_str(&warn_unknown_keys::<UserConfig>(&contents));- }+ invalid |= render_user_config_diagnostics(out, &contents);// Display TOML with syntax highlighting (gutter at column 0).// Skip when deprecations were shown — the proposed diff already covers it.@@ -758,7 +850,7 @@ fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Resurender_system_config_hint(out)?;}- Ok(())+ Ok(invalid | render_column_selection(out, repo)?)}fn render_system_config_hint(out: &mut String) -> anyhow::Result<()> {@@ -775,6 +867,48 @@ fn render_system_config_hint(out: &mut String) -> anyhow::Result<()> {Ok(())}+fn render_config_read_error(out: &mut String, err: &std::io::Error) {+ let _ = writeln!(out, "{}", error_message("Cannot read config"));+ let _ = writeln!(out, "{}", format_with_gutter(&err.to_string(), None));+}++/// Render parse, validation, and unknown-key diagnostics for a user-config source.+fn render_user_config_diagnostics(out: &mut String, contents: &str) -> bool {+ let Err(error) = parse_user_config(contents) else {+ out.push_str(&warn_unknown_keys::<UserConfig>(contents));+ return false;+ };++ let _ = writeln!(out, "{}", error_message("Invalid config"));+ // Use a gutter to avoid interpreting user-controlled parser output as markup.+ let _ = writeln!(out, "{}", format_with_gutter(&error, None));+ true+}++/// Report list-column settings that `wt list` would reject.+fn render_column_selection(out: &mut String, repo: Option<&Repository>) -> anyhow::Result<bool> {+ let Some(repo) = repo else {+ return Ok(false);+ };+ if let Err(e) = validate_column_selection(repo) {+ writeln!(out, "{}", error_message(e.to_string()))?;+ return Ok(true);+ }+ Ok(false)+}++/// Validate the resolved list-column config exactly as `wt list` does.+fn validate_column_selection(repo: &Repository) -> anyhow::Result<()> {+ let config = repo.config();+ let custom = crate::commands::list::custom_columns::resolve_custom_columns(+ &config.list.custom_columns,+ repo,+ )?;+ let custom_names: Vec<&str> = custom.iter().map(|c| c.name.as_str()).collect();+ crate::commands::list::columns::parse_selected_columns(&config.list.columns, &custom_names)?;+ Ok(())+}+/// Format warnings for unknown config keys in `raw_contents`.////// Generic over `C`, the config type. Classification is shared with the@@ -824,11 +958,12 @@ fn format_show_warning(warning: &worktrunk::config::UnknownWarning) -> String {}}-fn render_project_config(out: &mut String) -> anyhow::Result<()> {+/// Render the PROJECT CONFIG section. Returns true if the config is invalid.+fn render_project_config(out: &mut String, repo: Option<&Repository>) -> anyhow::Result<bool> {// Try to get current repository root- let repo = match Repository::current() {- Ok(repo) => repo,- Err(_) => {+ let repo = match repo {+ Some(repo) => repo,+ None => {writeln!(out,"{}",@@ -837,20 +972,15 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {format_heading("PROJECT CONFIG", Some("Not in a git repository"))))?;- return Ok(());+ return Ok(false);}};- // Helper: heading + project identifier, shared across the resolved and- // absent branches so their output stays uniform.fn write_heading_and_identifier(out: &mut String,repo: &Repository,source: &str,) -> anyhow::Result<()> {writeln!(out, "{}", format_heading("PROJECT CONFIG", Some(source)))?;- // Project identifier — used as the key for [projects."..."] sections in- // user config. Surface it here so users can find the right key without- // hand-deriving it from the remote URL.if let Ok(project_id) = repo.project_identifier() {let line = info_message(cformat!("Identifier: <bold>{project_id}</>"));writeln!(out, "{line}")?;@@ -858,49 +988,44 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {Ok(())}- // Resolve the effective config source, mirroring `ProjectConfig::load`: an- // on-disk `.config/wt.toml` when one exists, otherwise the committed- // default-branch config read from the object store (bare repo, default- // branch checked out in no worktree — #3461). Reading the raw text here- // rather than calling `load_project_config` keeps the deprecation and- // validation rendering below, which operates on the TOML source. Without- // this fallback, `config show` reports "Not found" while the hooks from the- // object-store config actually run — the opposite of reality.+ // Match ProjectConfig::load's on-disk then object-store source order.let on_disk = repo.project_config_path()?;let (config_path, contents) = match &on_disk {Some(path) if path.exists() => {- let contents = std::fs::read_to_string(path).context("Failed to read config file")?;let source = format!("@ {}", format_path_for_display(path));- write_heading_and_identifier(out, &repo, &source)?;+ write_heading_and_identifier(out, repo, &source)?;+ let contents = match std::fs::read_to_string(path) {+ Ok(contents) => contents,+ Err(err) => {+ render_config_read_error(out, &err);+ return Ok(true);+ }+ };(path.clone(), contents)}_ => match repo.default_branch_project_config_content() {Some((object_store_contents, spec)) => {- // `spec` is a git revision spec (`<default>:.config/wt.toml`),- // not a filesystem path — display it verbatim, tagged as the- // object-store source so it isn't mistaken for an on-disk file.let source = format!("@ {} (from object store)", spec.to_string_lossy());- write_heading_and_identifier(out, &repo, &source)?;+ write_heading_and_identifier(out, repo, &source)?;(spec, object_store_contents)}None => {- // Neither an on-disk file nor a committed fallback resolved.let Some(path) = on_disk else {let heading = format_heading("PROJECT CONFIG", Some("No project config"));writeln!(out, "{}", cformat!("<dim>{}</>", heading))?;- return Ok(());+ return Ok(false);};let source = format!("@ {}", format_path_for_display(&path));- write_heading_and_identifier(out, &repo, &source)?;+ write_heading_and_identifier(out, repo, &source)?;writeln!(out, "{}", hint_message("Not found"))?;- return Ok(());+ return Ok(false);}},};if contents.trim().is_empty() {writeln!(out, "{}", hint_message("Empty file"))?;- return Ok(());+ return Ok(false);}// Check for deprecations with emit_inline_warnings=false (silent mode)@@ -908,12 +1033,13 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {// Deprecated patterns supersede the TOML dump below because their diff// covers the file.let is_main_worktree = !repo.current_worktree().is_linked().unwrap_or(true);+ let mut invalid = false;let skip_dump = match worktrunk::config::check_and_migrate(&config_path,&contents,is_main_worktree,worktrunk::config::ConfigFileKind::Project,- Some(&repo),+ Some(repo),false, // silent mode - we'll format the output ourselves) {Ok(result) => {@@ -927,6 +1053,7 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {}}Err(err) => {+ invalid = true;writeln!(out, "{}", error_message(err.to_string()))?;false}@@ -935,6 +1062,7 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {// Validate config (syntax + schema) and warn if invalidif let Err(e) = toml::from_str::<ProjectConfig>(&contents) {// Use gutter for error details to avoid markup interpretation of user content+ invalid = true;writeln!(out, "{}", error_message("Invalid config"))?;writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;} else {@@ -947,7 +1075,81 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {writeln!(out, "{}", format_toml(&contents))?;}- Ok(())+ Ok(invalid)+}++/// Report an invalid approvals file or project commands awaiting approval.+fn render_approvals(out: &mut String, repo: Option<&Repository>) -> bool {+ match approvals_diagnostic(repo) {+ ApprovalsDiagnostic::Valid => false,+ ApprovalsDiagnostic::Invalid(err) => {+ render_approvals_heading(out);+ let _ = writeln!(out, "{}", error_message("Invalid approvals"));+ let _ = writeln!(out, "{}", format_with_gutter(&err, None));+ true+ }+ ApprovalsDiagnostic::Pending(pending) => {+ render_approvals_heading(out);+ let plural = if pending == 1 { "command" } else { "commands" };+ let status = info_message(format!("{pending} project {plural} awaiting approval"));+ let _ = writeln!(out, "{status}");+ let hint = hint_message(cformat!(+ "To review, run <underline>wt config approvals list</>"+ ));+ let _ = writeln!(out, "{hint}");+ false+ }+ }+}++fn render_approvals_heading(out: &mut String) {+ let source = worktrunk::config::approvals_path()+ .map(|path| format!("@ {}", format_path_for_display(&path)));+ let _ = writeln!(out, "{}", format_heading("APPROVALS", source.as_deref()));+}++enum ApprovalsDiagnostic {+ Valid,+ Invalid(String),+ Pending(usize),+}++fn approvals_diagnostic(repo: Option<&Repository>) -> ApprovalsDiagnostic {+ let approvals_file_exists = worktrunk::config::approvals_path()+ .as_ref()+ .is_some_and(|path| path.exists());+ let approvals = match worktrunk::config::Approvals::load() {+ Ok(approvals) => approvals,+ Err(err) if approvals_file_exists => {+ return ApprovalsDiagnostic::Invalid(err.to_string());+ }+ // With no approvals file, `Approvals::load` falls back to the user+ // config. Its error belongs to that section, which already reports the+ // same broken source and marks the whole diagnostic invalid.+ Err(_) => return ApprovalsDiagnostic::Valid,+ };+ let Some(repo) = repo else {+ return ApprovalsDiagnostic::Valid;+ };+ let Ok(Some(project_config)) = repo.load_project_config() else {+ return ApprovalsDiagnostic::Valid;+ };+ let commands = super::approvals::collect_approvable_commands(&project_config);+ if commands.is_empty() {+ return ApprovalsDiagnostic::Valid;+ }+ let Ok(project_id) = repo.project_identifier() else {+ return ApprovalsDiagnostic::Valid;+ };+ let pending = commands+ .into_iter()+ .filter(|cmd| !approvals.is_command_approved(&project_id, &cmd.command.template))+ .count();+ if pending == 0 {+ ApprovalsDiagnostic::Valid+ } else {+ ApprovalsDiagnostic::Pending(pending)+ }}/// Emit the "fish integration found in deprecated location" notice plus thediff --git a/src/commands/config/update.rs b/src/commands/config/update.rsindex 9a14a09e3..34ba303c4 100644--- a/src/commands/config/update.rs+++ b/src/commands/config/update.rs@@ -15,10 +15,10 @@ use worktrunk::config::{copy_approved_commands_to_approvals_file, format_deprecation_warnings, format_migration_diff,};use worktrunk::git::{Repository, resolve_input_path};-use worktrunk::path::format_path_for_display;+use worktrunk::path::{format_path_for_display, paths_match};use worktrunk::styling::{eprint, eprintln, format_bash_with_gutter, hint_message, info_message, print, success_message,- suggest_command_in_dir,+ suggest_command_in_dir, warning_message,};use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};@@ -122,13 +122,29 @@ fn write_migrated_output(output: &Path, candidates: &[UpdateCandidate]) -> anyho));}+ let output = resolve_input_path(output);+ if !stdout+ && let Some(candidate) = candidates+ .iter()+ .filter(|candidate| drops_approved_commands(candidate))+ .find(|candidate| paths_match(&output, &candidate.config_path))+ {+ bail!(cformat!(+ "Cannot overwrite <bold>{}</> with <bold>--output</>; run <bold>wt config update</> to apply the migration in place",+ candidate.info.label().to_lowercase()+ ));+ }++ for candidate in candidates {+ eprint!("{}", format_dropped_approvals_warning(candidate));+ }+let artifact = format_migrated_output(candidates);if stdout {print!("{artifact}");return Ok(());}- let output = resolve_input_path(output);worktrunk::utils::write_atomically(&output, &artifact).with_context(|| {format!("Failed to write output @ {}",@@ -161,6 +177,26 @@ fn format_migrated_output(candidates: &[UpdateCandidate]) -> String {artifact}+fn format_dropped_approvals_warning(candidate: &UpdateCandidate) -> String {+ if !drops_approved_commands(candidate) {+ return String::new();+ }+ format!(+ "{}\n",+ warning_message(cformat!(+ "Output omits deprecated <bold>approved-commands</>; run <underline>wt config update</> to migrate them to approvals.toml"+ ))+ )+}++fn drops_approved_commands(candidate: &UpdateCandidate) -> bool {+ candidate+ .info+ .deprecations+ .iter()+ .any(|kind| matches!(kind, DeprecationKind::ApprovedCommands))+}+/// Format update preview for display.////// Renders the per-pattern deprecation warnings followed by the diff. Thediff --git a/src/config/mod.rs b/src/config/mod.rsindex 7d8079e3a..5f7d215da 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -194,7 +194,7 @@ pub use project::{pub use unknown_tree::{UnknownAnalysis, UnknownTree, UnknownWarning, collect_unknown_warnings, compute_unknown_tree,};-pub(crate) use user::LoadError;+pub use user::LoadError;pub(crate) use user::project_match::matching_keys as matching_project_keys;pub use user::{CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListColumnConfig, ListConfig,diff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex e6bacd94b..a2cf7f6b4 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -27,8 +27,9 @@ mod sections;#[cfg(test)]mod tests;+use std::collections::HashSet;use std::path::{Path, PathBuf};-use std::sync::OnceLock;+use std::sync::{LazyLock, Mutex, OnceLock};use super::{ConfigError, ConfigFileKind};use schemars::JsonSchema;@@ -44,6 +45,10 @@ use serde::{Deserialize, Serialize};/// for the same key.static CONFIG_OVERRIDES: OnceLock<Vec<String>> = OnceLock::new();+/// Explicit config paths already reported missing in this process.+static WARNED_MISSING_CONFIG_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =+ LazyLock::new(|| Mutex::new(HashSet::new()));+/// Record the CLI `--config-set` overrides (called once from the/// `--config-set` flag in `main`).pub fn set_config_overrides(overrides: Vec<String>) {@@ -73,9 +78,9 @@ pub use sections::{/// identifies which layer failed so callers can emit targeted diagnostics/// (file errors with line/col vs env-var attribution).///-/// Used as an error by [`UserConfig::load_with_cause()`] (first issue is-/// fatal) and as warnings by [`UserConfig::load_with_warnings()`] (issues-/// are collected, best-effort config returned).+/// Strict loading treats the first issue as fatal; best-effort+/// [`UserConfig::load_with_warnings()`] returns all issues alongside the+/// usable config.#[derive(Debug)]pub enum LoadError {/// A config file failed to parse. The `toml::de::Error` includes@@ -345,14 +350,11 @@ fn merge_layer(merged_table: &mut toml::Table, layer: toml::Table) {match deserialize_and_validate(&candidate) {Ok(()) => *merged_table = candidate,- // Reachable two ways. A partial removal the enumerations above miss —- // none today, but they are enumerations, and the next required field- // would otherwise cost the user their whole config rather than one- // project entry. Or a document that was already invalid before this- // layer: step 3's env probe deserializes without validating, so an- // empty `worktree-path` from the environment lands here. Merging- // without the removals is right for both; `finalize` reports the- // second.+ // Reachable when a partial removal the enumerations above miss would+ // invalidate the candidate, or when the layer itself is invalid (for+ // example, an empty global `worktree-path` from the environment or+ // `--config-set`). Keep the layer without the removals so its caller+ // can validate and attribute the complete candidate.Err(err) => {log::debug!("keeping project precedence: {err}");deep_merge_table(merged_table, layer);@@ -601,7 +603,7 @@ impl UserConfig {/// - Bad env vars → ignored, file-based config preserved/// - Validation failure → warning emitted, defaults used (invalid config/// causes bad behavior if applied, e.g. empty worktree-path template)- pub(crate) fn load_with_warnings() -> (Self, Vec<LoadError>) {+ pub fn load_with_warnings() -> (Self, Vec<LoadError>) {let mut warnings = Vec::new();let mut merged_table = toml::Table::new();@@ -676,6 +678,10 @@ impl UserConfig {}} else if let Some(config_path) = config_path.as_ref()&& path::is_config_path_explicit()+ && WARNED_MISSING_CONFIG_PATHS+ .lock()+ .unwrap()+ .insert(config_path.clone()){crate::styling::eprintln!("{}",@@ -697,12 +703,13 @@ impl UserConfig {let env_overlay = migrate_env_overlay(resolve_env_overlay(&file_table, &env_vars));merge_layer(&mut merged_table, env_overlay);- // Env overlay broke deserialization — fall back to file-only config.- // Each file was individually validated by load_config_file(), so the- // merged table should deserialize cleanly.- if let Err(err) = toml::Value::Table(merged_table.clone()).try_into::<Self>() {+ // A bad env layer must not discard valid file layers. Attribute the+ // failure to env only when the file-only table itself is valid.+ if let Err(err) = deserialize_and_validate(&merged_table)+ && deserialize_and_validate(&file_table).is_ok()+ {warnings.push(LoadError::Env {- err: err.to_string(),+ err,vars: env_vars.iter().map(|v| (v.name.clone(), v.raw_value.clone()))diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rsindex 117b57a4b..36e4ea8dc 100644--- a/src/config/user/persistence.rs+++ b/src/config/user/persistence.rs@@ -201,7 +201,7 @@ impl UserConfig {impl UserConfig {/// Validate configuration values.- pub(super) fn validate(&self) -> Result<(), ConfigError> {+ pub fn validate(&self) -> Result<(), ConfigError> {// Validate worktree path (only if explicitly set - default is always valid)if let Some(ref path) = self.worktree_path&& path.trim().is_empty()diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 7b03d4ed2..07b32865c 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -81,6 +81,39 @@ fn test_config_show_no_project_config(mut repo: TestRepo, temp_home: TempDir) {});}+#[rstest]+fn test_config_show_rejects_invalid_approvals_file(repo: TestRepo) {+ fs::write(repo.test_approvals_path(), "not valid TOML [[[").unwrap();++ let output = repo.wt_command().args(["config", "show"]).output().unwrap();++ assert_eq!(output.status.code(), Some(1));+ let stdout = String::from_utf8_lossy(&output.stdout);+ let stdout = stdout.ansi_strip();+ assert!(stdout.contains("Invalid approvals"), "stdout:\n{stdout}");+ assert!(stdout.contains("approvals.toml"), "stdout:\n{stdout}");+}++#[rstest]+fn test_config_show_hides_fully_approved_commands(repo: TestRepo) {+ repo.write_project_config("pre-start = \"npm install\"\n");+ let project = repo.repo.project_identifier().unwrap();+ let project = toml::Value::String(project).to_string();+ fs::write(+ repo.test_approvals_path(),+ format!("[projects.{project}]\napproved-commands = [\"npm install\"]\n"),+ )+ .unwrap();++ let output = repo.wt_command().args(["config", "show"]).output().unwrap();++ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ let stdout = stdout.ansi_strip();+ assert!(!stdout.contains("APPROVALS"), "stdout:\n{stdout}");+ assert!(!stdout.contains("awaiting approval"), "stdout:\n{stdout}");+}+// ==================== System Config Tests ====================#[rstest]@@ -411,9 +444,7 @@ deps = "post-create-tool"}#[rstest]-fn test_config_show_system_config_hint_under_user_config(repo: TestRepo, temp_home: TempDir) {- // When no system config exists but user config does, config show should- // display a hint under USER CONFIG with the platform-specific default path+fn test_config_show_absent_system_config_is_a_user_config_hint(repo: TestRepo, temp_home: TempDir) {let global_config_dir = temp_home.path().join(".config").join("worktrunk");fs::create_dir_all(&global_config_dir).unwrap();fs::write(@@ -432,16 +463,11 @@ fn test_config_show_system_config_hint_under_user_config(repo: TestRepo, temp_holet output = cmd.output().unwrap();let stdout = String::from_utf8_lossy(&output.stdout);- // Should NOT show a full SYSTEM CONFIG heading- assert!(- !stdout.contains("SYSTEM CONFIG"),- "Should not show SYSTEM CONFIG section when absent, got:\n{stdout}"- );- // Should show a system config hint under USER CONFIGassert!(- stdout.contains("Optional system config not found")+ !stdout.contains("SYSTEM CONFIG")+ && stdout.contains("Optional system config not found")&& stdout.contains("worktrunk/config.toml"),- "Expected system config hint in output, got:\n{stdout}"+ "Expected a compact system config hint, got:\n{stdout}");}@@ -545,6 +571,40 @@ fn test_config_show_empty_system_config(mut repo: TestRepo, temp_home: TempDir)});}+#[rstest]+#[case::system("system")]+#[case::user("user")]+#[case::project("project")]+fn test_config_show_reports_unreadable_source_and_continues(repo: TestRepo, #[case] source: &str) {+ let mut cmd = repo.wt_command();+ let system_dir = if source == "system" {+ let dir = tempfile::tempdir().unwrap();+ cmd.env("WORKTRUNK_SYSTEM_CONFIG_PATH", dir.path());+ Some(dir)+ } else {+ None+ };++ match source {+ "user" => fs::write(repo.test_config_path(), [0xff]).unwrap(),+ "project" => {+ repo.write_project_config("");+ fs::write(repo.root_path().join(".config/wt.toml"), [0xff]).unwrap();+ }+ "system" => {}+ _ => unreachable!(),+ }++ let output = cmd.args(["config", "show"]).output().unwrap();+ drop(system_dir);++ assert_eq!(output.status.code(), Some(1));+ let stdout = String::from_utf8_lossy(&output.stdout);+ let stdout = stdout.ansi_strip();+ assert!(stdout.contains("Cannot read config"), "stdout:\n{stdout}");+ assert!(stdout.contains("OTHER"), "report was truncated:\n{stdout}");+}+/// A user config that doesn't parse must fail these commands *legibly*.////// `UserConfig::load()`'s error is `LoadError::File`'s multi-line Display —@@ -561,11 +621,8 @@ fn test_config_show_empty_system_config(mut repo: TestRepo, temp_home: TempDir)////// One case per fixed call site, because the `debug_assert!` only fires on a/// path something exercises: an uncovered site is one where a future bare `?`-/// regresses silently. `config show --format json` is the sharpest of them —-/// the text form of that same command renders a full diagnosis of this exact-/// file.+/// regresses silently. The JSON form has a separate in-band error test below.#[rstest]-#[case::config_show_json(&["config", "show", "--format=json"])]#[case::step_prune(&["step", "prune", "--dry-run"])]#[case::step_relocate(&["step", "relocate", "--dry-run"])]#[case::step_eval(&["step", "eval", "{{ branch }}"])]@@ -1354,6 +1411,29 @@ fn test_config_show_invalid_user_toml(mut repo: TestRepo, temp_home: TempDir) {});}+#[rstest]+fn test_config_show_unknown_list_column(mut repo: TestRepo, temp_home: TempDir) {+ repo.setup_mock_ci_tools_unauthenticated();++ let global_config_dir = temp_home.path().join(".config").join("worktrunk");+ fs::create_dir_all(&global_config_dir).unwrap();+ fs::write(+ global_config_dir.join("config.toml"),+ "[list]\njson-schema = 2\ncolumns = [\"branch\", \"nosuchcolumn\"]\n",+ )+ .unwrap();++ let settings = setup_snapshot_settings_with_home(&repo, &temp_home);+ settings.bind(|| {+ let mut cmd = repo.wt_command();+ cmd.arg("config").arg("show").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ set_xdg_config_path(&mut cmd, temp_home.path());++ assert_cmd_snapshot!(cmd);+ });+}+#[rstest]fn test_config_show_invalid_project_toml(mut repo: TestRepo, temp_home: TempDir) {repo.setup_mock_ci_tools_unauthenticated();@@ -3682,6 +3762,93 @@ fn test_config_update_rejects_print(repo: TestRepo) {);}+#[rstest]+fn test_config_update_output_warns_about_dropped_approvals(repo: TestRepo) {+ fs::write(+ repo.test_config_path(),+ r#"[list]+json-schema = 1++[projects."github.com/user/repo"]+approved-commands = ["npm ci", "npm test"]++[projects."github.com/other/repo"]+approved-commands = ["cargo test"]+"#,+ )+ .unwrap();++ let output = repo+ .wt_command()+ .args(["config", "update", "--output=-"])+ .output()+ .unwrap();++ assert!(output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = stderr.ansi_strip();+ assert!(+ stderr.contains("approved-commands") && stderr.contains("wt config update"),+ "stderr should explain how to preserve approvals, got: {stderr}"+ );+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ !stdout.contains("approved-commands"),+ "the printed config drops them, got: {stdout}"+ );+}++#[rstest]+fn test_config_update_output_rejects_source_path(repo: TestRepo) {+ let original = r#"[list]+json-schema = 1++[projects."github.com/user/repo"]+approved-commands = ["npm test"]+"#;+ fs::write(repo.test_config_path(), original).unwrap();++ let output = repo+ .wt_command()+ .args(["config", "update", "--output"])+ .arg(repo.test_config_path())+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(1));+ assert_eq!(+ fs::read_to_string(repo.test_config_path()).unwrap(),+ original+ );+ assert!(!repo.test_approvals_path().exists());+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = stderr.ansi_strip();+ assert!(+ stderr.contains("Cannot overwrite user config") && stderr.contains("wt config update"),+ "stderr:\n{stderr}"+ );+}++#[rstest]+fn test_config_update_output_can_replace_source_without_approvals(repo: TestRepo) {+ fs::write(+ repo.test_config_path(),+ "worktree-path = \"../{{ main_worktree }}.{{ branch }}\"\n",+ )+ .unwrap();++ let output = repo+ .wt_command()+ .args(["config", "update", "--output"])+ .arg(repo.test_config_path())+ .output()+ .unwrap();++ assert!(output.status.success());+ let updated = fs::read_to_string(repo.test_config_path()).unwrap();+ assert!(updated.contains("{{ repo }}"), "config:\n{updated}");+}+/// `wt config update` with no deprecated settings reports nothing to do#[rstest]fn test_config_update_no_deprecations(repo: TestRepo) {@@ -6410,6 +6577,13 @@ mod plugin_prompt_pty {#[rstest]fn test_config_show_json(repo: TestRepo, temp_home: TempDir) {+ let system_config_dir = tempfile::tempdir().unwrap();+ let system_config_path = system_config_dir.path().join("config.toml");+ fs::write(+ &system_config_path,+ "[list]\nfull = true\njson-schema = 2\n",+ )+ .unwrap();let global_config_dir = temp_home.path().join(".config").join("worktrunk");fs::create_dir_all(&global_config_dir).unwrap();fs::write(@@ -6422,6 +6596,7 @@ fn test_config_show_json(repo: TestRepo, temp_home: TempDir) {repo.configure_wt_cmd(&mut cmd);set_xdg_config_path(&mut cmd, temp_home.path());set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("WORKTRUNK_SYSTEM_CONFIG_PATH", system_config_path);cmd.args(["config", "show", "--format=json"]).current_dir(repo.root_path());@@ -6437,11 +6612,302 @@ fn test_config_show_json(repo: TestRepo, temp_home: TempDir) {assert!(json["user"]["exists"].as_bool().unwrap());assert!(json["user"]["path"].as_str().is_some());assert!(json["user"]["config"].is_object());+ assert_eq!(json["user"]["config"]["list"]["full"], true);// Project config doesn't exist in this fixtureassert!(!json["project"]["exists"].as_bool().unwrap());}+#[rstest]+#[case::environment("WORKTRUNK_LIST__TIMEOUT_MS", "invalid", None)]+#[case::environment_validation("WORKTRUNK_WORKTREE_PATH", "", None)]+#[case::inline("", "", Some("list.timeout-ms=\"invalid\""))]+fn test_config_show_json_allows_invalid_runtime_override(+ repo: TestRepo,+ temp_home: TempDir,+ #[case] env_name: &str,+ #[case] env_value: &str,+ #[case] inline: Option<&str>,+) {+ let system_config_dir = tempfile::tempdir().unwrap();+ let system_config_path = system_config_dir.path().join("config.toml");+ fs::write(&system_config_path, "[list]\nbranches = true\n").unwrap();+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");+ fs::create_dir_all(&global_config_dir).unwrap();+ fs::write(+ global_config_dir.join("config.toml"),+ "[list]\nfull = true\n",+ )+ .unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ set_xdg_config_path(&mut cmd, temp_home.path());+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("WORKTRUNK_SYSTEM_CONFIG_PATH", system_config_path);+ if let Some(inline) = inline {+ cmd.args(["--config-set", inline]);+ } else {+ cmd.env(env_name, env_value);+ }+ cmd.args(["config", "show", "--format=json"])+ .current_dir(repo.root_path());++ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "runtime overrides should warn without invalidating the source config: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert_eq!(json["user"]["config"]["list"]["branches"], true);+ assert_eq!(json["user"]["config"]["list"]["full"], true);+}++#[rstest]+#[case::text(&["config", "show"], false, false)]+#[case::json(&["config", "show", "--format=json"], false, false)]+#[case::json_with_unrelated_env(&["config", "show", "--format=json"], true, false)]+#[case::json_with_masking_env(&["config", "show", "--format=json"], false, true)]+fn test_config_show_rejects_semantically_invalid_user_config(+ repo: TestRepo,+ #[case] args: &[&str],+ #[case] with_unrelated_env: bool,+ #[case] with_masking_env: bool,+) {+ fs::write(repo.test_config_path(), "worktree-path = \"\"\n").unwrap();++ let mut cmd = repo.wt_command();+ cmd.args(args);+ if with_unrelated_env {+ cmd.env("WORKTRUNK_LIST__FULL", "true");+ } else if with_masking_env {+ cmd.env("WORKTRUNK_WORKTREE_PATH", "../valid");+ }+ let output = cmd.output().unwrap();++ assert_eq!(output.status.code(), Some(1));+ if args.contains(&"--format=json") {+ serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ } else {+ let stdout = String::from_utf8_lossy(&output.stdout);+ let user_section = stdout+ .split("USER CONFIG")+ .nth(1)+ .and_then(|rest| rest.split("PROJECT CONFIG").next())+ .unwrap();+ assert!(user_section.contains("Invalid config"), "{stdout}");+ assert!(+ user_section.contains("worktree-path cannot be empty"),+ "{stdout}"+ );+ }+}++#[rstest]+#[case::text(&["config", "show"])]+#[case::json(&["config", "show", "--format=json"])]+fn test_config_show_rejects_semantically_invalid_system_config(+ repo: TestRepo,+ #[case] args: &[&str],+) {+ let system_config_dir = tempfile::tempdir().unwrap();+ let system_config_path = system_config_dir.path().join("config.toml");+ fs::write(&system_config_path, "worktree-path = \"\"\n").unwrap();+ fs::write(repo.test_config_path(), "worktree-path = \"../valid\"\n").unwrap();++ let output = repo+ .wt_command()+ .env("WORKTRUNK_SYSTEM_CONFIG_PATH", system_config_path)+ .args(args)+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(1));+ if args.contains(&"--format=json") {+ serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ return;+ }+ let stdout = String::from_utf8_lossy(&output.stdout);+ let system_section = stdout+ .split("SYSTEM CONFIG")+ .nth(1)+ .and_then(|rest| rest.split("USER CONFIG").next())+ .unwrap();+ assert!(system_section.contains("Invalid config"), "{stdout}");+ assert!(+ system_section.contains("worktree-path cannot be empty"),+ "{stdout}"+ );+}++#[rstest]+#[case::text(&["config", "show"])]+#[case::json(&["config", "show", "--format=json"])]+fn test_config_show_warns_once_for_missing_explicit_config(repo: TestRepo, #[case] args: &[&str]) {+ let output = repo+ .wt_command()+ .args(["--config", "/nonexistent/worktrunk/config.toml"])+ .args(args)+ .output()+ .unwrap();++ assert!(output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert_eq!(+ stderr.matches("Config file not found").count(),+ 1,+ "{stderr}"+ );+}++#[rstest]+fn test_config_show_json_rejects_invalid_custom_column(repo: TestRepo, temp_home: TempDir) {+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");+ fs::create_dir_all(&global_config_dir).unwrap();+ fs::write(+ global_config_dir.join("config.toml"),+ "[list.custom-columns.ticket]\ntemplate = \"{{ branch }}\"\nwidth = 0\n",+ )+ .unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ set_xdg_config_path(&mut cmd, temp_home.path());+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.args(["config", "show", "--format=json"])+ .current_dir(repo.root_path());++ let output = cmd.output().unwrap();+ assert_eq!(output.status.code(), Some(1));+ serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert!(output.stderr.is_empty());+}++#[rstest]+fn test_config_show_json_rejects_invalid_system_config(repo: TestRepo, temp_home: TempDir) {+ let system_config_dir = tempfile::tempdir().unwrap();+ let system_config_path = system_config_dir.path().join("config.toml");+ fs::write(&system_config_path, "invalid = [toml\n").unwrap();+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");+ fs::create_dir_all(&global_config_dir).unwrap();+ fs::write(global_config_dir.join("config.toml"), "").unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ set_xdg_config_path(&mut cmd, temp_home.path());+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("WORKTRUNK_SYSTEM_CONFIG_PATH", &system_config_path);+ cmd.args(["config", "show", "--format=json"])+ .current_dir(repo.root_path());++ let output = cmd.output().unwrap();+ assert_eq!(output.status.code(), Some(1));+ let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert_eq!(json["system"]["exists"], true);+ assert!(+ json["user"]["config"].is_object(),+ "a broken system source must not erase valid user config"+ );+}++#[rstest]+fn test_config_show_json_rejects_unreadable_system_config(repo: TestRepo, temp_home: TempDir) {+ let system_config_dir = tempfile::tempdir().unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ set_xdg_config_path(&mut cmd, temp_home.path());+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("WORKTRUNK_SYSTEM_CONFIG_PATH", system_config_dir.path());+ cmd.args(["config", "show", "--format=json"])+ .current_dir(repo.root_path());++ let output = cmd.output().unwrap();+ assert_eq!(output.status.code(), Some(1));+ let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert_eq!(json["system"]["exists"], true);+}++#[rstest]+fn test_config_show_json_rejects_invalid_approvals_file(repo: TestRepo) {+ fs::write(repo.test_approvals_path(), "not valid TOML [[[").unwrap();++ let output = repo+ .wt_command()+ .args(["config", "show", "--format=json"])+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(1));+ serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+}++#[rstest]+fn test_config_show_json_rejects_invalid_user_config(repo: TestRepo) {+ fs::write(repo.test_config_path(), "invalid = [toml\n").unwrap();++ let output = repo+ .wt_command()+ .args(["config", "show", "--format=json"])+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(1));+ let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert_eq!(json["user"]["exists"], true);+ assert!(json["user"]["config"].is_null());+}++#[rstest]+fn test_config_show_json_rejects_unreadable_user_config(repo: TestRepo) {+ fs::write(repo.test_config_path(), [0xff]).unwrap();++ let output = repo+ .wt_command()+ .args(["config", "show", "--format=json"])+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(1));+ let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert_eq!(json["user"]["exists"], true);+ assert!(json["user"]["config"].is_null());+}++#[rstest]+fn test_config_show_json_rejects_invalid_project_config(repo: TestRepo) {+ repo.write_project_config("invalid = [toml\n");++ let output = repo+ .wt_command()+ .args(["config", "show", "--format=json"])+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(1));+ let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert_eq!(json["project"]["exists"], true);+ assert!(json["project"]["config"].is_null());+}++#[rstest]+fn test_config_show_json_rejects_unreadable_project_config(repo: TestRepo) {+ repo.write_project_config("");+ fs::write(repo.root_path().join(".config/wt.toml"), [0xff]).unwrap();++ let output = repo+ .wt_command()+ .args(["config", "show", "--format=json"])+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(1));+ let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();+ assert_eq!(json["project"]["exists"], true);+ assert!(json["project"]["config"].is_null());+}+#[rstest]fn test_config_show_json_with_project_config(repo: TestRepo, temp_home: TempDir) {let global_config_dir = temp_home.path().join(".config").join("worktrunk");diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_from_linked_worktree_shows_main_worktree_hint.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_from_linked_worktree_shows_main_worktree_hint.snapindex 1758cc982..7e77b37db 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_from_linked_worktree_shows_main_worktree_hint.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_from_linked_worktree_shows_main_worktree_hint.snap@@ -65,6 +65,10 @@ exit_code: 0[33m▲[39m [33mProject config: template variable [1mmain_worktree[22m is deprecated in favor of [1mrepo[22m[39m[2m↳[22m [2mTo apply: [4mwt -C _REPO_ config update[24m[22m+[36mAPPROVALS[39m @ [TEST_APPROVALS]+[2m○[22m 1 project command awaiting approval+[2m↳[22m [2mTo review, run [4mwt config approvals list[24m[22m+[36mSHELL INTEGRATION[39m[33m▲[39m [33mShell integration not configured[39m[2m↳[22m [2mTo configure, run [4mwt config shell install[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_project_toml.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_project_toml.snapindex 23c599ba2..06f19e385 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_project_toml.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_project_toml.snap@@ -54,8 +54,8 @@ info:WORKTRUNK_TEST_ZSH_INSTALLED: "0"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"----success: true-exit_code: 0+success: false+exit_code: 1----- stdout -----[36mUSER CONFIG[39m @ ~/.config/worktrunk/config.toml[107m [0m [2mworktree-path = [0m[2m[32m"../{{ repo }}.{{ branch }}"[0mdiff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_system_config.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_system_config.snapindex 2010e9c61..4a4cac546 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_system_config.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_system_config.snap@@ -54,8 +54,8 @@ info:WORKTRUNK_TEST_ZSH_INSTALLED: "0"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"----success: true-exit_code: 0+success: false+exit_code: 1----- stdout -----[36mSYSTEM CONFIG[39m @ [PROJECT_ID][31m✗[39m [31mInvalid config[39mdiff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_user_toml.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_user_toml.snapindex efd7d8219..6f17d220c 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_user_toml.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_invalid_user_toml.snap@@ -54,8 +54,8 @@ info:WORKTRUNK_TEST_ZSH_INSTALLED: "0"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"----success: true-exit_code: 0+success: false+exit_code: 1----- stdout -----[36mUSER CONFIG[39m @ ~/.config/worktrunk/config.toml[31m✗[39m [31mInvalid config[39mdiff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snapindex 0743de3ca..62c0bca5d 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap@@ -89,3 +89,4 @@ exit_code: 0[2m○[22m Hyperlinks: [1minactive[22m----- stderr -----+[33m▲[39m [33mProject config has key [1mcommit.generation.command[22m which belongs in user config (will be ignored); to scope it to this repo, add it under [projects."<id>"] in user config[39mdiff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_unknown_list_column.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_unknown_list_column.snapnew file mode 100644index 000000000..0b798ec07--- /dev/null+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_unknown_list_column.snap@@ -0,0 +1,81 @@+---+source: tests/integration_tests/config_show.rs+info:+ program: wt+ args:+ - config+ - show+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----+[36mUSER CONFIG[39m @ ~/.config/worktrunk/config.toml+[107m [0m [2m[36m[list][0m+[107m [0m [2mjson-schema = [0m[2m[33m2[0m+[107m [0m [2mcolumns = [[0m[2m[32m"branch"[0m[2m, [0m[2m[32m"nosuchcolumn"[0m[2m][0m+[2m↳[22m [2mOptional system config not found @ [2m/etc/xdg/worktrunk/config.toml[22m[22m+[31m✗[39m [31mUnknown column "nosuchcolumn" in [list] columns. Valid columns: branch, status, working-diff, ahead-behind, branch-diff, summary, upstream, ci, path, url, commit, age, message[39m++[36mPROJECT CONFIG[39m @ _REPO_/.config/wt.toml+[2m○[22m Identifier: [1m../origin[22m+[2m↳[22m [2mNot found[22m++[36mSHELL INTEGRATION[39m+[33m▲[39m [33mShell integration not configured[39m+[2m↳[22m [2mTo configure, run [4mwt config shell install[24m[22m+[107m [0m Invoked as: [1m[PROJECT_ROOT]/target/[BUILD_MODE]/wt[22m++[36mOTHER[39m+[2m○[22m wt: [1m[VERSION][22m+[2m○[22m git: [1m[VERSION][22m+[2m○[22m Hyperlinks: [1minactive[22m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_warns_unknown_project_keys.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_warns_unknown_project_keys.snapindex ca189874f..382330c7b 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_warns_unknown_project_keys.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_warns_unknown_project_keys.snap@@ -78,3 +78,4 @@ exit_code: 0[2m○[22m Hyperlinks: [1minactive[22m----- stderr -----+[33m▲[39m [33mProject config has unknown field [1mpost-merge-command[22m (will be ignored)[39mdiff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snapindex 57a923409..3b21b9fe7 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snap@@ -68,6 +68,10 @@ exit_code: 0[107m [0m [2m[36m[post-start][0m[107m [0m [2mserver = [0m[2m[32m"npm run dev"[0m+[36mAPPROVALS[39m @ [TEST_APPROVALS]+[2m○[22m 2 project commands awaiting approval+[2m↳[22m [2mTo review, run [4mwt config approvals list[24m[22m+[36mSHELL INTEGRATION[39m[33m▲[39m [33mShell integration not configured[39m[2m↳[22m [2mTo configure, run [4mwt config shell install[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_show.snap b/tests/snapshots/integration__integration_tests__help__help_config_show.snapindex d243f97cb..ea7063b41 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_show.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_show.snap@@ -77,10 +77,9 @@ Usage: [1m[36mwt config show[0m [36m[OPTIONS][0m[1m[36m-y[0m, [1m[36m--yes[0mSkip approval prompts-Shows location and contents of user config ([2m~/.config/worktrunk/config.toml[0m)-and project config ([2m.config/wt.toml[0m). Also shows system config if present.--If a config file doesn't exist, shows defaults that would be used.+Shows config sources and checks for invalid TOML or list columns, misplaced or+deprecated keys, and commands awaiting approval. It renders every section+before failing; warnings exit zero.[1m[32mFull diagnostics[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_update.snap b/tests/snapshots/integration__integration_tests__help__help_config_update.snapindex da0b27557..e99ec91f2 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_update.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_update.snap@@ -80,8 +80,8 @@ instead of applying it in place. Use [2m-[0m for stdout. When both user and prconfig need migration, stdout emits a labeled inspection artifact and fileoutput fails rather than combining the configs.-Output artifacts omit deprecated [2mapproved-commands[0m; only in-place updates-move those entries to [2mapprovals.toml[0m.+[2m--output[0m omits deprecated [2mapproved-commands[0m with a stderr warning; only an+in-place update migrates them to [2mapprovals.toml[0m.[1m[32mExamples[0mdiff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_validation_failure.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_validation_failure.snapindex 9b1f6591d..7255869a0 100644--- a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_validation_failure.snap+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_validation_failure.snap@@ -64,6 +64,7 @@ exit_code: 0+ feature-c [2m↑[22m [32m↑1[0m [32m+1[0m ../repo.feature-c [2m345c7c9[0m [2m16h[0m [2mAdd feature-c file[0m----- stderr ------[33m▲[39m [33mConfig validation warning: worktree-path cannot be empty[39m+[33m▲[39m [33mIgnoring env var overrides: WORKTRUNK_WORKTREE_PATH=[39m+[107m [0m worktree-path cannot be empty[2m○[22m [2mShowing 4 worktrees, 3 ahead[0m