git-parsec 0.3.0

Git worktree lifecycle manager — ticket to PR in one command. Parallel AI agent workflows with Jira & GitHub Issues integration.
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
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
use std::collections::HashSet;
use std::path::Path;

use anyhow::{Context, Result};
use colored::Colorize;

use crate::config::{ParsecConfig, TrackerProvider};
use crate::conflict;
use crate::git;
use crate::github;
use crate::gitlab;
use crate::output::{self, BoardTicketDisplay, Mode};
use crate::tracker;
use crate::tracker::jira::JiraTracker;
use crate::worktree::WorktreeManager;

pub async fn start(
    repo: &Path,
    ticket: &str,
    base: Option<&str>,
    title: Option<String>,
    on: Option<&str>,
    existing_branch: Option<&str>,
    mode: Mode,
) -> Result<()> {
    let mut config = ParsecConfig::load()?;
    let repo_root = git::get_repo_root(repo)?;
    config.resolve_for_repo(&repo_root);

    let ticket_title = if let Some(t) = title {
        // Manual title provided — skip tracker lookup
        Some(t)
    } else {
        // Fetch from tracker
        match tracker::fetch_ticket(&config, ticket, Some(&repo_root)).await {
            Ok(info) => info.map(|t| t.title),
            Err(e) => {
                eprintln!("warning: could not fetch ticket info: {e}");
                None
            }
        }
    };

    let manager = WorktreeManager::new(repo, &config)?;
    let workspace = manager.create(ticket, base, ticket_title, on, existing_branch)?;

    output::print_start(&workspace, mode);

    // Auto-transition ticket status
    if let Some(ref auto) = config.tracker.auto_transition {
        if let Some(ref status) = auto.on_start {
            tracker::try_transition(&config, ticket, status).await;
        }
    }

    if let Err(e) = crate::oplog::record(
        manager.repo_root(),
        crate::oplog::OpKind::Start,
        Some(ticket),
        &format!("Created workspace at {}", workspace.path.display()),
        Some(crate::oplog::UndoInfo {
            branch: Some(workspace.branch.clone()),
            base_branch: Some(workspace.base_branch.clone()),
            path: Some(workspace.path.clone()),
            ticket_title: workspace.ticket_title.clone(),
        }),
    ) {
        eprintln!("warning: failed to write oplog: {e}");
    }

    Ok(())
}

pub async fn adopt(
    repo: &Path,
    ticket: &str,
    branch: Option<&str>,
    title: Option<String>,
    mode: Mode,
) -> Result<()> {
    let mut config = ParsecConfig::load()?;
    let repo_root = git::get_repo_root(repo)?;
    config.resolve_for_repo(&repo_root);

    let ticket_title = if let Some(t) = title {
        Some(t)
    } else {
        match tracker::fetch_ticket(&config, ticket, Some(&repo_root)).await {
            Ok(info) => info.map(|t| t.title),
            Err(_) => None,
        }
    };

    let manager = WorktreeManager::new(repo, &config)?;
    let workspace = manager.adopt(ticket, branch, ticket_title)?;

    output::print_adopt(&workspace, mode);

    if let Err(e) = crate::oplog::record(
        manager.repo_root(),
        crate::oplog::OpKind::Adopt,
        Some(ticket),
        &format!(
            "Adopted branch '{}' at {}",
            workspace.branch,
            workspace.path.display()
        ),
        Some(crate::oplog::UndoInfo {
            branch: Some(workspace.branch.clone()),
            base_branch: Some(workspace.base_branch.clone()),
            path: Some(workspace.path.clone()),
            ticket_title: workspace.ticket_title.clone(),
        }),
    ) {
        eprintln!("warning: failed to write oplog: {e}");
    }

    // Auto-detect existing PR for the adopted branch
    if let Ok(remote_url) = git::run_output(manager.repo_root(), &["remote", "get-url", "origin"]) {
        if let Ok(Some(pr_number)) =
            github::find_pr_by_branch(&remote_url, &workspace.branch, &config).await
        {
            // Record synthetic Ship entry so merge/pr-status can find the PR
            let pr_url = if let Some(remote) = github::parse_github_remote(&remote_url) {
                format!(
                    "https://{}/{}/{}/pull/{}",
                    remote.host, remote.owner, remote.repo, pr_number
                )
            } else {
                format!("pull/{}", pr_number)
            };
            if let Err(e) = crate::oplog::record(
                manager.repo_root(),
                crate::oplog::OpKind::Ship,
                Some(ticket),
                &format!("Adopted branch '{}' -> {}", workspace.branch, pr_url),
                None,
            ) {
                eprintln!("warning: failed to record PR in oplog: {e}");
            } else if mode != Mode::Quiet {
                eprintln!("  Detected existing PR #{}", pr_number);
            }
        }
    }

    Ok(())
}

pub async fn list(repo: &Path, no_pr: bool, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;
    let workspaces = manager.list()?;

    // Build PR info map from oplog Ship entries
    let mut pr_map: std::collections::HashMap<String, (u64, String)> =
        std::collections::HashMap::new();
    if !no_pr {
        if let Ok(oplog) = crate::oplog::OpLog::load(manager.repo_root()) {
            let remote_url = git::get_remote_url(manager.repo_root()).ok();
            for entry in &oplog.entries {
                if matches!(entry.op, crate::oplog::OpKind::Ship) {
                    if let Some(ref ticket) = entry.ticket {
                        if let Some(pr_url) = extract_pr_url(&entry.detail) {
                            if let Some(pr_num) = extract_pr_number(&pr_url) {
                                pr_map
                                    .entry(ticket.clone())
                                    .or_insert((pr_num, "open".to_string()));
                            }
                        }
                    }
                }
            }

            // Fetch live PR status from GitHub
            if let Some(ref remote_url) = remote_url {
                for (_ticket, (pr_num, state)) in pr_map.iter_mut() {
                    if let Ok(Some(status)) =
                        github::get_pr_status(remote_url, *pr_num, &config).await
                    {
                        *state = status.state;
                    }
                }
            }
        }
    }

    output::print_list(&workspaces, &pr_map, mode);
    Ok(())
}

fn extract_pr_url(detail: &str) -> Option<String> {
    // Oplog detail for Ship contains the PR URL after " -> "
    detail
        .split(" -> ")
        .nth(1)
        .map(|s| s.trim().to_string())
        .filter(|s| s.starts_with("http"))
}

fn extract_pr_number(url: &str) -> Option<u64> {
    // Extract PR number from URL like "https://github.com/owner/repo/pull/123"
    url.rsplit('/').next().and_then(|s| s.parse().ok())
}

pub async fn status(repo: &Path, ticket: Option<&str>, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;

    let workspaces = match ticket {
        Some(t) => vec![manager.get(t)?],
        None => manager.list()?,
    };

    output::print_status(&workspaces, mode);
    Ok(())
}

pub async fn ship(
    repo: &Path,
    ticket: &str,
    draft: bool,
    no_pr: bool,
    base_override: Option<String>,
    mode: Mode,
) -> Result<()> {
    let mut config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;
    config.resolve_for_repo(manager.repo_root());

    // Phase 1: Push only (don't clean up yet)
    let mut result = manager.ship_push(ticket)?;

    // Resolve base branch: --base CLI > config default_base > worktree's base_branch
    if let Some(base) = base_override {
        result.base_branch = base;
    } else if let Some(ref default_base) = config.ship.default_base {
        result.base_branch = default_base.clone();
    }
    // else: keep the worktree's original base_branch

    // Phase 2: Create PR/MR (async)
    let mut pr_failed = false;
    if !no_pr && config.ship.auto_pr {
        let (ticket_title, ticket_url) =
            match tracker::fetch_ticket(&config, ticket, Some(manager.repo_root())).await {
                Ok(Some(t)) => (Some(t.title), t.url),
                _ => (None, None),
            };

        // Prefer freshly fetched title over stored one
        let effective_title = ticket_title.as_deref().or(result.ticket_title.as_deref());

        let pr_title = effective_title
            .map(|t| format!("{}: {}", result.ticket, t))
            .unwrap_or_else(|| result.ticket.clone());

        let pr_body = build_pr_body(&result.ticket, effective_title, ticket_url.as_deref());

        let remote_url = git::get_remote_url(manager.repo_root());
        if let Ok(ref remote_url) = remote_url {
            // Check if a PR already exists for this branch (#98)
            if let Ok(Some(existing_pr)) =
                github::find_pr_by_branch(remote_url, &result.branch, &config).await
            {
                let remote = github::parse_github_remote(remote_url);
                let pr_url = if let Some(r) = remote {
                    format!(
                        "https://{}/{}/{}/pull/{}",
                        r.host, r.owner, r.repo, existing_pr
                    )
                } else {
                    format!("PR #{}", existing_pr)
                };
                result.pr_url = Some(pr_url);
            } else {
                match github::create_pr(
                    remote_url,
                    &result.branch,
                    &result.base_branch,
                    &pr_title,
                    &pr_body,
                    draft || config.ship.draft,
                    &config,
                )
                .await
                {
                    Ok(Some(pr)) => {
                        result.pr_url = Some(pr.url);
                    }
                    Ok(None) => {
                        // GitHub had no token — try GitLab
                        match gitlab::create_mr(
                            remote_url,
                            &result.branch,
                            &result.base_branch,
                            &pr_title,
                            &pr_body,
                            draft || config.ship.draft,
                        )
                        .await
                        {
                            Ok(Some(mr)) => {
                                result.pr_url = Some(mr.url);
                            }
                            Ok(None) => {
                                eprintln!(
                                    "note: PR/MR creation skipped — no token found.\n      \
                                     Set PARSEC_GITHUB_TOKEN or PARSEC_GITLAB_TOKEN to enable."
                                );
                                pr_failed = true;
                            }
                            Err(e) => {
                                eprintln!("error: GitLab MR creation failed: {e}");
                                pr_failed = true;
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("error: PR creation failed: {e}");
                        pr_failed = true;
                    }
                }
            }
        }
    }

    // Auto-comment PR link on the ticket if configured
    if config.tracker.comment_on_ship {
        if let Some(ref pr_url) = result.pr_url {
            let comment_body = format!("PR opened: {}", pr_url);
            if let Err(e) =
                tracker::post_comment(&config, ticket, &comment_body, Some(manager.repo_root()))
                    .await
            {
                eprintln!("warning: failed to post comment on ticket: {e}");
            }
        }
    }

    if pr_failed {
        eprintln!(
            "note: worktree preserved at {} — fix the issue and retry `parsec ship {}`",
            manager
                .get(ticket)
                .map(|ws| ws.path.display().to_string())
                .unwrap_or_default(),
            ticket
        );
    }

    output::print_ship(&result, mode);

    // Auto-transition ticket status
    if let Some(ref auto) = config.tracker.auto_transition {
        if let Some(ref status) = auto.on_ship {
            tracker::try_transition(&config, ticket, status).await;
        }
    }

    if let Err(e) = crate::oplog::record(
        manager.repo_root(),
        crate::oplog::OpKind::Ship,
        Some(ticket),
        &format!(
            "Shipped branch '{}'{}{}",
            result.branch,
            result
                .pr_url
                .as_ref()
                .map(|u| format!(" -> {}", u))
                .unwrap_or_default(),
            if pr_failed {
                " (partial: PR failed)"
            } else {
                ""
            },
        ),
        Some(crate::oplog::UndoInfo {
            branch: Some(result.branch.clone()),
            base_branch: Some(result.base_branch.clone()),
            path: None,
            ticket_title: result.ticket_title.clone(),
        }),
    ) {
        eprintln!("warning: failed to write oplog: {e}");
    }

    if pr_failed {
        anyhow::bail!("Ship partial: branch pushed but PR/MR creation failed. Worktree preserved.");
    }

    Ok(())
}

pub async fn clean(repo: &Path, all: bool, dry_run: bool, orphans: bool, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;

    if orphans {
        // Orphan-only mode: just clean state entries without existing directories
        let orphan_list = manager.clean_orphans(dry_run)?;
        output::print_clean(&orphan_list, dry_run, mode);
        return Ok(());
    }

    // Regular clean — also report orphans as a hint
    let orphan_list = manager.clean_orphans(true)?; // dry-run detection only
    if !orphan_list.is_empty() {
        eprintln!(
            "note: {} orphan state entry(ies) found (directory missing). Use `parsec clean --orphans` to remove.",
            orphan_list.len()
        );
    }

    let removed = manager.clean(all, dry_run)?;

    output::print_clean(&removed, dry_run, mode);

    if !dry_run && !removed.is_empty() {
        for ws in &removed {
            if let Err(e) = crate::oplog::record(
                manager.repo_root(),
                crate::oplog::OpKind::Clean,
                Some(&ws.ticket),
                &format!("Cleaned workspace for branch '{}'", ws.branch),
                Some(crate::oplog::UndoInfo {
                    branch: Some(ws.branch.clone()),
                    base_branch: Some(ws.base_branch.clone()),
                    path: Some(ws.path.clone()),
                    ticket_title: ws.ticket_title.clone(),
                }),
            ) {
                eprintln!("warning: failed to write oplog: {e}");
            }
        }
    }

    Ok(())
}

pub async fn open(
    repo: &Path,
    ticket: &str,
    force_pr: bool,
    force_ticket: bool,
    mode: Mode,
) -> Result<()> {
    let mut config = ParsecConfig::load()?;

    // Try to find PR URL from oplog
    let repo_root = git::get_main_repo_root(repo).or_else(|_| git::get_repo_root(repo))?;
    config.resolve_for_repo(&repo_root);
    let oplog = crate::oplog::OpLog::load(&repo_root)?;
    let pr_url: Option<String> = oplog.get_entries(Some(ticket)).iter().rev().find_map(|e| {
        if matches!(e.op, crate::oplog::OpKind::Ship) {
            // PR URL is after " -> " in the detail string
            e.detail.split(" -> ").nth(1).map(|s| s.to_string())
        } else {
            None
        }
    });

    // Try to construct ticket tracker URL
    use crate::config::TrackerProvider;
    let ticket_url = match config.tracker.provider {
        TrackerProvider::Jira => config
            .tracker
            .jira
            .as_ref()
            .map(|j| format!("{}/browse/{}", j.base_url.trim_end_matches('/'), ticket)),
        TrackerProvider::Github => git::run_output(repo, &["remote", "get-url", "origin"])
            .ok()
            .map(|url| {
                let url = url
                    .trim_end_matches(".git")
                    .replace("git@github.com:", "https://github.com/");
                format!("{}/issues/{}", url, ticket.trim_start_matches('#'))
            }),
        TrackerProvider::Gitlab => config.tracker.gitlab.as_ref().map(|g| {
            let base = g.base_url.trim_end_matches('/');
            git::run_output(repo, &["remote", "get-url", "origin"])
                .ok()
                .and_then(|url| {
                    let path = url
                        .trim_end_matches(".git")
                        .rsplit_once("gitlab.com")
                        .map(|(_, p)| p.trim_start_matches([':', '/']))?;
                    Some(format!("{}/{}/-/issues/{}", base, path, ticket))
                })
                .unwrap_or_else(|| format!("{}/-/issues/{}", base, ticket))
        }),
        TrackerProvider::None => None,
    };

    // Decide which URL to open
    let url = if force_pr {
        pr_url.ok_or_else(|| anyhow::anyhow!("no PR found for ticket {ticket}. Ship it first."))?
    } else if force_ticket {
        ticket_url
            .ok_or_else(|| anyhow::anyhow!("no ticket URL for {ticket}. Configure a tracker."))?
    } else {
        // Default: PR if available, otherwise ticket
        pr_url.or(ticket_url).ok_or_else(|| {
            anyhow::anyhow!("no URL found for {ticket}. Ship it or configure a tracker.")
        })?
    };

    // Open in browser
    #[cfg(target_os = "macos")]
    let open_cmd = "open";
    #[cfg(not(target_os = "macos"))]
    let open_cmd = "xdg-open";

    std::process::Command::new(open_cmd)
        .arg(&url)
        .spawn()
        .with_context(|| format!("failed to open browser with {open_cmd}"))?;

    if mode == Mode::Json {
        let value = serde_json::json!({ "action": "open", "ticket": ticket, "url": url });
        println!("{}", value);
    } else if mode != Mode::Quiet {
        println!("Opening {}", url);
    }

    Ok(())
}

pub async fn pr_status(repo: &Path, ticket: Option<&str>, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let repo_root = git::get_main_repo_root(repo).or_else(|_| git::get_repo_root(repo))?;
    let oplog = crate::oplog::OpLog::load(&repo_root)?;
    let remote_url = git::run_output(repo, &["remote", "get-url", "origin"])?;

    // Find shipped entries with PR URLs
    let entries: Vec<_> = oplog
        .get_entries(ticket)
        .into_iter()
        .filter(|e| matches!(e.op, crate::oplog::OpKind::Ship))
        .filter_map(|e| {
            let url = e.detail.split(" -> ").nth(1)?;
            // Extract PR number from URL (e.g. .../pull/42)
            let number = url.rsplit('/').next()?.parse::<u64>().ok()?;
            Some((
                e.ticket.clone().unwrap_or_default(),
                number,
                url.to_string(),
            ))
        })
        .collect();

    // Fallback: search active workspaces for PRs by branch name
    let mut all_entries = entries;
    if all_entries.is_empty() {
        let manager = WorktreeManager::new(repo, &config)?;
        let workspaces = match ticket {
            Some(t) => vec![manager.get(t)?],
            None => manager.list()?,
        };

        for ws in &workspaces {
            if let Ok(Some(pr_number)) =
                github::find_pr_by_branch(&remote_url, &ws.branch, &config).await
            {
                all_entries.push((ws.ticket.clone(), pr_number, String::new()));
            }
        }

        if all_entries.is_empty() {
            if let Some(t) = ticket {
                anyhow::bail!("no PR found for {t}. Ship it first with `parsec ship {t}`, or check your GitHub token.");
            } else {
                anyhow::bail!("no PRs found. Ship a ticket first with `parsec ship`, or check your GitHub token.");
            }
        }
    }

    let mut statuses = Vec::new();
    for (ticket_id, pr_number, _url) in &all_entries {
        match crate::github::get_pr_status(&remote_url, *pr_number, &config).await? {
            Some(status) => statuses.push((ticket_id.clone(), status)),
            None => {
                anyhow::bail!("no GitHub token found. Set PARSEC_GITHUB_TOKEN.");
            }
        }
    }

    output::print_pr_status(&statuses, mode);
    Ok(())
}

pub async fn merge(
    repo: &Path,
    ticket: Option<&str>,
    rebase: bool,
    no_wait: bool,
    no_delete_branch: bool,
    mode: Mode,
) -> Result<()> {
    let config = ParsecConfig::load()?;
    let repo_root = git::get_main_repo_root(repo).or_else(|_| git::get_repo_root(repo))?;
    let remote_url = git::run_output(repo, &["remote", "get-url", "origin"])?;
    let oplog = crate::oplog::OpLog::load(&repo_root)?;
    let manager = WorktreeManager::new(repo, &config)?;

    // Resolve ticket
    let ticket_id = if let Some(t) = ticket {
        t.to_string()
    } else {
        let cwd = std::env::current_dir()?;
        let all_ws = manager.list()?;
        let found = all_ws
            .into_iter()
            .find(|w| cwd.starts_with(&w.path))
            .ok_or_else(|| anyhow::anyhow!("not inside a parsec worktree. Specify a ticket."))?;
        found.ticket
    };

    // Find PR number: check oplog first, then try open PR by branch
    let pr_number = {
        let shipped_pr = oplog
            .get_entries(Some(&ticket_id))
            .into_iter()
            .rev()
            .filter(|e| matches!(e.op, crate::oplog::OpKind::Ship))
            .find_map(|e| {
                let url = e.detail.split(" -> ").nth(1)?;
                url.rsplit('/').next()?.parse::<u64>().ok()
            });

        if let Some(pr) = shipped_pr {
            pr
        } else {
            let ws = manager.get(&ticket_id).with_context(|| {
                format!("ticket {ticket_id} not found in active workspaces or oplog")
            })?;
            github::find_pr_by_branch(&remote_url, &ws.branch, &config)
                .await?
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "no open PR found for {ticket_id} (branch '{}'). Either ship it with `parsec ship {ticket_id}`, or check that PARSEC_GITHUB_TOKEN is set.",
                        ws.branch
                    )
                })?
        }
    };

    // Wait for CI to pass (unless --no-wait)
    if !no_wait {
        if mode == Mode::Human {
            eprint!("Waiting for CI to pass...");
        }
        loop {
            match github::get_check_runs(&remote_url, pr_number, &config).await? {
                Some(ci) => {
                    if ci.overall == "passing" {
                        if mode == Mode::Human {
                            eprintln!(" {}", "".green());
                        }
                        break;
                    } else if ci.overall == "failing" {
                        if mode == Mode::Human {
                            eprintln!(" {}", "".red());
                        }
                        anyhow::bail!(
                            "CI is failing for PR #{}. Fix CI or use --no-wait to merge anyway.",
                            pr_number
                        );
                    }
                    // Still pending — wait and retry
                    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
                }
                None => {
                    anyhow::bail!("no GitHub token found. Set PARSEC_GITHUB_TOKEN.");
                }
            }
        }
    }

    // Determine merge method
    let method = if rebase { "rebase" } else { "squash" };
    let delete_branch = !no_delete_branch;

    // Merge the PR
    match github::merge_pr(&remote_url, pr_number, method, delete_branch, &config).await? {
        Some(result) => {
            output::print_merge(&ticket_id, pr_number, &result, method, mode);

            // Prune stale remote-tracking references after remote branch deletion
            if delete_branch {
                if let Err(e) = git::fetch(&repo_root) {
                    eprintln!("warning: failed to prune remote-tracking references: {e}");
                }
            }

            // Auto-transition ticket status
            if let Some(ref auto) = config.tracker.auto_transition {
                if let Some(ref status) = auto.on_merge {
                    tracker::try_transition(&config, &ticket_id, status).await;
                }
            }

            // Clean up local worktree if it exists and auto_cleanup is enabled
            if config.ship.auto_cleanup {
                if let Ok(ws) = manager.get(&ticket_id) {
                    if ws.path.exists() {
                        if let Err(e) = git::worktree_remove(&repo_root, &ws.path) {
                            eprintln!("warning: failed to remove worktree: {e}");
                        }
                    }
                    // Update state
                    let mut state = crate::worktree::ParsecState::load(&repo_root)?;
                    state.remove_workspace(&ticket_id);
                    state.save(&repo_root)?;

                    // Delete local branch
                    if let Some(branch) = &oplog
                        .get_entries(Some(&ticket_id))
                        .last()
                        .and_then(|e| e.undo_info.as_ref())
                        .and_then(|u| u.branch.clone())
                    {
                        if let Err(e) = git::delete_branch(&repo_root, branch) {
                            eprintln!("warning: failed to delete local branch '{}': {}", branch, e);
                        }
                    }

                    if mode == Mode::Human {
                        println!("  {}", "Local worktree cleaned up.".dimmed());
                    }
                }
            }

            // Record in oplog
            if let Err(e) = crate::oplog::record(
                &repo_root,
                crate::oplog::OpKind::Clean,
                Some(&ticket_id),
                &format!("Merged PR #{} ({})", pr_number, method),
                None,
            ) {
                eprintln!("warning: failed to write oplog: {e}");
            }
        }
        None => {
            anyhow::bail!("no GitHub token found. Set PARSEC_GITHUB_TOKEN.");
        }
    }

    Ok(())
}

pub async fn ci(
    repo: &Path,
    ticket: Option<&str>,
    watch: bool,
    all: bool,
    mode: Mode,
) -> Result<()> {
    let config = ParsecConfig::load()?;
    let repo_root = git::get_main_repo_root(repo).or_else(|_| git::get_repo_root(repo))?;
    let remote_url = git::run_output(repo, &["remote", "get-url", "origin"])?;
    let oplog = crate::oplog::OpLog::load(&repo_root)?;
    let manager = WorktreeManager::new(repo, &config)?;

    // Collect (ticket_id, pr_number) pairs to check
    let mut targets: Vec<(String, u64)> = Vec::new();

    if all {
        // All shipped entries with PR numbers from oplog
        let entries: Vec<_> = oplog
            .get_entries(None)
            .into_iter()
            .filter(|e| matches!(e.op, crate::oplog::OpKind::Ship))
            .filter_map(|e| {
                let url = e.detail.split(" -> ").nth(1)?;
                let number = url.rsplit('/').next()?.parse::<u64>().ok()?;
                Some((e.ticket.clone().unwrap_or_default(), number))
            })
            .collect();
        if entries.is_empty() {
            anyhow::bail!("no shipped PRs found. Ship a ticket first with `parsec ship`.");
        }
        targets = entries;
    } else {
        // Resolve which ticket to look up
        let ticket_id = if let Some(t) = ticket {
            t.to_string()
        } else {
            // Auto-detect from current worktree
            let cwd = std::env::current_dir()?;
            let all_ws = manager.list()?;
            let found = all_ws
                .into_iter()
                .find(|w| cwd.starts_with(&w.path))
                .ok_or_else(|| {
                    anyhow::anyhow!("not inside a parsec worktree. Specify a ticket or use --all.")
                })?;
            found.ticket
        };

        // First check if there's a shipped PR in the oplog
        let shipped_pr = oplog
            .get_entries(Some(&ticket_id))
            .into_iter()
            .rev()
            .filter(|e| matches!(e.op, crate::oplog::OpKind::Ship))
            .find_map(|e| {
                let url = e.detail.split(" -> ").nth(1)?;
                url.rsplit('/').next()?.parse::<u64>().ok()
            });

        if let Some(pr_number) = shipped_pr {
            targets.push((ticket_id, pr_number));
        } else {
            // Not shipped yet — try to find an open PR by branch name
            let ws = manager.get(&ticket_id).with_context(|| {
                format!("ticket {ticket_id} not found in active workspaces or oplog")
            })?;
            match github::find_pr_by_branch(&remote_url, &ws.branch, &config).await? {
                Some(pr_number) => targets.push((ticket_id, pr_number)),
                None => {
                    anyhow::bail!(
                        "no PR found for {ticket_id}. Push and create a PR first, or ship with `parsec ship {ticket_id}`."
                    );
                }
            }
        }
    }

    loop {
        let mut statuses: Vec<(String, crate::github::CiStatus)> = Vec::new();

        for (ticket_id, pr_number) in &targets {
            match github::get_check_runs(&remote_url, *pr_number, &config).await? {
                Some(ci) => statuses.push((ticket_id.clone(), ci)),
                None => {
                    anyhow::bail!("no GitHub token found. Set PARSEC_GITHUB_TOKEN.");
                }
            }
        }

        // In watch + human mode, clear screen before redraw
        if watch && mode == Mode::Human {
            print!("\x1B[2J\x1B[H");
        }

        output::print_ci_status(&statuses, mode);

        if !watch || mode != Mode::Human {
            // JSON/quiet mode prints once even with --watch
            // Determine exit code based on overall status
            let has_failure = statuses.iter().any(|(_t, ci)| ci.overall == "failing");
            if has_failure {
                std::process::exit(1);
            }
            return Ok(());
        }

        // Check if all checks are completed
        let all_completed = statuses
            .iter()
            .all(|(_t, ci)| ci.checks.iter().all(|c| c.status == "completed"));

        if all_completed {
            let has_failure = statuses.iter().any(|(_t, ci)| ci.overall == "failing");
            if has_failure {
                std::process::exit(1);
            }
            return Ok(());
        }

        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
    }
}

pub async fn diff(
    repo: &Path,
    ticket: Option<&str>,
    stat: bool,
    name_only: bool,
    mode: Mode,
) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;

    // Resolve workspace
    let ws = if let Some(t) = ticket {
        manager.get(t)?
    } else {
        let cwd = std::env::current_dir()?;
        let all_ws = manager.list()?;
        all_ws
            .into_iter()
            .find(|w| cwd.starts_with(&w.path))
            .ok_or_else(|| anyhow::anyhow!("not inside a parsec worktree. Specify a ticket."))?
    };

    // Find merge base
    let merge_base = git::run_output(
        &ws.path,
        &["merge-base", &format!("origin/{}", ws.base_branch), "HEAD"],
    )?;
    let merge_base = merge_base.trim();

    if name_only {
        let output = git::run_output(&ws.path, &["diff", "--name-only", merge_base])?;
        let files: Vec<String> = output.lines().map(|l| l.to_string()).collect();
        output::print_diff_names(&files, &ws.ticket, mode);
    } else if stat {
        let output = git::run_output(&ws.path, &["diff", "--stat", merge_base])?;
        output::print_diff_stat(&output, &ws.ticket, mode);
    } else {
        // Full diff — just pass through to terminal in human mode
        if mode == Mode::Json {
            let output = git::run_output(&ws.path, &["diff", "--name-status", merge_base])?;
            let files: Vec<(String, String)> = output
                .lines()
                .filter_map(|l| {
                    let mut parts = l.splitn(2, '\t');
                    let status = parts.next()?.to_string();
                    let file = parts.next()?.to_string();
                    Some((status, file))
                })
                .collect();
            output::print_diff_full_json(&files, &ws.ticket);
        } else if mode == Mode::Human {
            // Pass through with color
            let _ = std::process::Command::new("git")
                .args(["diff", "--color=always", merge_base])
                .current_dir(&ws.path)
                .status();
        }
    }
    Ok(())
}

pub async fn conflicts(repo: &Path, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;

    let workspaces = manager.list()?;
    let conflicts = conflict::detect(&workspaces)?;

    output::print_conflicts(&conflicts, mode);
    Ok(())
}

pub async fn sync(
    repo: &Path,
    ticket: Option<&str>,
    all: bool,
    strategy: &str,
    mode: Mode,
) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;

    let workspaces = if all {
        let ws = manager.list()?;
        if ws.is_empty() {
            anyhow::bail!("no active workspaces to sync");
        }
        ws
    } else if let Some(t) = ticket {
        vec![manager.get(t)?]
    } else {
        // Try to detect which worktree we're in
        let cwd = std::env::current_dir()?;
        let all_ws = manager.list()?;
        let found = all_ws
            .into_iter()
            .find(|w| cwd.starts_with(&w.path))
            .ok_or_else(|| {
                anyhow::anyhow!("not inside a parsec worktree. Specify a ticket or use --all.")
            })?;
        vec![found]
    };

    let mut synced = Vec::new();
    let mut failed = Vec::new();

    for ws in &workspaces {
        let ws_path = std::path::Path::new(&ws.path);
        // Fetch the base branch from remote
        if let Err(e) = git::run(ws_path, &["fetch", "origin", &ws.base_branch]) {
            failed.push((ws.ticket.clone(), format!("fetch failed: {e}")));
            continue;
        }
        let remote_base = format!("origin/{}", ws.base_branch);
        let result = match strategy {
            "merge" => git::run(ws_path, &["merge", &remote_base]),
            _ => git::run(ws_path, &["rebase", &remote_base]),
        };
        match result {
            Ok(()) => synced.push(ws.ticket.clone()),
            Err(e) => {
                // Abort failed rebase/merge to leave worktree clean
                if strategy != "merge" {
                    let _ = git::run(ws_path, &["rebase", "--abort"]);
                } else {
                    let _ = git::run(ws_path, &["merge", "--abort"]);
                }
                failed.push((ws.ticket.clone(), format!("{strategy} failed: {e}")));
            }
        }
    }

    output::print_sync(&synced, &failed, strategy, mode);
    Ok(())
}

pub async fn switch(repo: &Path, ticket: Option<&str>, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;

    let ticket = match ticket {
        Some(t) => t.to_string(),
        None => {
            let workspaces = manager.list()?;
            if workspaces.is_empty() {
                anyhow::bail!("no active workspaces. Run `parsec start <ticket>` to create one.");
            }
            let items: Vec<String> = workspaces
                .iter()
                .map(|w| {
                    let title = w
                        .ticket_title
                        .as_deref()
                        .map(|t| format!("{t}"))
                        .unwrap_or_default();
                    format!("{}{title}", w.ticket)
                })
                .collect();
            let selection = dialoguer::Select::new()
                .with_prompt("Switch to workspace")
                .items(&items)
                .default(0)
                .interact()?;
            workspaces[selection].ticket.clone()
        }
    };

    let workspace = manager.get(&ticket)?;
    output::print_switch(&workspace, mode);
    Ok(())
}

pub async fn log(repo: &Path, ticket: Option<&str>, last: usize, mode: Mode) -> Result<()> {
    let repo_root = git::get_main_repo_root(repo).or_else(|_| git::get_repo_root(repo))?;
    let oplog = crate::oplog::OpLog::load(&repo_root)?;
    let entries = oplog.get_entries(ticket);
    // Take last N entries
    let start = entries.len().saturating_sub(last);
    let entries: Vec<_> = entries[start..].to_vec();
    output::print_log(&entries, mode);
    Ok(())
}

pub async fn undo(repo: &Path, dry_run: bool, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let repo_root = git::get_main_repo_root(repo).or_else(|_| git::get_repo_root(repo))?;

    let mut oplog = crate::oplog::OpLog::load(&repo_root)?;

    let last = oplog.last_entry().cloned().ok_or_else(|| {
        anyhow::anyhow!("nothing to undo. Run `parsec log` to see operation history.")
    })?;

    let undo_info = last.undo_info.as_ref().ok_or_else(|| {
        anyhow::anyhow!(
            "last operation ({}) cannot be undone — no undo info recorded.",
            last.op
        )
    })?;

    if dry_run {
        output::print_undo_preview(&last, mode);
        return Ok(());
    }

    match last.op {
        crate::oplog::OpKind::Start | crate::oplog::OpKind::Adopt => {
            // Undo start/adopt = remove the worktree + branch + state
            let ticket = last
                .ticket
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("no ticket in oplog entry"))?;

            if let Some(path) = &undo_info.path {
                if path.exists() {
                    git::worktree_remove(&repo_root, path)
                        .with_context(|| format!("failed to remove worktree at {:?}", path))?;
                }
            }
            if let Some(branch) = &undo_info.branch {
                if let Err(e) = git::delete_branch(&repo_root, branch) {
                    eprintln!("warning: failed to delete branch '{}': {e}", branch);
                }
            }

            // Remove from state
            let mut state = crate::worktree::ParsecState::load(&repo_root)?;
            state.remove_workspace(ticket);
            state.save(&repo_root)?;
        }
        crate::oplog::OpKind::Ship | crate::oplog::OpKind::Clean => {
            // Undo ship/clean = re-create the worktree
            let ticket = last
                .ticket
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("no ticket in oplog entry"))?;
            let branch = undo_info
                .branch
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("no branch info to restore"))?;
            let base_branch = undo_info.base_branch.as_deref().unwrap_or("main");

            // Check if branch exists locally
            let branch_exists_locally = git::run_output(
                &repo_root,
                &["rev-parse", "--verify", &format!("refs/heads/{}", branch)],
            )
            .is_ok();

            // If not local, try to restore from remote
            if !branch_exists_locally {
                let remote_ref = format!("origin/{}", branch);
                if git::run_output(&repo_root, &["rev-parse", "--verify", &remote_ref]).is_ok() {
                    git::run(&repo_root, &["branch", branch, &remote_ref])?;
                } else {
                    anyhow::bail!(
                        "branch '{}' not found locally or on remote. Cannot restore workspace.",
                        branch
                    );
                }
            }

            // Compute worktree path based on layout
            let worktree_path = match config.workspace.layout {
                crate::config::WorktreeLayout::Sibling => {
                    let repo_name = repo_root
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| "repo".to_string());
                    repo_root
                        .parent()
                        .unwrap_or(&repo_root)
                        .join(format!("{}.{}", repo_name, ticket))
                }
                crate::config::WorktreeLayout::Internal => {
                    repo_root.join(&config.workspace.base_dir).join(ticket)
                }
            };

            git::run(
                &repo_root,
                &[
                    "worktree",
                    "add",
                    worktree_path.to_str().unwrap_or(""),
                    branch,
                ],
            )?;

            // Restore state (parent_ticket is lost on undo — acceptable)
            let workspace = crate::worktree::Workspace {
                ticket: ticket.to_owned(),
                path: worktree_path,
                branch: branch.to_owned(),
                base_branch: base_branch.to_owned(),
                created_at: chrono::Utc::now(),
                ticket_title: undo_info.ticket_title.clone(),
                status: crate::worktree::WorkspaceStatus::Active,
                parent_ticket: None,
            };

            let mut state = crate::worktree::ParsecState::load(&repo_root)?;
            state.add_workspace(workspace);
            state.save(&repo_root)?;
        }
        crate::oplog::OpKind::Undo => {
            anyhow::bail!("cannot undo an undo operation");
        }
    }

    // Record undo in oplog
    oplog.append(
        crate::oplog::OpKind::Undo,
        last.ticket.clone(),
        format!("Undid {} operation", last.op),
        None,
    );
    oplog.save(&repo_root)?;

    output::print_undo(&last, mode);
    Ok(())
}

pub async fn stack(repo: &Path, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;
    let workspaces = manager.list()?;

    // Build the set of workspaces that are part of any stack:
    // either they have a parent, or they ARE a parent of something.
    let stacked: Vec<_> = workspaces
        .iter()
        .filter(|w| {
            w.parent_ticket.is_some()
                || workspaces
                    .iter()
                    .any(|other| other.parent_ticket.as_deref() == Some(&w.ticket))
        })
        .cloned()
        .collect();

    if stacked.is_empty() {
        if mode == Mode::Human {
            println!(
                "No stacked worktrees. Use `parsec start <ticket> --on <parent>` to create a stack."
            );
        }
        return Ok(());
    }

    output::print_stack(&stacked, mode);
    Ok(())
}

pub async fn stack_sync(repo: &Path, mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config)?;
    let workspaces = manager.list()?;

    let mut synced = Vec::new();
    let mut failed = Vec::new();

    // Find roots: workspaces that have children but no parent themselves
    let roots: Vec<_> = workspaces
        .iter()
        .filter(|w| {
            w.parent_ticket.is_none()
                && workspaces
                    .iter()
                    .any(|other| other.parent_ticket.as_deref() == Some(&w.ticket))
        })
        .collect();

    if roots.is_empty() {
        if mode == Mode::Human {
            println!(
                "No stacked worktrees to sync. Use `parsec start <ticket> --on <parent>` to create a stack."
            );
        }
        return Ok(());
    }

    for root in &roots {
        // First sync root with its base branch
        if let Err(e) = git::run(&root.path, &["fetch", "origin", &root.base_branch]) {
            failed.push((root.ticket.clone(), format!("fetch failed: {e}")));
            continue;
        }
        let remote_base = format!("origin/{}", root.base_branch);
        if let Err(e) = git::run(&root.path, &["rebase", &remote_base]) {
            let _ = git::run(&root.path, &["rebase", "--abort"]);
            failed.push((root.ticket.clone(), format!("rebase failed: {e}")));
            continue;
        }
        synced.push(root.ticket.clone());

        // Then rebase children onto their parent, in topological order
        let mut queue: Vec<&str> = vec![&root.ticket];
        while let Some(parent_ticket) = queue.first().copied() {
            queue.remove(0);
            let children: Vec<_> = workspaces
                .iter()
                .filter(|w| w.parent_ticket.as_deref() == Some(parent_ticket))
                .collect();
            for child in &children {
                let parent_ws = workspaces
                    .iter()
                    .find(|w| w.ticket == parent_ticket)
                    .unwrap();
                if let Err(e) = git::run(&child.path, &["rebase", &parent_ws.branch]) {
                    let _ = git::run(&child.path, &["rebase", "--abort"]);
                    failed.push((
                        child.ticket.clone(),
                        format!("rebase onto {} failed: {e}", parent_ticket),
                    ));
                } else {
                    synced.push(child.ticket.clone());
                    queue.push(&child.ticket);
                }
            }
        }
    }

    output::print_sync(&synced, &failed, "rebase (stack)", mode);
    Ok(())
}

pub async fn ticket(
    repo: &Path,
    ticket_override: Option<&str>,
    comment: Option<String>,
    mode: Mode,
) -> Result<()> {
    let mut config = ParsecConfig::load()?;
    let repo_root = git::get_repo_root(repo)?;
    config.resolve_for_repo(&repo_root);

    // Resolve ticket: explicit arg > auto-detect from current worktree
    let ticket_id = if let Some(t) = ticket_override {
        t.to_string()
    } else {
        // Try to detect from current worktree
        let manager = WorktreeManager::new(repo, &config)?;
        let workspaces = manager.list()?;
        let current_dir = std::env::current_dir()?;

        workspaces
            .iter()
            .find(|ws| current_dir.starts_with(&ws.path))
            .map(|ws| ws.ticket.clone())
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Not inside a parsec worktree. Specify a ticket: `parsec ticket <TICKET>`"
                )
            })?
    };

    // If --comment is provided, post the comment and return
    if let Some(comment_text) = comment {
        tracker::post_comment(&config, &ticket_id, &comment_text, Some(&repo_root)).await?;
        output::print_comment(&ticket_id, mode);
        return Ok(());
    }

    // Fetch ticket from tracker
    let ticket = tracker::fetch_ticket(&config, &ticket_id, Some(repo))
        .await?
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Could not fetch ticket '{}'. Check your tracker configuration.",
                ticket_id
            )
        })?;

    output::print_ticket(&ticket, mode);
    Ok(())
}

pub async fn inbox(repo: &Path, pick: bool, mode: Mode) -> Result<()> {
    let mut config = ParsecConfig::load()?;
    if let Ok(repo_root) = git::get_repo_root(repo) {
        config.resolve_for_repo(&repo_root);
    }

    // Inbox currently supports Jira only
    if !matches!(
        config.tracker.provider,
        TrackerProvider::Jira | TrackerProvider::None
    ) {
        anyhow::bail!("Inbox currently supports Jira only.");
    }

    // Load atlassian env for auto-detection
    tracker::load_atlassian_env();

    // Resolve Jira base URL and email
    let base_url = config
        .tracker
        .jira
        .as_ref()
        .map(|j| j.base_url.clone())
        .or_else(|| std::env::var(crate::env::JIRA_BASE_URL).ok())
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Jira not configured. Run `parsec config init` or set {}.",
                crate::env::JIRA_BASE_URL,
            )
        })?;
    let email = config.tracker.jira.as_ref().and_then(|j| j.email.clone());
    let jira = JiraTracker::new(&base_url, email.as_deref());

    // JQL: assigned to current user, open statuses, ordered by priority
    let jql =
        "assignee = currentUser() AND status in (\"To Do\", \"In Progress\") ORDER BY priority DESC";

    let tickets = jira.search_assigned_issues(jql).await?;

    // Filter out tickets that already have an active parsec worktree
    let manager = WorktreeManager::new(repo, &config)?;
    let active_tickets: HashSet<String> =
        manager.list()?.iter().map(|ws| ws.ticket.clone()).collect();

    let inbox_tickets: Vec<_> = tickets
        .into_iter()
        .filter(|t| !active_tickets.contains(&t.key))
        .collect();

    if pick {
        if inbox_tickets.is_empty() {
            anyhow::bail!("No assigned tickets without active worktrees.");
        }
        let items: Vec<String> = inbox_tickets
            .iter()
            .map(|t| format!("{}{} [{}]", t.key, t.summary, t.priority))
            .collect();
        let selection = dialoguer::Select::new()
            .with_prompt("Pick a ticket to start")
            .items(&items)
            .default(0)
            .interact()?;
        let chosen = &inbox_tickets[selection];
        eprintln!("Starting workspace for {} ...", chosen.key.bold());
        // Delegate to `start` command
        return start(
            repo,
            &chosen.key,
            None,
            Some(chosen.summary.clone()),
            None,
            None,
            mode,
        )
        .await;
    }

    output::print_inbox(&inbox_tickets, mode);
    Ok(())
}

pub async fn board(
    repo: &Path,
    board_id_override: Option<u64>,
    project_override: Option<String>,
    assignee_override: Option<String>,
    show_all: bool,
    mode: Mode,
) -> Result<()> {
    let mut config = ParsecConfig::load()?;
    if let Ok(repo_root) = git::get_repo_root(repo) {
        config.resolve_for_repo(&repo_root);
    }

    // Board view currently supports Jira only
    if !matches!(
        config.tracker.provider,
        TrackerProvider::Jira | TrackerProvider::None
    ) {
        anyhow::bail!("Board view currently supports Jira only.");
    }

    // Load atlassian env for auto-detection
    tracker::load_atlassian_env();

    // Resolve Jira base URL and email
    let base_url = config
        .tracker
        .jira
        .as_ref()
        .map(|j| j.base_url.clone())
        .or_else(|| std::env::var(crate::env::JIRA_BASE_URL).ok())
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Jira not configured. Run `parsec config init` or set {}.",
                crate::env::JIRA_BASE_URL,
            )
        })?;
    let email = config.tracker.jira.as_ref().and_then(|j| j.email.clone());
    let jira = JiraTracker::new(&base_url, email.as_deref());

    // Resolve project key: --project CLI > PARSEC_JIRA_PROJECT env > config > worktree inference
    let project = if let Some(p) = project_override {
        p
    } else if let Ok(p) = std::env::var(crate::env::PARSEC_JIRA_PROJECT) {
        p
    } else if let Some(p) = config.tracker.jira.as_ref().and_then(|j| j.project.clone()) {
        p
    } else {
        let config2 = ParsecConfig::load()?;
        let manager = WorktreeManager::new(repo, &config2)?;
        let workspaces = manager.list()?;
        workspaces
            .iter()
            .find_map(|ws| ws.ticket.split('-').next().map(String::from))
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Could not infer project key. Use --project <KEY>, set {}, or start a worktree first.",
                    crate::env::PARSEC_JIRA_PROJECT,
                )
            })?
    };

    // Resolve board ID: --board-id CLI > PARSEC_JIRA_BOARD_ID env > config > API fetch
    let board_id = if let Some(id) = board_id_override {
        id
    } else if let Ok(id_str) = std::env::var(crate::env::PARSEC_JIRA_BOARD_ID) {
        id_str.parse::<u64>().map_err(|_| {
            anyhow::anyhow!(
                "{} must be a valid number, got: {}",
                crate::env::PARSEC_JIRA_BOARD_ID,
                id_str,
            )
        })?
    } else if let Some(id) = config.tracker.jira.as_ref().and_then(|j| j.board_id) {
        id
    } else {
        jira.fetch_board_id(&project).await?
    };

    // Resolve assignee filter: --assignee CLI > PARSEC_JIRA_ASSIGNEE env > config > none
    let assignee_filter = if show_all {
        None
    } else if let Some(a) = assignee_override {
        Some(a)
    } else if let Ok(a) = std::env::var(crate::env::PARSEC_JIRA_ASSIGNEE) {
        Some(a)
    } else {
        config
            .tracker
            .jira
            .as_ref()
            .and_then(|j| j.assignee.clone())
    };

    // Fetch active sprint
    let sprint = jira.fetch_active_sprint(board_id).await?;

    // Fetch sprint issues
    let tickets = jira.fetch_sprint_issues(sprint.id).await?;

    // Collect active worktree ticket set
    let config3 = ParsecConfig::load()?;
    let manager = WorktreeManager::new(repo, &config3)?;
    let active_worktree_tickets: HashSet<String> =
        manager.list()?.iter().map(|ws| ws.ticket.clone()).collect();

    // Collect shipped PR ticket set from oplog
    let repo_root = git::get_main_repo_root(repo).or_else(|_| git::get_repo_root(repo))?;
    let oplog = crate::oplog::OpLog::load(&repo_root)?;
    let shipped_tickets: HashSet<String> = oplog
        .entries
        .iter()
        .filter(|e| matches!(e.op, crate::oplog::OpKind::Ship))
        .filter_map(|e| e.ticket.clone())
        .collect();

    // Annotate tickets and group by status
    let mut column_map: Vec<(String, Vec<BoardTicketDisplay>)> = Vec::new();

    // Preserve unique status order as encountered
    let mut seen_statuses: Vec<String> = Vec::new();
    for ticket in &tickets {
        if !seen_statuses.contains(&ticket.status) {
            seen_statuses.push(ticket.status.clone());
        }
    }

    for status in &seen_statuses {
        let col_tickets: Vec<BoardTicketDisplay> = tickets
            .iter()
            .filter(|t| &t.status == status)
            .filter(|t| {
                // Apply assignee filter if set
                if let Some(ref filter) = assignee_filter {
                    t.assignee.as_deref() == Some(filter.as_str())
                } else {
                    true
                }
            })
            .map(|t| BoardTicketDisplay {
                key: t.key.clone(),
                summary: t.summary.clone(),
                assignee: t.assignee.clone(),
                has_worktree: active_worktree_tickets.contains(&t.key),
                has_pr: shipped_tickets.contains(&t.key),
                url: Some(format!(
                    "{}/browse/{}",
                    base_url.trim_end_matches('/'),
                    t.key
                )),
            })
            .collect();
        if !col_tickets.is_empty() {
            column_map.push((status.clone(), col_tickets));
        }
    }

    output::print_board(Some(&sprint), &column_map, mode);
    Ok(())
}

pub async fn config_init(mode: Mode) -> Result<()> {
    let config = ParsecConfig::init_interactive()?;
    config.save()?;

    output::print_config_init(mode);
    Ok(())
}

pub async fn config_show(mode: Mode) -> Result<()> {
    let config = ParsecConfig::load()?;

    output::print_config_show(&config, mode);
    Ok(())
}

pub async fn root(repo_path: &Path) -> Result<()> {
    let repo_root = git::get_main_repo_root(repo_path)?;
    print!("{}", repo_root.display());
    Ok(())
}

pub async fn init_shell(shell: &str) -> Result<()> {
    let script = match shell {
        "bash" => INIT_SHELL_BASH,
        _ => INIT_SHELL_ZSH,
    };
    print!("{}", script);
    Ok(())
}

pub async fn config_shell(shell: &str, _mode: Mode) -> Result<()> {
    let script = match shell {
        "bash" => SHELL_INTEGRATION_BASH,
        _ => SHELL_INTEGRATION_ZSH,
    };
    print!("{}", script);
    Ok(())
}

const SHELL_INTEGRATION_ZSH: &str = r#"
# parsec shell integration - add to ~/.zshrc
# eval "$(parsec config shell zsh)"
function parsec() {
    if [[ "$1" == "switch" && -n "$2" ]]; then
        local dir
        dir=$(command parsec switch "${@:2}" 2>&1)
        if [[ $? -eq 0 && -d "$dir" ]]; then
            cd "$dir"
        else
            echo "$dir" >&2
            return 1
        fi
    else
        command parsec "$@"
    fi
}
"#;

const SHELL_INTEGRATION_BASH: &str = r#"
# parsec shell integration - add to ~/.bashrc
# eval "$(parsec config shell bash)"
function parsec() {
    if [[ "$1" == "switch" && -n "$2" ]]; then
        local dir
        dir=$(command parsec switch "${@:2}" 2>&1)
        if [[ $? -eq 0 && -d "$dir" ]]; then
            cd "$dir"
        else
            echo "$dir" >&2
            return 1
        fi
    else
        command parsec "$@"
    fi
}
"#;

const INIT_SHELL_ZSH: &str = r#"
# parsec shell integration - add to ~/.zshrc
# eval "$(parsec init zsh)"
function parsec() {
    if [[ "$1" == "switch" && -n "$2" ]]; then
        local dir
        dir=$(command parsec switch "${@:2}" 2>&1)
        if [[ $? -eq 0 && -d "$dir" ]]; then
            cd "$dir"
        else
            echo "$dir" >&2
            return 1
        fi
    else
        # Save repo root before merge (CWD may be deleted after)
        local saved_root=""
        if [[ "$1" == "merge" ]]; then
            saved_root=$(command parsec root 2>/dev/null)
        fi
        command parsec "$@"
        local exit_code=$?
        # After merge, if CWD was deleted (worktree cleaned up), cd to main repo
        if [[ "$1" == "merge" && $exit_code -eq 0 ]] && [[ ! -d "$(pwd)" ]]; then
            if [[ -n "$saved_root" && -d "$saved_root" ]]; then
                cd "$saved_root"
                echo "  cd $saved_root"
            fi
        fi
        return $exit_code
    fi
}
"#;

const INIT_SHELL_BASH: &str = r#"
# parsec shell integration - add to ~/.bashrc
# eval "$(parsec init bash)"
function parsec() {
    if [[ "$1" == "switch" && -n "$2" ]]; then
        local dir
        dir=$(command parsec switch "${@:2}" 2>&1)
        if [[ $? -eq 0 && -d "$dir" ]]; then
            cd "$dir"
        else
            echo "$dir" >&2
            return 1
        fi
    else
        # Save repo root before merge (CWD may be deleted after)
        local saved_root=""
        if [[ "$1" == "merge" ]]; then
            saved_root=$(command parsec root 2>/dev/null)
        fi
        command parsec "$@"
        local exit_code=$?
        # After merge, if CWD was deleted (worktree cleaned up), cd to main repo
        if [[ "$1" == "merge" && $exit_code -eq 0 ]] && [[ ! -d "$(pwd)" ]]; then
            if [[ -n "$saved_root" && -d "$saved_root" ]]; then
                cd "$saved_root"
                echo "  cd $saved_root"
            fi
        fi
        return $exit_code
    fi
}
"#;

pub async fn config_man(dir: &Path) -> Result<()> {
    use clap::CommandFactory;
    let cmd = super::Cli::command();
    let man = clap_mangen::Man::new(cmd);
    let mut buf = Vec::new();
    man.render(&mut buf)?;

    let man1_dir = dir.join("man1");
    std::fs::create_dir_all(&man1_dir)
        .with_context(|| format!("Failed to create directory {}", man1_dir.display()))?;

    let path = man1_dir.join("parsec.1");
    std::fs::write(&path, buf)
        .with_context(|| format!("Failed to write man page to {}", path.display()))?;

    println!("Man page installed to {}", path.display());
    println!("Try: man parsec");
    Ok(())
}

pub async fn config_completions(shell: clap_complete::Shell) -> Result<()> {
    use clap::CommandFactory;
    let mut cmd = super::Cli::command();
    clap_complete::generate(shell, &mut cmd, "parsec", &mut std::io::stdout());
    Ok(())
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn build_pr_body(ticket: &str, title: Option<&str>, ticket_url: Option<&str>) -> String {
    let mut body = String::new();

    if let Some(title) = title {
        body.push_str(&format!("## {}\n\n", title));
    }

    // Add ticket link if URL is available (works for any tracker)
    if let Some(url) = ticket_url {
        body.push_str(&format!("**Ticket**: [{ticket}]({url})\n\n"));
    }

    body.push_str(&format!("Shipped via `parsec ship {ticket}`\n"));

    body
}