worktrunk 0.35.1

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
//! Config show command and rendering.
//!
//! Functions for displaying user config, project config, shell status,
//! diagnostics, and runtime info.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use anyhow::Context;
use color_print::cformat;
use worktrunk::config::{
    ProjectConfig, UserConfig, default_system_config_path, find_unknown_project_keys,
    find_unknown_user_keys, system_config_path,
};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::shell::{Shell, scan_for_detection_details};
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
    error_message, format_bash_with_gutter, format_heading, format_toml, format_with_gutter,
    hint_message, info_message, success_message, warning_message,
};

use super::state::require_user_config_path;
use crate::cli::{SwitchFormat, version_str};
use crate::commands::configure_shell::{ConfigAction, scan_shell_configs};
use crate::commands::list::ci_status::{CiPlatform, CiToolsStatus, platform_for_repo};
use crate::help_pager::show_help_in_pager;
use crate::llm::test_commit_generation;
use crate::output;

/// Handle the config show command
pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()> {
    if format == SwitchFormat::Json {
        return handle_config_show_json();
    }
    // Build the complete output as a string
    let 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 {
        show_output.push('\n');
    }

    // Render user config
    render_user_config(&mut show_output, has_system_config)?;
    show_output.push('\n');

    // Render project config if in a git repository
    render_project_config(&mut show_output)?;
    show_output.push('\n');

    // Render shell integration status
    render_shell_status(&mut show_output)?;

    // Render Claude Code status (only when claude CLI is available)
    if is_claude_available() {
        show_output.push('\n');
        render_claude_code_status(&mut show_output)?;
    }

    // Render OpenCode status (only when opencode CLI is available)
    if is_opencode_available() {
        show_output.push('\n');
        render_opencode_status(&mut show_output)?;
    }

    // Run full diagnostic checks if requested (includes slow network calls)
    if full {
        show_output.push('\n');
        render_diagnostics(&mut show_output)?;
    }

    // Render runtime info at the bottom (version, binary name, shell integration status)
    show_output.push('\n');
    render_runtime_info(&mut show_output)?;

    // Display through pager (config show is always long-form output)
    if let Err(e) = show_help_in_pager(&show_output, true) {
        log::debug!("Pager invocation failed: {}", e);
        // Fall back to direct output via eprintln (matches help behavior)
        worktrunk::styling::eprintln!("{}", show_output);
    }

    Ok(())
}

/// JSON output for config show: paths, existence, and parsed config contents.
fn handle_config_show_json() -> anyhow::Result<()> {
    let user_path = require_user_config_path()?;
    let user_exists = user_path.exists();
    let user_config = if user_exists {
        Some(serde_json::to_value(&UserConfig::load()?)?)
    } else {
        None
    };

    let (project_path, project_config) = if let Ok(repo) = Repository::current() {
        let path = repo.current_worktree().root()?.join(".config/wt.toml");
        let config = repo.load_project_config()?;
        (
            Some(path),
            config.map(|c| serde_json::to_value(&c)).transpose()?,
        )
    } else {
        (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 output = serde_json::json!({
        "user": {
            "path": user_path,
            "exists": user_exists,
            "config": user_config,
        },
        "project": {
            "path": project_path,
            "exists": project_path.as_ref().is_some_and(|p| p.exists()),
            "config": project_config,
        },
        "system": {
            "path": system_path,
            "exists": system_exists,
        },
    });
    worktrunk::styling::println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

// ==================== Helper Functions ====================

/// Check if Claude Code CLI is available
pub(super) fn is_claude_available() -> bool {
    // Allow tests to override detection
    if let Ok(val) = std::env::var("WORKTRUNK_TEST_CLAUDE_INSTALLED") {
        return val == "1";
    }
    which::which("claude").is_ok()
}

/// Get the home directory for Claude Code config detection
pub(super) fn home_dir() -> Option<PathBuf> {
    // Try HOME/USERPROFILE env vars first (for tests and explicit overrides), then fall back to dirs
    std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .ok()
        .map(PathBuf::from)
        .or_else(dirs::home_dir)
}

/// Check if the worktrunk plugin is installed in Claude Code
pub(super) fn is_plugin_installed() -> bool {
    let Some(home) = home_dir() else {
        return false;
    };

    let plugins_file = home.join(".claude/plugins/installed_plugins.json");
    let Ok(content) = std::fs::read_to_string(&plugins_file) else {
        return false;
    };

    let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
        return false;
    };

    json.get("plugins")
        .and_then(|p| p.get("worktrunk@worktrunk"))
        .is_some()
}

/// Check if the statusline is configured in Claude Code settings
pub(super) fn is_statusline_configured() -> bool {
    let Some(home) = home_dir() else {
        return false;
    };

    let settings_file = home.join(".claude/settings.json");
    let Ok(content) = std::fs::read_to_string(&settings_file) else {
        return false;
    };

    let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
        return false;
    };

    json.get("statusLine")
        .and_then(|s| s.get("command"))
        .and_then(|c| c.as_str())
        .is_some_and(|cmd| cmd.contains("wt "))
}

/// Get the git version string (e.g., "2.47.1")
fn git_version() -> Option<String> {
    let output = Cmd::new("git").arg("--version").run().ok()?;
    if !output.status.success() {
        return None;
    }

    // Parse "git version 2.47.1" -> "2.47.1"
    let stdout = String::from_utf8_lossy(&output.stdout);
    stdout
        .trim()
        .strip_prefix("git version ")
        .map(|s| s.to_string())
}

/// Check if zsh has compinit enabled by spawning an interactive shell
///
/// Returns true if compinit is NOT enabled (i.e., user needs to add it).
/// Returns false if compinit is enabled or we can't determine (fail-safe: don't warn).
fn check_zsh_compinit_missing() -> bool {
    // Allow tests to bypass this check since zsh subprocess behavior varies across CI envs
    if std::env::var("WORKTRUNK_TEST_COMPINIT_CONFIGURED").is_ok() {
        return false; // Assume compinit is configured
    }

    // Force compinit to be missing (for tests that expect the warning)
    if std::env::var("WORKTRUNK_TEST_COMPINIT_MISSING").is_ok() {
        return true; // Force warning to appear
    }

    // Probe zsh to check if compdef function exists (indicates compinit has run)
    // Use --no-globalrcs to skip system files (like /etc/zshrc on macOS which enables compinit)
    // This ensures we're checking the USER's configuration, not system defaults
    // Suppress stderr to avoid noise like "can't change option: zle"
    // The (( ... )) arithmetic returns exit 0 if true (compdef exists), 1 if false
    // Suppress zsh's "insecure directories" warning from compinit.
    // See detailed rationale in shell::detect_zsh_compinit().
    let Ok(output) = Cmd::new("zsh")
        .args(["--no-globalrcs", "-ic", "(( $+functions[compdef] ))"])
        .env("ZSH_DISABLE_COMPFIX", "true")
        .run()
    else {
        return false; // Can't determine, don't warn
    };

    // compdef NOT found = need to warn
    !output.status.success()
}

// ==================== Render Functions ====================

/// Render CLAUDE CODE section (plugin and statusline status).
/// Caller must check `is_claude_available()` first.
fn render_claude_code_status(out: &mut String) -> anyhow::Result<()> {
    writeln!(out, "{}", format_heading("CLAUDE CODE", None))?;

    // Plugin status
    let plugin_installed = is_plugin_installed();
    if plugin_installed {
        writeln!(out, "{}", success_message("Plugin installed"))?;
    } else {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "Plugin not installed. To install, run <underline>wt config plugins claude install</>"
            ))
        )?;
    }

    // Statusline status
    let statusline_configured = is_statusline_configured();
    if statusline_configured {
        writeln!(out, "{}", success_message("Statusline configured"))?;
    } else {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "Statusline not configured. To configure, run <underline>wt config plugins claude install-statusline</>"
            ))
        )?;
    }

    Ok(())
}

/// Check if OpenCode CLI is available
fn is_opencode_available() -> bool {
    // Allow tests to override detection
    if let Ok(val) = std::env::var("WORKTRUNK_TEST_OPENCODE_INSTALLED") {
        return val == "1";
    }
    which::which("opencode").is_ok()
}

/// Render OPENCODE section (plugin status).
/// Caller must check `is_opencode_available()` first.
fn render_opencode_status(out: &mut String) -> anyhow::Result<()> {
    writeln!(out, "{}", format_heading("OPENCODE", None))?;

    // Plugin status
    let plugin_installed = super::opencode::is_plugin_installed();
    let plugin_exists = super::opencode::plugin_file_exists();
    if plugin_installed {
        writeln!(out, "{}", success_message("Plugin installed"))?;
    } else if plugin_exists {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "Plugin outdated. To update, run <underline>wt config plugins opencode install</>"
            ))
        )?;
    } else {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "Plugin not installed. To install, run <underline>wt config plugins opencode install</>"
            ))
        )?;
    }

    Ok(())
}

/// Render OTHER section (version, hyperlinks)
fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {
    let cmd = crate::binary_name();
    let version = version_str();

    writeln!(out, "{}", format_heading("OTHER", None))?;

    // Version info
    writeln!(
        out,
        "{}",
        info_message(cformat!("{cmd}: <bold>{version}</>"))
    )?;
    if let Some(git_version) = git_version() {
        writeln!(
            out,
            "{}",
            info_message(cformat!("git: <bold>{git_version}</>"))
        )?;
    }

    // Show hyperlink support status
    let hyperlinks_supported =
        worktrunk::styling::supports_hyperlinks(worktrunk::styling::Stream::Stderr);
    let status = if hyperlinks_supported {
        "active"
    } else {
        "inactive"
    };
    writeln!(
        out,
        "{}",
        info_message(cformat!("Hyperlinks: <bold>{status}</>"))
    )?;

    Ok(())
}

/// Run full diagnostic checks (CI tools, commit generation) and render to buffer
fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
    writeln!(out, "{}", format_heading("DIAGNOSTICS", None))?;

    // Check CI tool based on detected platform (with config override support)
    let repo = Repository::current()?;
    let platform = platform_for_repo(&repo, None);

    match platform {
        Some(CiPlatform::GitHub) => {
            let ci_tools = CiToolsStatus::detect(None);
            render_ci_tool_status(
                out,
                "gh",
                "GitHub",
                ci_tools.gh_installed,
                ci_tools.gh_authenticated,
            )?;
        }
        Some(CiPlatform::GitLab) => {
            let ci_tools = CiToolsStatus::detect(None);
            render_ci_tool_status(
                out,
                "glab",
                "GitLab",
                ci_tools.glab_installed,
                ci_tools.glab_authenticated,
            )?;
        }
        None => {
            writeln!(
                out,
                "{}",
                hint_message("CI status requires GitHub or GitLab remote")
            )?;
        }
    }

    // Check for newer version on GitHub
    render_version_check(out)?;

    // Test commit generation - use effective config for current project
    let config = UserConfig::load()?;
    let project_id = Repository::current()
        .ok()
        .and_then(|r| r.project_identifier().ok());
    let commit_config = config.commit_generation(project_id.as_deref());

    if !commit_config.is_configured() {
        writeln!(out, "{}", hint_message("Commit generation not configured"))?;
    } else {
        let command_display = commit_config.command.as_ref().unwrap().clone();

        match test_commit_generation(&commit_config) {
            Ok(message) => {
                writeln!(
                    out,
                    "{}",
                    success_message(cformat!(
                        "Commit generation working (<bold>{command_display}</>)"
                    ))
                )?;
                writeln!(out, "{}", format_with_gutter(&message, None))?;
            }
            Err(e) => {
                writeln!(
                    out,
                    "{}",
                    error_message(cformat!(
                        "Commit generation failed (<bold>{command_display}</>)"
                    ))
                )?;
                writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;
            }
        }
    }

    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);
    };

    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")?;

    if contents.trim().is_empty() {
        writeln!(out, "{}", hint_message("Empty file (no system defaults)"))?;
        return Ok(true);
    }

    // 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>(&find_unknown_user_keys(
            &contents,
        )));
    }

    // Display TOML with syntax highlighting
    writeln!(out, "{}", format_toml(&contents))?;

    Ok(true)
}

fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Result<()> {
    let config_path = require_user_config_path()?;

    writeln!(
        out,
        "{}",
        format_heading(
            "USER CONFIG",
            Some(&format!("@ {}", format_path_for_display(&config_path)))
        )
    )?;

    // Check if file exists
    if !config_path.exists() {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "Not found; to create one, run <underline>wt config create</>"
            ))
        )?;
        return Ok(());
    }

    // Read and display the file contents
    let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;

    if contents.trim().is_empty() {
        writeln!(out, "{}", hint_message("Empty file (using defaults)"))?;
        return Ok(());
    }

    // Check for deprecations with show_brief_warning=false (silent mode)
    // User config is global, not tied to any repository
    let has_deprecations = if let Ok(result) = worktrunk::config::check_and_migrate(
        &config_path,
        &contents,
        true,
        "User config",
        None,
        false, // silent mode - we'll format the output ourselves
    ) {
        if let Some(info) = result.info {
            // Add deprecation details to the output buffer
            out.push_str(&worktrunk::config::format_deprecation_details(&info));
            true
        } else {
            false
        }
    } else {
        false
    };

    // 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 {
        // Only check for unknown keys if config is valid.
        // Filter deprecated section keys to avoid duplicate warnings
        // (deprecation system already warns about these).
        out.push_str(&warn_unknown_keys::<UserConfig>(&find_unknown_user_keys(
            &contents,
        )));
    }

    // Add "Current config" label when deprecations shown (to separate from diff)
    if has_deprecations {
        writeln!(out, "{}", info_message("Current config:"))?;
    }

    // Display TOML with syntax highlighting (gutter at column 0)
    writeln!(out, "{}", format_toml(&contents))?;

    if !has_system_config {
        render_system_config_hint(out)?;
    }

    Ok(())
}

fn render_system_config_hint(out: &mut String) -> anyhow::Result<()> {
    if let Some(path) = default_system_config_path() {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "Optional system config not found @ <dim>{}</>",
                format_path_for_display(&path)
            ))
        )?;
    }
    Ok(())
}

/// Format warnings for any unknown config keys.
///
/// Generic over `C`, the config type where the keys were found. When an unknown
/// key belongs in `C::Other`, the warning includes a hint about where to move it.
pub(super) fn warn_unknown_keys<C: worktrunk::config::WorktrunkConfig>(
    unknown_keys: &HashMap<String, toml::Value>,
) -> String {
    let mut out = String::new();

    let mut keys: Vec<_> = unknown_keys.keys().collect();
    keys.sort();

    for key in keys {
        let msg = match worktrunk::config::classify_unknown_key::<C>(key) {
            worktrunk::config::UnknownKeyKind::DeprecatedHandled => continue,
            worktrunk::config::UnknownKeyKind::DeprecatedWrongConfig {
                other_description,
                canonical_display,
            } => {
                cformat!("Key <bold>{key}</> belongs in {other_description} as {canonical_display}")
            }
            worktrunk::config::UnknownKeyKind::WrongConfig { other_description } => {
                cformat!("Key <bold>{key}</> belongs in {other_description} (will be ignored)")
            }
            worktrunk::config::UnknownKeyKind::Unknown => {
                cformat!("Unknown key <bold>{key}</> will be ignored")
            }
        };
        let _ = writeln!(out, "{}", warning_message(msg));
    }
    out
}

fn render_project_config(out: &mut String) -> anyhow::Result<()> {
    // Try to get current repository root
    let repo = match Repository::current() {
        Ok(repo) => repo,
        Err(_) => {
            writeln!(
                out,
                "{}",
                cformat!(
                    "<dim>{}</>",
                    format_heading("PROJECT CONFIG", Some("Not in a git repository"))
                )
            )?;
            return Ok(());
        }
    };
    let config_path = match repo.project_config_path() {
        Ok(Some(path)) => path,
        _ => {
            writeln!(
                out,
                "{}",
                cformat!(
                    "<dim>{}</>",
                    format_heading("PROJECT CONFIG", Some("Not in a git repository"))
                )
            )?;
            return Ok(());
        }
    };

    writeln!(
        out,
        "{}",
        format_heading(
            "PROJECT CONFIG",
            Some(&format!("@ {}", format_path_for_display(&config_path)))
        )
    )?;

    // Check if file exists
    if !config_path.exists() {
        writeln!(out, "{}", hint_message("Not found"))?;
        return Ok(());
    }

    // Read and display the file contents
    let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;

    if contents.trim().is_empty() {
        writeln!(out, "{}", hint_message("Empty file"))?;
        return Ok(());
    }

    // Check for deprecations with show_brief_warning=false (silent mode)
    // Only write migration file in main worktree, not linked worktrees
    let is_main_worktree = !repo.current_worktree().is_linked().unwrap_or(true);
    let has_deprecations = if let Ok(result) = worktrunk::config::check_and_migrate(
        &config_path,
        &contents,
        is_main_worktree,
        "Project config",
        Some(&repo),
        false, // silent mode - we'll format the output ourselves
    ) {
        if let Some(info) = result.info {
            // Add deprecation details to the output buffer
            out.push_str(&worktrunk::config::format_deprecation_details(&info));
            true
        } else {
            false
        }
    } else {
        false
    };

    // Validate config (syntax + schema) and warn if invalid
    if let Err(e) = toml::from_str::<ProjectConfig>(&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 {
        // Only check for unknown keys if config is valid
        out.push_str(&warn_unknown_keys::<ProjectConfig>(
            &find_unknown_project_keys(&contents),
        ));
    }

    // Add "Current config" label when deprecations shown (to separate from diff)
    if has_deprecations {
        writeln!(out, "{}", info_message("Current config:"))?;
    }

    // Display TOML with syntax highlighting (gutter at column 0)
    writeln!(out, "{}", format_toml(&contents))?;

    Ok(())
}

fn render_shell_status(out: &mut String) -> anyhow::Result<()> {
    writeln!(out, "{}", format_heading("SHELL INTEGRATION", None))?;

    // Shell integration runtime status (moved from RUNTIME section)
    let shell_active = output::is_shell_integration_active();
    if shell_active {
        writeln!(out, "{}", info_message("Shell integration active"))?;
    } else {
        writeln!(out, "{}", warning_message("Shell integration not active"))?;
        // Show invocation details to help diagnose
        let invocation = crate::invocation_path();
        let is_git_subcommand = crate::is_git_subcommand();
        let mut debug_lines = vec![cformat!("Invoked as: <bold>{invocation}</>")];

        // Show actual binary path if different from invocation (helps detect wrong wt in PATH)
        if let Ok(exe_path) = std::env::current_exe() {
            let exe_display = format_path_for_display(&exe_path);
            // Only show if meaningfully different (not just ./ prefix differences)
            let invocation_canonical = std::fs::canonicalize(&invocation).ok();
            let exe_canonical = std::fs::canonicalize(&exe_path).ok();
            if invocation_canonical != exe_canonical {
                debug_lines.push(cformat!("Running from: <bold>{exe_display}</>"));
            }
        }

        // Show $SHELL to help diagnose rc file sourcing issues
        let shell_env = std::env::var("SHELL").ok().filter(|s| !s.is_empty());
        if let Some(shell_env) = &shell_env {
            debug_lines.push(cformat!("$SHELL: <bold>{shell_env}</>"));
        } else if let Some(detected) = worktrunk::shell::current_shell() {
            debug_lines.push(cformat!(
                "Detected shell: <bold>{detected}</> (via PSModulePath)"
            ));
        }

        if is_git_subcommand {
            debug_lines.push("Git subcommand: yes (GIT_EXEC_PATH set)".to_string());
        }
        writeln!(out, "{}", format_with_gutter(&debug_lines.join("\n"), None))?;
    }
    writeln!(out)?;

    // Use the same detection logic as `wt config shell install`
    let cmd = crate::binary_name();
    let scan_result = match scan_shell_configs(None, true, &cmd) {
        Ok(r) => r,
        Err(e) => {
            writeln!(
                out,
                "{}",
                hint_message(format!("Could not determine shell status: {e}"))
            )?;
            return Ok(());
        }
    };

    // Get detection details to show matched lines inline
    let detection_results = scan_for_detection_details(&cmd).unwrap_or_default();

    // Check for legacy fish conf.d path (deprecated location from before #566)
    // We need this early to handle the case where fish shows "Not configured" at the
    // new location but has valid integration at the legacy location.
    let legacy_fish_conf_d = Shell::legacy_fish_conf_d_path(&cmd).ok();
    let legacy_fish_has_integration = legacy_fish_conf_d.as_ref().is_some_and(|legacy_path| {
        detection_results
            .iter()
            .any(|d| d.path == *legacy_path && !d.matched_lines.is_empty())
    });

    let mut any_not_configured = false;
    let mut has_any_unmatched = false;

    // Show configured and not-configured shells (matching `config shell install` format exactly)
    // Bash/Zsh: inline completions, show "shell extension & completions"
    // Fish: separate completion file, show "shell extension" for functions/ and "completions" for completions/
    for result in &scan_result.configured {
        let shell = result.shell;
        let path = format_path_for_display(&result.path);
        // Fish has separate completion file; bash/zsh have inline completions
        let what = if matches!(shell, Shell::Fish) {
            "shell extension"
        } else {
            "shell extension & completions"
        };

        match result.action {
            ConfigAction::AlreadyExists => {
                // Show the matched lines directly under this status
                let detection = detection_results
                    .iter()
                    .find(|d| d.path == result.path && !d.matched_lines.is_empty());

                // Build file:line location (clickable in terminals - use first line only)
                let location = if let Some(det) = detection {
                    if let Some(first_line) = det.matched_lines.first() {
                        format!("{}:{}", path, first_line.line_number)
                    } else {
                        path.to_string()
                    }
                } else {
                    path.to_string()
                };

                writeln!(
                    out,
                    "{}",
                    info_message(cformat!(
                        "<bold>{shell}</>: Already configured {what} @ {location}"
                    ))
                )?;

                if let Some(det) = detection {
                    for detected in &det.matched_lines {
                        writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;
                    }

                    // Check if any matched lines use .exe suffix and warn about function name
                    let uses_exe = det.matched_lines.iter().any(|m| m.content.contains(".exe"));
                    if uses_exe {
                        writeln!(
                            out,
                            "{}",
                            hint_message(cformat!(
                                "Creates shell function <bold>{cmd}</>. Aliases should use <underline>{cmd}</>, not <underline>{cmd}.exe</>"
                            ))
                        )?;
                    }
                }

                // Check if zsh has compinit enabled (required for completions)
                if matches!(shell, Shell::Zsh) && check_zsh_compinit_missing() {
                    writeln!(
                        out,
                        "{}",
                        warning_message(
                            "Completions won't work; add to ~/.zshrc before the wt line:"
                        )
                    )?;
                    writeln!(
                        out,
                        "{}",
                        format_with_gutter("autoload -Uz compinit && compinit", None)
                    )?;
                }

                // For fish, check completions file separately
                if matches!(shell, Shell::Fish)
                    && let Ok(completion_path) = shell.completion_path(&cmd)
                {
                    let completion_display = format_path_for_display(&completion_path);
                    if completion_path.exists() {
                        writeln!(
                            out,
                            "{}",
                            info_message(cformat!(
                                "<bold>{shell}</>: Already configured completions @ {completion_display}"
                            ))
                        )?;
                    } else {
                        any_not_configured = true;
                        writeln!(
                            out,
                            "{}",
                            hint_message(format!("{shell}: Not configured completions"))
                        )?;
                    }
                }

                // When configured but not active, show how to verify the wrapper loaded
                if !shell_active {
                    let verify_cmd = match shell {
                        Shell::PowerShell => format!("Get-Command {cmd}"),
                        _ => format!("type {cmd}"),
                    };
                    let hint = hint_message(cformat!(
                        "To verify wrapper loaded: <underline>{verify_cmd}</>"
                    ));
                    writeln!(out, "{hint}")?;
                }
            }
            ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
                // For fish, check if we have valid integration at the legacy conf.d location
                if matches!(shell, Shell::Fish) && legacy_fish_has_integration {
                    // Show migration hint instead of "Not configured"
                    let legacy_path = legacy_fish_conf_d
                        .as_ref()
                        .map(|p| format_path_for_display(p))
                        .unwrap_or_default();
                    writeln!(
                        out,
                        "{}",
                        info_message(cformat!(
                            "Fish integration found in deprecated location @ <bold>{legacy_path}</>"
                        ))
                    )?;
                    // Get canonical path for the migration hint
                    let canonical_path = Shell::Fish
                        .config_paths(&cmd)
                        .ok()
                        .and_then(|p| p.into_iter().next())
                        .map(|p| format_path_for_display(&p))
                        .unwrap_or_else(|| "~/.config/fish/functions/".to_string());
                    writeln!(
                        out,
                        "{}",
                        hint_message(cformat!(
                            "To migrate to <underline>{canonical_path}</>, run <underline>{cmd} config shell install fish</>"
                        ))
                    )?;
                } else if shell.is_wrapper_based()
                    && matches!(result.action, ConfigAction::WouldAdd)
                {
                    // File exists but has different content (e.g. outdated version)
                    any_not_configured = true;
                    let warning = warning_message(cformat!(
                        "<bold>{shell}</>: Outdated shell extension @ {path}"
                    ));
                    let hint = hint_message(cformat!(
                        "To update, run <underline>{cmd} config shell install {shell}</>"
                    ));
                    writeln!(out, "{warning}\n{hint}")?;
                } else {
                    any_not_configured = true;
                    writeln!(
                        out,
                        "{}",
                        hint_message(format!("{shell}: Not configured {what}"))
                    )?;
                }
            }
            _ => {} // Added/Created won't appear in dry_run mode
        }
    }

    // Show skipped (not installed) shells
    // For fish with legacy integration, show migration hint instead of "skipped"
    for (shell, path) in &scan_result.skipped {
        if matches!(shell, Shell::Fish) && legacy_fish_has_integration {
            // Show migration hint for legacy fish location
            let legacy_path = legacy_fish_conf_d
                .as_ref()
                .map(|p| format_path_for_display(p))
                .unwrap_or_default();
            let canonical_path = Shell::Fish
                .config_paths(&cmd)
                .ok()
                .and_then(|p| p.into_iter().next())
                .map(|p| format_path_for_display(&p))
                .unwrap_or_else(|| "~/.config/fish/functions/".to_string());
            writeln!(
                out,
                "{}",
                info_message(cformat!(
                    "Fish integration found in deprecated location @ <bold>{legacy_path}</>"
                ))
            )?;
            writeln!(
                out,
                "{}",
                hint_message(cformat!(
                    "To migrate to <underline>{canonical_path}</>, run <underline>{cmd} config shell install fish</>"
                ))
            )?;
            continue;
        }
        let path = format_path_for_display(path);
        writeln!(
            out,
            "{}",
            info_message(cformat!("<dim>{shell}: Skipped; {path} not found</>"))
        )?;
    }

    // Summary hint when shells need configuration
    if any_not_configured {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "To configure, run <underline>{cmd} config shell install</>"
            ))
        )?;
    }

    // Show potential false negatives (lines containing cmd but not detected)
    // Skip files that have valid integration detected (matched_lines) - those are fine,
    // and the other lines containing cmd are just part of the integration script.
    // Also skip files already confirmed as integration by scan_shell_configs (e.g., Nushell/Fish
    // wrapper files that ARE the integration, not config files that source it).
    let confirmed_paths: HashSet<&Path> = scan_result
        .configured
        .iter()
        .filter(|r| {
            // For wrapper-based shells, the file at the path IS the integration — any
            // action means it was recognized. For eval-based shells, only AlreadyExists
            // means the config line was found.
            r.shell.is_wrapper_based() || matches!(r.action, ConfigAction::AlreadyExists)
        })
        .map(|r| r.path.as_path())
        .collect();
    for detection in &detection_results {
        if !detection.unmatched_candidates.is_empty()
            && detection.matched_lines.is_empty()
            && !confirmed_paths.contains(detection.path.as_path())
        {
            has_any_unmatched = true;
            let path = format_path_for_display(&detection.path);

            // Build file:line location (clickable in terminals - use first line only)
            let location = if let Some(first) = detection.unmatched_candidates.first() {
                format!("{}:{}", path, first.line_number)
            } else {
                path.to_string()
            };
            writeln!(
                out,
                "{}",
                warning_message(cformat!(
                    "Found <bold>{cmd}</> in <bold>{location}</> but not detected as integration:"
                ))
            )?;
            for detected in &detection.unmatched_candidates {
                writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;
            }

            // If any unmatched lines contain .exe, explain the function name issue
            let uses_exe = detection
                .unmatched_candidates
                .iter()
                .any(|m| m.content.contains(".exe"));
            if uses_exe {
                writeln!(
                    out,
                    "{}",
                    hint_message(cformat!(
                        "Note: <bold>{cmd}.exe</> creates shell function <bold>{cmd}</>. \
                         Aliases should use <underline>{cmd}</>, not <underline>{cmd}.exe</>"
                    ))
                )?;
            }
        }
    }

    // Show aliases that bypass shell integration (Issue #348)
    for detection in &detection_results {
        for alias in &detection.bypass_aliases {
            let path = format_path_for_display(&detection.path);
            let location = format!("{}:{}", path, alias.line_number);
            writeln!(
                out,
                "{}",
                warning_message(cformat!(
                    "Alias <bold>{}</> bypasses shell integration — won't auto-cd",
                    alias.alias_name
                ))
            )?;
            writeln!(out, "{}", format_bash_with_gutter(alias.content.trim()))?;
            writeln!(
                out,
                "{}",
                hint_message(cformat!(
                    "Change to <underline>alias {}=\"{cmd}\"</> @ {location}",
                    alias.alias_name
                ))
            )?;
        }
    }

    // Check if any shell has config already (eval line present)
    let has_any_configured = scan_result
        .configured
        .iter()
        .any(|r| matches!(r.action, ConfigAction::AlreadyExists));

    // If we have unmatched candidates but no configured shells, suggest raising an issue
    // Apply the same confirmed_paths filter used above to avoid including wrapper files
    if has_any_unmatched && !has_any_configured {
        let unmatched_summary: Vec<_> = detection_results
            .iter()
            .filter(|r| {
                !r.unmatched_candidates.is_empty()
                    && r.matched_lines.is_empty()
                    && !confirmed_paths.contains(r.path.as_path())
            })
            .flat_map(|r| {
                r.unmatched_candidates
                    .iter()
                    .map(|d| d.content.trim().to_string())
            })
            .collect();
        let body = format!(
            "Shell integration not detected despite config containing `{cmd}`.\n\n\
             **Unmatched lines:**\n```\n{}\n```\n\n\
             **Expected behavior:** These lines should be detected as shell integration.",
            unmatched_summary.join("\n")
        );
        let issue_url = format!(
            "https://github.com/max-sixty/worktrunk/issues/new?title={}&body={}",
            urlencoding::encode("Shell integration detection false negative"),
            urlencoding::encode(&body)
        );

        // Quote a short version of the unmatched content in the hint
        let quoted = if unmatched_summary.len() == 1 {
            format!("`{}`", unmatched_summary[0])
        } else {
            format!(
                "`{}` (and {} more)",
                unmatched_summary[0],
                unmatched_summary.len() - 1
            )
        };
        writeln!(
            out,
            "{}",
            hint_message(format!(
                "If {quoted} is shell integration, report a false negative: {issue_url}"
            ))
        )?;
    }

    Ok(())
}

pub(super) fn render_ci_tool_status(
    out: &mut String,
    tool: &str,
    platform: &str,
    installed: bool,
    authenticated: bool,
) -> anyhow::Result<()> {
    if installed {
        if authenticated {
            writeln!(
                out,
                "{}",
                success_message(cformat!("<bold>{tool}</> installed & authenticated"))
            )?;
        } else {
            writeln!(
                out,
                "{}",
                warning_message(cformat!(
                    "<bold>{tool}</> installed but not authenticated; run <bold>{tool} auth login</>"
                ))
            )?;
        }
    } else {
        writeln!(
            out,
            "{}",
            hint_message(cformat!(
                "<bold>{tool}</> not found ({platform} CI status unavailable)"
            ))
        )?;
    }
    Ok(())
}

/// Render version update check (fetches from GitHub)
fn render_version_check(out: &mut String) -> anyhow::Result<()> {
    match fetch_latest_version() {
        Ok(latest) => {
            let current = crate::cli::version_str();
            let current_semver = env!("CARGO_PKG_VERSION");
            if is_newer_version(&latest, current_semver) {
                writeln!(
                    out,
                    "{}",
                    info_message(cformat!(
                        "Update available: <bold>{latest}</> (current: {current})"
                    ))
                )?;
            } else {
                writeln!(
                    out,
                    "{}",
                    success_message(cformat!("Up to date (<bold>{current}</>)"))
                )?;
            }
        }
        Err(e) => {
            log::debug!("Version check failed: {e}");
            writeln!(out, "{}", hint_message("Version check unavailable"))?;
        }
    }
    Ok(())
}

/// Fetch the latest release version from GitHub
fn fetch_latest_version() -> anyhow::Result<String> {
    // Allow tests to inject a version without network access.
    // Set to "error" to simulate a fetch failure.
    if let Ok(version) = std::env::var("WORKTRUNK_TEST_LATEST_VERSION") {
        if version == "error" {
            anyhow::bail!("simulated fetch failure");
        }
        return Ok(version);
    }

    let user_agent = format!(
        "worktrunk/{} (https://worktrunk.dev)",
        env!("CARGO_PKG_VERSION")
    );
    let output = Cmd::new("curl")
        .args([
            "--silent",
            "--fail",
            "--max-time",
            "5",
            "--header",
            &format!("User-Agent: {user_agent}"),
            "https://api.github.com/repos/max-sixty/worktrunk/releases/latest",
        ])
        .run()?;

    if !output.status.success() {
        anyhow::bail!("GitHub API request failed");
    }

    let json: serde_json::Value = serde_json::from_slice(&output.stdout)?;
    let tag = json["tag_name"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("missing tag_name in response"))?;

    // Strip leading 'v' prefix (e.g., "v0.23.2" -> "0.23.2")
    Ok(tag.strip_prefix('v').unwrap_or(tag).to_string())
}

/// Compare two semver version strings (e.g., "0.24.0" > "0.23.2")
fn is_newer_version(latest: &str, current: &str) -> bool {
    let parse = |s: &str| -> Option<(u32, u32, u32)> {
        let mut parts = s.splitn(3, '.');
        Some((
            parts.next()?.parse().ok()?,
            parts.next()?.parse().ok()?,
            parts.next()?.parse().ok()?,
        ))
    };
    match (parse(latest), parse(current)) {
        (Some(l), Some(c)) => l > c,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_git_version_returns_version() {
        // In a normal environment with git installed, should return a version
        let version = git_version();
        assert!(version.is_some());
        let version = version.unwrap();
        // Version should look like a semver (e.g., "2.47.1")
        assert!(version.chars().next().unwrap().is_ascii_digit());
        assert!(version.contains('.'));
    }

    #[test]
    fn test_is_newer_version() {
        // Newer versions
        assert!(is_newer_version("0.24.0", "0.23.2"));
        assert!(is_newer_version("1.0.0", "0.99.99"));
        assert!(is_newer_version("0.23.3", "0.23.2"));
        assert!(is_newer_version("0.23.2", "0.23.1"));

        // Same version
        assert!(!is_newer_version("0.23.2", "0.23.2"));

        // Older versions
        assert!(!is_newer_version("0.23.1", "0.23.2"));
        assert!(!is_newer_version("0.22.0", "0.23.2"));

        // Invalid input
        assert!(!is_newer_version("invalid", "0.23.2"));
        assert!(!is_newer_version("0.23.2", "invalid"));
    }
}