worktrunk 0.37.0

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
//! JSON output types for `wt list --format=json`
//!
//! This module defines the structured JSON output format, designed for:
//! - Query-friendly filtering with jq
//! - Self-describing field names
//! - Alignment with CLI status subcolumns
//!
//! ## Structure
//!
//! Fields are organized by concept, matching the status display subcolumns:
//! - `working_tree`: staged/modified/untracked changes
//! - `main_state`: relationship to the default branch (would_conflict, same_commit, integrated, diverged, ahead, behind)
//! - `operation_state`: git operations in progress (conflicts, rebase, merge)
//! - `main`: relationship to the default branch (ahead/behind/diff counts)
//! - `remote`: relationship to tracking branch
//! - `worktree`: worktree-specific state (locked, prunable, etc.)

use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;

use schemars::JsonSchema;
use serde::Serialize;
use worktrunk::git::{LineDiff, Repository};

use super::ci_status::{CiSource, PrStatus};
use super::model::{ItemKind, ListItem, UpstreamStatus};

/// JSON output for a single list item
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonItem {
    /// Branch name, null for detached HEAD
    pub branch: Option<String>,

    /// Filesystem path to the worktree
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,

    /// Item kind: "worktree" or "branch"
    pub kind: &'static str,

    /// Commit information
    pub commit: JsonCommit,

    /// Working tree state (staged, modified, untracked changes)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_tree: Option<JsonWorkingTree>,

    /// Default branch relationship: would_conflict, same_commit, integrated, diverged, ahead, behind
    /// (null for default branch itself)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub main_state: Option<&'static str>,

    /// Why branch is integrated (only present when main_state == "integrated")
    /// Values: ancestor, trees_match, no_added_changes, merge_adds_nothing
    #[serde(skip_serializing_if = "Option::is_none")]
    pub integration_reason: Option<&'static str>,

    /// Git operation in progress: conflicts, rebase, merge (null when none)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation_state: Option<&'static str>,

    /// Relationship to default branch (absent when is_main == true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub main: Option<JsonMain>,

    /// Relationship to remote tracking branch (absent when no tracking branch)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote: Option<JsonRemote>,

    /// Worktree-specific state
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worktree: Option<JsonWorktree>,

    /// This is the main worktree
    pub is_main: bool,

    /// This is the current worktree (matches repo discovery path: PWD or `-C`)
    pub is_current: bool,

    /// This was the previous worktree (from `worktrunk.history`)
    pub is_previous: bool,

    /// CI status from PR or branch workflow
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ci: Option<JsonCi>,

    /// Dev server URL from project config template
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Whether the dev server URL's port is listening
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url_active: Option<bool>,

    /// LLM-generated branch summary (requires `[list] summary = true`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,

    /// Pre-formatted statusline for statusline tools (tmux, starship)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub statusline: Option<String>,

    /// Raw status symbols without ANSI colors (e.g., "+! ✖ ↑")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbols: Option<String>,

    /// Custom variables stored via `wt config state vars`
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub vars: BTreeMap<String, String>,
}

/// Commit information
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonCommit {
    /// Full commit SHA
    pub sha: String,

    /// Short commit SHA (7 characters)
    pub short_sha: String,

    /// Commit message (first line)
    pub message: String,

    /// Unix timestamp of commit
    pub timestamp: i64,
}

/// Working tree state
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonWorkingTree {
    /// Has staged files (+)
    pub staged: bool,

    /// Has modified files (!)
    pub modified: bool,

    /// Has untracked files (?)
    pub untracked: bool,

    /// Has renamed files (»)
    pub renamed: bool,

    /// Has deleted files (✘)
    pub deleted: bool,

    /// Lines added/deleted in working tree vs HEAD
    #[serde(skip_serializing_if = "Option::is_none")]
    pub diff: Option<JsonDiff>,
}

/// Line diff statistics
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonDiff {
    pub added: usize,
    pub deleted: usize,
}

impl From<LineDiff> for JsonDiff {
    fn from(d: LineDiff) -> Self {
        Self {
            added: d.added,
            deleted: d.deleted,
        }
    }
}

/// Relationship to default branch
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonMain {
    /// Commits ahead of default branch
    pub ahead: usize,

    /// Commits behind default branch
    pub behind: usize,

    /// Lines added/deleted vs default branch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub diff: Option<JsonDiff>,
}

/// Relationship to remote tracking branch
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonRemote {
    /// Remote name (e.g., "origin")
    pub name: String,

    /// Remote branch name (e.g., "feature-login")
    pub branch: String,

    /// Commits ahead of remote
    pub ahead: usize,

    /// Commits behind remote
    pub behind: usize,
}

/// Worktree-specific state
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonWorktree {
    /// Worktree state: "branch_worktree_mismatch", "prunable", "locked" (absent when normal)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<&'static str>,

    /// Reason for locked/prunable state
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,

    /// HEAD is detached (not on a branch)
    pub detached: bool,
}

/// CI status from PR or branch workflow
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonCi {
    /// CI status: "passed", "running", "failed", "conflicts", "no-ci", "error"
    pub status: &'static str,

    /// Source: "pr" or "branch"
    pub source: CiSource,

    /// True if local HEAD differs from remote HEAD (unpushed changes)
    pub stale: bool,

    /// URL to the PR/MR (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

impl JsonItem {
    /// Convert a ListItem to the new JSON structure
    ///
    /// `all_vars` is pre-fetched vars data for all branches (from `repo.all_vars_entries()`),
    /// avoiding N+1 git process spawns. Entries are moved out via `.remove()` to avoid cloning.
    pub fn from_list_item(
        item: &ListItem,
        all_vars: &mut HashMap<String, BTreeMap<String, String>>,
    ) -> Self {
        let (kind_str, worktree_data) = match &item.kind {
            ItemKind::Worktree(data) => ("worktree", Some(data.as_ref())),
            ItemKind::Branch => ("branch", None),
        };

        let is_main = worktree_data.is_some_and(|d| d.is_main);
        let is_current = worktree_data.is_some_and(|d| d.is_current);
        let is_previous = worktree_data.is_some_and(|d| d.is_previous);

        // Commit info — empty strings for null OID (unborn branches)
        let (sha, short_sha) = if item.head == worktrunk::git::NULL_OID {
            (String::new(), String::new())
        } else {
            let sha = item.head.clone();
            let short_sha = sha[..7.min(sha.len())].to_string();
            (sha, short_sha)
        };
        let commit = JsonCommit {
            sha,
            short_sha,
            message: item
                .commit
                .as_ref()
                .map(|c| c.commit_message.clone())
                .unwrap_or_default(),
            timestamp: item.commit.as_ref().map(|c| c.timestamp).unwrap_or(0),
        };

        // Working tree: read directly from `WorktreeData`, not from
        // `status_symbols.working_tree`. `status_symbols` may be set by
        // the metadata-only fallback in `compute_status_symbols` (locked
        // / prunable / mismatched worktrees) carrying a default
        // `WorkingTreeStatus`. The JSON output must reflect whether
        // `WorkingTreeDiff` actually loaded the field — collapsing
        // "unknown" into "clean" misleads consumers.
        let working_tree = worktree_data.and_then(|data| {
            data.working_tree_status.map(|wt| JsonWorkingTree {
                staged: wt.staged,
                modified: wt.modified,
                untracked: wt.untracked,
                renamed: wt.renamed,
                deleted: wt.deleted,
                diff: data.working_tree_diff.map(JsonDiff::from),
            })
        });

        // Main state and integration reason. Unresolved gate 3 → both
        // absent from JSON. Resolved → emit as today.
        let main_state = item.status_symbols.main_state.and_then(|s| s.as_json_str());
        let integration_reason = item
            .status_symbols
            .main_state
            .and_then(|s| s.integration_reason())
            .map(|r| r.into());

        // Operation state (conflicts, rebase, merge). Unresolved gate 2
        // (operation family) → absent from JSON.
        let operation_state = item
            .status_symbols
            .operation_state
            .and_then(|s| s.as_json_str());

        // Main relationship (absent when is_main)
        let main = if is_main {
            None
        } else {
            item.counts.map(|counts| JsonMain {
                ahead: counts.ahead,
                behind: counts.behind,
                diff: item.branch_diff.map(|bd| JsonDiff::from(bd.diff)),
            })
        };

        // Remote relationship
        let remote = item
            .upstream
            .as_ref()
            .and_then(|u| upstream_to_json(u, &item.branch));

        // Worktree state
        let worktree = worktree_data.map(|data| {
            let (state, reason) = worktree_state_to_json(data, &item.status_symbols);
            JsonWorktree {
                state,
                reason,
                detached: data.detached,
            }
        });

        // Path
        let path = worktree_data.map(|d| d.path.clone());

        // CI status
        let ci = item
            .pr_status
            .as_ref()
            .and_then(|opt| opt.as_ref())
            .map(JsonCi::from);

        // Statusline and symbols (raw, without ANSI codes)
        let statusline = item.display.statusline.clone();
        let symbols = Some(format_raw_symbols(&item.status_symbols)).filter(|s| !s.is_empty());

        // Per-branch vars data (pre-fetched, moved out to avoid cloning)
        let vars = item
            .branch
            .as_deref()
            .and_then(|b| all_vars.remove(b))
            .unwrap_or_default();

        // Summary: flatten Option<Option<String>> → Option<String>
        let summary = item.summary.as_ref().and_then(|s| s.clone());

        JsonItem {
            branch: item.branch.clone(),
            path,
            kind: kind_str,
            commit,
            working_tree,
            main_state,
            integration_reason,
            operation_state,
            main,
            remote,
            worktree,
            is_main,
            is_current,
            is_previous,
            ci,
            url: item.url.clone(),
            url_active: item.url_active,
            summary,
            statusline,
            symbols,
            vars,
        }
    }
}

/// Convert UpstreamStatus to JsonRemote
fn upstream_to_json(upstream: &UpstreamStatus, branch: &Option<String>) -> Option<JsonRemote> {
    upstream.active().map(|active| {
        // Use local branch name since UpstreamStatus only stores the remote name,
        // not the full tracking refspec. In most cases these match (e.g., feature -> origin/feature).
        JsonRemote {
            name: active.remote.to_string(),
            branch: branch.clone().unwrap_or_default(),
            ahead: active.ahead,
            behind: active.behind,
        }
    })
}

/// Extract worktree state and reason from WorktreeData
fn worktree_state_to_json(
    data: &super::model::WorktreeData,
    status_symbols: &super::model::StatusSymbols,
) -> (Option<&'static str>, Option<String>) {
    use super::model::WorktreeState;

    // Check status symbols for worktree state. `None` means gate 2
    // (metadata family) hasn't been populated yet; fall through to the
    // direct-field fallback below.
    match status_symbols.worktree_state {
        None | Some(WorktreeState::None) => {}
        Some(WorktreeState::Branch) => return (Some("no_worktree"), None),
        Some(WorktreeState::BranchWorktreeMismatch) => {
            return (Some("branch_worktree_mismatch"), None);
        }
        Some(WorktreeState::Prunable) => return (Some("prunable"), data.prunable.clone()),
        Some(WorktreeState::Locked) => return (Some("locked"), data.locked.clone()),
    }

    // Fallback: check direct fields when status_symbols hasn't resolved
    // worktree_state yet. This can happen early in progressive rendering
    // before status is computed.
    if data.is_prunable() {
        return (Some("prunable"), data.prunable.clone());
    }
    if data.locked.is_some() {
        return (Some("locked"), data.locked.clone());
    }

    (None, None)
}

impl From<&PrStatus> for JsonCi {
    fn from(pr: &PrStatus) -> Self {
        Self {
            status: pr.ci_status.into(),
            source: pr.source,
            stale: pr.is_stale,
            url: pr.url.clone(),
        }
    }
}

/// Format status symbols as raw characters (no ANSI codes).
///
/// Unresolved gates (`None` fields) contribute nothing — their symbols are
/// simply absent from the output string, not replaced by a placeholder.
/// This matches the per-symbol atomic model: machine consumers see only the
/// symbols that have been computed so far.
fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {
    let mut result = String::new();

    // Working tree symbols (gate 1)
    if let Some(wt) = symbols.working_tree {
        result.push_str(&wt.to_symbols());
    }

    // Main state (gate 3) — merged column: ^✗_⊂↕↑↓
    if let Some(ms) = symbols.main_state {
        let s = ms.to_string();
        if !s.is_empty() {
            result.push_str(&s);
        }
    }

    // Upstream divergence (gate 4)
    if let Some(div) = symbols.upstream_divergence {
        let s = div.symbol();
        if !s.is_empty() {
            result.push_str(s);
        }
    }

    // Worktree state (gate 2) — operations (✘⤴⤵) take priority over
    // location (/⚑⊟⊞). Gate 2 is "operation_state is Some"; the metadata
    // worktree_state is filled synchronously and always Some by the time
    // the operation family is known.
    if let Some(op) = symbols.operation_state {
        let s = op.to_string();
        if !s.is_empty() {
            result.push_str(&s);
        } else if let Some(wt_state) = symbols.worktree_state {
            let s = wt_state.to_string();
            if !s.is_empty() {
                result.push_str(&s);
            }
        }
    }

    // User marker (gate 5)
    if let Some(Some(ref marker)) = symbols.user_marker {
        result.push_str(marker);
    }

    result
}

/// Convert a list of ListItems to JSON output
///
/// Fetches all vars data in a single git call, then distributes per-branch.
pub fn to_json_items(items: &[ListItem], repo: &Repository) -> Vec<JsonItem> {
    let mut all_vars = repo.all_vars_entries();
    items
        .iter()
        .map(|item| JsonItem::from_list_item(item, &mut all_vars))
        .collect()
}

#[cfg(test)]
mod tests {
    use insta::assert_snapshot;

    use super::*;
    use crate::commands::list::ci_status::CiStatus;
    use crate::commands::list::model::{
        ActiveGitOperation, Divergence, MainState, OperationState, StatusSymbols,
        WorkingTreeStatus, WorktreeData, WorktreeState,
    };

    // ============================================================================
    // JsonDiff Tests
    // ============================================================================

    #[test]
    fn test_json_diff_from_line_diff() {
        let nonzero = JsonDiff::from(LineDiff {
            added: 10,
            deleted: 5,
        });
        assert_eq!(nonzero.added, 10);
        assert_eq!(nonzero.deleted, 5);

        let zeros = JsonDiff::from(LineDiff {
            added: 0,
            deleted: 0,
        });
        assert_eq!(zeros.added, 0);
        assert_eq!(zeros.deleted, 0);
    }

    // ============================================================================
    // JsonCi::from Tests
    // ============================================================================

    #[test]
    fn test_json_ci_from_pr_status() {
        // Full field mapping with URL
        let passed = JsonCi::from(&PrStatus {
            ci_status: CiStatus::Passed,
            source: CiSource::PullRequest,
            is_stale: false,
            url: Some("https://github.com/org/repo/pull/123".to_string()),
        });
        assert_eq!(passed.status, "passed");
        assert_eq!(passed.source, CiSource::PullRequest);
        assert!(!passed.stale);
        assert_eq!(
            passed.url,
            Some("https://github.com/org/repo/pull/123".to_string())
        );

        // Stale branch with no URL
        let failed = JsonCi::from(&PrStatus {
            ci_status: CiStatus::Failed,
            source: CiSource::Branch,
            is_stale: true,
            url: None,
        });
        assert_eq!(failed.status, "failed");
        assert_eq!(failed.source, CiSource::Branch);
        assert!(failed.stale);
        assert!(failed.url.is_none());

        // All status string mappings
        let status_mappings = [
            (CiStatus::Running, "running"),
            (CiStatus::Conflicts, "conflicts"),
            (CiStatus::NoCI, "no-ci"),
            (CiStatus::Error, "error"),
        ];
        for (ci_status, expected) in status_mappings {
            let json = JsonCi::from(&PrStatus {
                ci_status,
                source: CiSource::Branch,
                is_stale: false,
                url: None,
            });
            assert_eq!(json.status, expected);
        }
    }

    // ============================================================================
    // upstream_to_json Tests
    // ============================================================================

    #[test]
    fn test_upstream_to_json_with_remote() {
        let upstream = UpstreamStatus {
            remote: Some("origin".to_string()),
            ahead: 3,
            behind: 2,
        };
        let branch = Some("feature".to_string());
        let json = upstream_to_json(&upstream, &branch);
        assert!(json.is_some());
        let json = json.unwrap();
        assert_eq!(json.name, "origin");
        assert_eq!(json.branch, "feature");
        assert_eq!(json.ahead, 3);
        assert_eq!(json.behind, 2);
    }

    #[test]
    fn test_upstream_to_json_no_remote() {
        let upstream = UpstreamStatus {
            remote: None,
            ahead: 0,
            behind: 0,
        };
        let branch = Some("feature".to_string());
        let json = upstream_to_json(&upstream, &branch);
        assert!(json.is_none());
    }

    #[test]
    fn test_upstream_to_json_no_branch() {
        let upstream = UpstreamStatus {
            remote: Some("origin".to_string()),
            ahead: 1,
            behind: 0,
        };
        let branch = None;
        let json = upstream_to_json(&upstream, &branch);
        assert!(json.is_some());
        let json = json.unwrap();
        assert_eq!(json.branch, ""); // Empty string when branch is None
    }

    // ============================================================================
    // worktree_state_to_json Tests
    // ============================================================================

    fn make_worktree_data() -> WorktreeData {
        WorktreeData {
            path: PathBuf::from("/test/path"),
            is_main: false,
            is_current: false,
            is_previous: false,
            detached: false,
            locked: None,
            prunable: None,
            working_tree_diff: None,
            working_tree_status: None,
            has_conflicts: None,
            has_working_tree_conflicts: None,
            git_operation: Some(ActiveGitOperation::None),
            branch_worktree_mismatch: false,
            working_diff_display: None,
        }
    }

    fn make_status_symbols_with_worktree_state(state: WorktreeState) -> StatusSymbols {
        StatusSymbols {
            working_tree: Some(WorkingTreeStatus::default()),
            worktree_state: Some(state),
            main_state: Some(MainState::None),
            operation_state: Some(OperationState::None),
            upstream_divergence: Some(Divergence::None),
            user_marker: Some(None),
        }
    }

    #[test]
    fn test_worktree_state_to_json_none() {
        let data = make_worktree_data();
        let symbols = make_status_symbols_with_worktree_state(WorktreeState::None);
        let (state, reason) = worktree_state_to_json(&data, &symbols);
        assert!(state.is_none());
        assert!(reason.is_none());
    }

    #[test]
    fn test_worktree_state_to_json_no_worktree() {
        let data = make_worktree_data();
        let symbols = make_status_symbols_with_worktree_state(WorktreeState::Branch);
        let (state, reason) = worktree_state_to_json(&data, &symbols);
        assert_eq!(state, Some("no_worktree"));
        assert!(reason.is_none());
    }

    #[test]
    fn test_worktree_state_to_json_branch_worktree_mismatch() {
        let data = make_worktree_data();
        let symbols =
            make_status_symbols_with_worktree_state(WorktreeState::BranchWorktreeMismatch);
        let (state, reason) = worktree_state_to_json(&data, &symbols);
        assert_eq!(state, Some("branch_worktree_mismatch"));
        assert!(reason.is_none());
    }

    #[test]
    fn test_worktree_state_to_json_locked() {
        let mut data = make_worktree_data();
        data.locked = Some("manual lock".to_string());
        let symbols = make_status_symbols_with_worktree_state(WorktreeState::Locked);
        let (state, reason) = worktree_state_to_json(&data, &symbols);
        assert_eq!(state, Some("locked"));
        assert_eq!(reason, Some("manual lock".to_string()));
    }

    #[test]
    fn test_worktree_state_to_json_prunable() {
        let mut data = make_worktree_data();
        data.prunable = Some("gitdir file missing".to_string());
        let symbols = make_status_symbols_with_worktree_state(WorktreeState::Prunable);
        let (state, reason) = worktree_state_to_json(&data, &symbols);
        assert_eq!(state, Some("prunable"));
        assert_eq!(reason, Some("gitdir file missing".to_string()));
    }

    #[test]
    fn test_worktree_state_to_json_fallback_prunable() {
        let mut data = make_worktree_data();
        data.prunable = Some("missing gitdir".to_string());
        // Default status symbols — fallback to data fields
        let symbols = StatusSymbols::default();
        let (state, reason) = worktree_state_to_json(&data, &symbols);
        assert_eq!(state, Some("prunable"));
        assert_eq!(reason, Some("missing gitdir".to_string()));
    }

    #[test]
    fn test_worktree_state_to_json_fallback_locked() {
        let mut data = make_worktree_data();
        data.locked = Some("in use".to_string());
        let symbols = StatusSymbols::default();
        let (state, reason) = worktree_state_to_json(&data, &symbols);
        assert_eq!(state, Some("locked"));
        assert_eq!(reason, Some("in use".to_string()));
    }

    // ============================================================================
    // format_raw_symbols Tests
    // ============================================================================

    #[test]
    fn test_format_raw_symbols_empty() {
        let symbols = StatusSymbols::default();
        assert!(format_raw_symbols(&symbols).is_empty());
    }

    #[test]
    fn test_format_raw_symbols_each_category() {
        let working_tree = format_raw_symbols(&StatusSymbols {
            working_tree: Some(WorkingTreeStatus::new(true, true, true, false, false)),
            ..Default::default()
        });
        assert_snapshot!(working_tree, @"+!?");

        let main_state = format_raw_symbols(&StatusSymbols {
            main_state: Some(MainState::Ahead),
            ..Default::default()
        });
        assert_snapshot!(main_state, @"");

        let upstream = format_raw_symbols(&StatusSymbols {
            upstream_divergence: Some(Divergence::Behind),
            ..Default::default()
        });
        assert_snapshot!(upstream, @"");

        // Operation state takes priority over worktree state
        let operation = format_raw_symbols(&StatusSymbols {
            operation_state: Some(OperationState::Rebase),
            ..Default::default()
        });
        assert_snapshot!(operation, @"");

        // Worktree metadata renders only once the operation-family gate
        // has resolved to "no operation" — otherwise we can't rule out
        // ✘⤴⤵ taking priority. Callers that want just the metadata
        // symbol must set both `operation_state` and `worktree_state`.
        let worktree = format_raw_symbols(&StatusSymbols {
            operation_state: Some(OperationState::None),
            worktree_state: Some(WorktreeState::Locked),
            ..Default::default()
        });
        assert_snapshot!(worktree, @"");

        let marker = format_raw_symbols(&StatusSymbols {
            user_marker: Some(Some("\u{1f525}".to_string())),
            ..Default::default()
        });
        assert_snapshot!(marker, @"🔥");
    }

    #[test]
    fn test_format_raw_symbols_combined() {
        let result = format_raw_symbols(&StatusSymbols {
            working_tree: Some(WorkingTreeStatus::new(true, false, false, false, false)),
            main_state: Some(MainState::Behind),
            upstream_divergence: Some(Divergence::Ahead),
            ..Default::default()
        });
        assert_snapshot!(result, @"+↓⇡");
    }

    // ============================================================================
    // JSON Serialization Tests
    // ============================================================================

    #[test]
    fn test_json_serialization() {
        let commit = serde_json::to_string_pretty(&JsonCommit {
            sha: "abc123def456".to_string(),
            short_sha: "abc123d".to_string(),
            message: "Fix bug".to_string(),
            timestamp: 1700000000,
        })
        .unwrap();
        assert_snapshot!(commit, @r#"
        {
          "sha": "abc123def456",
          "short_sha": "abc123d",
          "message": "Fix bug",
          "timestamp": 1700000000
        }
        "#);

        let working_tree = serde_json::to_string_pretty(&JsonWorkingTree {
            staged: true,
            modified: false,
            untracked: true,
            renamed: false,
            deleted: false,
            diff: Some(JsonDiff {
                added: 10,
                deleted: 5,
            }),
        })
        .unwrap();
        assert_snapshot!(working_tree, @r#"
        {
          "staged": true,
          "modified": false,
          "untracked": true,
          "renamed": false,
          "deleted": false,
          "diff": {
            "added": 10,
            "deleted": 5
          }
        }
        "#);

        let main = serde_json::to_string_pretty(&JsonMain {
            ahead: 3,
            behind: 1,
            diff: Some(JsonDiff {
                added: 50,
                deleted: 20,
            }),
        })
        .unwrap();
        assert_snapshot!(main, @r#"
        {
          "ahead": 3,
          "behind": 1,
          "diff": {
            "added": 50,
            "deleted": 20
          }
        }
        "#);

        let remote = serde_json::to_string_pretty(&JsonRemote {
            name: "origin".to_string(),
            branch: "feature".to_string(),
            ahead: 2,
            behind: 0,
        })
        .unwrap();
        assert_snapshot!(remote, @r#"
        {
          "name": "origin",
          "branch": "feature",
          "ahead": 2,
          "behind": 0
        }
        "#);

        let worktree = serde_json::to_string_pretty(&JsonWorktree {
            state: Some("locked"),
            reason: Some("manual".to_string()),
            detached: false,
        })
        .unwrap();
        assert_snapshot!(worktree, @r#"
        {
          "state": "locked",
          "reason": "manual",
          "detached": false
        }
        "#);
    }

    fn test_repo() -> (worktrunk::testing::TestRepo, Repository) {
        let t = worktrunk::testing::TestRepo::new();
        let repo = Repository::at(t.path()).unwrap();
        (t, repo)
    }

    #[test]
    fn test_json_item_summary_present() {
        let (_tmp, repo) = test_repo();
        let mut all_vars = repo.all_vars_entries();

        let mut item = ListItem::new_branch("abc1234".into(), "feature".into());
        item.summary = Some(Some("Add login page".to_string()));
        let json_item = JsonItem::from_list_item(&item, &mut all_vars);
        assert_eq!(json_item.summary, Some("Add login page".to_string()));
    }

    #[test]
    fn test_json_item_summary_absent() {
        let (_tmp, repo) = test_repo();
        let mut all_vars = repo.all_vars_entries();

        let mut item = ListItem::new_branch("abc1234".into(), "feature".into());
        // Both "not collected" and "no summary" should be absent in JSON
        assert!(
            JsonItem::from_list_item(&item, &mut all_vars)
                .summary
                .is_none()
        );

        item.summary = Some(None);
        assert!(
            JsonItem::from_list_item(&item, &mut all_vars)
                .summary
                .is_none()
        );
    }

    #[test]
    fn test_json_ci_serialization() {
        let json = serde_json::to_string_pretty(&JsonCi {
            status: "passed",
            source: CiSource::PullRequest,
            stale: false,
            url: Some("https://example.com".to_string()),
        })
        .unwrap();
        assert_snapshot!(json, @r#"
        {
          "status": "passed",
          "source": "pr",
          "stale": false,
          "url": "https://example.com"
        }
        "#);
    }
}