bones-cli 0.24.0

CLI binary for bones issue tracker
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
// ---------------------------------------------------------------------------
// Clipboard
// ---------------------------------------------------------------------------

/// Copy text to the system clipboard using platform-native tools.
///
/// macOS: `pbcopy`
/// Linux: tries `wl-copy` (Wayland), then `xclip`, then `xsel`.
fn copy_to_clipboard(text: &str) -> Result<(), String> {
    use std::process::{Command, Stdio};

    let candidates: &[&[&str]] = if cfg!(target_os = "macos") {
        &[&["pbcopy"]]
    } else {
        &[
            &["wl-copy"],
            &["xclip", "-selection", "clipboard"],
            &["xsel", "--clipboard", "--input"],
        ]
    };

    for args in candidates {
        let prog = args[0];
        let extra = &args[1..];
        if let Ok(mut child) = Command::new(prog)
            .args(extra)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
        {
            if let Some(stdin) = child.stdin.as_mut() {
                use std::io::Write;
                let _ = stdin.write_all(text.as_bytes());
            }
            if child.wait().is_ok_and(|s| s.success()) {
                return Ok(());
            }
        }
    }

    Err("no clipboard tool found (install xclip, xsel, or wl-copy)".to_string())
}

// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------

/// Filter criteria applied to the item list.
#[derive(Debug, Clone, Default)]
pub struct FilterState {
    /// Filter by lifecycle state (open, doing, done, archived).
    pub state: Option<String>,
    /// Filter by item kind (task, goal, bug).
    pub kind: Option<String>,
    /// Filter by label (substring match on the label string).
    pub label: Option<String>,
    /// Filter by urgency (urgent, default, punt).
    pub urgency: Option<String>,
    /// Free-text search query (matches against title via substring).
    pub search_query: String,
}

impl FilterState {
    /// Returns true if no filter criteria are active.
    pub const fn is_empty(&self) -> bool {
        self.state.is_none()
            && self.kind.is_none()
            && self.label.is_none()
            && self.urgency.is_none()
            && self.search_query.is_empty()
    }

    /// Apply this filter to a list of items.
    ///
    /// Returns a new vec containing only items that match all active criteria.
    pub fn apply(&self, items: &[WorkItem]) -> Vec<WorkItem> {
        items
            .iter()
            .filter(|item| self.matches(item))
            .cloned()
            .collect()
    }

    /// Returns true if the item satisfies all active filter criteria.
    pub fn matches(&self, item: &WorkItem) -> bool {
        if let Some(ref state) = self.state
            && item.state != *state
        {
            return false;
        }
        if let Some(ref kind) = self.kind
            && item.kind != *kind
        {
            return false;
        }
        if let Some(ref urgency) = self.urgency
            && item.urgency != *urgency
        {
            return false;
        }
        if let Some(ref label) = self.label
            && !item.labels.iter().any(|l| l.contains(label.as_str()))
        {
            return false;
        }
        if !self.search_query.is_empty() {
            let q = self.search_query.to_ascii_lowercase();
            if !item.title.to_ascii_lowercase().contains(&q)
                && !item.item_id.to_ascii_lowercase().contains(&q)
            {
                return false;
            }
        }
        true
    }
}

/// Sort field for the item list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortField {
    /// Sort by dependency execution order (blockers before blocked),
    /// using priority as the tie-breaker among ready items.
    #[default]
    Execution,
    /// Sort by priority: urgent → default → punt, then `updated_at` desc.
    Priority,
    /// Sort by `created_at` descending (newest first).
    Created,
    /// Sort by `updated_at` descending (most recently changed first).
    Updated,
    /// Sort by label/tag alphabetically, then by `updated_at` within each group.
    Tags,
}

impl SortField {
    const fn label(self) -> &'static str {
        match self {
            Self::Execution => "execution",
            Self::Priority => "priority",
            Self::Created => "created",
            Self::Updated => "updated",
            Self::Tags => "tags",
        }
    }

    const fn next(self) -> Self {
        match self {
            Self::Execution => Self::Priority,
            Self::Priority => Self::Created,
            Self::Created => Self::Updated,
            Self::Updated => Self::Tags,
            Self::Tags => Self::Execution,
        }
    }
}

/// A single item held in memory by the list view.
#[derive(Debug, Clone)]
pub struct WorkItem {
    pub item_id: String,
    pub title: String,
    pub kind: String,
    pub state: String,
    pub urgency: String,
    pub size: Option<String>,
    pub labels: Vec<String>,
    pub created_at_us: i64,
    pub updated_at_us: i64,
}

impl WorkItem {
    /// Construct from a `QueryItem` plus its label list.
    pub fn from_query(qi: QueryItem, labels: Vec<String>) -> Self {
        Self {
            item_id: qi.item_id,
            title: qi.title,
            kind: qi.kind,
            state: qi.state,
            urgency: qi.urgency,
            size: qi.size,
            labels,
            created_at_us: qi.created_at_us,
            updated_at_us: qi.updated_at_us,
        }
    }
}

#[derive(Debug, Clone)]
struct DetailComment {
    author: String,
    body: String,
    created_at_us: i64,
}

#[derive(Debug, Clone)]
struct DetailRef {
    id: String,
    title: Option<String>,
}

#[derive(Debug, Clone)]
struct DetailItem {
    id: String,
    title: String,
    description: Option<String>,
    kind: String,
    state: String,
    urgency: String,
    size: Option<String>,
    parent_id: Option<String>,
    labels: Vec<String>,
    assignees: Vec<String>,
    blockers: Vec<DetailRef>,
    blocked: Vec<DetailRef>,
    relationships: Vec<DetailRef>,
    comments: Vec<DetailComment>,
    created_at_us: i64,
    updated_at_us: i64,
}

fn urgency_rank(u: &str) -> u8 {
    match u {
        "urgent" => 0,
        "default" => 1,
        "punt" => 2,
        _ => 3,
    }
}

fn is_related_link(link_type: &str) -> bool {
    matches!(link_type, "related_to" | "related" | "relates")
}

fn load_detail_refs(conn: &rusqlite::Connection, mut ids: Vec<String>) -> Result<Vec<DetailRef>> {
    ids.sort_unstable();
    ids.dedup();
    ids.into_iter()
        .map(|id| {
            let title = query::get_item(conn, &id, false)?.map(|item| item.title);
            Ok(DetailRef { id, title })
        })
        .collect()
}

/// Sort a mutable slice of `WorkItem` by the given `SortField`.
///
/// Uses `sort_unstable_by` because every comparator below breaks ties on
/// `item_id`, which makes the ordering total and deterministic — `item_id`
/// is unique per row, so stability adds no visible guarantee.
pub fn sort_items(items: &mut [WorkItem], sort: SortField) {
    items.sort_unstable_by(|a, b| match sort {
        SortField::Execution => urgency_rank(&a.urgency)
            .cmp(&urgency_rank(&b.urgency))
            .then_with(|| b.updated_at_us.cmp(&a.updated_at_us))
            .then_with(|| a.item_id.cmp(&b.item_id)),
        SortField::Priority => urgency_rank(&a.urgency)
            .cmp(&urgency_rank(&b.urgency))
            .then_with(|| b.updated_at_us.cmp(&a.updated_at_us))
            .then_with(|| a.item_id.cmp(&b.item_id)),
        SortField::Created => b
            .created_at_us
            .cmp(&a.created_at_us)
            .then_with(|| a.item_id.cmp(&b.item_id)),
        SortField::Updated => b
            .updated_at_us
            .cmp(&a.updated_at_us)
            .then_with(|| a.item_id.cmp(&b.item_id)),
        SortField::Tags => {
            let a_tag = a.labels.first().map(String::as_str).unwrap_or("\u{ffff}");
            let b_tag = b.labels.first().map(String::as_str).unwrap_or("\u{ffff}");
            a_tag
                .cmp(b_tag)
                .then_with(|| b.updated_at_us.cmp(&a.updated_at_us))
                .then_with(|| a.item_id.cmp(&b.item_id))
        }
    });
}

fn sort_items_execution(items: &mut Vec<WorkItem>, blocker_map: &HashMap<String, Vec<String>>) {
    if items.is_empty() {
        return;
    }

    let base_order: Vec<String> = items.iter().map(|item| item.item_id.clone()).collect();
    let base_rank: HashMap<String, usize> = base_order
        .iter()
        .enumerate()
        .map(|(idx, id)| (id.clone(), idx))
        .collect();
    let id_set: HashSet<String> = base_order.iter().cloned().collect();

    let mut indegree: HashMap<String, usize> =
        base_order.iter().map(|id| (id.clone(), 0)).collect();
    let mut outgoing: HashMap<String, Vec<String>> = HashMap::new();

    for blocked_id in &base_order {
        if let Some(blockers) = blocker_map.get(blocked_id) {
            for blocker_id in blockers {
                if !id_set.contains(blocker_id) {
                    continue;
                }
                *indegree.entry(blocked_id.clone()).or_insert(0) += 1;
                outgoing
                    .entry(blocker_id.clone())
                    .or_default()
                    .push(blocked_id.clone());
            }
        }
    }

    let mut ready: Vec<String> = base_order
        .iter()
        .filter(|id| indegree.get(*id).copied().unwrap_or(0) == 0)
        .cloned()
        .collect();

    let mut ordered_ids = Vec::with_capacity(base_order.len());
    while let Some(next_id) = ready.first().cloned() {
        ready.remove(0);
        ordered_ids.push(next_id.clone());

        if let Some(children) = outgoing.get(&next_id) {
            for child in children {
                if let Some(deg) = indegree.get_mut(child) {
                    if *deg > 0 {
                        *deg -= 1;
                    }
                    if *deg == 0 {
                        let rank = base_rank.get(child).copied().unwrap_or(usize::MAX);
                        let insert_at = ready
                            .binary_search_by_key(&rank, |id| {
                                base_rank.get(id).copied().unwrap_or(usize::MAX)
                            })
                            .unwrap_or_else(|idx| idx);
                        ready.insert(insert_at, child.clone());
                    }
                }
            }
        }
    }

    if ordered_ids.len() < base_order.len() {
        for id in &base_order {
            if !ordered_ids.iter().any(|seen| seen == id) {
                ordered_ids.push(id.clone());
            }
        }
    }

    let mut by_id: HashMap<String, WorkItem> = items
        .drain(..)
        .map(|item| (item.item_id.clone(), item))
        .collect();
    for item_id in ordered_ids {
        if let Some(item) = by_id.remove(&item_id) {
            items.push(item);
        }
    }
}

fn load_blocker_map(conn: &rusqlite::Connection) -> Result<HashMap<String, Vec<String>>> {
    let mut stmt = conn.prepare(
        "SELECT item_id, depends_on_item_id
         FROM item_dependencies
         WHERE link_type IN ('blocks', 'blocked_by')
         ORDER BY item_id, depends_on_item_id",
    )?;

    let rows = stmt.query_map([], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
    })?;

    let mut map: HashMap<String, Vec<String>> = HashMap::new();
    for row in rows {
        let (item_id, blocker_id) = row?;
        map.entry(item_id).or_default().push(blocker_id);
    }

    for blockers in map.values_mut() {
        blockers.sort_unstable();
        blockers.dedup();
    }

    Ok(map)
}

fn build_hierarchy_order(
    sorted_items: Vec<WorkItem>,
    parent_map: &HashMap<String, Option<String>>,
) -> (Vec<WorkItem>, Vec<usize>) {
    if sorted_items.is_empty() {
        return (Vec::new(), Vec::new());
    }

    let sorted_ids: Vec<String> = sorted_items.iter().map(|i| i.item_id.clone()).collect();
    let id_set: HashSet<String> = sorted_ids.iter().cloned().collect();

    let mut children: HashMap<String, Vec<String>> = HashMap::new();
    let mut roots: Vec<String> = Vec::new();

    for item_id in &sorted_ids {
        let parent_id = parent_map.get(item_id).cloned().flatten();
        if let Some(parent_id) = parent_id {
            if id_set.contains(&parent_id) {
                children.entry(parent_id).or_default().push(item_id.clone());
            } else {
                roots.push(item_id.clone());
            }
        } else {
            roots.push(item_id.clone());
        }
    }

    let mut by_id: HashMap<String, WorkItem> = sorted_items
        .into_iter()
        .map(|item| (item.item_id.clone(), item))
        .collect();
    let mut visited: HashSet<String> = HashSet::new();
    let mut ordered = Vec::new();
    let mut depths = Vec::new();

    fn visit(
        item_id: &str,
        depth: usize,
        children: &HashMap<String, Vec<String>>,
        by_id: &mut HashMap<String, WorkItem>,
        visited: &mut HashSet<String>,
        ordered: &mut Vec<WorkItem>,
        depths: &mut Vec<usize>,
    ) {
        if !visited.insert(item_id.to_string()) {
            return;
        }

        if let Some(item) = by_id.remove(item_id) {
            ordered.push(item);
            depths.push(depth);
        }

        if let Some(kids) = children.get(item_id) {
            for child in kids {
                visit(child, depth + 1, children, by_id, visited, ordered, depths);
            }
        }
    }

    for root in &roots {
        visit(
            root,
            0,
            &children,
            &mut by_id,
            &mut visited,
            &mut ordered,
            &mut depths,
        );
    }

    for item_id in &sorted_ids {
        if !visited.contains(item_id) {
            visit(
                item_id,
                0,
                &children,
                &mut by_id,
                &mut visited,
                &mut ordered,
                &mut depths,
            );
        }
    }

    (ordered, depths)
}

fn build_dependency_order(
    sorted_items: Vec<WorkItem>,
    blocker_map: &HashMap<String, Vec<String>>,
    parent_map: &HashMap<String, Option<String>>,
) -> (Vec<WorkItem>, Vec<usize>) {
    if sorted_items.is_empty() {
        return (Vec::new(), Vec::new());
    }

    let sorted_ids: Vec<String> = sorted_items
        .iter()
        .map(|item| item.item_id.clone())
        .collect();
    let id_set: HashSet<String> = sorted_ids.iter().cloned().collect();
    let base_rank: HashMap<String, usize> = sorted_ids
        .iter()
        .enumerate()
        .map(|(idx, id)| (id.clone(), idx))
        .collect();

    // Build parent-child tree from the parent_map (hierarchy relationships).
    // An item whose parent_id points to an item in the current set is a
    // hierarchy child.
    let mut hierarchy_children: HashMap<String, Vec<String>> = HashMap::new();
    let mut has_hierarchy_parent: HashSet<String> = HashSet::new();
    for item_id in &sorted_ids {
        if let Some(Some(pid)) = parent_map.get(item_id)
            && id_set.contains(pid)
        {
            hierarchy_children
                .entry(pid.clone())
                .or_default()
                .push(item_id.clone());
            has_hierarchy_parent.insert(item_id.clone());
        }
    }
    // Sort hierarchy children by their execution rank so they appear in
    // the right relative order under their parent.
    for kids in hierarchy_children.values_mut() {
        kids.sort_by_key(|id| base_rank.get(id).copied().unwrap_or(usize::MAX));
    }

    // Build a lookup: item_id -> parent_id (for items that have a hierarchy parent).
    let mut item_parent: HashMap<String, String> = HashMap::new();
    for item_id in &sorted_ids {
        if let Some(Some(pid)) = parent_map.get(item_id)
            && id_set.contains(pid)
        {
            item_parent.insert(item_id.clone(), pid.clone());
        }
    }

    // Build dependency nesting.  Items with a hierarchy parent can still nest
    // under a blocker *if that blocker shares the same hierarchy parent* (i.e.
    // both are siblings under the same goal).  This preserves intra-phase
    // dependency indentation while keeping cross-phase items grouped under
    // their parent goal.
    let mut primary_blocker: HashMap<String, String> = HashMap::new();
    for blocked_id in &sorted_ids {
        let Some(blockers) = blocker_map.get(blocked_id) else {
            continue;
        };

        let blocked_parent = item_parent.get(blocked_id);

        let chosen = blockers
            .iter()
            .filter(|blocker_id| {
                if !id_set.contains((*blocker_id).as_str()) {
                    return false;
                }
                // If blocked item has a hierarchy parent, only nest under a
                // blocker that shares the same parent (sibling dependency).
                if let Some(bp) = blocked_parent {
                    let blocker_parent = item_parent.get((*blocker_id).as_str());
                    return blocker_parent == Some(bp);
                }
                true
            })
            .min_by_key(|blocker_id| {
                base_rank
                    .get((*blocker_id).as_str())
                    .copied()
                    .unwrap_or(usize::MAX)
            })
            .cloned();

        if let Some(blocker_id) = chosen {
            primary_blocker.insert(blocked_id.clone(), blocker_id);
        }
    }

    // Merge dependency children and hierarchy children into one tree.
    let mut children: HashMap<String, Vec<String>> = HashMap::new();
    for (blocked_id, blocker_id) in &primary_blocker {
        children
            .entry(blocker_id.clone())
            .or_default()
            .push(blocked_id.clone());
    }
    for dep_children in children.values_mut() {
        dep_children.sort_by_key(|item_id| {
            base_rank
                .get(item_id.as_str())
                .copied()
                .unwrap_or(usize::MAX)
        });
    }
    // Layer hierarchy children on top.  Only add children that are NOT already
    // nested under a sibling blocker (those are reachable via the dependency
    // tree within the parent group).
    for (parent_id, kids) in &hierarchy_children {
        let entry = children.entry(parent_id.clone()).or_default();
        let mut top_kids: Vec<String> = kids
            .iter()
            .filter(|kid| !primary_blocker.contains_key((*kid).as_str()))
            .cloned()
            .collect();
        top_kids.append(entry);
        *entry = top_kids;
    }

    // A root is any item that is neither a dependency child nor a hierarchy
    // child.
    let roots: Vec<String> = sorted_ids
        .iter()
        .filter(|item_id| {
            !primary_blocker.contains_key((*item_id).as_str())
                && !has_hierarchy_parent.contains((*item_id).as_str())
        })
        .cloned()
        .collect();

    let mut by_id: HashMap<String, WorkItem> = sorted_items
        .into_iter()
        .map(|item| (item.item_id.clone(), item))
        .collect();
    let mut visited: HashSet<String> = HashSet::new();
    let mut ordered = Vec::new();
    let mut depths = Vec::new();

    fn visit(
        item_id: &str,
        depth: usize,
        children: &HashMap<String, Vec<String>>,
        by_id: &mut HashMap<String, WorkItem>,
        visited: &mut HashSet<String>,
        ordered: &mut Vec<WorkItem>,
        depths: &mut Vec<usize>,
    ) {
        if !visited.insert(item_id.to_string()) {
            return;
        }

        if let Some(item) = by_id.remove(item_id) {
            ordered.push(item);
            depths.push(depth);
        }

        if let Some(direct) = children.get(item_id) {
            for child_id in direct {
                visit(
                    child_id,
                    depth + 1,
                    children,
                    by_id,
                    visited,
                    ordered,
                    depths,
                );
            }
        }
    }

    for root_id in &roots {
        visit(
            root_id,
            0,
            &children,
            &mut by_id,
            &mut visited,
            &mut ordered,
            &mut depths,
        );
    }

    for item_id in &sorted_ids {
        if !visited.contains(item_id) {
            visit(
                item_id,
                0,
                &children,
                &mut by_id,
                &mut visited,
                &mut ordered,
                &mut depths,
            );
        }
    }

    (ordered, depths)
}

// ---------------------------------------------------------------------------
// Application input modes
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum InputMode {
    #[default]
    Normal,
    /// User is typing a search query.
    Search,
    /// Create-bone modal is open.
    CreateModal,
    /// Comment/close/reopen note modal is open.
    NoteModal,
    /// Help overlay is open.
    Help,
    /// Filter popup is open.
    FilterPopup,
    /// Filter popup: editing a text field (label).
    FilterLabel,
    /// Blocker/link picker modal is open.
    BlockerModal,
    /// Edit-link modal is open.
    EditLinkModal,
}

// ---------------------------------------------------------------------------
// Application state
// ---------------------------------------------------------------------------

/// Current focus inside the filter popup.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum FilterField {
    #[default]
    State,
    Kind,
    Urgency,
    Label,
}

impl FilterField {
    const fn next(self) -> Self {
        match self {
            Self::State => Self::Kind,
            Self::Kind => Self::Urgency,
            Self::Urgency => Self::Label,
            Self::Label => Self::State,
        }
    }

    const fn prev(self) -> Self {
        match self {
            Self::State => Self::Label,
            Self::Kind => Self::State,
            Self::Urgency => Self::Kind,
            Self::Label => Self::Urgency,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum CreateField {
    #[default]
    Title,
    Description,
    Kind,
    Size,
    Urgency,
    Labels,
}

impl CreateField {
    const fn next(self) -> Self {
        match self {
            Self::Title => Self::Description,
            Self::Description => Self::Kind,
            Self::Kind => Self::Size,
            Self::Size => Self::Urgency,
            Self::Urgency => Self::Labels,
            Self::Labels => Self::Title,
        }
    }

    const fn prev(self) -> Self {
        match self {
            Self::Title => Self::Labels,
            Self::Description => Self::Title,
            Self::Kind => Self::Description,
            Self::Size => Self::Kind,
            Self::Urgency => Self::Size,
            Self::Labels => Self::Urgency,
        }
    }
}

#[derive(Debug, Clone)]
struct CreateDraft {
    title: String,
    description: Option<String>,
    kind: String,
    size: Option<String>,
    urgency: String,
    labels: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CreateAction {
    None,
    Submit,
    Cancel,
    OpenEditor,
}

#[derive(Debug, Clone)]
struct CreateModalState {
    focus: CreateField,
    title: String,
    title_cursor: usize,
    description: Vec<String>,
    desc_row: usize,
    desc_col: usize,
    kind_idx: usize,
    size_idx: usize,
    urgency_idx: usize,
    labels: String,
    labels_cursor: usize,
}

impl Default for CreateModalState {
    fn default() -> Self {
        Self {
            focus: CreateField::Title,
            title: String::new(),
            title_cursor: 0,
            description: vec![String::new()],
            desc_row: 0,
            desc_col: 0,
            kind_idx: 0,
            size_idx: 0,
            urgency_idx: 0,
            labels: String::new(),
            labels_cursor: 0,
        }
    }
}

impl CreateModalState {
    fn from_detail(detail: &DetailItem) -> Self {
        let mut modal = Self::default();
        modal.title = detail.title.clone();
        modal.title_cursor = char_len(&modal.title);
        modal.description = detail
            .description
            .as_deref()
            .map(|d| {
                d.lines()
                    .map(std::string::ToString::to_string)
                    .collect::<Vec<_>>()
            })
            .filter(|lines| !lines.is_empty())
            .unwrap_or_else(|| vec![String::new()]);
        modal.desc_row = modal.description.len().saturating_sub(1);
        modal.desc_col = char_len(&modal.description[modal.desc_row]);
        modal.kind_idx = match detail.kind.as_str() {
            "goal" => 1,
            "bug" => 2,
            _ => 0,
        };
        modal.size_idx = Self::size_index(detail.size.as_deref());
        modal.urgency_idx = Self::urgency_index(&detail.urgency);
        modal.labels = detail.labels.join(", ");
        modal.labels_cursor = char_len(&modal.labels);
        modal
    }

    const fn kind(&self) -> &str {
        match self.kind_idx {
            0 => "task",
            1 => "goal",
            2 => "bug",
            _ => "task",
        }
    }

    const fn size_options() -> [&'static str; 6] {
        ["(none)", "xs", "s", "m", "l", "xl"]
    }

    fn size_index(size: Option<&str>) -> usize {
        match size {
            Some("xs") => 1,
            Some("s") => 2,
            Some("m") => 3,
            Some("l") => 4,
            Some("xl") => 5,
            _ => 0,
        }
    }

    fn size(&self) -> Option<String> {
        if self.size_idx == 0 {
            None
        } else {
            Some(Self::size_options()[self.size_idx].to_string())
        }
    }

    const fn urgency_options() -> [&'static str; 3] {
        ["none", "urgent", "punted"]
    }

    fn urgency_index(urgency: &str) -> usize {
        match urgency {
            "urgent" => 1,
            "punt" => 2,
            _ => 0,
        }
    }

    const fn urgency_raw(&self) -> &'static str {
        match self.urgency_idx {
            1 => "urgent",
            2 => "punt",
            _ => "default",
        }
    }

    const fn urgency_display(&self) -> &'static str {
        Self::urgency_options()[self.urgency_idx]
    }

    fn can_submit(&self) -> bool {
        !self.title.trim().is_empty()
    }

    fn labels_vec(&self) -> Vec<String> {
        self.labels
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    fn description_value(&self) -> Option<String> {
        let text = self.description.join("\n");
        if text.trim().is_empty() {
            None
        } else {
            Some(text)
        }
    }

    fn build_draft(&self) -> CreateDraft {
        CreateDraft {
            title: self.title.trim().to_string(),
            description: self.description_value(),
            kind: self.kind().to_string(),
            size: self.size(),
            urgency: self.urgency_raw().to_string(),
            labels: self.labels_vec(),
        }
    }

    fn handle_key(&mut self, key: KeyEvent) -> CreateAction {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);

        match key.code {
            KeyCode::Esc => return CreateAction::Cancel,
            KeyCode::Char('s') if ctrl => {
                if self.can_submit() {
                    return CreateAction::Submit;
                }
                return CreateAction::None;
            }
            KeyCode::Enter if ctrl => {
                if self.can_submit() {
                    return CreateAction::Submit;
                }
                return CreateAction::None;
            }
            KeyCode::Char('g') if ctrl => {
                if matches!(self.focus, CreateField::Title | CreateField::Description) {
                    return CreateAction::OpenEditor;
                }
                return CreateAction::None;
            }
            KeyCode::BackTab => {
                self.focus = self.focus.prev();
                return CreateAction::None;
            }
            KeyCode::Tab if shift => {
                self.focus = self.focus.prev();
                return CreateAction::None;
            }
            KeyCode::Tab => {
                self.focus = self.focus.next();
                return CreateAction::None;
            }
            _ => {}
        }

        match self.focus {
            CreateField::Title => {
                if key.code == KeyCode::Enter {
                    self.focus = CreateField::Description;
                } else {
                    Self::edit_single_line(&mut self.title, &mut self.title_cursor, key);
                }
            }
            CreateField::Description => {
                self.edit_description(key);
            }
            CreateField::Kind => match key.code {
                KeyCode::Left | KeyCode::Up | KeyCode::Char('h' | 'k') => {
                    self.kind_idx = self.kind_idx.saturating_sub(1);
                }
                KeyCode::Right | KeyCode::Down | KeyCode::Char('l' | 'j') => {
                    self.kind_idx = (self.kind_idx + 1).min(2);
                }
                KeyCode::Char('t') => self.kind_idx = 0,
                KeyCode::Char('g') => self.kind_idx = 1,
                KeyCode::Char('b') => self.kind_idx = 2,
                _ => {}
            },
            CreateField::Size => match key.code {
                KeyCode::Left | KeyCode::Up | KeyCode::Char('h' | 'k') => {
                    self.size_idx = self.size_idx.saturating_sub(1);
                }
                KeyCode::Right | KeyCode::Down | KeyCode::Char('j') => {
                    self.size_idx = (self.size_idx + 1).min(Self::size_options().len() - 1);
                }
                KeyCode::Char('n') => self.size_idx = 0,
                KeyCode::Char('z') => self.size_idx = 1,
                KeyCode::Char('x') => self.size_idx = 2,
                KeyCode::Char('s') => self.size_idx = 3,
                KeyCode::Char('m') => self.size_idx = 4,
                KeyCode::Char('l') => self.size_idx = 5,
                _ => {}
            },
            CreateField::Urgency => match key.code {
                KeyCode::Left | KeyCode::Up | KeyCode::Char('h' | 'k') => {
                    self.urgency_idx = self.urgency_idx.saturating_sub(1);
                }
                KeyCode::Right | KeyCode::Down | KeyCode::Char('j') => {
                    self.urgency_idx =
                        (self.urgency_idx + 1).min(Self::urgency_options().len() - 1);
                }
                KeyCode::Char('n') => self.urgency_idx = 0,
                KeyCode::Char('u') => self.urgency_idx = 1,
                KeyCode::Char('p') => self.urgency_idx = 2,
                _ => {}
            },
            CreateField::Labels => {
                Self::edit_single_line(&mut self.labels, &mut self.labels_cursor, key);
            }
        }

        CreateAction::None
    }

    fn edit_single_line(text: &mut String, cursor: &mut usize, key: KeyEvent) {
        let _ = edit_single_line_readline(text, cursor, key);
    }

    fn edit_description(&mut self, key: KeyEvent) {
        edit_multiline(
            &mut self.description,
            &mut self.desc_row,
            &mut self.desc_col,
            key,
        );
    }

    fn handle_paste(&mut self, text: &str) {
        match self.focus {
            CreateField::Title => {
                insert_single_line_text(&mut self.title, &mut self.title_cursor, text);
            }
            CreateField::Description => paste_multiline_text(
                &mut self.description,
                &mut self.desc_row,
                &mut self.desc_col,
                text,
            ),
            CreateField::Labels => {
                insert_single_line_text(&mut self.labels, &mut self.labels_cursor, text);
            }
            _ => {}
        }
    }
}

/// Open `$EDITOR` (falling back to `vi`) with `initial` content.
///
/// Suspends the TUI's raw-mode/alt-screen, launches the editor, then
/// re-enters raw-mode/alt-screen.  Returns the edited text on success,
/// or `None` if the editor exited with a non-zero status.
fn open_in_editor(initial: &str) -> anyhow::Result<Option<String>> {
    use crossterm::{
        event::{DisableMouseCapture, EnableMouseCapture},
        execute,
        terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
    };

    let editor = std::env::var("EDITOR")
        .or_else(|_| std::env::var("VISUAL"))
        .unwrap_or_else(|_| "vi".to_string());

    let tmp_path = std::env::temp_dir().join(format!("bones-edit-{}.md", std::process::id()));
    {
        let mut f = std::fs::File::create(&tmp_path)?;
        f.write_all(initial.as_bytes())?;
    }

    disable_raw_mode()?;
    execute!(std::io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?;

    let status = std::process::Command::new(&editor).arg(&tmp_path).status();

    enable_raw_mode()?;
    execute!(std::io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;

    match status {
        Ok(s) if s.success() => {
            let content = std::fs::read_to_string(&tmp_path).unwrap_or_default();
            let _ = std::fs::remove_file(&tmp_path);
            Ok(Some(content))
        }
        _ => {
            let _ = std::fs::remove_file(&tmp_path);
            Ok(None)
        }
    }
}

enum NoteAction {
    None,
    Submit,
    Cancel,
    OpenEditor,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NoteMode {
    Comment,
    Transition { target: State, reopen: bool },
}

#[derive(Debug, Clone)]
struct NoteModalState {
    mode: NoteMode,
    lines: Vec<String>,
    row: usize,
    col: usize,
}

impl NoteModalState {
    fn comment() -> Self {
        Self {
            mode: NoteMode::Comment,
            lines: vec![String::new()],
            row: 0,
            col: 0,
        }
    }

    fn transition(target: State, reopen: bool) -> Self {
        Self {
            mode: NoteMode::Transition { target, reopen },
            lines: vec![String::new()],
            row: 0,
            col: 0,
        }
    }

    fn handle_key(&mut self, key: KeyEvent) -> NoteAction {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Esc => NoteAction::Cancel,
            KeyCode::Char('s') if ctrl => {
                if self.text().trim().is_empty() {
                    NoteAction::None
                } else {
                    NoteAction::Submit
                }
            }
            KeyCode::Enter if ctrl => {
                if self.text().trim().is_empty() {
                    NoteAction::None
                } else {
                    NoteAction::Submit
                }
            }
            KeyCode::Char('g') if ctrl => NoteAction::OpenEditor,
            _ => {
                edit_multiline(&mut self.lines, &mut self.row, &mut self.col, key);
                NoteAction::None
            }
        }
    }

    fn text(&self) -> String {
        self.lines.join("\n")
    }

    fn handle_paste(&mut self, text: &str) {
        paste_multiline_text(&mut self.lines, &mut self.row, &mut self.col, text);
    }
}

/// Which relationship the blocker modal will create.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlockerRelType {
    /// Current bone blocks the selected bone.
    Blocks,
    /// Current bone is blocked by the selected bone.
    BlockedBy,
    /// Current bone becomes a child of the selected bone.
    ChildOf,
    /// Selected bone becomes a child of the current bone.
    ParentOf,
}

impl BlockerRelType {
    const fn label(self) -> &'static str {
        match self {
            Self::Blocks => "Blocks",
            Self::BlockedBy => "Blocked by",
            Self::ChildOf => "Child of",
            Self::ParentOf => "Parent of",
        }
    }

    const fn next(self) -> Self {
        match self {
            Self::Blocks => Self::BlockedBy,
            Self::BlockedBy => Self::ChildOf,
            Self::ChildOf => Self::ParentOf,
            Self::ParentOf => Self::Blocks,
        }
    }

    const fn prev(self) -> Self {
        match self {
            Self::Blocks => Self::ParentOf,
            Self::BlockedBy => Self::Blocks,
            Self::ChildOf => Self::BlockedBy,
            Self::ParentOf => Self::ChildOf,
        }
    }
}

struct BlockerModalState {
    rel_type: BlockerRelType,
    search: String,
    search_cursor: usize,
    /// All active items (excluding the current bone).
    items: Vec<(String, String)>,
    /// Index into the filtered view.
    list_idx: usize,
    /// Whether the search field is focused (accepts all character input).
    search_focused: bool,
}

impl BlockerModalState {
    const fn new(items: Vec<(String, String)>) -> Self {
        Self {
            rel_type: BlockerRelType::Blocks,
            search: String::new(),
            search_cursor: 0,
            items,
            list_idx: 0,
            search_focused: false,
        }
    }

    fn filtered(&self) -> Vec<&(String, String)> {
        let q = self.search.to_ascii_lowercase();
        if q.is_empty() {
            self.items.iter().collect()
        } else {
            self.items
                .iter()
                .filter(|(id, title)| {
                    id.to_ascii_lowercase().contains(&q) || title.to_ascii_lowercase().contains(&q)
                })
                .collect()
        }
    }

    fn selected_item(&self) -> Option<&(String, String)> {
        let filtered = self.filtered();
        filtered.get(self.list_idx).copied()
    }
}

// ---------------------------------------------------------------------------
// Edit-link modal types
// ---------------------------------------------------------------------------

/// Direction of a link relative to the current bone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinkDirection {
    /// The link event is recorded on the current bone (`item_id = current`).
    Outgoing,
    /// The link event is recorded on the peer bone (`item_id = peer`).
    Incoming,
}

/// Display type for a link in the edit-link modal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EditLinkType {
    Blocks,
    BlockedBy,
    Related,
    /// Current bone is a child of the peer (parent relationship).
    ChildOf,
    /// Peer bone is a child of the current bone.
    ParentOf,
}

impl EditLinkType {
    const fn label(self) -> &'static str {
        match self {
            Self::Blocks => "Blocks",
            Self::BlockedBy => "Blocked by",
            Self::Related => "Related",
            Self::ChildOf => "Child of",
            Self::ParentOf => "Parent of",
        }
    }

    /// Cycle to next type. Parent/child types only cycle among themselves;
    /// link types (Blocks/BlockedBy/Related) cycle among themselves.
    const fn next(self) -> Self {
        match self {
            Self::Blocks => Self::BlockedBy,
            Self::BlockedBy => Self::Related,
            Self::Related => Self::Blocks,
            Self::ChildOf => Self::ParentOf,
            Self::ParentOf => Self::ChildOf,
        }
    }

    const fn prev(self) -> Self {
        match self {
            Self::Blocks => Self::Related,
            Self::BlockedBy => Self::Blocks,
            Self::Related => Self::BlockedBy,
            Self::ChildOf => Self::ParentOf,
            Self::ParentOf => Self::ChildOf,
        }
    }
}

/// A single link row in the edit-link modal.
#[derive(Debug, Clone)]
struct EditableLink {
    peer_id: String,
    peer_title: Option<String>,
    /// Original link type as stored in the event model.
    original_type: String,
    /// Original direction relative to the current bone.
    original_direction: LinkDirection,
    /// Current (proposed) display type.
    current_type: EditLinkType,
    /// Whether this link is marked for deletion.
    deleted: bool,
}

impl EditableLink {
    /// Whether this link has been changed from its original state.
    fn is_changed(&self) -> bool {
        self.deleted || self.display_type_for_original() != self.current_type
    }

    /// Compute the display type that corresponds to the original link.
    fn display_type_for_original(&self) -> EditLinkType {
        if self.original_type == "parent" {
            match self.original_direction {
                LinkDirection::Outgoing => EditLinkType::ChildOf,
                LinkDirection::Incoming => EditLinkType::ParentOf,
            }
        } else if is_related_link(&self.original_type) {
            EditLinkType::Related
        } else {
            match self.original_direction {
                LinkDirection::Outgoing => EditLinkType::BlockedBy,
                LinkDirection::Incoming => EditLinkType::Blocks,
            }
        }
    }
}

/// State for the edit-link modal.
struct EditLinkModalState {
    /// The bone whose links we are editing.
    item_id: String,
    /// Editable link rows.
    links: Vec<EditableLink>,
    /// Currently selected row index.
    list_idx: usize,
}

fn edit_multiline(lines: &mut Vec<String>, row: &mut usize, col: &mut usize, key: KeyEvent) {
    if lines.is_empty() {
        lines.push(String::new());
    }
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let alt = key.modifiers.contains(KeyModifiers::ALT);

    if matches!(key.code, KeyCode::Char('j')) && key.modifiers.contains(KeyModifiers::SHIFT) {
        insert_newline(lines, row, col);
        return;
    }

    if ctrl {
        match key.code {
            KeyCode::Char('a') => {
                *col = 0;
                return;
            }
            KeyCode::Char('e') => {
                *col = char_len(&lines[*row]);
                return;
            }
            KeyCode::Char('h') => {
                backspace_multiline(lines, row, col);
                return;
            }
            KeyCode::Char('d') => {
                delete_multiline(lines, row, col);
                return;
            }
            KeyCode::Char('w') => {
                delete_prev_word_in_line(&mut lines[*row], col);
                return;
            }
            KeyCode::Char('u') => {
                let start = byte_index_at_char(&lines[*row], 0);
                let end = byte_index_at_char(&lines[*row], *col);
                lines[*row].replace_range(start..end, "");
                *col = 0;
                return;
            }
            KeyCode::Char('k') => {
                let start = byte_index_at_char(&lines[*row], *col);
                lines[*row].replace_range(start.., "");
                return;
            }
            _ => {}
        }
    }

    if alt {
        match key.code {
            KeyCode::Char('b') => {
                *col = prev_word_boundary(&lines[*row], *col);
                return;
            }
            KeyCode::Char('f') => {
                *col = next_word_boundary(&lines[*row], *col);
                return;
            }
            _ => {}
        }
    }

    match key.code {
        KeyCode::Left => {
            if *col > 0 {
                *col -= 1;
            } else if *row > 0 {
                *row -= 1;
                *col = char_len(&lines[*row]);
            }
        }
        KeyCode::Right => {
            let line_len = char_len(&lines[*row]);
            if *col < line_len {
                *col += 1;
            } else if *row + 1 < lines.len() {
                *row += 1;
                *col = 0;
            }
        }
        KeyCode::Up => {
            if *row > 0 {
                *row -= 1;
                *col = (*col).min(char_len(&lines[*row]));
            }
        }
        KeyCode::Down => {
            if *row + 1 < lines.len() {
                *row += 1;
                *col = (*col).min(char_len(&lines[*row]));
            }
        }
        KeyCode::Home => *col = 0,
        KeyCode::End => *col = char_len(&lines[*row]),
        KeyCode::Enter => insert_newline(lines, row, col),
        KeyCode::Backspace => {
            backspace_multiline(lines, row, col);
        }
        KeyCode::Delete => delete_multiline(lines, row, col),
        KeyCode::Char('\n' | '\r') => insert_newline(lines, row, col),
        KeyCode::Char(c) => {
            if !ctrl && !alt {
                insert_char_at(&mut lines[*row], *col, c);
                *col += 1;
            }
        }
        _ => {}
    }
}

fn is_word_char(ch: char) -> bool {
    ch.is_alphanumeric() || matches!(ch, '_' | '-')
}

fn prev_word_boundary(text: &str, cursor: usize) -> usize {
    let chars: Vec<char> = text.chars().collect();
    if chars.is_empty() || cursor == 0 {
        return 0;
    }

    let mut idx = cursor.min(chars.len());
    while idx > 0 && !is_word_char(chars[idx - 1]) {
        idx -= 1;
    }
    while idx > 0 && is_word_char(chars[idx - 1]) {
        idx -= 1;
    }
    idx
}

fn next_word_boundary(text: &str, cursor: usize) -> usize {
    let chars: Vec<char> = text.chars().collect();
    if chars.is_empty() {
        return 0;
    }

    let mut idx = cursor.min(chars.len());
    while idx < chars.len() && !is_word_char(chars[idx]) {
        idx += 1;
    }
    while idx < chars.len() && is_word_char(chars[idx]) {
        idx += 1;
    }
    idx
}

fn delete_prev_word_in_line(text: &mut String, cursor: &mut usize) {
    if *cursor == 0 {
        return;
    }
    let start = prev_word_boundary(text, *cursor);
    let start_byte = byte_index_at_char(text, start);
    let end_byte = byte_index_at_char(text, *cursor);
    text.replace_range(start_byte..end_byte, "");
    *cursor = start;
}

fn insert_newline(lines: &mut Vec<String>, row: &mut usize, col: &mut usize) {
    let split_at = byte_index_at_char(&lines[*row], *col);
    let tail = lines[*row].split_off(split_at);
    *row += 1;
    *col = 0;
    lines.insert(*row, tail);
}

fn backspace_multiline(lines: &mut Vec<String>, row: &mut usize, col: &mut usize) {
    if *col > 0 {
        let remove_idx = *col - 1;
        remove_char_at(&mut lines[*row], remove_idx);
        *col = remove_idx;
    } else if *row > 0 {
        let current = lines.remove(*row);
        *row -= 1;
        *col = char_len(&lines[*row]);
        lines[*row].push_str(&current);
    }
}

fn delete_multiline(lines: &mut Vec<String>, row: &mut usize, col: &mut usize) {
    let line_len = char_len(&lines[*row]);
    if *col < line_len {
        remove_char_at(&mut lines[*row], *col);
    } else if *row + 1 < lines.len() {
        let next = lines.remove(*row + 1);
        lines[*row].push_str(&next);
    }
}

fn normalize_paste_text(text: &str) -> String {
    text.replace("\r\n", "\n").replace('\r', "\n")
}

fn insert_single_line_text(text: &mut String, cursor: &mut usize, pasted: &str) {
    let flattened = normalize_paste_text(pasted).replace('\n', " ");
    if flattened.is_empty() {
        return;
    }
    let idx = byte_index_at_char(text, *cursor);
    text.insert_str(idx, &flattened);
    *cursor += flattened.chars().count();
}

fn paste_multiline_text(lines: &mut Vec<String>, row: &mut usize, col: &mut usize, pasted: &str) {
    if pasted.is_empty() {
        return;
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    for ch in normalize_paste_text(pasted).chars() {
        if ch == '\n' {
            insert_newline(lines, row, col);
        } else {
            insert_char_at(&mut lines[*row], *col, ch);
            *col += 1;
        }
    }
}

fn edit_single_line_readline(text: &mut String, cursor: &mut usize, key: KeyEvent) -> bool {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let alt = key.modifiers.contains(KeyModifiers::ALT);

    if ctrl {
        match key.code {
            KeyCode::Char('a') => {
                *cursor = 0;
                return false;
            }
            KeyCode::Char('e') => {
                *cursor = char_len(text);
                return false;
            }
            KeyCode::Char('h') => {
                if *cursor > 0 {
                    let remove_idx = *cursor - 1;
                    remove_char_at(text, remove_idx);
                    *cursor = remove_idx;
                    return true;
                }
                return false;
            }
            KeyCode::Char('d') => {
                let before = text.len();
                remove_char_at(text, *cursor);
                return text.len() != before;
            }
            KeyCode::Char('w') => {
                let before = text.len();
                delete_prev_word_in_line(text, cursor);
                return text.len() != before;
            }
            KeyCode::Char('u') => {
                let start = byte_index_at_char(text, 0);
                let end = byte_index_at_char(text, *cursor);
                text.replace_range(start..end, "");
                *cursor = 0;
                return true;
            }
            KeyCode::Char('k') => {
                let start = byte_index_at_char(text, *cursor);
                text.replace_range(start.., "");
                return true;
            }
            _ => {}
        }
    }

    if alt {
        match key.code {
            KeyCode::Char('b') => {
                *cursor = prev_word_boundary(text, *cursor);
                return false;
            }
            KeyCode::Char('f') => {
                *cursor = next_word_boundary(text, *cursor);
                return false;
            }
            _ => {}
        }
    }

    match key.code {
        KeyCode::Left => *cursor = cursor.saturating_sub(1),
        KeyCode::Right => *cursor = (*cursor + 1).min(char_len(text)),
        KeyCode::Home => *cursor = 0,
        KeyCode::End => *cursor = char_len(text),
        KeyCode::Backspace => {
            if *cursor > 0 {
                let remove_idx = *cursor - 1;
                remove_char_at(text, remove_idx);
                *cursor = remove_idx;
                return true;
            }
        }
        KeyCode::Delete => {
            let before = text.len();
            remove_char_at(text, *cursor);
            return text.len() != before;
        }
        KeyCode::Char(c) => {
            if !ctrl && !alt && !matches!(c, '\n' | '\r') {
                insert_char_at(text, *cursor, c);
                *cursor += 1;
                return true;
            }
        }
        _ => {}
    }
    false
}

fn char_len(value: &str) -> usize {
    value.chars().count()
}

fn byte_index_at_char(value: &str, char_idx: usize) -> usize {
    value
        .char_indices()
        .nth(char_idx)
        .map_or(value.len(), |(idx, _)| idx)
}

fn insert_char_at(value: &mut String, char_idx: usize, ch: char) {
    let idx = byte_index_at_char(value, char_idx);
    value.insert(idx, ch);
}

fn remove_char_at(value: &mut String, char_idx: usize) {
    if char_idx >= char_len(value) {
        return;
    }
    let start = byte_index_at_char(value, char_idx);
    let end = byte_index_at_char(value, char_idx + 1);
    value.replace_range(start..end, "");
}

fn with_cursor_marker(value: &str, char_idx: usize) -> String {
    let cursor = char_idx.min(char_len(value));
    let mut out = String::new();
    let mut inserted = false;
    for (idx, ch) in value.chars().enumerate() {
        if idx == cursor {
            out.push('|');
            inserted = true;
        }
        out.push(ch);
    }
    if !inserted {
        out.push('|');
    }
    out
}

fn with_cursor_spans(value: &str, char_idx: usize, base_style: Style) -> Vec<Span<'static>> {
    let chars: Vec<char> = value.chars().collect();
    let cursor = char_idx.min(chars.len());
    let cursor_style = base_style.add_modifier(Modifier::REVERSED);

    let mut spans = Vec::with_capacity(chars.len() + 1);
    for (idx, ch) in chars.iter().enumerate() {
        let style = if idx == cursor {
            cursor_style
        } else {
            base_style
        };
        spans.push(Span::styled(ch.to_string(), style));
    }

    if cursor == chars.len() {
        spans.push(Span::styled(" ".to_string(), cursor_style));
    }

    spans
}

fn with_cursor_line(value: &str, char_idx: usize, base_style: Style) -> Line<'static> {
    Line::from(with_cursor_spans(value, char_idx, base_style))
}

/// Main application state for the TUI list view.
pub struct ListView {
    /// Path to the bones projection database.
    db_path: PathBuf,
    /// Project root path.
    project_root: PathBuf,
    /// Agent name used for mutations from TUI.
    agent: String,
    /// All items loaded from the projection (unfiltered, unsorted for display).
    all_items: Vec<WorkItem>,
    /// Items after filtering and sorting — this is what the table shows.
    visible_items: Vec<WorkItem>,
    /// Parallel depths for each row in `visible_items`.
    visible_depths: Vec<usize>,
    /// First index in `visible_items` where done/archived items start.
    done_start_idx: Option<usize>,
    /// Parent relationship map from `item_id -> parent_id`.
    parent_map: HashMap<String, Option<String>>,
    /// Blocking dependency map from `blocked_item_id -> [blocker_item_id...]`.
    blocker_map: HashMap<String, Vec<String>>,
    /// Semantic model used for slash search.
    semantic_model: Option<std::sync::Arc<SemanticModel>>,
    /// Ranked IDs returned by semantic/hybrid slash search.
    semantic_search_ids: Vec<String>,
    /// Whether semantic search executed successfully for the active query.
    semantic_search_active: bool,
    /// Receiver for background semantic refinement results.
    semantic_refinement_rx: Option<std::sync::mpsc::Receiver<Vec<String>>>,
    /// Generation counter to discard stale background results.
    semantic_search_gen: u64,
    /// Query that was last searched (to avoid re-triggering on auto-refresh).
    last_searched_query: String,
    /// Whether a background semantic refinement is in progress.
    search_refining: bool,
    /// Current filter criteria.
    pub filter: FilterState,
    /// Current sort order.
    pub sort: SortField,
    /// Table navigation state (selected row index in `visible_items`).
    table_state: TableState,
    /// Current input mode.
    input_mode: InputMode,
    /// Buffer for the search query being typed.
    search_buf: String,
    /// Cursor position within `search_buf`.
    search_cursor: usize,
    /// Query value before entering Search mode (for Esc cancel).
    search_prev_query: String,
    /// Buffer for the label filter being typed in the popup.
    label_buf: String,
    /// Cursor position within `label_buf`.
    label_cursor: usize,
    /// Current focus inside the filter popup.
    filter_field: FilterField,
    /// Whether to quit.
    should_quit: bool,
    /// Last refresh timestamp (for status bar).
    last_refresh: Instant,
    /// Background auto-refresh interval.
    refresh_interval: Duration,
    /// Whether a status message should be shown temporarily.
    status_msg: Option<(String, Instant)>,
    /// Most recent tracing ERROR captured from the log sink (shown in red).
    error_msg: Option<(String, Instant)>,
    /// Whether the right-side detail pane is open.
    show_detail: bool,
    /// Whether done/archived bones are shown.
    show_done: bool,
    /// Split percentage for list/detail panes.
    split_percent: u16,
    /// Current detail-pane vertical scroll offset.
    detail_scroll: u16,
    /// Geometry used for mouse interactions.
    list_area: Rect,
    /// Geometry used for mouse interactions.
    detail_area: Rect,
    /// Whether split drag is active.
    split_resize_active: bool,
    /// Cached detail content for the selected item.
    detail_item: Option<DetailItem>,
    /// Item ID currently loaded into `detail_item`.
    detail_item_id: Option<String>,
    /// Cached rendered lines for the detail pane (invalidated when `detail_item` changes).
    detail_lines_cache: Vec<Line<'static>>,
    /// Create-bone modal state when open.
    create_modal: Option<CreateModalState>,
    /// Item being edited in create modal; None means create mode.
    create_modal_edit_item_id: Option<String>,
    /// Comment/close/reopen note modal state when open.
    note_modal: Option<NoteModalState>,
    /// Blocker/link picker modal state when open.
    blocker_modal: Option<BlockerModalState>,
    /// Edit-link modal state when open.
    edit_link_modal: Option<EditLinkModalState>,
    /// Help overlay filter query.
    help_query: String,
    /// Cursor position within `help_query`.
    help_cursor: usize,
    /// Set after an external editor is closed; the run loop should clear the
    /// terminal so the TUI repaints cleanly.
    pub needs_terminal_refresh: bool,
}