worktrunk 0.34.2

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
//! State management commands.
//!
//! Commands for getting, setting, and clearing stored state like default branch,
//! previous branch, CI status, markers, and logs.

use std::fmt::Write as _;
use std::path::PathBuf;

use anyhow::Context;
use color_print::cformat;
use worktrunk::config::config_path;
use worktrunk::git::Repository;
use worktrunk::path::{format_path_for_display, sanitize_for_filename};
use worktrunk::styling::{
    eprintln, format_heading, format_with_gutter, info_message, println, success_message,
    warning_message,
};

use crate::cli::OutputFormat;
use crate::commands::process::HookLog;
use worktrunk::utils::epoch_now;

use super::super::list::ci_status::{CachedCiStatus, CiBranchName};
use crate::display::format_relative_time_short;
use crate::help_pager::show_help_in_pager;

// ==================== Path Helpers ====================

/// Get the user config path, or error if it cannot be determined.
///
/// Delegates to `config_path()` so that `config create` and `config show`
/// resolve the same path that config loading uses — including any CLI
/// (`--config`) or environment variable (`WORKTRUNK_CONFIG_PATH`) overrides.
pub fn require_user_config_path() -> anyhow::Result<PathBuf> {
    config_path().context("Cannot determine config directory")
}

// ==================== Log Management ====================

/// Check if a file in `.git/wt/logs/` is a worktrunk log file.
///
/// Matches `.log` (hook output), `.jsonl` (command audit log), and `.jsonl.old` (rotated).
fn is_wt_log_file(path: &std::path::Path) -> bool {
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    name.ends_with(".log") || name.ends_with(".jsonl") || name.ends_with(".jsonl.old")
}

/// Clear all log files from the wt/logs directory
fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
    let log_dir = repo.wt_logs_dir();

    if !log_dir.exists() {
        return Ok(0);
    }

    let mut cleared = 0;
    for entry in std::fs::read_dir(&log_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_file() && is_wt_log_file(&path) {
            std::fs::remove_file(&path)?;
            cleared += 1;
        }
    }

    // Remove the directory if empty
    if std::fs::read_dir(&log_dir)?.next().is_none() {
        let _ = std::fs::remove_dir(&log_dir);
    }

    Ok(cleared)
}

/// Check if a filename belongs to the command audit log (`.jsonl` / `.jsonl.old`).
fn is_command_log_file(name: &str) -> bool {
    name.ends_with(".jsonl") || name.ends_with(".jsonl.old")
}

/// Render a table of log file entries, or "(none)" if empty.
fn render_log_table(out: &mut String, entries: &mut [std::fs::DirEntry]) -> std::fmt::Result {
    if entries.is_empty() {
        writeln!(out, "{}", format_with_gutter("(none)", None))?;
        return Ok(());
    }

    // Sort by modification time (newest first), then by name for stability
    entries.sort_by(|a, b| {
        let a_time = a.metadata().and_then(|m| m.modified()).ok();
        let b_time = b.metadata().and_then(|m| m.modified()).ok();
        b_time
            .cmp(&a_time)
            .then_with(|| a.file_name().cmp(&b.file_name()))
    });

    let rows: Vec<Vec<String>> = entries
        .iter()
        .map(|entry| {
            let path = entry.path();
            let name = path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string();
            let meta = entry.metadata().ok();

            let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
            let size_str = if size < 1024 {
                format!("{size}B")
            } else {
                format!("{}K", size / 1024)
            };

            let age = meta
                .and_then(|m| m.modified().ok())
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| format_relative_time_short(d.as_secs() as i64))
                .unwrap_or_else(|| "?".to_string());

            vec![name, size_str, age]
        })
        .collect();

    let rendered = crate::md_help::render_data_table(&["File", "Size", "Age"], &rows);
    write!(out, "{}", rendered.trim_end())?;

    Ok(())
}

/// Render the COMMAND LOG section into the output buffer.
pub(super) fn render_command_log(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
    let log_dir = repo.wt_logs_dir();
    let log_dir_display = format_path_for_display(&log_dir);

    writeln!(
        out,
        "{}",
        format_heading("COMMAND LOG", Some(&format!("@ {log_dir_display}")))
    )?;

    if !log_dir.exists() {
        writeln!(out, "{}", format_with_gutter("(none)", None))?;
        return Ok(());
    }

    let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
        .filter_map(|e| e.ok())
        .filter(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            e.path().is_file() && is_command_log_file(&name)
        })
        .collect();

    render_log_table(out, &mut entries)?;
    Ok(())
}

/// Render the HOOK OUTPUT section into the output buffer.
pub(super) fn render_hook_output(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
    let log_dir = repo.wt_logs_dir();
    let log_dir_display = format_path_for_display(&log_dir);

    writeln!(
        out,
        "{}",
        format_heading("HOOK OUTPUT", Some(&format!("@ {log_dir_display}")))
    )?;

    if !log_dir.exists() {
        writeln!(out, "{}", format_with_gutter("(none)", None))?;
        return Ok(());
    }

    let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
        .filter_map(|e| e.ok())
        .filter(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            e.path().is_file() && is_wt_log_file(&e.path()) && !is_command_log_file(&name)
        })
        .collect();

    render_log_table(out, &mut entries)?;
    Ok(())
}

// ==================== Logs Get Command ====================

/// Handle the logs get command
///
/// When `hook` is None, lists all log files.
/// When `hook` is Some, returns the path to the specific log file for that hook.
///
/// # Hook spec format
///
/// - `source:hook-type:name` for hook commands (e.g., `user:post-start:server`)
/// - `internal:op` for internal operations (e.g., `internal:remove`)
pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::Result<()> {
    let repo = Repository::current()?;

    match hook {
        None => {
            // No hook specified, show all log files
            let mut out = String::new();
            render_command_log(&mut out, &repo)?;
            writeln!(out)?;
            render_hook_output(&mut out, &repo)?;

            // Display through pager (fall back to stderr if pager unavailable)
            if show_help_in_pager(&out, true).is_err() {
                eprintln!("{}", out);
            }
        }
        Some(hook_spec) => {
            // Get the branch name
            let branch = match branch {
                Some(b) => b,
                None => repo.require_current_branch("get log for current branch")?,
            };

            let log_dir = repo.wt_logs_dir();

            // Parse the hook spec using HookLog
            let hook_log = HookLog::parse(&hook_spec).map_err(|e| anyhow::anyhow!("{}", e))?;

            // Check log directory exists
            if !log_dir.exists() {
                anyhow::bail!(
                    "No log directory exists. Run a background hook first to create logs."
                );
            }

            // Get the expected log path
            let log_path = hook_log.path(&log_dir, &branch);

            if log_path.exists() {
                // Output just the path to stdout for easy piping
                println!("{}", log_path.display());
                return Ok(());
            }

            // No match found - show expected filename and available files
            let expected_filename = hook_log.filename(&branch);
            let safe_branch = sanitize_for_filename(&branch);
            let mut available = Vec::new();
            if let Ok(entries) = std::fs::read_dir(&log_dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.starts_with(&format!("{}-", safe_branch)) && name.ends_with(".log") {
                        available.push(name);
                    }
                }
            }

            if available.is_empty() {
                anyhow::bail!(cformat!(
                    "No log files for branch <bold>{}</>. Run a background hook first.",
                    branch
                ));
            } else {
                let available_list = available.join(", ");
                let details = format!(
                    "Expected: {}\nAvailable: {}",
                    expected_filename, available_list
                );
                return Err(anyhow::anyhow!(details).context(cformat!(
                    "No log file matches <bold>{}</> for branch <bold>{}</>",
                    hook_log.to_spec(),
                    branch
                )));
            }
        }
    }

    Ok(())
}

// ==================== State Get/Set/Clear Commands ====================

/// Handle the state get command
pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {
    use super::super::list::ci_status::PrStatus;

    let repo = Repository::current()?;

    match key {
        "default-branch" => {
            let branch_name = repo.default_branch().ok_or_else(|| {
                anyhow::anyhow!(cformat!(
                    "Cannot determine default branch. To configure, run <bold>wt config state default-branch set BRANCH</>"
                ))
            })?;
            println!("{branch_name}");
        }
        "previous-branch" => match repo.switch_previous() {
            Some(prev) => println!("{prev}"),
            None => println!(""),
        },
        "marker" => {
            let branch_name = match branch {
                Some(b) => b,
                None => repo.require_current_branch("get marker for current branch")?,
            };
            match repo.branch_marker(&branch_name) {
                Some(marker) => println!("{marker}"),
                None => println!(""),
            }
        }
        "ci-status" => {
            let branch_name = match branch {
                Some(b) => b,
                None => repo.require_current_branch("get ci-status for current branch")?,
            };

            // Determine if this is a remote ref by checking git refs directly.
            // This is authoritative - we check actual refs, not guessing from name.
            let is_remote = repo
                .run_command(&[
                    "show-ref",
                    "--verify",
                    "--quiet",
                    &format!("refs/remotes/{}", branch_name),
                ])
                .is_ok();

            // Get the HEAD commit for this branch
            let head = repo
                .run_command(&["rev-parse", &branch_name])
                .map(|s| s.trim().to_string())
                .unwrap_or_default();

            if head.is_empty() {
                return Err(worktrunk::git::GitError::BranchNotFound {
                    branch: branch_name,
                    show_create_hint: true,
                    last_fetch_ago: None,
                }
                .into());
            }

            let ci_branch = CiBranchName::from_branch_ref(&branch_name, is_remote);
            let ci_status = PrStatus::detect(&repo, &ci_branch, &head)
                .map_or(super::super::list::ci_status::CiStatus::NoCI, |s| {
                    s.ci_status
                });
            let status_str: &'static str = ci_status.into();
            println!("{status_str}");
        }
        // TODO: Consider simplifying to just print the path and let users run `ls -al` themselves
        "logs" => {
            let mut out = String::new();
            render_command_log(&mut out, &repo)?;
            writeln!(out)?;
            render_hook_output(&mut out, &repo)?;

            // Display through pager (fall back to stderr if pager unavailable)
            if show_help_in_pager(&out, true).is_err() {
                eprintln!("{}", out);
            }
        }
        _ => {
            anyhow::bail!(
                "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"
            )
        }
    }

    Ok(())
}

/// Handle the state set command
pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> anyhow::Result<()> {
    let repo = Repository::current()?;

    match key {
        "default-branch" => {
            // Warn if the branch doesn't exist locally
            if !repo.branch(&value).exists_locally()? {
                eprintln!(
                    "{}",
                    warning_message(cformat!("Branch <bold>{value}</> does not exist locally"))
                );
            }
            repo.set_default_branch(&value)?;
            eprintln!(
                "{}",
                success_message(cformat!("Set default branch to <bold>{value}</>"))
            );
        }
        "previous-branch" => {
            repo.set_switch_previous(Some(&value))?;
            eprintln!(
                "{}",
                success_message(cformat!("Set previous branch to <bold>{value}</>"))
            );
        }
        "marker" => {
            let branch_name = match branch {
                Some(b) => b,
                None => repo.require_current_branch("set marker for current branch")?,
            };

            // Store as JSON with timestamp
            let now = epoch_now();
            let json = serde_json::json!({
                "marker": value,
                "set_at": now
            });

            let config_key = format!("worktrunk.state.{branch_name}.marker");
            repo.run_command(&["config", &config_key, &json.to_string()])?;

            eprintln!(
                "{}",
                success_message(cformat!(
                    "Set marker for <bold>{branch_name}</> to <bold>{value}</>"
                ))
            );
        }
        _ => {
            anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, previous-branch, marker")
        }
    }

    Ok(())
}

/// Handle the state clear command
pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyhow::Result<()> {
    let repo = Repository::current()?;

    match key {
        "default-branch" => {
            if repo.clear_default_branch_cache()? {
                eprintln!("{}", success_message("Cleared default branch cache"));
            } else {
                eprintln!("{}", info_message("No default branch cache to clear"));
            }
        }
        "previous-branch" => {
            if repo
                .run_command(&["config", "--unset", "worktrunk.history"])
                .is_ok()
            {
                eprintln!("{}", success_message("Cleared previous branch"));
            } else {
                eprintln!("{}", info_message("No previous branch to clear"));
            }
        }
        "ci-status" => {
            if all {
                let cleared = CachedCiStatus::clear_all(&repo);
                if cleared == 0 {
                    eprintln!("{}", info_message("No CI cache entries to clear"));
                } else {
                    eprintln!(
                        "{}",
                        success_message(cformat!(
                            "Cleared <bold>{cleared}</> CI cache entr{}",
                            if cleared == 1 { "y" } else { "ies" }
                        ))
                    );
                }
            } else {
                // Clear CI status for specific branch
                let branch_name = match branch {
                    Some(b) => b,
                    None => repo.require_current_branch("clear ci-status for current branch")?,
                };
                let config_key = format!("worktrunk.state.{branch_name}.ci-status");
                if repo
                    .run_command(&["config", "--unset", &config_key])
                    .is_ok()
                {
                    eprintln!(
                        "{}",
                        success_message(cformat!("Cleared CI cache for <bold>{branch_name}</>"))
                    );
                } else {
                    eprintln!(
                        "{}",
                        info_message(cformat!("No CI cache for <bold>{branch_name}</>"))
                    );
                }
            }
        }
        "marker" => {
            if all {
                let output = repo
                    .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])
                    .unwrap_or_default();

                let mut cleared_count = 0;
                for line in output.lines() {
                    if let Some(config_key) = line.split_whitespace().next() {
                        repo.run_command(&["config", "--unset", config_key])?;
                        cleared_count += 1;
                    }
                }

                if cleared_count == 0 {
                    eprintln!("{}", info_message("No markers to clear"));
                } else {
                    eprintln!(
                        "{}",
                        success_message(cformat!(
                            "Cleared <bold>{cleared_count}</> marker{}",
                            if cleared_count == 1 { "" } else { "s" }
                        ))
                    );
                }
            } else {
                let branch_name = match branch {
                    Some(b) => b,
                    None => repo.require_current_branch("clear marker for current branch")?,
                };

                let config_key = format!("worktrunk.state.{branch_name}.marker");
                if repo
                    .run_command(&["config", "--unset", &config_key])
                    .is_ok()
                {
                    eprintln!(
                        "{}",
                        success_message(cformat!("Cleared marker for <bold>{branch_name}</>"))
                    );
                } else {
                    eprintln!(
                        "{}",
                        info_message(cformat!("No marker set for <bold>{branch_name}</>"))
                    );
                }
            }
        }
        "logs" => {
            let cleared = clear_logs(&repo)?;
            if cleared == 0 {
                eprintln!("{}", info_message("No logs to clear"));
            } else {
                eprintln!(
                    "{}",
                    success_message(cformat!(
                        "Cleared <bold>{cleared}</> log file{}",
                        if cleared == 1 { "" } else { "s" }
                    ))
                );
            }
        }
        _ => {
            anyhow::bail!(
                "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"
            )
        }
    }

    Ok(())
}

/// Handle the state clear all command
pub fn handle_state_clear_all() -> anyhow::Result<()> {
    let repo = Repository::current()?;
    let mut cleared_any = false;

    // Clear default branch cache
    if matches!(repo.clear_default_branch_cache(), Ok(true)) {
        cleared_any = true;
    }

    // Clear previous branch
    if repo
        .run_command(&["config", "--unset", "worktrunk.history"])
        .is_ok()
    {
        cleared_any = true;
    }

    // Clear all markers
    let markers_output = repo
        .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])
        .unwrap_or_default();
    for line in markers_output.lines() {
        if let Some(config_key) = line.split_whitespace().next() {
            let _ = repo.run_command(&["config", "--unset", config_key]);
            cleared_any = true;
        }
    }

    // Clear all CI status cache
    let ci_cleared = CachedCiStatus::clear_all(&repo);
    if ci_cleared > 0 {
        cleared_any = true;
    }

    // Clear all vars data
    let vars_cleared = clear_all_vars(&repo)?;
    if vars_cleared > 0 {
        cleared_any = true;
    }

    // Clear all logs
    let logs_cleared = clear_logs(&repo)?;
    if logs_cleared > 0 {
        cleared_any = true;
    }

    // Clear all hints
    let hints_cleared = repo.clear_all_hints()?;
    if hints_cleared > 0 {
        cleared_any = true;
    }

    if cleared_any {
        eprintln!("{}", success_message("Cleared all stored state"));
    } else {
        eprintln!("{}", info_message("No stored state to clear"));
    }

    Ok(())
}

// ==================== State Show Commands ====================

/// Handle the state get command (shows all state)
pub fn handle_state_show(format: OutputFormat) -> anyhow::Result<()> {
    let repo = Repository::current()?;

    match format {
        OutputFormat::Json => handle_state_show_json(&repo),
        OutputFormat::Table | OutputFormat::ClaudeCode => handle_state_show_table(&repo),
    }
}

/// Output state as JSON
fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
    // Get default branch
    let default_branch = repo.default_branch();

    // Get previous branch
    let previous_branch = repo.switch_previous();

    // Get markers
    let markers: Vec<serde_json::Value> = all_markers(repo)
        .into_iter()
        .map(|m| {
            serde_json::json!({
                "branch": m.branch,
                "marker": m.marker,
                "set_at": if m.set_at > 0 { Some(m.set_at) } else { None }
            })
        })
        .collect();

    // Get CI status cache
    let mut ci_entries = CachedCiStatus::list_all(repo);
    ci_entries.sort_by(|a, b| {
        b.1.checked_at
            .cmp(&a.1.checked_at)
            .then_with(|| a.0.cmp(&b.0))
    });
    let ci_status: Vec<serde_json::Value> = ci_entries
        .into_iter()
        .map(|(branch, cached)| {
            let status = cached
                .status
                .as_ref()
                .map(|s| -> &'static str { s.ci_status.into() });
            serde_json::json!({
                "branch": branch,
                "status": status,
                "checked_at": cached.checked_at,
                "head": cached.head
            })
        })
        .collect();

    // Get log files, partitioned into command log and hook output
    let log_dir = repo.wt_logs_dir();
    let (command_log, hook_output): (Vec<serde_json::Value>, Vec<serde_json::Value>) =
        if log_dir.exists() {
            let mut all_entries: Vec<_> = std::fs::read_dir(&log_dir)?
                .filter_map(|e| e.ok())
                .filter(|e| e.path().is_file() && is_wt_log_file(&e.path()))
                .collect();

            all_entries.sort_by(|a, b| {
                let a_time = a.metadata().and_then(|m| m.modified()).ok();
                let b_time = b.metadata().and_then(|m| m.modified()).ok();
                b_time.cmp(&a_time)
            });

            let to_json = |entry: &std::fs::DirEntry| -> serde_json::Value {
                let path = entry.path();
                let name = path
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string();
                let meta = entry.metadata().ok();
                let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
                let modified = meta
                    .and_then(|m| m.modified().ok())
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .map(|d| d.as_secs());

                serde_json::json!({
                    "file": name,
                    "size": size,
                    "modified_at": modified
                })
            };

            let mut cmd_log = Vec::new();
            let mut hook_out = Vec::new();
            for entry in &all_entries {
                let name = entry.file_name().to_string_lossy().to_string();
                if is_command_log_file(&name) {
                    cmd_log.push(to_json(entry));
                } else {
                    hook_out.push(to_json(entry));
                }
            }
            (cmd_log, hook_out)
        } else {
            (vec![], vec![])
        };

    // Get vars data (all branches) — collect into BTreeMap for sorted output
    let all_vars: std::collections::BTreeMap<_, _> = repo.all_vars_entries().into_iter().collect();
    let vars_data: Vec<serde_json::Value> = all_vars
        .into_iter()
        .flat_map(|(branch, entries)| {
            entries.into_iter().map(move |(key, value)| {
                serde_json::json!({
                    "branch": branch,
                    "key": key,
                    "value": value
                })
            })
        })
        .collect();

    // Get hints
    let hints = repo.list_shown_hints();

    let output = serde_json::json!({
        "default_branch": default_branch,
        "previous_branch": previous_branch,
        "markers": markers,
        "ci_status": ci_status,
        "vars": vars_data,
        "command_log": command_log,
        "hook_output": hook_output,
        "hints": hints
    });

    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

/// Output state as human-readable table
fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
    // Build complete output as a string
    let mut out = String::new();

    // Show default branch cache
    writeln!(out, "{}", format_heading("DEFAULT BRANCH", None))?;
    match repo.default_branch() {
        Some(branch) => writeln!(out, "{}", format_with_gutter(&branch, None))?,
        None => writeln!(out, "{}", format_with_gutter("(not available)", None))?,
    }
    writeln!(out)?;

    // Show previous branch (for `wt switch -`)
    writeln!(out, "{}", format_heading("PREVIOUS BRANCH", None))?;
    match repo.switch_previous() {
        Some(prev) => writeln!(out, "{}", format_with_gutter(&prev, None))?,
        None => writeln!(out, "{}", format_with_gutter("(none)", None))?,
    }
    writeln!(out)?;

    // Show branch markers
    writeln!(out, "{}", format_heading("BRANCH MARKERS", None))?;
    let markers = all_markers(repo);
    if markers.is_empty() {
        writeln!(out, "{}", format_with_gutter("(none)", None))?;
    } else {
        let rows: Vec<Vec<String>> = markers
            .iter()
            .map(|entry| {
                let age = format_relative_time_short(entry.set_at as i64);
                vec![entry.branch.clone(), entry.marker.clone(), age]
            })
            .collect();
        let rendered = crate::md_help::render_data_table(&["Branch", "Marker", "Age"], &rows);
        writeln!(out, "{}", rendered.trim_end())?;
    }
    writeln!(out)?;

    // Show vars data
    writeln!(out, "{}", format_heading("VARS", None))?;
    let all_vars: std::collections::BTreeMap<_, _> = repo.all_vars_entries().into_iter().collect();

    if all_vars.is_empty() {
        writeln!(out, "{}", format_with_gutter("(none)", None))?;
    } else {
        let headers = &["Branch", "Key", "Value"];
        let mut rows: Vec<Vec<String>> = Vec::new();
        for (branch, entries) in &all_vars {
            for (key, value) in entries {
                // Truncate long values for display
                let display_value = if value.len() > 40 {
                    format!("{}...", &value[..37])
                } else {
                    value.to_string()
                };
                rows.push(vec![branch.to_string(), key.to_string(), display_value]);
            }
        }
        let rendered = crate::md_help::render_data_table(headers, &rows);
        writeln!(out, "{}", rendered.trim_end())?;
    }
    writeln!(out)?;

    // Show CI status cache
    writeln!(out, "{}", format_heading("CI STATUS CACHE", None))?;
    let mut entries = CachedCiStatus::list_all(repo);
    // Sort by age (most recent first), then by branch name for ties
    entries.sort_by(|a, b| {
        b.1.checked_at
            .cmp(&a.1.checked_at)
            .then_with(|| a.0.cmp(&b.0))
    });
    if entries.is_empty() {
        writeln!(out, "{}", format_with_gutter("(none)", None))?;
    } else {
        let rows: Vec<Vec<String>> = entries
            .iter()
            .map(|(branch, cached)| {
                let status = match &cached.status {
                    Some(pr_status) => {
                        let s: &'static str = pr_status.ci_status.into();
                        s.to_string()
                    }
                    None => "none".to_string(),
                };
                let age = format_relative_time_short(cached.checked_at as i64);
                let head: String = cached.head.chars().take(8).collect();
                vec![branch.clone(), status, age, head]
            })
            .collect();
        let rendered =
            crate::md_help::render_data_table(&["Branch", "Status", "Age", "Head"], &rows);
        writeln!(out, "{}", rendered.trim_end())?;
    }
    writeln!(out)?;

    // Show hints
    writeln!(out, "{}", format_heading("HINTS", None))?;
    let hints = repo.list_shown_hints();
    if hints.is_empty() {
        writeln!(out, "{}", format_with_gutter("(none)", None))?;
    } else {
        for hint in hints {
            writeln!(out, "{}", format_with_gutter(&hint, None))?;
        }
    }
    writeln!(out)?;

    // Show command log
    render_command_log(&mut out, repo)?;
    writeln!(out)?;

    // Show hook output logs
    render_hook_output(&mut out, repo)?;

    // Display through pager (fall back to stderr if pager unavailable)
    if let Err(e) = show_help_in_pager(&out, true) {
        log::debug!("Pager invocation failed: {}", e);
        // Fall back to direct output via eprintln (matches help behavior)
        eprintln!("{}", out);
    }

    Ok(())
}

// ==================== Vars Operations ====================

/// Validate a vars key name: letters, digits, hyphens, underscores only.
fn validate_vars_key(key: &str) -> anyhow::Result<()> {
    if key.is_empty() {
        anyhow::bail!("Key cannot be empty");
    }
    if !key
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        anyhow::bail!(
            "Invalid key {key:?}: keys must contain only letters, digits, hyphens, and underscores"
        );
    }
    Ok(())
}

/// Handle vars get
pub fn handle_vars_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {
    validate_vars_key(key)?;
    let repo = Repository::current()?;
    let branch_name = match branch {
        Some(b) => b,
        None => repo.require_current_branch("get variable for current branch")?,
    };

    let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
    if let Some(value) = repo.config_value(&config_key)? {
        println!("{value}");
    }
    Ok(())
}

/// Handle vars set
pub fn handle_vars_set(key: &str, value: &str, branch: Option<String>) -> anyhow::Result<()> {
    validate_vars_key(key)?;
    let repo = Repository::current()?;
    let branch_name = match branch {
        Some(b) => b,
        None => repo.require_current_branch("set variable for current branch")?,
    };

    let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
    repo.run_command(&["config", &config_key, value])?;

    eprintln!(
        "{}",
        success_message(cformat!("Set <bold>{key}</> for <bold>{branch_name}</>"))
    );
    Ok(())
}

/// Handle vars list
pub fn handle_vars_list(branch: Option<String>) -> anyhow::Result<()> {
    let repo = Repository::current()?;
    let branch_name = match branch {
        Some(b) => b,
        None => repo.require_current_branch("list variables for current branch")?,
    };

    let entries: Vec<_> = repo.vars_entries(&branch_name).into_iter().collect();
    if entries.is_empty() {
        eprintln!(
            "{}",
            info_message(cformat!("No variables for <bold>{branch_name}</>"))
        );
    } else {
        for (key, value) in &entries {
            println!("{key}\t{value}");
        }
    }
    Ok(())
}

/// Handle vars clear
pub fn handle_vars_clear(
    key: Option<&str>,
    all: bool,
    branch: Option<String>,
) -> anyhow::Result<()> {
    let repo = Repository::current()?;
    let branch_name = match branch {
        Some(b) => b,
        None => repo.require_current_branch("clear variable for current branch")?,
    };

    if !all && key.is_none() {
        anyhow::bail!("Specify a key to clear, or use --all to clear all keys");
    }

    if all {
        let entries: Vec<_> = repo.vars_entries(&branch_name).into_iter().collect();
        if entries.is_empty() {
            eprintln!(
                "{}",
                info_message(cformat!("No variables for <bold>{branch_name}</>"))
            );
        } else {
            let count = entries.len();
            for (key, _) in entries {
                let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
                let _ = repo.run_command(&["config", "--unset", &config_key]);
            }
            eprintln!(
                "{}",
                success_message(cformat!(
                    "Cleared <bold>{count}</> variable{} for <bold>{branch_name}</>",
                    if count == 1 { "" } else { "s" }
                ))
            );
        }
    } else {
        let key = key.expect("key required when --all not set");
        validate_vars_key(key)?;
        let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
        if repo
            .run_command(&["config", "--unset", &config_key])
            .is_ok()
        {
            eprintln!(
                "{}",
                success_message(cformat!(
                    "Cleared <bold>{key}</> for <bold>{branch_name}</>"
                ))
            );
        } else {
            eprintln!(
                "{}",
                info_message(cformat!(
                    "No variable <bold>{key}</> for <bold>{branch_name}</>"
                ))
            );
        }
    }
    Ok(())
}

/// Clear all vars entries across all branches (used by handle_state_clear_all).
fn clear_all_vars(repo: &Repository) -> anyhow::Result<usize> {
    let all_vars = repo.all_vars_entries();
    let mut cleared = 0;
    for (branch, entries) in &all_vars {
        for key in entries.keys() {
            let config_key = format!("worktrunk.state.{branch}.vars.{key}");
            let _ = repo.run_command(&["config", "--unset", &config_key]);
            cleared += 1;
        }
    }
    Ok(cleared)
}

// ==================== Marker Helpers ====================

/// Marker entry with branch, text, and timestamp
pub(super) struct MarkerEntry {
    pub branch: String,
    pub marker: String,
    pub set_at: u64,
}

/// Get all branch markers from git config with timestamps
pub(super) fn all_markers(repo: &Repository) -> Vec<MarkerEntry> {
    let output = repo
        .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])
        .unwrap_or_default();

    let mut markers = Vec::new();
    for line in output.lines() {
        // Format: "worktrunk.state.<branch>.marker json_value"
        let Some((key, value)) = line.split_once(' ') else {
            continue;
        };
        let Some(branch) = key
            .strip_prefix("worktrunk.state.")
            .and_then(|s| s.strip_suffix(".marker"))
        else {
            continue;
        };
        let Ok(parsed) = serde_json::from_str::<serde_json::Value>(value) else {
            continue; // Skip invalid JSON
        };
        let Some(marker) = parsed.get("marker").and_then(|v| v.as_str()) else {
            continue; // Skip if "marker" field is missing
        };
        let set_at = parsed.get("set_at").and_then(|v| v.as_u64()).unwrap_or(0);
        markers.push(MarkerEntry {
            branch: branch.to_string(),
            marker: marker.to_string(),
            set_at,
        });
    }

    // Sort by age (most recent first), then by branch name for ties
    markers.sort_by(|a, b| {
        b.set_at
            .cmp(&a.set_at)
            .then_with(|| a.branch.cmp(&b.branch))
    });
    markers
}