cliban 0.3.0

Self-hosted, agent-first kanban for the terminal: flat CLI, ratatui board, SQLite storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
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
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
//! `cliban issue` subcommands. Output is byte-for-byte parity with the Go
//! oracle (`internal/cli/issue.go`).

use std::io::{Read, Write};

use cliban_core::contexts::issues::{CreateIssue, ListOpts, UpdateIssue};
use cliban_core::contexts::{issues, milestones, relations};
use cliban_core::schema::{Issue, ISSUE_PRIORITIES, ISSUE_STATUSES};
use cliban_core::time::{format_date, format_usec, parse_date};
use cliban_core::Store;

use chrono::Utc;
use rusqlite::OptionalExtension;

use crate::descmd;
use crate::descmd::find_section;
use crate::errors::{CliError, CliResult};
use crate::output::{
    build_issue_json, write_issue_table, Detail, IssueJsonInputs, IssueRow, RelationOut,
};
use crate::store_open;

#[derive(clap::Args)]
pub struct IssueArgs {
    #[command(subcommand)]
    pub cmd: IssueCmd,
}

#[derive(clap::Subcommand)]
pub enum IssueCmd {
    /// Add an issue (pass --editor to open $EDITOR for input)
    Add(AddArgs),
    /// Show an issue
    Show(ShowArgs),
    /// List issues
    Ls(LsArgs),
    /// Edit an issue
    Edit(EditArgs),
    /// Append an entry to the issue's ## Activity Log section
    Log(LogArgs),
    /// Tick a step in the issue's ## Plan section
    Tick(TickArgs),
    /// Promote a plan step into its own issue
    Promote(PromoteArgs),
    /// Archive done issues
    #[command(name = "archive-done")]
    ArchiveDone(ArchiveDoneArgs),
    /// Bulk-create issues from an NDJSON file (or stdin with '-')
    Import(ImportArgs),
    /// Move an issue to a new status
    Mv {
        key: String,
        status: String,
        /// why — recorded on the issue's timeline with the transition
        #[arg(long)]
        note: Option<String>,
    },
    /// Archives instead of deleting (kept for muscle memory; hidden)
    #[command(hide = true)]
    Rm { key: String },
    /// Archive an issue (hides it from the default board and lists)
    Archive { key: String },
    /// Unarchive an issue
    Unarchive { key: String },
    /// Show the issue inferred from the current git branch
    Current {
        #[arg(long)]
        json: bool,
    },
    /// List issues that have at least one open blocker
    Blocked {
        #[arg(long)]
        project: Option<String>,
        #[arg(long)]
        json: bool,
        /// include each issue's `description` body in --json output
        #[arg(long)]
        full: bool,
    },
}

#[derive(clap::Args)]
pub struct ShowArgs {
    /// issue key
    key: String,
    /// JSON output
    #[arg(long)]
    json: bool,
    /// show only one section: spec|plan|activity|notes
    #[arg(long)]
    section: Option<String>,
    /// pipe human-readable output through $PAGER
    #[arg(long)]
    pager: bool,
}

#[derive(clap::Args)]
pub struct LsArgs {
    /// project key filter
    #[arg(long)]
    project: Option<String>,
    /// status filter
    #[arg(long)]
    status: Option<String>,
    /// priority filter
    #[arg(long)]
    priority: Option<String>,
    /// milestone filter
    #[arg(long)]
    milestone: Option<String>,
    /// list sub-issues of this parent key
    #[arg(long)]
    parent: Option<String>,
    /// sort key: priority|created|updated|position[:asc|desc]
    #[arg(long)]
    sort: Option<String>,
    /// filter to issues with ALL of these labels (repeatable)
    #[arg(long)]
    label: Vec<String>,
    /// exclude sub-issues
    #[arg(long = "no-subs")]
    no_subs: bool,
    /// NDJSON output (one compact JSON object per line)
    #[arg(long)]
    json: bool,
    /// include each issue's `description` body in --json output
    #[arg(long)]
    full: bool,
    /// include archived issues
    #[arg(long)]
    archived: bool,
    /// only issues updated since: 4h, 3d, 2w, today, yesterday, 2026-07-25, or RFC3339
    #[arg(long = "updated-since")]
    updated_since: Option<String>,
    /// fuzzy search query across title/key/labels/description
    #[arg(long)]
    search: Option<String>,
    /// cap result count (default 50 when --search is set; ignored otherwise)
    #[arg(long, default_value_t = 0)]
    limit: i64,
}

#[derive(clap::Args)]
pub struct AddArgs {
    /// project key (required)
    #[arg(long)]
    project: String,
    /// issue title
    #[arg(long)]
    title: Option<String>,
    /// description (use '-' to read from stdin)
    #[arg(long)]
    description: Option<String>,
    /// read description from a file (use '-' for stdin)
    #[arg(long = "description-file")]
    description_file: Option<String>,
    /// parent issue key (sub-issue)
    #[arg(long)]
    parent: Option<String>,
    /// milestone name
    #[arg(long)]
    milestone: Option<String>,
    /// priority
    #[arg(long)]
    priority: Option<String>,
    /// status
    #[arg(long)]
    status: Option<String>,
    /// due date YYYY-MM-DD
    #[arg(long)]
    due: Option<String>,
    /// label name (repeatable)
    #[arg(long)]
    label: Vec<String>,
    /// this issue blocks KEY (repeatable)
    #[arg(long)]
    blocks: Vec<String>,
    /// this issue is blocked by KEY (repeatable)
    #[arg(long = "blocked-by")]
    blocked_by: Vec<String>,
    /// this issue relates to KEY (repeatable)
    #[arg(long = "related-to")]
    related_to: Vec<String>,
    /// JSON output
    #[arg(long)]
    json: bool,
    /// open $EDITOR for input when no --title supplied
    #[arg(long)]
    editor: bool,
}

#[derive(clap::Args)]
pub struct EditArgs {
    /// issue key
    key: String,
    /// new title
    #[arg(long)]
    title: Option<String>,
    /// new description (use '-' for stdin)
    #[arg(long)]
    description: Option<String>,
    /// read description from a file (use '-' for stdin)
    #[arg(long = "description-file")]
    description_file: Option<String>,
    /// new priority
    #[arg(long)]
    priority: Option<String>,
    /// new milestone
    #[arg(long)]
    milestone: Option<String>,
    /// clear milestone
    #[arg(long = "clear-milestone")]
    clear_milestone: bool,
    /// new parent key
    #[arg(long)]
    parent: Option<String>,
    /// clear parent
    #[arg(long = "clear-parent")]
    clear_parent: bool,
    /// new due date YYYY-MM-DD
    #[arg(long)]
    due: Option<String>,
    /// clear due date
    #[arg(long = "clear-due")]
    clear_due: bool,
    /// add label (repeatable)
    #[arg(long)]
    label: Vec<String>,
    /// remove label (repeatable)
    #[arg(long = "remove-label")]
    remove_label: Vec<String>,
    /// add 'blocks' relation to KEY (repeatable)
    #[arg(long)]
    blocks: Vec<String>,
    /// add 'blocked by' relation from KEY (repeatable)
    #[arg(long = "blocked-by")]
    blocked_by: Vec<String>,
    /// add 'related to' relation to KEY (repeatable)
    #[arg(long = "related-to")]
    related_to: Vec<String>,
    /// remove any relation involving KEY (repeatable)
    #[arg(long = "remove-relation")]
    remove_relation: Vec<String>,
    /// open $EDITOR for full edit
    #[arg(long, short = 'e')]
    editor: bool,
    /// JSON output
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args)]
pub struct LogArgs {
    /// issue key
    key: String,
    /// log message
    message: Option<String>,
    /// read message from file (use '-' for stdin)
    #[arg(long = "message-file")]
    message_file: Option<String>,
    /// JSON output
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args)]
pub struct TickArgs {
    /// issue key
    key: String,
    /// task number (required, 1-indexed)
    #[arg(long)]
    task: i32,
    /// step number (required, 1-indexed)
    #[arg(long)]
    step: i32,
    /// JSON output
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args)]
pub struct PromoteArgs {
    /// issue key
    key: String,
    /// task number (required, 1-indexed)
    #[arg(long)]
    task: i32,
    /// step number (required, 1-indexed)
    #[arg(long)]
    step: i32,
    /// title for the promoted issue (required)
    #[arg(long, default_value = "")]
    title: String,
    /// promotion mode: sub-issue|related
    #[arg(long = "as", default_value = "sub-issue")]
    as_mode: String,
    /// JSON output
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args)]
pub struct ArchiveDoneArgs {
    /// project key
    #[arg(long)]
    project: Option<String>,
    /// sweep every project per its auto_archive_done_after_days policy
    #[arg(long)]
    auto: bool,
    /// JSON output
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args)]
pub struct ImportArgs {
    /// NDJSON file path (default: stdin)
    file_arg: Option<String>,
    /// NDJSON file path (default: stdin)
    #[arg(long)]
    file: Option<String>,
    /// default project key for records that omit it
    #[arg(long)]
    project: Option<String>,
    /// emit each created issue as a JSON line
    #[arg(long)]
    json: bool,
}

pub async fn run(db: &Option<String>, args: IssueArgs) -> CliResult<()> {
    match args.cmd {
        IssueCmd::Add(a) => add(db, a).await,
        IssueCmd::Show(a) => show(db, a).await,
        IssueCmd::Ls(a) => ls(db, a).await,
        IssueCmd::Edit(a) => edit(db, a).await,
        IssueCmd::Log(a) => log(db, a).await,
        IssueCmd::Tick(a) => tick(db, a).await,
        IssueCmd::Promote(a) => promote(db, a).await,
        IssueCmd::ArchiveDone(a) => archive_done(db, a).await,
        IssueCmd::Import(a) => import(db, a).await,
        IssueCmd::Mv { key, status, note } => mv(db, key, status, note).await,
        IssueCmd::Rm { key } => {
            // Do the closest safe thing rather than spending a turn refusing.
            let key = parse_issue_key(&key)?;
            set_archived(db, key.clone(), true).await?;
            println!(
                "archived {key} — cliban archives instead of deleting \
                 (undo: cliban issue unarchive {key})"
            );
            Ok(())
        }
        IssueCmd::Archive { key } => set_archived(db, key, true).await,
        IssueCmd::Unarchive { key } => set_archived(db, key, false).await,
        IssueCmd::Current { json } => current(db, json).await,
        IssueCmd::Blocked {
            project,
            json,
            full,
        } => blocked(db, project, json, full).await,
    }
}

/// `domain.ParseStatus`: lowercase+trim, must be a known status. Returns a
/// plain (exit-3) error to mirror the Go oracle, which does NOT wrap this in
/// `ErrValidation` at the `issue mv`/`issue ls` call sites.
fn parse_status(s: &str) -> Result<String, CliError> {
    let norm = s.trim().to_lowercase();
    if ISSUE_STATUSES.contains(&norm.as_str()) {
        Ok(norm)
    } else {
        Err(CliError::other(format!(
            "invalid status {s:?} (valid: backlog, in-progress, blocked, in-review, done)"
        )))
    }
}

/// `domain.ParsePriority`: lowercase+trim, must be a known priority. Plain
/// (exit-3) error, mirroring the Go oracle.
fn parse_priority(s: &str) -> Result<String, CliError> {
    let norm = s.trim().to_lowercase();
    if ISSUE_PRIORITIES.contains(&norm.as_str()) {
        Ok(norm)
    } else {
        Err(CliError::other(format!(
            "invalid priority {s:?} (valid: none, low, medium, high, urgent)"
        )))
    }
}

/// `domain.PriorityRank`: none<low<medium<high<urgent.
fn priority_rank(p: &str) -> i32 {
    match p {
        "urgent" => 4,
        "high" => 3,
        "medium" => 2,
        "low" => 1,
        _ => 0,
    }
}

/// `ParseIssueKey`: trim, split on the LAST `-`. Returns the normalized key
/// `"<UPPER>-<seq>"`. Mirrors Go `domain.ParseIssueKey`.
fn parse_issue_key(s: &str) -> Result<String, CliError> {
    let s = s.trim();
    match s.rfind('-') {
        // idx <= 0 (no dash, or dash at start) or trailing dash → malformed.
        Some(idx) if idx > 0 && idx < s.len() - 1 => {
            let project = s[..idx].to_uppercase();
            let seq_str = &s[idx + 1..];
            match seq_str.parse::<i64>() {
                Ok(n) if n > 0 => Ok(format!("{project}-{n}")),
                _ => Err(CliError::validation(format!(
                    "invalid issue key {s:?} (sequence must be positive integer)"
                ))),
            }
        }
        _ => Err(CliError::validation(format!(
            "invalid issue key {s:?} (want PROJECT-N)"
        ))),
    }
}

/// Public wrapper over `parse_issue_key` for use by the search module.
pub fn parse_issue_key_pub(s: &str) -> Result<String, CliError> {
    parse_issue_key(s)
}

/// `resolveDescription`: returns `(content, was_set)`.
///   * `--description` and `--description-file` are mutually exclusive.
///   * `-` reads stdin.
fn resolve_description(
    description: Option<String>,
    description_file: Option<String>,
) -> CliResult<(String, bool)> {
    if let Some(file) = description_file {
        if description.is_some() {
            return Err(CliError::validation(
                "--description and --description-file are mutually exclusive",
            ));
        }
        if file == "-" {
            return Ok((read_stdin()?, true));
        }
        match std::fs::read_to_string(&file) {
            Ok(s) => Ok((s, true)),
            Err(e) => Err(CliError::validation(e.to_string())),
        }
    } else if let Some(desc) = description {
        if desc == "-" {
            Ok((read_stdin()?, true))
        } else {
            Ok((desc, true))
        }
    } else {
        Ok((String::new(), false))
    }
}

fn read_stdin() -> CliResult<String> {
    let mut buf = String::new();
    std::io::stdin()
        .read_to_string(&mut buf)
        .map_err(|e| CliError::other(e.to_string()))?;
    Ok(buf)
}

async fn add(db: &Option<String>, a: AddArgs) -> CliResult<()> {
    let project_key = a.project.to_uppercase();
    let title = a.title.unwrap_or_default();

    let (description, desc_set) = resolve_description(a.description, a.description_file)?;

    let contentless = title.is_empty() && !desc_set;
    if contentless {
        if a.editor {
            // The interactive editor path requires a TTY; it is out of
            // golden-test scope, so a non-TTY validation error suffices.
            return Err(CliError::validation("--editor requires a TTY"));
        }
        return Err(CliError::validation(
            "--title required (pass --editor to open $EDITOR)",
        ));
    }

    // Pre-parse the parent key (Go parses before the store call).
    let parent_key = match &a.parent {
        Some(p) if !p.is_empty() => Some(parse_issue_key(p)?),
        _ => None,
    };

    // Parse the due date (Go parseDueDate, validation on failure).
    let due_date = match &a.due {
        Some(d) if !d.is_empty() => match parse_date(d) {
            Some(dt) => Some(dt),
            None => {
                return Err(CliError::validation(format!(
                    "invalid --due {d:?} (want YYYY-MM-DD)"
                )))
            }
        },
        _ => None,
    };

    // Normalize the relation key flags up front (Go ParseIssueKey on each).
    let blocks: Vec<String> = a
        .blocks
        .iter()
        .map(|k| parse_issue_key(k))
        .collect::<Result<_, _>>()?;
    let blocked_by: Vec<String> = a
        .blocked_by
        .iter()
        .map(|k| parse_issue_key(k))
        .collect::<Result<_, _>>()?;
    let related_to: Vec<String> = a
        .related_to
        .iter()
        .map(|k| parse_issue_key(k))
        .collect::<Result<_, _>>()?;

    let store = store_open::open(db).await?;

    // Step 1: create the issue (core validates status/priority/milestone/parent).
    let milestone = a.milestone.filter(|m| !m.is_empty());
    let priority = a.priority.filter(|p| !p.is_empty());
    let status = a.status.filter(|s| !s.is_empty());
    let create_project = project_key.clone();
    let mut issue = store
        .call(move |conn| {
            issues::create(
                conn,
                &create_project,
                CreateIssue {
                    title,
                    description: Some(description),
                    status,
                    priority,
                    milestone,
                    parent_key,
                    due_date,
                    position: None,
                },
            )
        })
        .await?;

    // Step 2: attach labels (idempotent, sequential — matches Go).
    for lbl in a.label {
        let id = issue.id;
        let name = lbl;
        store
            .call(move |conn| {
                let issue = issues::get_by_id(conn, id)?.ok_or(cliban_core::Error::NotFound)?;
                issues::add_label(conn, &issue, &name)
            })
            .await?;
    }

    // Step 3: relations. `--blocks K` → from issue to K; `--blocked-by K` →
    // from K to issue; `--related-to K` → from issue to K.
    let issue_key = issue.key.clone();
    for other in blocks {
        let from = issue_key.clone();
        store
            .call(move |conn| relations::add(conn, &from, &other, "blocks"))
            .await?;
    }
    for other in blocked_by {
        let to = issue_key.clone();
        store
            .call(move |conn| relations::add(conn, &other, &to, "blocks"))
            .await?;
    }
    for other in related_to {
        let from = issue_key.clone();
        store
            .call(move |conn| relations::add(conn, &from, &other, "related_to"))
            .await?;
    }

    // Reload to pick up labels/relations in the output.
    let reload_key = issue.key.clone();
    if let Some(fresh) = store
        .call(move |conn| issues::get_by_key(conn, &reload_key))
        .await?
    {
        issue = fresh;
    }

    print_issue_result(&store, &issue, "created", a.json).await
}

/// Mirrors Go `printIssueResult`: human `{verb} {KEY}: {title}\n`; json pretty.
async fn print_issue_result(store: &Store, issue: &Issue, verb: &str, json: bool) -> CliResult<()> {
    if json {
        let inputs = issue_json_inputs(store, issue).await?;
        println!(
            "{}",
            serde_json::to_string_pretty(&build_issue_json(inputs, Detail::Full)).unwrap()
        );
    } else {
        println!("{verb} {}: {}", issue.key, issue.title);
    }
    Ok(())
}

/// Resolve every reference an `IssueJsonInputs` needs (project key, milestone
/// name, parent key, labels, relations, formatted dates) in a single writer
/// round-trip.
pub async fn issue_json_inputs(store: &Store, issue: &Issue) -> CliResult<IssueJsonInputs> {
    let id = issue.id;
    let milestone_id = issue.milestone_id;
    let parent_id = issue.parent_id;
    let key = issue.key.clone();
    let title = issue.title.clone();
    let description = issue.description.clone();
    let status = issue.status.clone();
    let priority = issue.priority.clone();
    let position = issue.position;
    let archived = issue.archived;
    let due_date = issue.due_date.map(format_date);
    let completed_at = issue.completed_at.map(format_usec);
    let created_at = format_usec(issue.inserted_at);
    let updated_at = format_usec(issue.updated_at);

    let inputs = store
        .call(move |conn| {
            // The issue's `key` field already carries the full "PROJECT-N"
            // string, so no project lookup is needed for the JSON projection.
            let milestone = match milestone_id {
                Some(mid) => milestones::get_by_id(conn, mid)?.map(|m| m.name),
                None => None,
            };
            let parent = match parent_id {
                Some(pid) => issues::get_by_id(conn, pid)?.map(|i| i.key),
                None => None,
            };
            let labels = issues::label_names(conn, id)?;
            let relations = relations::for_issue(conn, id)?
                .into_iter()
                .map(|r| RelationOut {
                    kind: r.kind,
                    target: r.target_key,
                })
                .collect();
            Ok(IssueJsonInputs {
                key,
                title,
                description,
                status,
                priority,
                position,
                archived,
                due_date,
                completed_at,
                milestone,
                parent,
                labels,
                relations,
                created_at,
                updated_at,
            })
        })
        .await?;
    Ok(inputs)
}

/// Resolve milestone name + parent key for an issue (empty when unset).
async fn resolve_refs(store: &Store, issue: &Issue) -> CliResult<(String, String)> {
    let milestone_id = issue.milestone_id;
    let parent_id = issue.parent_id;
    let pair = store
        .call(move |conn| {
            let milestone = match milestone_id {
                Some(mid) => milestones::get_by_id(conn, mid)?.map(|m| m.name),
                None => None,
            };
            let parent = match parent_id {
                Some(pid) => issues::get_by_id(conn, pid)?.map(|i| i.key),
                None => None,
            };
            Ok((milestone.unwrap_or_default(), parent.unwrap_or_default()))
        })
        .await?;
    Ok(pair)
}

/// `sectionAnchor`: map a `--section` short name to its canonical H2 anchor.
fn section_anchor(s: &str) -> Result<&'static str, CliError> {
    match s {
        "spec" => Ok("Spec"),
        "plan" => Ok("Plan"),
        "activity" => Ok("Activity Log"),
        "notes" => Ok("Notes"),
        _ => Err(CliError::validation(format!(
            "invalid --section {s:?} (want spec|plan|activity|notes)"
        ))),
    }
}

async fn show(db: &Option<String>, a: ShowArgs) -> CliResult<()> {
    let key = parse_issue_key(&a.key)?;
    let store = store_open::open(db).await?;
    let lookup = key.clone();
    let issue = store
        .call(move |conn| issues::get_by_key(conn, &lookup))
        .await?
        .ok_or(cliban_core::Error::NotFound)?;

    // --section is a targeted machine read; mutually exclusive with json/pager.
    if let Some(section) = &a.section {
        let anchor = section_anchor(section)?;
        // The activity view is the union of the author's narrative and the
        // transitions cliban recorded; either alone is a partial history.
        let recorded = if anchor == "Activity Log" {
            let id = issue.id;
            store
                .call(move |conn| {
                    cliban_core::contexts::activity_log::list_for_issue(conn, id, 200)
                })
                .await?
        } else {
            Vec::new()
        };
        let (start, end, ok) = find_section(&issue.description, anchor);
        if !ok && recorded.is_empty() {
            // Go wraps with %w on store.ErrNotFound → "not found: <msg>".
            return Err(CliError::not_found(format!(
                "not found: no ## {anchor} section in {}",
                a.key
            )));
        }
        let written = if ok {
            &issue.description[start..end]
        } else {
            ""
        };
        if recorded.is_empty() {
            // Nothing recorded: emit the section byte-for-byte as stored.
            print!("{written}");
        } else {
            print!("{}", merge_activity_view(written, &recorded));
        }
        return Ok(());
    }

    if a.json {
        let inputs = issue_json_inputs(&store, &issue).await?;
        println!(
            "{}",
            serde_json::to_string_pretty(&build_issue_json(inputs, Detail::Full)).unwrap()
        );
        return Ok(());
    }

    let (ms_name, parent_key) = resolve_refs(&store, &issue).await?;
    let body = format!(
        "{} — {}\nstatus:    {}\npriority:  {}\nmilestone: {}\nparent:    {}\n\n{}\n",
        key,
        issue.title,
        issue.status,
        issue.priority,
        dash_if_empty(&ms_name),
        dash_if_empty(&parent_key),
        issue.description
    );
    if a.pager {
        run_pager(&body)?;
    } else {
        print!("{body}");
    }
    Ok(())
}

/// One chronological view over the two activity sources: the `## Activity Log`
/// lines an author wrote, and the entries cliban recorded itself. Both render
/// as `- <ts> — <msg>`; recorded ones carry `[actor]` when attribution was set.
///
/// Only called when there is something recorded — with an empty table the
/// stored section is emitted verbatim, so a description that was never
/// auto-recorded reads exactly as it always did.
fn merge_activity_view(
    written: &str,
    recorded: &[cliban_core::schema::ActivityLogEntry],
) -> String {
    const STAMP: &str = "%Y-%m-%dT%H:%MZ";
    // `issue log` records into both places, so drop the markdown copy of any
    // line a recorded entry already covers — the recorded one carries the
    // actor. What survives is hand-written, or predates recording.
    let already: std::collections::HashSet<(i64, String)> = recorded
        .iter()
        .filter(|e| e.kind == "log")
        .map(|e| crate::audit::log_dedupe_key(e.ts, &e.message))
        .collect();
    let mut lines: Vec<(chrono::DateTime<Utc>, String)> =
        descmd::parse_activity_log(&format!("## Activity Log\n{written}"))
            .into_iter()
            .filter(|(ts, msg)| !already.contains(&crate::audit::log_dedupe_key(*ts, msg)))
            .map(|(ts, msg)| (ts, format!("- {} — {msg}", ts.format(STAMP))))
            .collect();
    for e in recorded {
        let who = crate::audit::actor_of(&e.extra)
            .map(|a| format!("[{a}] "))
            .unwrap_or_default();
        lines.push((
            e.ts,
            format!("- {} — {who}{}", e.ts.format(STAMP), e.message),
        ));
    }
    lines.sort_by_key(|(ts, _)| *ts);
    let mut out = String::from("\n");
    for (_, line) in &lines {
        out.push_str(line);
        out.push('\n');
    }
    out
}

fn dash_if_empty(s: &str) -> String {
    if s.is_empty() {
        "-".into()
    } else {
        s.into()
    }
}

/// `runPager`: pipe through `sh -c $PAGER` when set, else write to stdout.
fn run_pager(body: &str) -> CliResult<()> {
    match std::env::var("PAGER") {
        Ok(pager) if !pager.is_empty() => {
            use std::process::{Command, Stdio};
            let mut child = Command::new("sh")
                .arg("-c")
                .arg(&pager)
                .stdin(Stdio::piped())
                .spawn()
                .map_err(|e| CliError::other(e.to_string()))?;
            if let Some(stdin) = child.stdin.as_mut() {
                stdin
                    .write_all(body.as_bytes())
                    .map_err(|e| CliError::other(e.to_string()))?;
            }
            child.wait().map_err(|e| CliError::other(e.to_string()))?;
            Ok(())
        }
        _ => {
            print!("{body}");
            Ok(())
        }
    }
}

fn parse_updated_since(s: &str) -> Result<chrono::DateTime<Utc>, CliError> {
    crate::since::parse(s, "--updated-since")
}

async fn ls(db: &Option<String>, a: LsArgs) -> CliResult<()> {
    // --search branch. The flag being *present* (even empty) maps to Go's
    // `cmd.Flags().Changed("search")`; an empty/whitespace value is a clean
    // validation error.
    if let Some(raw) = &a.search {
        if raw.trim().is_empty() {
            return Err(CliError::validation("--search requires a non-empty query"));
        }
        // --sort is ignored under --search; emit the Go note to stderr.
        if a.sort.is_some() {
            eprintln!("note: --sort is ignored when --search is set");
        }
        return run_search(db, &a, raw.clone()).await;
    }

    // Pre-parse the typed filters (Go parses before the store call).
    let project = a.project.as_deref().map(str::to_uppercase);
    let status = match &a.status {
        Some(s) if !s.is_empty() => Some(parse_status(s)?),
        _ => None,
    };
    let priority = match &a.priority {
        Some(p) if !p.is_empty() => Some(parse_priority(p)?),
        _ => None,
    };
    let parent_key = match &a.parent {
        Some(p) if !p.is_empty() => Some(parse_issue_key(p)?),
        _ => None,
    };
    let updated_since = match &a.updated_since {
        Some(s) if !s.is_empty() => Some(parse_updated_since(s)?),
        _ => None,
    };
    // Validate sort spec up front (matches Go: sort runs after the fetch, but a
    // bad spec is a clean validation error either way).
    let sort = a.sort.clone().filter(|s| !s.is_empty());
    if let Some(spec) = &sort {
        validate_sort_spec(spec)?;
    }

    let store = store_open::open(db).await?;

    // Core list handles project/status/milestone, but its `archived` flag is an
    // exact match (archived = this). Go's `--archived` means *include* archived:
    // unset → only non-archived; set → both. So when set we fetch both and
    // concatenate (the base ordering below re-sorts the union).
    let list_project = project.clone();
    let list_status = status.clone();
    let list_milestone = a.milestone.clone().filter(|m| !m.is_empty());
    let include_archived = a.archived;
    let mut issues = store
        .call(move |conn| {
            let mut out = issues::list(
                conn,
                ListOpts {
                    project: list_project.as_deref(),
                    status: list_status.as_deref(),
                    milestone: list_milestone.as_deref(),
                    archived: false,
                },
            )?;
            if include_archived {
                let archived = issues::list(
                    conn,
                    ListOpts {
                        project: list_project.as_deref(),
                        status: list_status.as_deref(),
                        milestone: list_milestone.as_deref(),
                        archived: true,
                    },
                )?;
                out.extend(archived);
            }
            Ok(out)
        })
        .await?;

    // Rust-side filters applied AFTER fetch (Go applies these in the store
    // query, but the net result set is identical).
    if let Some(pr) = &priority {
        issues.retain(|i| &i.priority == pr);
    }
    if let Some(pk) = &parent_key {
        // Resolve the parent key to its id, then keep issues whose parent_id
        // matches. An unresolvable parent yields an empty result.
        let lookup = pk.clone();
        let parent_id = store
            .call(move |conn| issues::get_by_key(conn, &lookup).map(|o| o.map(|i| i.id)))
            .await?;
        match parent_id {
            Some(pid) => issues.retain(|i| i.parent_id == Some(pid)),
            None => issues.clear(),
        }
    }
    if a.no_subs {
        issues.retain(|i| i.parent_id.is_none());
    }
    if !a.label.is_empty() {
        let want = a.label.clone();
        let mut kept = Vec::with_capacity(issues.len());
        for i in issues.into_iter() {
            let id = i.id;
            let names = store
                .call(move |conn| issues::label_names(conn, id))
                .await?;
            if want.iter().all(|w| names.iter().any(|n| n == w)) {
                kept.push(i);
            }
        }
        issues = kept;
    }
    if let Some(threshold) = updated_since {
        issues.retain(|i| i.updated_at >= threshold);
    }

    // Base ordering mirrors the Go store query: ORDER BY p.key, i.status,
    // i.position (the issue key embeds the project key, so its prefix sorts by
    // project). The explicit --sort below is then applied stably on top.
    base_order(&mut issues);

    if let Some(spec) = &sort {
        sort_issues(&mut issues, spec);
    }

    if a.json {
        for i in &issues {
            let inputs = issue_json_inputs(&store, i).await?;
            println!(
                "{}",
                serde_json::to_string(&build_issue_json(inputs, Detail::from_full_flag(a.full)))
                    .unwrap()
            );
        }
        return Ok(());
    }

    let rows = issue_rows(&store, &issues).await?;
    print!("{}", write_issue_table(&rows));
    Ok(())
}

/// `issue ls --search` branch. Mirrors Go `runIssueSearch`: default limit 50
/// (the `--limit` flag overrides; 0 → 50), NDJSON rows carry a `score` field,
/// human output uses the search table with a leading SCORE column.
async fn run_search(db: &Option<String>, a: &LsArgs, query: String) -> CliResult<()> {
    let effective_limit = if a.limit == 0 { 50 } else { a.limit };
    let store = store_open::open(db).await?;
    let opts = crate::search::Options {
        query,
        project: a.project.as_deref().map(str::to_uppercase),
        label: a.label.clone(),
        milestone: a.milestone.clone(),
        status: a.status.clone(),
        priority: a.priority.clone(),
        parent: a.parent.clone(),
        include_archived: a.archived,
        exclude_subs: a.no_subs,
        limit: effective_limit,
    };
    let matches = crate::search::search(&store, opts).await?;

    if a.json {
        for m in &matches {
            let inputs = issue_json_inputs(&store, &m.issue).await?;
            println!(
                "{}",
                serde_json::to_string(&crate::output::build_search_match_json(
                    inputs,
                    m.score,
                    Detail::from_full_flag(a.full)
                ))
                .unwrap()
            );
        }
        return Ok(());
    }

    let mut rows = Vec::with_capacity(matches.len());
    for m in &matches {
        let (ms_name, parent_key) = crate::search::resolve_refs(&store, &m.issue).await?;
        rows.push(crate::output::SearchRow {
            score: m.score,
            key: m.issue.key.clone(),
            title: m.issue.title.clone(),
            status: m.issue.status.clone(),
            priority: m.issue.priority.clone(),
            milestone: ms_name,
            parent: parent_key,
        });
    }
    print!("{}", crate::output::write_search_table(&rows));
    Ok(())
}

/// Project-key prefix of an issue key (`CLI-12` → `CLI`).
fn project_prefix(key: &str) -> &str {
    match key.rfind('-') {
        Some(idx) => &key[..idx],
        None => key,
    }
}

/// Base ordering matching the Go store: (project key, status, position).
fn base_order(issues: &mut [Issue]) {
    issues.sort_by(|a, b| {
        project_prefix(&a.key)
            .cmp(project_prefix(&b.key))
            .then_with(|| a.status.cmp(&b.status))
            .then_with(|| {
                a.position
                    .partial_cmp(&b.position)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
    });
}

/// Build display rows (resolving milestone/parent) for the issue table.
async fn issue_rows(store: &Store, issues: &[Issue]) -> CliResult<Vec<IssueRow>> {
    let mut rows = Vec::with_capacity(issues.len());
    for i in issues {
        let (ms_name, parent_key) = resolve_refs(store, i).await?;
        rows.push(IssueRow {
            key: i.key.clone(),
            title: i.title.clone(),
            status: i.status.clone(),
            priority: i.priority.clone(),
            milestone: ms_name,
            parent: parent_key,
        });
    }
    Ok(rows)
}

/// Validate a `--sort` spec (`field[:asc|desc]`).
fn validate_sort_spec(spec: &str) -> Result<(), CliError> {
    let (field, dir) = match spec.find(':') {
        Some(idx) => (&spec[..idx], &spec[idx + 1..]),
        None => (spec, ""),
    };
    match dir {
        "" | "asc" | "desc" => {}
        other => {
            return Err(CliError::validation(format!(
                "invalid sort direction {other:?} (use asc or desc)"
            )))
        }
    }
    match field {
        "priority" | "created" | "updated" | "position" => Ok(()),
        other => Err(CliError::validation(format!(
            "invalid --sort field {other:?} (priority|created|updated|position)"
        ))),
    }
}

/// Stable in-place sort by the (pre-validated) spec. Priority defaults to desc.
fn sort_issues(issues: &mut [Issue], spec: &str) {
    let (field, dir) = match spec.find(':') {
        Some(idx) => (&spec[..idx], &spec[idx + 1..]),
        None => (spec, ""),
    };
    let mut desc = dir == "desc";
    match field {
        "priority" => {
            if dir.is_empty() {
                desc = true;
            }
            issues.sort_by(|a, b| {
                let (x, y) = if desc { (b, a) } else { (a, b) };
                priority_rank(&x.priority).cmp(&priority_rank(&y.priority))
            });
        }
        "created" => issues.sort_by(|a, b| {
            if desc {
                b.inserted_at.cmp(&a.inserted_at)
            } else {
                a.inserted_at.cmp(&b.inserted_at)
            }
        }),
        "updated" => issues.sort_by(|a, b| {
            if desc {
                b.updated_at.cmp(&a.updated_at)
            } else {
                a.updated_at.cmp(&b.updated_at)
            }
        }),
        "position" => issues.sort_by(|a, b| {
            let ord = a
                .position
                .partial_cmp(&b.position)
                .unwrap_or(std::cmp::Ordering::Equal);
            if desc {
                ord.reverse()
            } else {
                ord
            }
        }),
        _ => {}
    }
}

async fn edit(db: &Option<String>, a: EditArgs) -> CliResult<()> {
    let key = parse_issue_key(&a.key)?;
    let project_part = project_prefix(&key).to_string();

    // resolveDescription: respects mutual exclusivity, only "set" when changed.
    let (desc_content, desc_set) = resolve_description(a.description, a.description_file)?;

    let title = a.title.clone(); // --title given → Some (even if "")
    let priority = match &a.priority {
        Some(p) => Some(parse_priority(p)?),
        None => None,
    };
    let due_date: Option<Option<chrono::NaiveDate>> = if a.clear_due {
        Some(None)
    } else if let Some(d) = &a.due {
        match parse_date(d) {
            Some(dt) => Some(Some(dt)),
            None => {
                return Err(CliError::validation(format!(
                    "invalid --due {d:?} (want YYYY-MM-DD)"
                )))
            }
        }
    } else {
        None
    };
    // Parent: parse key now (validates form).
    let parent_key = if a.clear_parent {
        None
    } else {
        match &a.parent {
            Some(p) => Some(parse_issue_key(p)?),
            None => None,
        }
    };

    let any_change = title.is_some()
        || desc_set
        || priority.is_some()
        || a.clear_milestone
        || a.milestone.is_some()
        || a.clear_parent
        || a.parent.is_some()
        || a.clear_due
        || a.due.is_some()
        || !a.label.is_empty()
        || !a.remove_label.is_empty()
        || !a.blocks.is_empty()
        || !a.blocked_by.is_empty()
        || !a.related_to.is_empty()
        || !a.remove_relation.is_empty();

    if !any_change && a.editor {
        // Interactive editor path requires a TTY; out of golden-test scope.
        return Err(CliError::validation("--editor requires a TTY"));
    }
    if !any_change {
        return Err(CliError::validation(
            "no edits requested (pass a flag or --editor)",
        ));
    }

    // Normalize relation keys up front.
    let blocks: Vec<String> = a
        .blocks
        .iter()
        .map(|k| parse_issue_key(k))
        .collect::<Result<_, _>>()?;
    let blocked_by: Vec<String> = a
        .blocked_by
        .iter()
        .map(|k| parse_issue_key(k))
        .collect::<Result<_, _>>()?;
    let related_to: Vec<String> = a
        .related_to
        .iter()
        .map(|k| parse_issue_key(k))
        .collect::<Result<_, _>>()?;
    let remove_relation: Vec<String> = a
        .remove_relation
        .iter()
        .map(|k| parse_issue_key(k))
        .collect::<Result<_, _>>()?;

    let store = store_open::open(db).await?;

    // Resolve milestone name → id (project-scoped) up front.
    let milestone_field: Option<Option<i64>> = if a.clear_milestone {
        Some(None)
    } else if let Some(name) = a.milestone.clone() {
        let pk = project_part.clone();
        let mid = store
            .call(move |conn| Ok(milestones::get(conn, &pk, &name)?.map(|m| m.id)))
            .await?;
        match mid {
            Some(id) => Some(Some(id)),
            None => {
                // Match Go: ErrNotFound "not found: milestone \"name\"".
                let n = a.milestone.clone().unwrap_or_default();
                return Err(CliError::not_found(format!("not found: milestone {n:?}")));
            }
        }
    } else {
        None
    };

    // Resolve parent key → id (same-project + own-parent checks mirror Go).
    let parent_field: Option<Option<i64>> = if a.clear_parent {
        Some(None)
    } else if let Some(pk) = parent_key.clone() {
        if project_prefix(&pk) != project_part {
            return Err(CliError::validation("parent must be in same project"));
        }
        if pk == key {
            return Err(CliError::validation("issue cannot be its own parent"));
        }
        let lookup = pk.clone();
        let pid = store
            .call(move |conn| Ok(issues::get_by_key(conn, &lookup)?.map(|i| i.id)))
            .await?;
        match pid {
            Some(id) => Some(Some(id)),
            None => return Err(CliError::not_found(format!("not found: parent {pk}"))),
        }
    } else {
        None
    };

    let description = if desc_set { Some(desc_content) } else { None };

    // Snapshot before anything moves, so the timeline entry can say what
    // actually changed rather than just "edited".
    let snapshot_key = key.clone();
    let before = store
        .call(move |conn| issues::get_by_key(conn, &snapshot_key))
        .await?
        .ok_or(cliban_core::Error::NotFound)?;
    let (before_milestone, before_parent) = resolve_refs(&store, &before).await?;

    // Apply the core update (only when there is a field-level change).
    let has_field_update = title.is_some()
        || description.is_some()
        || priority.is_some()
        || milestone_field.is_some()
        || parent_field.is_some()
        || due_date.is_some();
    if has_field_update {
        let lookup = key.clone();
        let upd = UpdateIssue {
            title: title.clone(),
            description: description.clone(),
            priority: priority.clone(),
            milestone_id: milestone_field,
            parent_id: parent_field,
            due_date,
            ..Default::default()
        };
        store
            .call(move |conn| {
                let issue =
                    issues::get_by_key(conn, &lookup)?.ok_or(cliban_core::Error::NotFound)?;
                issues::update(conn, &issue, upd)?;
                Ok(())
            })
            .await?;
    } else {
        // Even with no field update, confirm the issue exists (Go fetches it).
        let lookup = key.clone();
        store
            .call(move |conn| issues::get_by_key(conn, &lookup))
            .await?
            .ok_or(cliban_core::Error::NotFound)?;
    }

    // Capture the relation/label intent before the loops below consume it.
    let added_labels = a.label.clone();
    let removed_labels = a.remove_label.clone();
    let summary_blocks = blocks.clone();
    let summary_blocked_by = blocked_by.clone();
    let summary_related_to = related_to.clone();
    let summary_remove_relation = remove_relation.clone();

    // Labels.
    for lbl in a.label {
        let lookup = key.clone();
        store
            .call(move |conn| {
                let issue =
                    issues::get_by_key(conn, &lookup)?.ok_or(cliban_core::Error::NotFound)?;
                issues::add_label(conn, &issue, &lbl)
            })
            .await?;
    }
    for lbl in a.remove_label {
        let lookup = key.clone();
        store
            .call(move |conn| {
                let issue =
                    issues::get_by_key(conn, &lookup)?.ok_or(cliban_core::Error::NotFound)?;
                issues::remove_label(conn, &issue, &lbl)
            })
            .await?;
    }

    // Relations.
    for other in blocks {
        let from = key.clone();
        store
            .call(move |conn| relations::add(conn, &from, &other, "blocks"))
            .await?;
    }
    for other in blocked_by {
        let to = key.clone();
        store
            .call(move |conn| relations::add(conn, &other, &to, "blocks"))
            .await?;
    }
    for other in related_to {
        let from = key.clone();
        store
            .call(move |conn| relations::add(conn, &from, &other, "related_to"))
            .await?;
    }
    for other in remove_relation {
        let k = key.clone();
        store
            .call(move |conn| {
                let _ = relations::remove(conn, &k, &other, "blocks");
                let _ = relations::remove(conn, &other, &k, "blocks");
                let _ = relations::remove(conn, &k, &other, "related_to");
                Ok(())
            })
            .await?;
    }

    let reload = key.clone();
    let issue = store
        .call(move |conn| issues::get_by_key(conn, &reload))
        .await?
        .ok_or(cliban_core::Error::NotFound)?;

    // Everything applied; record what moved.
    let (after_milestone, after_parent) = resolve_refs(&store, &issue).await?;
    let mut summary = crate::audit::EditSummary::default();
    summary.field("title", &before.title, &issue.title);
    summary.field("priority", &before.priority, &issue.priority);
    summary.field("milestone", &before_milestone, &after_milestone);
    summary.field("parent", &before_parent, &after_parent);
    summary.field(
        "due",
        &before.due_date.map(format_date).unwrap_or_default(),
        &issue.due_date.map(format_date).unwrap_or_default(),
    );
    if before.description != issue.description {
        // The text itself is not worth replaying, but a rewrite that drops
        // sections is exactly what someone auditing the ticket wants to see.
        let lost: Vec<&str> = ["Spec", "Plan", "Activity Log", "Notes"]
            .into_iter()
            .filter(|anchor| {
                find_section(&before.description, anchor).2
                    && !find_section(&issue.description, anchor).2
            })
            .collect();
        if lost.is_empty() {
            summary.note("description rewritten");
        } else {
            summary.note(format!(
                "description rewritten, dropped ## {}",
                lost.join(", ## ")
            ));
        }
    }
    for l in &added_labels {
        summary.note(format!("+label {l}"));
    }
    for l in &removed_labels {
        summary.note(format!("-label {l}"));
    }
    for (verb, keys) in [
        ("blocks", &summary_blocks),
        ("blocked-by", &summary_blocked_by),
        ("related-to", &summary_related_to),
    ] {
        for k in keys {
            summary.note(format!("+{verb} {k}"));
        }
    }
    for k in &summary_remove_relation {
        summary.note(format!("-relation {k}"));
    }
    if !summary.is_empty() {
        let (id, message) = (issue.id, summary.message());
        store
            .call(move |conn| {
                if let Some(i) = issues::get_by_id(conn, id)? {
                    crate::audit::record(conn, &i, "edit", &message);
                }
                Ok(())
            })
            .await?;
    }

    print_issue_result(&store, &issue, "updated", a.json).await
}

async fn log(db: &Option<String>, a: LogArgs) -> CliResult<()> {
    let key = parse_issue_key(&a.key)?;
    let mut msg = a.message.clone().unwrap_or_default();
    if let Some(file) = &a.message_file {
        if !msg.is_empty() {
            return Err(CliError::validation(
                "pass <message> OR --message-file, not both",
            ));
        }
        let content = if file == "-" {
            read_stdin()?
        } else {
            std::fs::read_to_string(file).map_err(|e| CliError::validation(e.to_string()))?
        };
        msg = content.trim_end_matches('\n').to_string();
    }
    if msg.is_empty() {
        return Err(CliError::validation(
            "message required (positional or --message-file)",
        ));
    }

    let store = store_open::open(db).await?;
    let lookup = key.clone();
    let now = Utc::now();
    let entry = msg.clone();
    store
        .call(move |conn| {
            let tx = conn.unchecked_transaction()?;
            let issue = issues::get_by_key(&tx, &lookup)?.ok_or(cliban_core::Error::NotFound)?;
            let new_desc = descmd::append_activity_log(&issue.description, &entry, now);
            let updated = format_usec(now);
            tx.execute(
                "UPDATE issues SET description = ?1, updated_at = ?2 WHERE id = ?3",
                rusqlite::params![new_desc, updated, issue.id],
            )?;
            // Also record it durably: the markdown line lives in the
            // description and a later `--description` rewrite would erase it,
            // taking the note out of the timeline with it.
            crate::audit::record(&tx, &issue, "log", &entry);
            tx.commit()?;
            Ok(())
        })
        .await?;

    if a.json {
        let mut m = serde_json::Map::new();
        m.insert("entry".into(), serde_json::json!(msg));
        m.insert("key".into(), serde_json::json!(a.key));
        m.insert("timestamp".into(), serde_json::json!(format_usec(now)));
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::Value::Object(m)).unwrap()
        );
    } else {
        println!("logged on {}: {}", a.key, msg);
    }
    Ok(())
}

async fn tick(db: &Option<String>, a: TickArgs) -> CliResult<()> {
    let key = parse_issue_key(&a.key)?;
    let store = store_open::open(db).await?;
    let lookup = key.clone();
    let task = a.task;
    let step = a.step;
    let updated_at = store
        .call(move |conn| {
            let tx = conn.unchecked_transaction()?;
            let issue = issues::get_by_key(&tx, &lookup)?.ok_or(cliban_core::Error::NotFound)?;
            let new_desc = match descmd::tick_step(&issue.description, task, step) {
                Ok(d) => d,
                Err(msg) => return Err(cliban_core::Error::validation("plan", &msg)),
            };
            let now = format_usec(cliban_core::time::now_usec());
            tx.execute(
                "UPDATE issues SET description = ?1, updated_at = ?2 WHERE id = ?3",
                rusqlite::params![new_desc, now, issue.id],
            )?;
            crate::audit::record(
                &tx,
                &issue,
                "plan",
                &format!("ticked Task {task} Step {step}"),
            );
            tx.commit()?;
            Ok(now)
        })
        .await?;

    if a.json {
        let mut m = serde_json::Map::new();
        m.insert("checked".into(), serde_json::json!(true));
        m.insert("key".into(), serde_json::json!(a.key));
        m.insert("step".into(), serde_json::json!(a.step));
        m.insert("task".into(), serde_json::json!(a.task));
        m.insert("updated_at".into(), serde_json::json!(updated_at));
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::Value::Object(m)).unwrap()
        );
    } else {
        println!("ticked {} Task {} Step {}", a.key, a.task, a.step);
    }
    Ok(())
}

async fn promote(db: &Option<String>, a: PromoteArgs) -> CliResult<()> {
    let key = parse_issue_key(&a.key)?;
    let project_part = project_prefix(&key).to_string();

    // Up-front validations (mirror Go PromoteStep ordering).
    if a.title.is_empty() {
        return Err(CliError::validation("--title required"));
    }
    if a.as_mode != "sub-issue" && a.as_mode != "related" {
        return Err(CliError::validation(format!(
            "invalid --as {:?} (want sub-issue|related)",
            a.as_mode
        )));
    }

    let store = store_open::open(db).await?;
    let lookup = key.clone();
    let child_origin = key.clone();
    let task = a.task;
    let step = a.step;
    let title = a.title.clone();
    let mode = a.as_mode.clone();
    let proj_key = project_part.clone();

    let new_key = store
        .call(move |conn| {
            let tx = conn.unchecked_transaction()?;

            // 1. Read parent issue + project.
            let parent: Option<(i64, i64, String, Option<i64>, i64)> = tx
                .query_row(
                    "SELECT i.id, i.project_id, i.description, i.parent_id, p.issue_seq \
                     FROM issues i JOIN projects p ON p.id = i.project_id WHERE i.key = ?1",
                    rusqlite::params![lookup],
                    |r| {
                        Ok((
                            r.get(0)?,
                            r.get(1)?,
                            r.get(2)?,
                            r.get(3)?,
                            r.get(4)?,
                        ))
                    },
                )
                .optional()?;
            let (parent_id, proj_id, parent_desc, parent_parent, issue_seq) = match parent {
                Some(v) => v,
                None => return Err(cliban_core::Error::NotFound),
            };

            if mode == "sub-issue" && parent_parent.is_some() {
                return Err(cliban_core::Error::validation(
                    "depth",
                    "cannot promote as sub-issue of a sub-issue (would exceed depth 2)",
                ));
            }

            // 2. Allocate seq + insert new issue.
            let new_seq = issue_seq + 1;
            let max_pos: Option<f64> = tx.query_row(
                "SELECT max(position) FROM issues WHERE project_id = ?1 AND status = 'backlog'",
                rusqlite::params![proj_id],
                |r| r.get(0),
            )?;
            let pos = max_pos.unwrap_or(0.0) + 1000.0;
            let now = format_usec(cliban_core::time::now_usec());
            let new_key = format!("{proj_key}-{new_seq}");
            let sub_parent: Option<i64> = if mode == "sub-issue" {
                Some(parent_id)
            } else {
                None
            };
            tx.execute(
                "INSERT INTO issues (key, project_id, milestone_id, parent_id, title, \
                 description, status, priority, position, archived, inserted_at, updated_at) \
                 VALUES (?1, ?2, NULL, ?3, ?4, '', 'backlog', 'none', ?5, 0, ?6, ?6)",
                rusqlite::params![new_key, proj_id, sub_parent, title, pos, now],
            )?;
            let new_id = tx.last_insert_rowid();
            tx.execute(
                "UPDATE projects SET issue_seq = ?1, updated_at = ?2 WHERE id = ?3",
                rusqlite::params![new_seq, now, proj_id],
            )?;

            // 3. Related mode: insert related_to in BOTH directions.
            if mode == "related" {
                tx.execute(
                    "INSERT OR IGNORE INTO issue_relation (from_issue_id, to_issue_id, type, created_at) \
                     VALUES (?1, ?2, 'related_to', ?3)",
                    rusqlite::params![new_id, parent_id, now],
                )?;
                tx.execute(
                    "INSERT OR IGNORE INTO issue_relation (from_issue_id, to_issue_id, type, created_at) \
                     VALUES (?1, ?2, 'related_to', ?3)",
                    rusqlite::params![parent_id, new_id, now],
                )?;
            }

            // 4. Rewrite the parent's step line.
            let step_obj = find_step_for_rewrite(&parent_desc, task, step);
            let raw = match step_obj {
                Some(s) => s,
                None => {
                    return Err(cliban_core::Error::validation(
                        "plan",
                        &format!("cannot find Task {task} Step {step} in parent description"),
                    ))
                }
            };
            let new_line = build_promoted_line(&raw, &new_key);
            let new_desc = match descmd::rewrite_step_line(&parent_desc, task, step, &new_line) {
                Ok(d) => d,
                Err(msg) => return Err(cliban_core::Error::validation("plan", &msg)),
            };
            tx.execute(
                "UPDATE issues SET description = ?1, updated_at = ?2 WHERE id = ?3",
                rusqlite::params![new_desc, now, parent_id],
            )?;

            // Both sides of the split get the record: the parent lost a step,
            // the new issue says where it came from.
            if let Some(parent_issue) = issues::get_by_id(&tx, parent_id)? {
                crate::audit::record(
                    &tx,
                    &parent_issue,
                    "plan",
                    &format!("promoted Task {task} Step {step} → {new_key}"),
                );
            }
            if let Some(child) = issues::get_by_id(&tx, new_id)? {
                crate::audit::record(
                    &tx,
                    &child,
                    "plan",
                    &format!("promoted from {} Task {task} Step {step}", child_origin),
                );
            }

            tx.commit()?;
            Ok(new_key)
        })
        .await?;

    if a.json {
        let mut m = serde_json::Map::new();
        m.insert("new_key".into(), serde_json::json!(new_key));
        m.insert("parent".into(), serde_json::json!(a.key));
        m.insert("step".into(), serde_json::json!(a.step));
        m.insert("task".into(), serde_json::json!(a.task));
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::Value::Object(m)).unwrap()
        );
    } else {
        println!(
            "promoted {} Task {} Step {} → {}",
            a.key, a.task, a.step, new_key
        );
    }
    Ok(())
}

/// Mirror Go `findStepForRewrite`: FindSection(Plan) → FindTask → FindStep,
/// returning the raw step line.
fn find_step_for_rewrite(desc: &str, task_n: i32, step_m: i32) -> Option<String> {
    let (plan_start, plan_end, ok) = find_section(desc, "Plan");
    if !ok {
        return None;
    }
    let plan_body = &desc[plan_start..plan_end];
    let (task_start, task_end, ok) = crate::descmd::find_task(plan_body, task_n);
    if !ok {
        return None;
    }
    crate::descmd::find_step(&plan_body[task_start..task_end], step_m).map(|s| s.raw)
}

/// Mirror Go `buildPromotedLine`: strip an existing " → ..." suffix and append
/// " → {NEWKEY}\n".
fn build_promoted_line(original: &str, new_key: &str) -> String {
    let trimmed = original.trim_end_matches('\n');
    let trimmed = match trimmed.rfind(" → ") {
        Some(idx) => &trimmed[..idx],
        None => trimmed,
    };
    format!("{trimmed} → {new_key}\n")
}

async fn archive_done(db: &Option<String>, a: ArchiveDoneArgs) -> CliResult<()> {
    let store = store_open::open(db).await?;
    if a.auto {
        let n = store
            .call(|conn| {
                let now = format_usec(cliban_core::time::now_usec());
                // Per-project policy sweep (mirror Go SweepAutoArchive).
                let mut pols: Vec<(String, i64)> = Vec::new();
                {
                    let mut stmt = conn.prepare(
                        "SELECT key, auto_archive_done_after_days FROM projects \
                         WHERE auto_archive_done_after_days IS NOT NULL",
                    )?;
                    let rows =
                        stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
                    for row in rows {
                        pols.push(row?);
                    }
                }
                let mut total = 0i64;
                for (pkey, days) in pols {
                    let n = conn.execute(
                        "UPDATE issues SET archived = 1, updated_at = ?1 \
                         WHERE archived = 0 AND status = 'done' AND completed_at IS NOT NULL \
                         AND project_id = (SELECT id FROM projects WHERE key = ?2) \
                         AND datetime(completed_at, '+' || ?3 || ' days') < datetime('now')",
                        rusqlite::params![now, pkey, days],
                    )?;
                    total += n as i64;
                }
                Ok(total)
            })
            .await?;
        if a.json {
            let mut m = serde_json::Map::new();
            m.insert("archived".into(), serde_json::json!(n));
            m.insert("mode".into(), serde_json::json!("auto"));
            println!(
                "{}",
                serde_json::to_string_pretty(&serde_json::Value::Object(m)).unwrap()
            );
        } else {
            println!("archived {n} done issue(s) (auto sweep)");
        }
        return Ok(());
    }

    let project = a.project.filter(|p| !p.is_empty());
    let project = match project {
        Some(p) => p.to_uppercase(),
        None => {
            return Err(CliError::validation(
                "--project is required (or use --auto for the per-project policy)",
            ))
        }
    };
    let pkey = project.clone();
    let n = store
        .call(move |conn| {
            let now = format_usec(cliban_core::time::now_usec());
            let n = conn.execute(
                "UPDATE issues SET archived = 1, updated_at = ?1 \
                 WHERE archived = 0 AND status = 'done' \
                 AND project_id = (SELECT id FROM projects WHERE key = ?2)",
                rusqlite::params![now, pkey],
            )?;
            Ok(n as i64)
        })
        .await?;
    if a.json {
        let mut m = serde_json::Map::new();
        m.insert("archived".into(), serde_json::json!(n));
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::Value::Object(m)).unwrap()
        );
    } else {
        println!("archived {n} done issue(s) in {project}");
    }
    Ok(())
}

async fn import(db: &Option<String>, a: ImportArgs) -> CliResult<()> {
    let path = a.file_arg.clone().or(a.file.clone());
    let content = match path.as_deref() {
        None | Some("") | Some("-") => read_stdin()?,
        Some(p) => std::fs::read_to_string(p).map_err(|e| CliError::other(e.to_string()))?,
    };
    let default_project = a.project.clone().unwrap_or_default();

    let store = store_open::open(db).await?;
    let mut created = 0i64;
    let mut line_no = 0i64;
    for raw in content.lines() {
        line_no += 1;
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let spec: serde_json::Value = serde_json::from_str(line)
            .map_err(|e| CliError::other(format!("line {line_no}: invalid JSON: {e}")))?;

        let get_str = |k: &str| {
            spec.get(k)
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string()
        };
        let mut project = get_str("project");
        if project.is_empty() {
            project = default_project.clone();
        }
        if project.is_empty() {
            return Err(CliError::validation(format!(
                "line {line_no}: project required (set per-record or pass --project)"
            )));
        }
        let project = project.to_uppercase();
        let title = get_str("title");
        let description = get_str("description");
        let status = {
            let s = get_str("status");
            if s.is_empty() {
                None
            } else {
                Some(parse_status_lined(&s, line_no)?)
            }
        };
        let priority = {
            let p = get_str("priority");
            if p.is_empty() {
                None
            } else {
                Some(parse_priority_lined(&p, line_no)?)
            }
        };
        let milestone = {
            let m = get_str("milestone");
            if m.is_empty() {
                None
            } else {
                Some(m)
            }
        };
        let parent_key = {
            let p = get_str("parent");
            if p.is_empty() {
                None
            } else {
                Some(parse_issue_key_lined(&p, line_no)?)
            }
        };
        let labels: Vec<String> = spec
            .get("labels")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();

        let create_project = project.clone();
        let create = CreateIssue {
            title,
            description: Some(description),
            status,
            priority,
            milestone,
            parent_key,
            due_date: None,
            position: None,
        };
        let issue = store
            .call(move |conn| issues::create(conn, &create_project, create))
            .await
            .map_err(|e| prefix_line_err(e, line_no))?;

        for lbl in labels {
            let id = issue.id;
            let name = lbl.clone();
            store
                .call(move |conn| {
                    let issue = issues::get_by_id(conn, id)?.ok_or(cliban_core::Error::NotFound)?;
                    issues::add_label(conn, &issue, &name)
                })
                .await
                .map_err(|e| {
                    let code = crate::errors::exit_code_for(&e);
                    let msg = crate::errors::message_for(&e);
                    CliError::Coded(code, format!("line {line_no}: attach label {lbl:?}: {msg}"))
                })?;
        }

        created += 1;
        if a.json {
            let inputs = issue_json_inputs(&store, &issue).await?;
            println!(
                "{}",
                serde_json::to_string(&build_issue_json(inputs, Detail::Full)).unwrap()
            );
        }
    }
    if !a.json {
        println!("imported {created} issue(s)");
    }
    Ok(())
}

/// Prefix a core error's message with `line {n}: `, preserving the exit code.
fn prefix_line_err(e: cliban_core::Error, line_no: i64) -> CliError {
    let code = crate::errors::exit_code_for(&e);
    let msg = crate::errors::message_for(&e);
    CliError::Coded(code, format!("line {line_no}: {msg}"))
}

fn parse_status_lined(s: &str, line_no: i64) -> Result<String, CliError> {
    parse_status(s)
        .map_err(|e| CliError::Coded(e.code(), format!("line {line_no}: {}", e.message())))
}

fn parse_priority_lined(s: &str, line_no: i64) -> Result<String, CliError> {
    parse_priority(s)
        .map_err(|e| CliError::Coded(e.code(), format!("line {line_no}: {}", e.message())))
}

fn parse_issue_key_lined(s: &str, line_no: i64) -> Result<String, CliError> {
    parse_issue_key(s)
        .map_err(|e| CliError::Coded(e.code(), format!("line {line_no}: {}", e.message())))
}

async fn mv(
    db: &Option<String>,
    key: String,
    status: String,
    note: Option<String>,
) -> CliResult<()> {
    let key = parse_issue_key(&key)?;
    let status = parse_status(&status)?;
    let store = store_open::open(db).await?;
    store
        .call(move |conn| {
            let issue = issues::get_by_key(conn, &key)?.ok_or(cliban_core::Error::NotFound)?;
            let from = issue.status.clone();
            issues::move_issue(conn, &issue, &status)?;
            // The move is the event worth recording; `--note` carries the why.
            crate::audit::record_move(conn, &issue, &from, &status, note.as_deref());
            Ok(())
        })
        .await?;
    Ok(())
}

async fn set_archived(db: &Option<String>, key: String, archived: bool) -> CliResult<()> {
    let key = parse_issue_key(&key)?;
    let store = store_open::open(db).await?;
    store
        .call(move |conn| {
            let issue = issues::get_by_key(conn, &key)?.ok_or(cliban_core::Error::NotFound)?;
            issues::update(
                conn,
                &issue,
                UpdateIssue {
                    archived: Some(archived),
                    ..Default::default()
                },
            )?;
            crate::audit::record(
                conn,
                &issue,
                "archive",
                if archived { "archived" } else { "unarchived" },
            );
            Ok(())
        })
        .await?;
    Ok(())
}

/// `branchIssueRE`: `^([a-z][a-z0-9]+)-(\d+)(?:-|$)`. Hand-written, no regex
/// crate. Returns `(project_lower, seq_digits)` on match.
fn parse_branch(branch: &str) -> Option<(String, String)> {
    let bytes = branch.as_bytes();
    let n = bytes.len();
    // [a-z]
    if n == 0 || !bytes[0].is_ascii_lowercase() {
        return None;
    }
    // [a-z0-9]+ (at least one more char after the leading [a-z])
    let mut i = 1;
    while i < n && (bytes[i].is_ascii_lowercase() || bytes[i].is_ascii_digit()) {
        i += 1;
    }
    // The regex requires `[a-z][a-z0-9]+` — i.e. >= 2 chars in the project run.
    if i < 2 {
        return None;
    }
    // `-`
    if i >= n || bytes[i] != b'-' {
        return None;
    }
    let dash = i;
    i += 1;
    // \d+
    let seq_start = i;
    while i < n && bytes[i].is_ascii_digit() {
        i += 1;
    }
    if i == seq_start {
        return None;
    }
    // (?:-|$)
    if i != n && bytes[i] != b'-' {
        return None;
    }
    let project = branch[..dash].to_string();
    let seq = branch[seq_start..i].to_string();
    Some((project, seq))
}

fn current_branch() -> Result<String, CliError> {
    if let Ok(v) = std::env::var("CLIBAN_CURRENT_BRANCH_OVERRIDE") {
        if !v.is_empty() {
            return Ok(v);
        }
    }
    let out = std::process::Command::new("git")
        .args(["branch", "--show-current"])
        .output()
        .map_err(|e| CliError::other(format!("git branch --show-current: {e}")))?;
    if !out.status.success() {
        return Err(CliError::other(
            "git branch --show-current: command failed".to_string(),
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

async fn current(db: &Option<String>, json: bool) -> CliResult<()> {
    let branch = current_branch()?;
    let (proj, seq) = parse_branch(&branch).ok_or_else(|| {
        // Go wraps with %w on store.ErrNotFound → "not found: <msg>".
        CliError::not_found(format!(
            "not found: no issue found for current branch {branch:?}"
        ))
    })?;
    let key = format!("{}-{}", proj.to_uppercase(), seq);
    let store = store_open::open(db).await?;
    let lookup = key.clone();
    let issue = match store
        .call(move |conn| issues::get_by_key(conn, &lookup))
        .await?
    {
        Some(i) => i,
        None => {
            return Err(CliError::not_found(format!(
                "not found: no issue found for current branch {branch:?} (parsed {key})"
            )))
        }
    };
    if json {
        let inputs = issue_json_inputs(&store, &issue).await?;
        println!(
            "{}",
            serde_json::to_string_pretty(&build_issue_json(inputs, Detail::Full)).unwrap()
        );
    } else {
        println!("{} {}", issue.key, issue.title);
    }
    Ok(())
}

async fn blocked(
    db: &Option<String>,
    project: Option<String>,
    json: bool,
    full: bool,
) -> CliResult<()> {
    let project = project.map(|p| p.to_uppercase()).filter(|p| !p.is_empty());
    let store = store_open::open(db).await?;
    let pk = project.clone();
    let mut issues = store
        .call(move |conn| relations::list_blocked(conn, pk.as_deref()))
        .await?;
    // Match the Go store ordering: ORDER BY p.key, i.status, i.position.
    base_order(&mut issues);
    if json {
        for i in &issues {
            let inputs = issue_json_inputs(&store, i).await?;
            println!(
                "{}",
                serde_json::to_string(&build_issue_json(inputs, Detail::from_full_flag(full)))
                    .unwrap()
            );
        }
        return Ok(());
    }
    let rows = issue_rows(&store, &issues).await?;
    print!("{}", write_issue_table(&rows));
    Ok(())
}