linesmith-core 0.1.3

Internal core engine for linesmith. No SemVer guarantee for direct dependents — depend on the `linesmith` binary or accept breakage between minor versions.
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
use super::*;
use crate::input::{ModelInfo, StatusContext, Tool, WorkspaceInfo};
use crate::theme;
use std::borrow::Cow;
use std::path::PathBuf;
use std::sync::Arc;

/// Stub `Segment` for layout tests that build [`LayoutItem`] literals
/// directly. The reflow loop's `shrink_to_fit` callback gets the
/// default `None`, so layout tests focused on priority-drop /
/// separators / truncatable behavior don't need to mint a fresh
/// segment per case.
struct NoopSegment;
impl Segment for NoopSegment {
    fn render(&self, _ctx: &DataContext, _rc: &RenderContext) -> RenderResult {
        Ok(None)
    }
}
static NOOP: NoopSegment = NoopSegment;
fn noop_segment() -> &'static dyn Segment {
    &NOOP
}

/// Stable id shared by layout test fixtures. Tests asserting distinct ids
/// per slot must define their own statics; copy-pasting `TEST_SEG_ID`
/// across two slots would compare `"test"` to `"test"` and silently pass.
static TEST_SEG_ID: Cow<'static, str> = Cow::Borrowed("test");

fn empty_ctx() -> DataContext {
    DataContext::new(StatusContext {
        tool: Tool::ClaudeCode,
        model: Some(ModelInfo {
            display_name: "X".into(),
        }),
        workspace: Some(WorkspaceInfo {
            project_dir: PathBuf::from("/"),
            git_worktree: None,
        }),
        context_window: None,
        cost: None,
        effort: None,
        vim: None,
        output_style: None,
        agent_name: None,
        version: None,
        raw: Arc::new(serde_json::Value::Null),
    })
}

fn empty_rc() -> RenderContext {
    RenderContext::new(80)
}

/// Build a [`LayoutItem::Segment`] for a stub render. Most layout
/// tests use this; pair adjacent calls with [`space`], [`pl`], or
/// [`lit`] to interleave separator items the way the production
/// builder does.
fn item(text: &str, priority: u8) -> LayoutItem<'static> {
    LayoutItem::Segment(SegmentEntry {
        id: &TEST_SEG_ID,
        rendered: RenderedSegment::new(text),
        defaults: SegmentDefaults::with_priority(priority),
        segment: noop_segment(),
    })
}

fn space() -> LayoutItem<'static> {
    LayoutItem::Separator(Separator::Space)
}

fn pl() -> LayoutItem<'static> {
    LayoutItem::Separator(Separator::powerline())
}

fn lit(s: &'static str) -> LayoutItem<'static> {
    LayoutItem::Separator(Separator::Literal(Cow::Borrowed(s)))
}

fn none_sep() -> LayoutItem<'static> {
    LayoutItem::Separator(Separator::None)
}

/// Build a `Vec<LayoutItem>` with [`Separator::Space`] interleaved
/// between every adjacent `(text, priority)` pair.
fn spaced(specs: &[(&str, u8)]) -> Vec<LayoutItem<'static>> {
    interleaved(specs, space)
}

/// Build a `Vec<LayoutItem>` with [`Separator::powerline()`]
/// interleaved between every adjacent `(text, priority)` pair.
fn pl_spec(specs: &[(&str, u8)]) -> Vec<LayoutItem<'static>> {
    interleaved(specs, pl)
}

fn interleaved(
    specs: &[(&str, u8)],
    mut sep: impl FnMut() -> LayoutItem<'static>,
) -> Vec<LayoutItem<'static>> {
    let mut out = Vec::with_capacity(specs.len().saturating_mul(2));
    for (i, &(text, priority)) in specs.iter().enumerate() {
        out.push(item(text, priority));
        if i + 1 < specs.len() {
            out.push(sep());
        }
    }
    out
}

/// Bind a `LayoutObservers` that discards warnings.
macro_rules! let_noop_observers {
    ($name:ident) => {
        let mut __warn_for_observers: fn(&str) = |_: &str| {};
        let mut $name = LayoutObservers::new(&mut __warn_for_observers);
    };
}

/// Wrap `segments` as a [`LineItem`] sequence with `sep` interleaved
/// between adjacent segments. For tests that drive the public render
/// entry points (`render_with_observers`, `render_to_runs`). Synthesizes
/// stable test ids (`"seg0"`, `"seg1"`, ...) so the `LineItem`
/// addressing contract from ADR-0026 stays exercised; tests that need
/// a specific id should build the `LineItem` literal directly.
fn line_items_with(segments: Vec<Box<dyn Segment>>, sep: Separator) -> Vec<LineItem> {
    let n = segments.len();
    let mut out = Vec::with_capacity(n.saturating_mul(2));
    for (i, segment) in segments.into_iter().enumerate() {
        out.push(LineItem::Segment {
            id: std::borrow::Cow::Owned(format!("seg{i}")),
            segment,
        });
        if i + 1 < n {
            out.push(LineItem::Separator(sep.clone()));
        }
    }
    out
}

fn line_items_spaced(segments: Vec<Box<dyn Segment>>) -> Vec<LineItem> {
    line_items_with(segments, Separator::Space)
}

/// Test helper: exercise `render_items` with the default theme and
/// no color capability so output is plain text — the invariant most
/// layout tests actually care about (priority-drop, separators,
/// truncation behavior) is independent of theming.
fn render_plain(items: Vec<LayoutItem<'_>>, terminal_width: u16) -> String {
    render_items(
        items,
        &empty_ctx(),
        &empty_rc(),
        terminal_width,
        theme::default_theme(),
        theme::Capability::None,
    )
}

#[test]
fn render_items_wraps_each_styled_segment_under_palette16() {
    // Plain + styled + plain layout: the styled one gets SGR
    // wrapping, the plain ones pass through. Confirms the layout
    // emits SGR *per segment* rather than globally, so decorations
    // don't leak across separators.
    use crate::theme::Role;
    let items = vec![
        item("a", 10),
        space(),
        LayoutItem::Segment(SegmentEntry {
            id: &TEST_SEG_ID,
            rendered: RenderedSegment::new("b").with_role(Role::Warning),
            defaults: SegmentDefaults::with_priority(10),
            segment: noop_segment(),
        }),
        space(),
        item("c", 10),
    ];
    let out = render_items(
        items,
        &empty_ctx(),
        &empty_rc(),
        100,
        theme::default_theme(),
        theme::Capability::Palette16,
    );
    // Warning → BrightYellow (SGR 93) on the default theme.
    assert_eq!(out, "a \x1b[93mb\x1b[0m c");
}

#[test]
fn total_width_sums_all_layout_items() {
    let items = spaced(&[("ab", 10), ("cd", 10), ("ef", 10)]);
    // widths 2+1+2+1+2 = 8.
    assert_eq!(total_width(&items), 8);
}

#[test]
fn total_width_zero_for_empty() {
    assert_eq!(total_width(&[]), 0);
}

#[test]
fn total_width_single_segment_has_no_separator() {
    let items = vec![item("abcde", 10)];
    assert_eq!(total_width(&items), 5);
}

#[test]
fn no_width_pressure_renders_all_with_separators() {
    let items = spaced(&[("one", 10), ("two", 20), ("three", 30)]);
    assert_eq!(render_plain(items, 100), "one two three");
}

#[test]
fn drops_highest_priority_under_pressure() {
    let items = spaced(&[
        ("aaaa", 10),
        ("bbbb", 200), // highest priority → drops first
        ("cccc", 50),
    ]);
    // Full: 4+1+4+1+4 = 14. Budget 10 forces one drop.
    let out = render_plain(items, 10);
    assert!(!out.contains("bbbb"));
    assert!(out.contains("aaaa"));
    assert!(out.contains("cccc"));
}

#[test]
fn drops_in_descending_priority_order() {
    let items = spaced(&[
        ("one", 10),
        ("two", 200), // drops first
        ("three", 20),
        ("four", 150), // drops second
        ("five", 30),
    ]);
    // Full: 3+1+3+1+5+1+4+1+4 = 23. Budget 15 forces two drops.
    assert_eq!(render_plain(items, 15), "one three five");
}

#[test]
fn priority_zero_never_drops_even_over_budget() {
    let items = spaced(&[("aaaa", 0), ("bbbb", 0)]);
    let out = render_plain(items, 3);
    assert_eq!(out, "aaaa bbbb");
}

#[test]
fn priority_drop_recomputes_budget_with_powerline_separators() {
    // Three priority-0 segments at width 4 with powerline chevrons
    // between them: full = 4 + chev + 4 + chev + 4. The middle
    // segment is the only droppable one (priority 200); after one
    // drop the layout becomes "aaaa <chev> cccc" (4 + chev + 4)
    // and fits the budget without a second drop. A regression that
    // forgot to subtract a chevron's cells when its preceding
    // segment dropped would over-drop or mis-budget.
    let items = pl_spec(&[("aaaa", 0), ("bbbb", 200), ("cccc", 0)]);
    // Full = 4 + 3 + 4 + 3 + 4 = 18; after drop = 4 + 3 + 4 = 11.
    let out = render_plain(items, 14);
    assert!(out.contains("aaaa"));
    assert!(!out.contains("bbbb"));
    assert!(out.contains("cccc"));
    assert!(
        out.contains('\u{E0B0}'),
        "chevron survives the drop: {out:?}"
    );
}

#[test]
fn mix_drops_positives_keeps_zeros() {
    let items = spaced(&[("keep-me", 0), ("droppable", 200), ("sticky", 0)]);
    // Budget forces drop; only the priority-200 segment is eligible.
    let out = render_plain(items, 20);
    assert_eq!(out, "keep-me sticky");
}

#[test]
fn no_trailing_separator() {
    let items = spaced(&[("a", 10), ("b", 10)]);
    assert_eq!(render_plain(items, 100), "a b");
}

#[test]
fn empty_input_renders_empty_string() {
    assert_eq!(render_plain(vec![], 100), "");
}

#[test]
fn respects_inline_literal_separator() {
    let items = vec![item("a", 10), lit(" | "), item("b", 10)];
    assert_eq!(render_plain(items, 100), "a | b");
}

#[test]
fn render_inline_none_separator_collapses_neighbors() {
    // Inline `Separator::None` between two segments produces no run
    // and no width — neighbors collapse against each other.
    let items = vec![item("a", 10), none_sep(), item("b", 10)];
    assert_eq!(render_plain(items, 100), "ab");
}

// --- width-bounds helpers ------------------------------------------

#[test]
fn apply_width_bounds_drops_below_min() {
    let bounds = WidthBounds::new(5, 10);
    let rendered = RenderedSegment::new("abc"); // width 3
    let_noop_observers!(observers);
    assert!(apply_width_bounds(rendered, bounds, &TEST_SEG_ID, &mut observers).is_none());
}

#[test]
fn apply_width_bounds_truncates_above_max() {
    let bounds = WidthBounds::new(0, 5);
    let rendered = RenderedSegment::new("abcdefghij"); // width 10
    let_noop_observers!(observers);
    let truncated =
        apply_width_bounds(rendered, bounds, &TEST_SEG_ID, &mut observers).expect("truncated");
    assert_eq!(truncated.width, 5);
    assert!(truncated.text.ends_with(''));
    assert_eq!(truncated.text, "abcd…");
}

#[test]
fn apply_width_bounds_passthrough_within_range() {
    let bounds = WidthBounds::new(2, 10);
    let original = RenderedSegment::new("hello");
    let_noop_observers!(observers);
    let result =
        apply_width_bounds(original.clone(), bounds, &TEST_SEG_ID, &mut observers).expect("kept");
    assert_eq!(result, original);
}

#[test]
fn apply_width_bounds_none_is_passthrough() {
    let original = RenderedSegment::new("anything");
    let_noop_observers!(observers);
    let result =
        apply_width_bounds(original.clone(), None, &TEST_SEG_ID, &mut observers).expect("kept");
    assert_eq!(result, original);
}

#[test]
fn truncate_to_zero_yields_empty() {
    let out = truncate_to(RenderedSegment::new("abc"), 0);
    assert_eq!(out.text, "");
    assert_eq!(out.width, 0);
}

#[test]
fn truncate_handles_wide_grapheme_without_splitting() {
    // The middle-dot is 1 cell; truncating "42% · 200k" (10 cells) to
    // 6 cells should yield "42% ·…" (5 cells of content + ellipsis).
    let bounds = WidthBounds::new(0, 6);
    let_noop_observers!(observers);
    let truncated = apply_width_bounds(
        RenderedSegment::new("42% · 200k"),
        bounds,
        &TEST_SEG_ID,
        &mut observers,
    )
    .expect("truncated");
    assert_eq!(truncated.text, "42% ·…");
    assert_eq!(truncated.width, 6);
}

#[test]
fn truncate_preserves_combining_mark_with_base() {
    // "é" is U+0065 U+0301 (2 code points, 1 grapheme, 1 cell).
    // `abéde` is 5 cells, truncate to 4 should yield `abé…`.
    let r = RenderedSegment::new("ab\u{65}\u{301}de");
    assert_eq!(r.width, 5);
    let out = truncate_to(r, 4);
    assert_eq!(out.text, "ab\u{65}\u{301}");
    assert_eq!(out.width, 4);
}

#[test]
fn truncate_does_not_split_zwj_emoji_sequence() {
    // 👨‍👩‍👦 is a ZWJ sequence (5 code points, 1 grapheme, 2 cells).
    // Total "a👨‍👩‍👦b" = 1 + 2 + 1 = 4 cells. Truncating to 3 cells:
    // budget for content is 2; we can fit "a" (1 cell) then the ZWJ
    // family (2 cells) would exceed budget, so output is "a…".
    let text = "a\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F466}b";
    let r = RenderedSegment::new(text);
    let out = truncate_to(r, 3);
    assert_eq!(out.text, "a…");
    assert_eq!(out.width, 2);
}

#[test]
fn truncate_to_max_cells_one_emits_only_ellipsis() {
    let r = RenderedSegment::new("anything");
    let out = truncate_to(r, 1);
    assert_eq!(out.text, "");
    assert_eq!(out.width, 1);
}

#[test]
fn priority_ties_drop_rightmost_first() {
    let items = spaced(&[("left", 200), ("mid", 50), ("right", 200)]);
    // Full: 4+1+3+1+5 = 14. Budget 10 forces one drop; tied priorities
    // on "left" and "right" — right drops first.
    assert_eq!(render_plain(items, 10), "left mid");
}

#[test]
fn separator_none_not_charged_to_budget() {
    // Inline Separator::None between b and c collapses them against
    // each other. Widths 1+1+1 = 3; separators: Space (1) between
    // 0–1, None (0) between 1–2. Total = 4. Budget 4 must keep
    // everything and emit "a bc".
    let items = vec![
        item("a", 200),
        space(),
        item("b", 200),
        none_sep(),
        item("c", 200),
    ];
    assert_eq!(render_plain(items, 4), "a bc");
}

#[test]
fn total_width_returns_u32_beyond_u16_range() {
    // Three segments at u16::MAX each plus two Space separators:
    // sum = 3 * u16::MAX + 2. Must not wrap u32.
    fn wide(text: String) -> LayoutItem<'static> {
        LayoutItem::Segment(SegmentEntry {
            id: &TEST_SEG_ID,
            rendered: RenderedSegment::new(text),
            defaults: SegmentDefaults::with_priority(10),
            segment: noop_segment(),
        })
    }
    let items = vec![
        wide("x".repeat(u16::MAX as usize)),
        space(),
        wide("x".repeat(u16::MAX as usize)),
        space(),
        wide("x".repeat(u16::MAX as usize)),
    ];
    assert_eq!(total_width(&items), 3 * u32::from(u16::MAX) + 2);
}

#[test]
fn all_priority_zero_keeps_every_segment_even_when_overfull() {
    let items = spaced(&[("aaa", 0), ("bbb", 0), ("ccc", 0)]);
    // Full 3+1+3+1+3 = 11. Budget 4 is nowhere near; all three stay.
    assert_eq!(render_plain(items, 4), "aaa bbb ccc");
}

// --- error handling ---

use crate::segments::{RenderResult, SegmentError};

struct StubSegment(RenderResult);

impl Segment for StubSegment {
    fn render(&self, _ctx: &DataContext, _rc: &RenderContext) -> RenderResult {
        match &self.0 {
            Ok(Some(r)) => Ok(Some(r.clone())),
            Ok(None) => Ok(None),
            Err(e) => Err(SegmentError::new(e.message.clone())),
        }
    }
}

#[test]
fn segment_error_is_logged_and_hides_segment() {
    let line = line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("ok-before"))))),
        Box::new(StubSegment(Err(SegmentError::new("boom")))),
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("ok-after"))))),
    ]);
    let mut warnings = Vec::new();
    let mut warn = |msg: &str| warnings.push(msg.to_string());
    let mut observers = LayoutObservers::new(&mut warn);
    let items = collect_items_with(&line, &empty_ctx(), &empty_rc(), &mut observers);
    // The Err segment vanishes; the separator that flanked it goes
    // with it (both adjacency rules at once). Two surviving segments
    // separated by one surviving Space = 3 LayoutItems.
    assert_eq!(items.len(), 3);
    assert_eq!(segment_text(&items[0]), "ok-before");
    assert!(matches!(items[1], LayoutItem::Separator(_)));
    assert_eq!(segment_text(&items[2]), "ok-after");
    // The error is surfaced to stderr exactly once.
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].contains("segment error"));
    assert!(warnings[0].contains("boom"));
}

#[test]
fn ok_none_is_silently_hidden() {
    let line = line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("visible"))))),
        Box::new(StubSegment(Ok(None))),
    ]);
    let mut warnings = Vec::new();
    let mut warn = |msg: &str| warnings.push(msg.to_string());
    let mut observers = LayoutObservers::new(&mut warn);
    let items = collect_items_with(&line, &empty_ctx(), &empty_rc(), &mut observers);
    // Hidden segment plus its trailing separator both prune away.
    assert_eq!(items.len(), 1);
    assert_eq!(segment_text(&items[0]), "visible");
    assert!(warnings.is_empty());
}

/// `WidthEcho` emits whatever `terminal_width` it receives — used
/// by both reflow-threading tests below.
struct WidthEcho;
impl Segment for WidthEcho {
    fn render(&self, _ctx: &DataContext, rc: &RenderContext) -> RenderResult {
        Ok(Some(RenderedSegment::new(rc.terminal_width.to_string())))
    }
}

#[test]
fn render_context_threads_terminal_width_into_segments() {
    // Asserts the engine threads `RenderContext::new(42)` to the
    // segment unmodified at the `collect_items_with` layer —
    // pinning runtime behavior, since type-signature compilation
    // alone doesn't prove the value moves.
    let line = line_items_spaced(vec![Box::new(WidthEcho)]);
    let mut warnings = Vec::new();
    let mut warn = |msg: &str| warnings.push(msg.to_string());
    let mut observers = LayoutObservers::new(&mut warn);
    let rc = RenderContext::new(42);
    let items = collect_items_with(&line, &empty_ctx(), &rc, &mut observers);
    assert_eq!(items.len(), 1);
    assert_eq!(segment_text(&items[0]), "42");
}

#[test]
fn render_with_observers_constructs_render_context_from_terminal_width_arg() {
    // Pins the construction line in `render_with_observers`: the
    // public entrypoint must build `RenderContext::new(terminal_width)`
    // from its argument and pass it to segments. A regression that
    // hard-coded a default would slip past the
    // `collect_items_with`-only test above.
    let line = line_items_spaced(vec![Box::new(WidthEcho)]);
    let mut warnings = Vec::new();
    let mut warn = |msg: &str| warnings.push(msg.to_string());
    let mut observers = LayoutObservers::new(&mut warn);
    let out = render_with_observers(
        &line,
        &empty_ctx(),
        137,
        &mut observers,
        theme::default_theme(),
        theme::Capability::None,
        false,
    );
    assert!(out.contains("137"), "got {out:?}");
}

// --- truncate-before-drop (reflow) ---

fn truncatable_item(text: &str, priority: u8) -> LayoutItem<'static> {
    LayoutItem::Segment(SegmentEntry {
        id: &TEST_SEG_ID,
        rendered: RenderedSegment::new(text),
        defaults: SegmentDefaults::with_priority(priority).with_truncatable(true),
        segment: noop_segment(),
    })
}

/// Shorthand for the field-reach `out.rendered.text` pattern used in
/// many `collect_items_with` assertions: matches the `Segment` variant
/// and panics with a descriptive message when the slot is a separator.
#[track_caller]
fn segment_text<'a>(item: &'a LayoutItem<'_>) -> &'a str {
    match item {
        LayoutItem::Segment(seg) => &seg.rendered.text,
        LayoutItem::Separator(_) => panic!("expected segment, got separator"),
    }
}

#[test]
fn reflow_truncates_highest_priority_before_dropping() {
    // Workspace-style scenario: long location plus a small fixed
    // segment. Without reflow the location would drop entirely;
    // with reflow it shrinks to fit so the user keeps orientation.
    let items = vec![
        truncatable_item("linesmith/very-long-feature-branch-name", 200),
        space(),
        item("Sonnet", 0),
    ];
    // Total: 39 + 1 + 6 = 46. Budget 30 → overflow 16.
    // Workspace truncates from 39 → 23 cells; result fits exactly.
    let out = render_plain(items, 30);
    assert!(out.starts_with("linesmith/very-long-fe"), "got {out:?}");
    assert!(out.ends_with("… Sonnet"), "got {out:?}");
    assert_eq!(text_width(&out), 30);
}

#[test]
fn reflow_drops_when_truncation_would_fall_below_floor() {
    // Budget so tight that truncating the workspace segment would
    // leave only the ellipsis (or less). Engine falls back to drop.
    let items = vec![
        truncatable_item("workspace-name", 200),
        space(),
        item("KEEP", 0),
    ];
    // Total: 14 + 1 + 4 = 19. Budget 4 → overflow 15.
    // workspace target = 14 - 15 < 0 → reflow returns None → drop.
    let out = render_plain(items, 4);
    assert_eq!(out, "KEEP");
}

fn truncatable_with_bounds(text: &str, priority: u8, bounds: WidthBounds) -> LayoutItem<'static> {
    LayoutItem::Segment(SegmentEntry {
        id: &TEST_SEG_ID,
        rendered: RenderedSegment::new(text),
        defaults: SegmentDefaults::with_priority(priority)
            .with_truncatable(true)
            .with_width(bounds),
        segment: noop_segment(),
    })
}

#[test]
fn reflow_respects_explicit_width_min_floor() {
    // Segment declares min=8; reflow must not shrink below that
    // even if a smaller truncation would fit the budget.
    let bounds = WidthBounds::new(8, u16::MAX).expect("valid");
    let items = vec![
        truncatable_with_bounds("abcdefghijklmnop", 200, bounds), // width 16
        space(),
        item("X", 0),
    ];
    // Total 16 + 1 + 1 = 18. Budget 10 → overflow 8 → target 8 ✓
    // (target equals floor; reflow proceeds).
    let out = render_plain(items, 10);
    assert!(out.contains(''), "got {out:?}");
    assert!(out.ends_with(" X"), "got {out:?}");

    // Now budget 9 → overflow 9 → target 7 < floor 8 → drop.
    let items = vec![
        truncatable_with_bounds("abcdefghijklmnop", 200, bounds),
        space(),
        item("X", 0),
    ];
    let out = render_plain(items, 9);
    assert_eq!(out, "X");
}

#[test]
fn non_truncatable_drops_unchanged_under_pressure() {
    // Default `truncatable=false` keeps the legacy whole-segment
    // drop path so numeric segments don't suddenly start emitting
    // half-cut percentages or dollar figures.
    let items = spaced(&[("45% · 200k", 200), ("Sonnet", 0)]);
    // Total 10 + 1 + 6 = 17. Budget 10 → drop the wider one.
    let out = render_plain(items, 10);
    assert_eq!(out, "Sonnet");
}

#[test]
fn reflow_iterates_when_first_truncation_insufficient() {
    // Two truncatable segments, both same priority. After tying
    // priority we drop the right-most first; if that's still over
    // budget the loop comes back for the left one.
    let items = vec![
        truncatable_item("aaaaaaaaaa", 100),
        space(),
        truncatable_item("bbbbbbbbbb", 100),
        space(),
        item("KEEP", 0),
    ];
    // Total: 10 + 1 + 10 + 1 + 4 = 26. Budget 12 → overflow 14.
    // Right-most ("b...") is chosen first; truncating it to
    // 10-14 < 0 fails, so it drops. New total 10+1+4 = 15.
    // Loop continues; next iteration overflow=3, "a..." truncates
    // to 10-3 = 7 ("aaaaaa…").
    let out = render_plain(items, 12);
    assert_eq!(out, "aaaaaa… KEEP");
    assert_eq!(text_width(&out), 12);
}

#[test]
fn reflow_does_not_touch_priority_zero_even_when_truncatable() {
    // Priority 0 is "user said don't drop"; the reflow loop never
    // selects it (the existing droppable filter guards this).
    let items = vec![
        LayoutItem::Segment(SegmentEntry {
            id: &TEST_SEG_ID,
            rendered: RenderedSegment::new("untouchable-long-name"),
            defaults: SegmentDefaults::with_priority(0).with_truncatable(true),
            segment: noop_segment(),
        }),
        space(),
        item("Sonnet", 0),
    ];
    let out = render_plain(items, 5);
    assert_eq!(out, "untouchable-long-name Sonnet");
}

// --- shrink_to_fit (layout-pressure-aware compaction) ---

/// Stub segment whose `shrink_to_fit` returns the configured
/// compact form unconditionally — the engine's `target` check
/// gates whether it's accepted. Higher-than-default priority so
/// it's the one the reflow loop selects under pressure.
struct ShrinkableSegment {
    full: &'static str,
    compact: &'static str,
}
impl Segment for ShrinkableSegment {
    fn render(&self, _ctx: &DataContext, _rc: &RenderContext) -> RenderResult {
        Ok(Some(RenderedSegment::new(self.full)))
    }
    fn shrink_to_fit(
        &self,
        _ctx: &DataContext,
        _rc: &RenderContext,
        target: u16,
    ) -> Option<RenderedSegment> {
        let r = RenderedSegment::new(self.compact);
        (r.width <= target).then_some(r)
    }
    fn defaults(&self) -> SegmentDefaults {
        SegmentDefaults::with_priority(200)
    }
}

/// Segment that always renders `text` and is priority-0 (never
/// dropped under pressure). Used as the "anchor" in shrink tests
/// so the reflow loop has only one droppable target.
struct AnchorSegment(&'static str);
impl Segment for AnchorSegment {
    fn render(&self, _ctx: &DataContext, _rc: &RenderContext) -> RenderResult {
        Ok(Some(RenderedSegment::new(self.0)))
    }
    fn defaults(&self) -> SegmentDefaults {
        SegmentDefaults::with_priority(0)
    }
}

#[test]
fn shrink_to_fit_replaces_full_render_when_compact_form_fits() {
    // Engine-level pin: the reflow loop calls shrink_to_fit
    // before considering drop. Full = "longbranch * ↑2 ↓1" (18
    // cells), compact = "longbranch" (10 cells). KEEP is
    // priority-0 so it can't be the drop target — only the
    // shrinkable segment is eligible.
    let items = line_items_spaced(vec![
        Box::new(ShrinkableSegment {
            full: "longbranch * ↑2 ↓1",
            compact: "longbranch",
        }),
        Box::new(AnchorSegment("KEEP")),
    ]);
    let mut warnings = Vec::new();
    let mut warn = |m: &str| warnings.push(m.to_string());
    let mut observers = LayoutObservers::new(&mut warn);
    let line = render_with_observers(
        &items,
        &empty_ctx(),
        17,
        &mut observers,
        theme::default_theme(),
        theme::Capability::None,
        false,
    );
    // Full 18 + sep 1 + KEEP 4 = 23. Budget 17 → overflow 6.
    // shrink target = 18 - 6 = 12. Compact "longbranch" (10)
    // fits → "longbranch KEEP" (15 cells).
    assert_eq!(line, "longbranch KEEP");
}

#[test]
fn shrink_to_fit_falls_back_to_drop_when_compact_form_too_wide() {
    // Compact form is wider than target → engine rejects it,
    // falls through to drop (segment isn't truncatable).
    let items = line_items_spaced(vec![
        Box::new(ShrinkableSegment {
            full: "longbranch",
            compact: "stilltoolongtruly",
        }),
        Box::new(AnchorSegment("X")),
    ]);
    let mut warnings = Vec::new();
    let mut warn = |m: &str| warnings.push(m.to_string());
    let mut observers = LayoutObservers::new(&mut warn);
    let line = render_with_observers(
        &items,
        &empty_ctx(),
        5,
        &mut observers,
        theme::default_theme(),
        theme::Capability::None,
        false,
    );
    // Compact form 17 cells > target → reject → drop. Only the
    // anchor remains.
    assert_eq!(line, "X");
}

#[test]
fn shrink_to_fit_honors_configured_width_min_floor() {
    // A segment with `width.min = 8` configured: even though its
    // compact form is 5 cells (would otherwise fit a target ≥ 5),
    // the engine must reject the shrunk render and drop the
    // segment because the user contracted "at least 8 cells or
    // hide me." Pins parity with `apply_width_bounds` /
    // `try_reflow`.
    struct LowFloorShrink;
    impl Segment for LowFloorShrink {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new("longerprefix")))
        }
        fn shrink_to_fit(
            &self,
            _: &DataContext,
            _: &RenderContext,
            _target: u16,
        ) -> Option<RenderedSegment> {
            Some(RenderedSegment::new("five5"))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(200)
                .with_width(WidthBounds::new(8, u16::MAX).expect("valid"))
        }
    }
    let items = line_items_spaced(vec![Box::new(LowFloorShrink), Box::new(AnchorSegment("X"))]);
    let_noop_observers!(observers);
    let line = render_with_observers(
        &items,
        &empty_ctx(),
        7,
        &mut observers,
        theme::default_theme(),
        theme::Capability::None,
        false,
    );
    // shrunk would deliver 5 cells, but width.min=8 → rejected,
    // segment drops. Only anchor remains.
    assert_eq!(line, "X");
}

#[test]
fn shrink_to_fit_rejects_too_wide_response_and_drops() {
    // A misbehaving segment ignores `target` and emits a render
    // wider than the engine asked for. The engine must reject
    // the response (preserving the layout-fit invariant) and
    // fall through to drop. The contract violation also fires
    // `lsm_warn!` (visible on stderr during test runs); that
    // side effect isn't captured by the warn closure passed to
    // `render_with_observers`, which only carries segment-render
    // errors — asserting layout outcome is the testable
    // contract here.
    struct MisbehavingSegment;
    impl Segment for MisbehavingSegment {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new("longbranch")))
        }
        fn shrink_to_fit(
            &self,
            _: &DataContext,
            _: &RenderContext,
            _target: u16,
        ) -> Option<RenderedSegment> {
            Some(RenderedSegment::new("stilltoolongtruly"))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(200)
        }
    }
    let items = line_items_spaced(vec![
        Box::new(MisbehavingSegment),
        Box::new(AnchorSegment("X")),
    ]);
    let_noop_observers!(observers);
    let line = render_with_observers(
        &items,
        &empty_ctx(),
        5,
        &mut observers,
        theme::default_theme(),
        theme::Capability::None,
        false,
    );
    assert_eq!(line, "X");
}

#[test]
fn shrink_to_fit_runs_before_truncatable_end_ellipsis() {
    // A segment that's both truncatable AND has shrink_to_fit:
    // segment-side intelligence wins. The compact form replaces
    // the full render before generic end-ellipsis fires.
    struct DualSegment;
    impl Segment for DualSegment {
        fn render(&self, _ctx: &DataContext, _rc: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new("longprefix-with-tail")))
        }
        fn shrink_to_fit(
            &self,
            _ctx: &DataContext,
            _rc: &RenderContext,
            target: u16,
        ) -> Option<RenderedSegment> {
            let r = RenderedSegment::new("longprefix");
            (r.width <= target).then_some(r)
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(200).with_truncatable(true)
        }
    }
    let items = line_items_spaced(vec![
        Box::new(DualSegment),
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("X"))))),
    ]);
    let mut warnings = Vec::new();
    let mut warn = |m: &str| warnings.push(m.to_string());
    let mut observers = LayoutObservers::new(&mut warn);
    let line = render_with_observers(
        &items,
        &empty_ctx(),
        13,
        &mut observers,
        theme::default_theme(),
        theme::Capability::None,
        false,
    );
    // Full = 20, X = 1, separator = 1 → total 22. Budget 13 →
    // overflow 9. shrink target = 20 - 9 = 11. Compact
    // "longprefix" (10) fits → "longprefix X" (12 cells).
    // No "…" appears because shrink_to_fit ran first.
    assert!(line.contains("longprefix"), "got {line:?}");
    assert!(!line.contains(''), "no end-ellipsis: {line:?}");
}

// --- render_to_runs ---------------------------------------------------

#[test]
fn render_to_runs_empty_input_yields_no_runs() {
    let items: Vec<LineItem> = vec![];
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert!(runs.is_empty());
}

#[test]
fn render_to_runs_emits_segment_then_separator_then_segment() {
    // Neither segment requested a role, so all three emitted runs
    // carry Style::default().
    let items = line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("a"))))),
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("b"))))),
    ]);
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert_eq!(runs.len(), 3);
    assert_eq!(runs[0].text, "a");
    assert_eq!(runs[0].style, Style::default());
    assert_eq!(runs[1].text, " ");
    assert_eq!(runs[1].style, Style::default());
    assert_eq!(runs[2].text, "b");
    assert_eq!(runs[2].style, Style::default());
}

#[test]
fn render_to_runs_preserves_segment_style() {
    // The styled segment's role lands on its run unchanged; the
    // TUI consumer maps role → ratatui Color, so anything dropped
    // here would silently break themed preview.
    use crate::theme::Role;
    let items = line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("plain"))))),
        Box::new(StubSegment(Ok(Some(
            RenderedSegment::new("warn").with_role(Role::Warning),
        )))),
    ]);
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert_eq!(runs.len(), 3);
    assert_eq!(runs[2].text, "warn");
    assert_eq!(runs[2].style.role, Some(Role::Warning));
}

#[test]
fn render_to_runs_skips_separator_none_between_segments() {
    // `Separator::None` is "no gap"; the runs view skips it
    // entirely so consumers don't have to filter empty-text runs.
    let items = line_items_with(
        vec![
            Box::new(StubSegment(Ok(Some(RenderedSegment::with_separator(
                "a",
                Separator::None,
            ))))),
            Box::new(StubSegment(Ok(Some(RenderedSegment::new("b"))))),
        ],
        Separator::Space,
    );
    // The plugin per-render override on segment "a" replaces the
    // inline Space with Separator::None at that boundary.
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert_eq!(runs.len(), 2);
    assert_eq!(runs[0].text, "a");
    assert_eq!(runs[1].text, "b");
}

#[test]
fn render_to_runs_drops_segments_under_width_pressure() {
    // The runs view reflects post-layout state: dropped segments
    // produce no run, and the separator that would have followed
    // a dropped segment also vanishes.
    let items = line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(
            RenderedSegment::new("keep").with_role(crate::theme::Role::Primary),
        )))),
        Box::new(DroppableStub("droppable")),
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("anchor"))))),
    ]);
    // Total: 4 + 1 + 9 + 1 + 6 = 21. Budget 12 forces the
    // priority-200 middle segment to drop.
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 12, &mut observers);
    let texts: Vec<&str> = runs.iter().map(|r| r.text.as_str()).collect();
    assert_eq!(texts, vec!["keep", " ", "anchor"]);
}

/// Build a styled multi-segment line for round-trip tests: roled
/// segments + a plain literal in the middle so both styled and
/// unstyled run paths are exercised.
fn round_trip_line() -> Vec<LineItem> {
    use crate::theme::Role;
    line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(
            RenderedSegment::new("ctx").with_role(Role::Info),
        )))),
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("|"))))),
        Box::new(StubSegment(Ok(Some(
            RenderedSegment::new("err").with_role(Role::Error),
        )))),
    ])
}

fn round_trip_assert(terminal_width: u16, capability: theme::Capability, hyperlinks: bool) {
    let items = round_trip_line();
    let_noop_observers!(observers_direct);
    let direct = render_with_observers(
        &items,
        &empty_ctx(),
        terminal_width,
        &mut observers_direct,
        theme::default_theme(),
        capability,
        hyperlinks,
    );
    let_noop_observers!(observers_runs);
    let runs = render_to_runs(&items, &empty_ctx(), terminal_width, &mut observers_runs);
    let recomposed = runs_to_ansi(&runs, theme::default_theme(), capability, hyperlinks);
    assert_eq!(
        direct, recomposed,
        "cap={capability:?} width={terminal_width} hyperlinks={hyperlinks}"
    );
}

#[test]
fn render_to_runs_then_runs_to_ansi_matches_render_with_observers() {
    // Round-trip pin: `render_to_runs` → `runs_to_ansi` must match
    // `render_with_observers` byte-for-byte. The contract that lets
    // `render_with_observers` stay a thin wrapper.
    round_trip_assert(100, theme::Capability::Palette16, false);
}

#[test]
fn render_to_runs_round_trip_holds_under_capability_none() {
    // No-color path: every run goes through the `open.is_empty()`
    // branch in `runs_to_ansi`. A future change to `sgr_open`
    // returning a non-empty string for `Capability::None` would
    // silently leak escapes; this pins it.
    round_trip_assert(100, theme::Capability::None, false);
}

#[test]
fn render_to_runs_round_trip_holds_under_width_pressure() {
    // Width pressure forces `apply_layout` to drop a segment;
    // both emit paths must produce the same post-drop output.
    // `round_trip_segments` totals 9 cells; budget 5 drops the
    // rightmost priority-128 tie ("err"), leaving "ctx |".
    round_trip_assert(5, theme::Capability::Palette16, false);
}

#[test]
fn render_to_runs_round_trip_holds_with_hyperlinks_enabled() {
    // The `hyperlinks` bool must thread identically through both
    // emit paths. `round_trip_segments` carries no hyperlinks
    // today, so the equivalence is structural — a regression
    // where one path silently dropped the bool would still match
    // here. Adding a hyperlinked segment to the round-trip set
    // is a follow-up; this test names the bool-thread contract.
    round_trip_assert(100, theme::Capability::Palette16, true);
}

#[test]
fn render_to_runs_with_one_survivor_emits_no_trailing_separator() {
    // Drop pressure leaves a single segment. `pop_trailing_separator`
    // (run when the priority-drop loop removes a segment whose
    // right-edge separator was already adjacent) must remove the
    // surviving separator so the runs view doesn't end with a stray
    // " " run.
    let items = line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("a"))))),
        Box::new(DroppableStub("droppable")),
    ]);
    // Total: 1 + 1 + 9 = 11. Budget 1 drops the priority-200
    // segment; "a" survives alone with no trailing separator.
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 1, &mut observers);
    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].text, "a");
}

#[test]
fn render_to_runs_emits_powerline_chevron_with_muted_role() {
    // Pins both the glyph and the `Role::Muted` style — a future
    // bg-transition restyle should land as an intentional update
    // to this assertion.
    use crate::theme::Role;
    let items = line_items_with(
        vec![
            Box::new(StubSegment(Ok(Some(
                RenderedSegment::new("a").with_role(Role::Primary),
            )))),
            Box::new(StubSegment(Ok(Some(RenderedSegment::new("b"))))),
        ],
        Separator::powerline(),
    );
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert_eq!(runs.len(), 3);
    assert_eq!(runs[1].text, " \u{E0B0} ");
    assert_eq!(runs[1].style.role, Some(Role::Muted));
}

#[test]
fn powerline_separator_emits_padded_chevron_with_correct_width() {
    // The chevron is a Nerd Font glyph in the private-use range;
    // unicode-width doesn't know its cell count, so the layout's
    // total_width math depends on `Separator::width()`'s answer.
    // Pin both the emitted text (single-space pad on each side of
    // the chevron) and the reported width (1-cell chevron + 2
    // padding cells = 3).
    assert_eq!(Separator::powerline().width(), 3);
    assert_eq!(Separator::powerline().text(), " \u{E0B0} ");
}

#[test]
fn powerline_chevrons_are_charged_to_total_width_in_layout() {
    // total_width sums every layout item. Three priority-0 segments
    // at width 4 plus two powerline chevrons between them = 4 + chev
    // + 4 + chev + 4. A regression that stopped counting Powerline
    // width would silently push lines past budget. Computed (not
    // hardcoded) so a future change to the chevron's padding-cell
    // count fails this assertion at the right line.
    let items = pl_spec(&[("aaaa", 0), ("bbbb", 0), ("cccc", 0)]);
    let chev = u32::from(Separator::powerline().width());
    assert_eq!(total_width(&items), 4 + chev + 4 + chev + 4);
}

#[test]
fn render_with_observers_emits_powerline_chevron_wrapped_in_muted_sgr() {
    // End-to-end pin: drive two segments through `render_with_observers`
    // under Palette16 with powerline separators between them. The
    // output must contain the padded chevron wrapped in *some* SGR
    // open + reset; the exact bytes are computed from
    // `theme::sgr_open` for the Muted role on the default theme,
    // so this test adapts if the default theme's Muted color is
    // ever retuned. Decouples "chevron emits styled" from "the
    // exact ANSI code for Muted on theme X."
    struct RoledSeg(&'static str, theme::Role);
    impl Segment for RoledSeg {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new(self.0).with_role(self.1)))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(10)
        }
    }
    let items = line_items_with(
        vec![
            Box::new(RoledSeg("a", theme::Role::Primary)),
            Box::new(RoledSeg("b", theme::Role::Info)),
        ],
        Separator::powerline(),
    );
    let_noop_observers!(observers);
    let line = render_with_observers(
        &items,
        &empty_ctx(),
        100,
        &mut observers,
        theme::default_theme(),
        theme::Capability::Palette16,
        false,
    );
    let muted_sgr = theme::sgr_open(
        &Style::role(theme::Role::Muted),
        theme::default_theme(),
        theme::Capability::Palette16,
    );
    let expected = format!("{muted_sgr} \u{E0B0} \x1b[0m");
    assert!(
        line.contains(&expected),
        "padded chevron with Muted SGR not in line: {line:?} (expected substring: {expected:?})"
    );
}

#[test]
fn render_to_runs_emits_literal_separator_with_default_style() {
    // An inline `Separator::Literal(" | ")` becomes a separator run
    // with that exact text and Style::default() — separators don't
    // inherit segment styling, even when the flanking segment carries
    // a role.
    let items = line_items_with(
        vec![
            Box::new(StubSegment(Ok(Some(
                RenderedSegment::new("a").with_role(crate::theme::Role::Warning),
            )))),
            Box::new(StubSegment(Ok(Some(RenderedSegment::new("b"))))),
        ],
        Separator::Literal(Cow::Borrowed(" | ")),
    );
    let_noop_observers!(observers);
    let runs = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert_eq!(runs.len(), 3);
    assert_eq!(runs[1].text, " | ");
    assert_eq!(runs[1].style, Style::default());
}

#[test]
fn runs_to_ansi_emits_osc8_around_styled_run_when_hyperlinks_supported() {
    // Pin the OSC 8 envelope and its order: the link wraps
    // *outside* the SGR pair so the link survives `sgr_reset`.
    // Bytes asserted explicitly so a future change to the OSC 8
    // emitter (BEL terminator, different escape) is caught.
    use crate::theme::Role;
    let runs = vec![StyledRun::new(
        "branch",
        Style::role(Role::Primary).with_hyperlink("https://example.com/b"),
    )];
    let out = runs_to_ansi(
        &runs,
        theme::default_theme(),
        theme::Capability::Palette16,
        true,
    );
    assert_eq!(
        out, "\x1b]8;;https://example.com/b\x1b\\\x1b[95mbranch\x1b[0m\x1b]8;;\x1b\\",
        "got {out:?}"
    );
}

#[test]
fn runs_to_ansi_drops_hyperlink_when_not_supported() {
    // `hyperlinks = false` must produce zero OSC 8 bytes; the
    // run still emits with its SGR styling. The URL is dropped
    // silently — capable terminals get the link, others get the
    // text.
    use crate::theme::Role;
    let runs = vec![StyledRun::new(
        "branch",
        Style::role(Role::Primary).with_hyperlink("https://example.com/b"),
    )];
    let out = runs_to_ansi(
        &runs,
        theme::default_theme(),
        theme::Capability::Palette16,
        false,
    );
    assert_eq!(out, "\x1b[95mbranch\x1b[0m");
    assert!(!out.contains("\x1b]8"), "no OSC 8: {out:?}");
}

#[test]
fn runs_to_ansi_emits_no_osc8_when_style_has_no_hyperlink() {
    // `hyperlinks = true` is permission, not obligation: a run
    // with `Style.hyperlink = None` emits no OSC 8 even when the
    // terminal supports it.
    let runs = vec![StyledRun::new("plain", Style::default())];
    let out = runs_to_ansi(&runs, theme::default_theme(), theme::Capability::None, true);
    assert_eq!(out, "plain");
    assert!(!out.contains("\x1b]8"), "no OSC 8: {out:?}");
}

#[test]
fn runs_to_ansi_emits_osc8_around_unstyled_run() {
    // An unstyled run with a hyperlink still gets OSC 8: the link
    // is independent of color/decoration. The text passes through
    // without an SGR pair.
    let runs = vec![StyledRun::new(
        "click",
        Style::default().with_hyperlink("https://example.com"),
    )];
    let out = runs_to_ansi(&runs, theme::default_theme(), theme::Capability::None, true);
    assert_eq!(out, "\x1b]8;;https://example.com\x1b\\click\x1b]8;;\x1b\\");
}

#[test]
fn osc8_pair_balanced_when_hyperlinked_run_is_truncated() {
    // Truncation rewrites the run's text; the OSC 8 wrapper sits
    // outside text in `runs_to_ansi`, so truncated text still
    // emits a balanced OSC 8 open/close. Pins the design
    // contract: hyperlinks live on `Style`, never in `text`, so
    // there's no escape-sequence inside the string for
    // truncation to split.
    let mut rendered = RenderedSegment::new("very-long-branch-name")
        .with_style(Style::default().with_hyperlink("https://example.com/branch"));
    rendered = truncate_to(rendered, 8);
    // Truncation produces "very-lo…" (7 graphemes + ellipsis = 8 cells).
    let runs = vec![StyledRun::new(
        rendered.text().to_string(),
        rendered.style.clone(),
    )];
    let out = runs_to_ansi(&runs, theme::default_theme(), theme::Capability::None, true);
    assert!(
        out.starts_with("\x1b]8;;https://example.com/branch\x1b\\"),
        "OSC 8 open present: {out:?}"
    );
    assert!(
        out.ends_with("\x1b]8;;\x1b\\"),
        "OSC 8 close present: {out:?}"
    );
    assert!(out.contains(''), "truncation marker preserved: {out:?}");
    assert_eq!(
        out.matches("\x1b]8;;").count(),
        2,
        "exactly one open and one close: {out:?}"
    );
}

#[test]
fn osc8_pair_balanced_when_hyperlinked_run_truncated_to_zero() {
    // truncate_to(_, 0) yields empty text + preserved style. The
    // OSC 8 pair must still be balanced — emitting a half-open
    // envelope would break every later byte on the line.
    let rendered = RenderedSegment::new("anything")
        .with_style(Style::default().with_hyperlink("https://example.com"));
    let truncated = truncate_to(rendered, 0);
    let runs = vec![StyledRun::new(
        truncated.text().to_string(),
        truncated.style.clone(),
    )];
    let out = runs_to_ansi(&runs, theme::default_theme(), theme::Capability::None, true);
    assert_eq!(
        out, "\x1b]8;;https://example.com\x1b\\\x1b]8;;\x1b\\",
        "empty-text run still emits balanced OSC 8 pair: {out:?}"
    );
}

#[test]
fn runs_to_ansi_emits_independent_osc8_pairs_for_adjacent_hyperlinked_runs() {
    // Adjacent runs with different links must each get their own
    // open/close pair — no nesting, no leak across the boundary.
    // Pins the per-run scoping of OSC 8 emission.
    let runs = vec![
        StyledRun::new("a", Style::default().with_hyperlink("https://a.example")),
        StyledRun::new("b", Style::default().with_hyperlink("https://b.example")),
    ];
    let out = runs_to_ansi(&runs, theme::default_theme(), theme::Capability::None, true);
    assert_eq!(
        out,
        "\x1b]8;;https://a.example\x1b\\a\x1b]8;;\x1b\\\x1b]8;;https://b.example\x1b\\b\x1b]8;;\x1b\\"
    );
    assert_eq!(out.matches("\x1b]8;;").count(), 4, "two opens + two closes");
}

#[test]
fn push_osc8_open_strips_control_chars_from_url() {
    // Security regression: a URL with embedded ESC `\` would
    // close the OSC 8 envelope early, turning the rest of the
    // line into raw control sequences. `push_osc8_open` strips
    // control bytes before emit. The bare `\` survives but
    // cannot reconstitute a String Terminator without the
    // stripped ESC.
    let runs = vec![StyledRun::new(
        "x",
        Style::default().with_hyperlink("https://example.com\x1b\\evil\x07more"),
    )];
    let out = runs_to_ansi(&runs, theme::default_theme(), theme::Capability::None, true);
    // Exactly one OSC 8 open and one close — the embedded ESC `\`
    // can't smuggle a second close into the output.
    assert_eq!(
        out.matches("\x1b]8;;").count(),
        2,
        "exactly one pair: {out:?}"
    );
    assert!(!out.contains("\x1b\\evil"), "ESC \\ stripped: {out:?}");
    assert!(!out.contains('\x07'), "BEL stripped: {out:?}");
    assert!(
        out.contains("https://example.com\\evilmore"),
        "non-control chars survive: {out:?}"
    );
}

#[test]
fn push_osc8_open_strips_c1_string_terminator_and_nul() {
    // `char::is_control()` covers C0 (0x00-0x1F, 0x7F) and C1
    // (0x80-0x9F). The most plausible bypass via the C1 range is
    // 0x9C (single-byte ST in 8-bit terminals); NUL and DEL are
    // the other classics. Pin that all three are stripped so a
    // future change to the sanitizer can't quietly narrow the
    // filter.
    let runs = vec![StyledRun::new(
        "x",
        Style::default().with_hyperlink("https://a.example\x00b\x7fc\u{009C}d"),
    )];
    let out = runs_to_ansi(&runs, theme::default_theme(), theme::Capability::None, true);
    assert_eq!(out.matches("\x1b]8;;").count(), 2, "single pair: {out:?}");
    assert!(!out.contains('\x00'), "NUL stripped: {out:?}");
    assert!(!out.contains('\x7f'), "DEL stripped: {out:?}");
    assert!(!out.contains('\u{009C}'), "C1 ST stripped: {out:?}");
    assert!(out.contains("https://a.examplebcd"));
}

#[test]
fn runs_to_ansi_capability_none_emits_unwrapped_text() {
    // Pin the no-color emit path independent of layout: a run
    // with a styled role + Capability::None must produce zero
    // ANSI escapes. Catches a regression where `sgr_open` would
    // start emitting decoration codes for the no-color tier.
    use crate::theme::Role;
    let runs = vec![
        StyledRun::new("plain", Style::default()),
        StyledRun::new(" ", Style::default()),
        StyledRun::new("warn", Style::role(Role::Warning)),
    ];
    let out = runs_to_ansi(
        &runs,
        theme::default_theme(),
        theme::Capability::None,
        false,
    );
    assert_eq!(out, "plain warn");
    assert!(!out.contains('\x1b'), "unexpected ANSI escape: {out:?}");
}

/// Stub for the drop-under-pressure run test: priority-200 so it
/// becomes the layout's first drop target. `StubSegment`'s default
/// priority (128) wouldn't be eligible against the anchors.
struct DroppableStub(&'static str);
impl Segment for DroppableStub {
    fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
        Ok(Some(RenderedSegment::new(self.0)))
    }
    fn defaults(&self) -> SegmentDefaults {
        SegmentDefaults::with_priority(200)
    }
}

#[test]
fn try_reflow_preserves_segment_id_reference() {
    // ADR-0026 contract: try_reflow rebuilds the SegmentEntry but
    // must thread the original id reference through, otherwise the
    // emit sites in apply_layout (lsm-b00q) would lose the user's
    // config name across reflow. Pointer-equality pins that the
    // borrow chain survives — a regression that re-borrows from a
    // different Cow (or worse, clones it) would fail here.
    static ALT_ID: Cow<'static, str> = Cow::Borrowed("alt");
    let entry = SegmentEntry {
        id: &ALT_ID,
        rendered: RenderedSegment::new("workspace-with-extra-content"),
        defaults: SegmentDefaults::with_priority(100).with_truncatable(true),
        segment: noop_segment(),
    };
    let original_id_ptr = std::ptr::from_ref(entry.id);
    let reflowed =
        super::try_reflow(&entry, 10).expect("reflow must succeed at target 18 / floor 2");
    assert!(
        std::ptr::eq(std::ptr::from_ref(reflowed.id), original_id_ptr),
        "try_reflow must preserve the id reference, not clone it",
    );
    assert_eq!(
        reflowed.id.as_ref(),
        "alt",
        "id content must survive — defense-in-depth alongside ptr::eq",
    );
}

/// Capture LayoutDecision events into a Vec for assertion. Bind two
/// locals via the macro because both `warn_buf` and `decisions` need
/// to outlive `observers`; a fn-returning helper would fail the borrow
/// check at the call site.
macro_rules! let_capturing_observers {
    ($name:ident, $decisions:ident) => {
        let mut __warn_for_capture: fn(&str) = |_: &str| {};
        let mut $decisions: Vec<LayoutDecision> = Vec::new();
        let mut __on_decision_for_capture = |d: &LayoutDecision| $decisions.push(d.clone());
        let mut $name = LayoutObservers::new(&mut __warn_for_capture)
            .with_decision(&mut __on_decision_for_capture);
    };
}

#[test]
fn emit_priority_drop_when_segment_dropped_under_pressure() {
    // High-priority `DroppableStub` (priority 200) next to a
    // priority-0 anchor; budget forces a drop.
    let items: Vec<LineItem> = vec![
        LineItem::Segment {
            id: Cow::Borrowed("anchor"),
            segment: Box::new(StubSegment(Ok(Some(RenderedSegment::new("a"))))),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("droppable"),
            segment: Box::new(DroppableStub("zzzzzz")),
        },
    ];
    // Total 1+1+6 = 8. Budget 1 drops droppable; anchor survives.
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 1, &mut observers);
    assert_eq!(decisions.len(), 1, "exactly one decision: {decisions:?}");
    match &decisions[0] {
        LayoutDecision::PriorityDrop {
            id,
            priority,
            terminal_width,
            overflow,
            dropped_width,
            ..
        } => {
            assert_eq!(id.as_ref(), "droppable");
            assert_eq!(*priority, 200);
            assert_eq!(*terminal_width, 1);
            assert!(*overflow >= 1);
            assert_eq!(*dropped_width, 6);
        }
        other => panic!("expected PriorityDrop, got {other:?}"),
    }
}

#[test]
fn emit_shrink_applied_when_shrink_to_fit_succeeds() {
    // Segment offers a shrink_to_fit form. Layout pressure forces it
    // before drop.
    let items: Vec<LineItem> = vec![
        LineItem::Segment {
            id: Cow::Borrowed("shrinkable"),
            segment: Box::new(ShrinkableSegment {
                full: "longbranch * ↑2 ↓1",
                compact: "longbranch",
            }),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("anchor"),
            segment: Box::new(AnchorSegment("KEEP")),
        },
    ];
    // Full: 18 + 1 + 4 = 23. Budget 17 → overflow 6 → target 12.
    // Compact 10 cells fits → shrink applied; line = "longbranch KEEP" (15).
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 17, &mut observers);
    assert_eq!(decisions.len(), 1, "exactly one decision: {decisions:?}");
    match &decisions[0] {
        LayoutDecision::ShrinkApplied {
            id,
            from,
            to,
            target,
            ..
        } => {
            assert_eq!(id.as_ref(), "shrinkable");
            assert_eq!(*from, 18);
            assert_eq!(*to, 10);
            assert_eq!(*target, 12);
        }
        other => panic!("expected ShrinkApplied, got {other:?}"),
    }
}

#[test]
fn emit_reflow_applied_when_truncatable_segment_end_ellipsis_fits() {
    // Truncatable segment without shrink_to_fit; budget forces
    // try_reflow's end-ellipsis path.
    struct TruncatableStub(&'static str);
    impl Segment for TruncatableStub {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new(self.0)))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(200).with_truncatable(true)
        }
    }
    let items: Vec<LineItem> = vec![
        LineItem::Segment {
            id: Cow::Borrowed("reflowed"),
            segment: Box::new(TruncatableStub("workspace-very-long-name")),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("anchor"),
            segment: Box::new(AnchorSegment("X")),
        },
    ];
    // Full: 24 + 1 + 1 = 26. Budget 10 → overflow 16 → target 8.
    // try_reflow truncates to 8 cells ("workspa…" or similar).
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 10, &mut observers);
    assert_eq!(decisions.len(), 1, "exactly one decision: {decisions:?}");
    match &decisions[0] {
        LayoutDecision::ReflowApplied {
            id,
            from,
            to,
            target,
            ..
        } => {
            assert_eq!(id.as_ref(), "reflowed");
            assert_eq!(*from, 24);
            assert!(*to <= *target);
            assert_eq!(*target, 8);
        }
        other => panic!("expected ReflowApplied, got {other:?}"),
    }
}

#[test]
fn emit_width_bound_under_min_drop_when_render_below_min_floor() {
    // Segment with width.min=10 renders 3 cells → dropped before
    // the layout pass.
    struct NarrowSegment;
    impl Segment for NarrowSegment {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new("abc")))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(10)
                .with_width(WidthBounds::new(10, u16::MAX).expect("valid"))
        }
    }
    let items: Vec<LineItem> = vec![LineItem::Segment {
        id: Cow::Borrowed("narrow"),
        segment: Box::new(NarrowSegment),
    }];
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert_eq!(decisions.len(), 1, "exactly one decision: {decisions:?}");
    match &decisions[0] {
        LayoutDecision::WidthBoundUnderMinDrop {
            id,
            rendered_width,
            min,
            ..
        } => {
            assert_eq!(id.as_ref(), "narrow");
            assert_eq!(*rendered_width, 3);
            assert_eq!(*min, 10);
        }
        other => panic!("expected WidthBoundUnderMinDrop, got {other:?}"),
    }
}

#[test]
fn emit_width_bound_over_max_truncate_when_render_above_max() {
    // Segment with width.max=5 renders 10 cells → truncated at
    // apply_width_bounds before the layout pass.
    struct WideSegment;
    impl Segment for WideSegment {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new("abcdefghij")))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(10).with_width(WidthBounds::new(0, 5).expect("valid"))
        }
    }
    let items: Vec<LineItem> = vec![LineItem::Segment {
        id: Cow::Borrowed("wide"),
        segment: Box::new(WideSegment),
    }];
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert_eq!(decisions.len(), 1, "exactly one decision: {decisions:?}");
    match &decisions[0] {
        LayoutDecision::WidthBoundOverMaxTruncate {
            id,
            rendered_width,
            max,
            ..
        } => {
            assert_eq!(id.as_ref(), "wide");
            assert_eq!(*rendered_width, 10);
            assert_eq!(*max, 5);
        }
        other => panic!("expected WidthBoundOverMaxTruncate, got {other:?}"),
    }
}

#[test]
fn no_decisions_emitted_when_no_pressure_no_bounds() {
    // Happy path: segments render within their bounds and the line
    // fits the budget. No LayoutDecision events fire. Pins the
    // "zero events on the disabled path" cost contract.
    let items = line_items_spaced(vec![
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("a"))))),
        Box::new(StubSegment(Ok(Some(RenderedSegment::new("b"))))),
    ]);
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 100, &mut observers);
    assert!(
        decisions.is_empty(),
        "no decisions on happy path: {decisions:?}"
    );
}

#[test]
fn emit_priority_drop_via_truncatable_path_when_reflow_target_below_floor() {
    // Truncatable segment with width.min=8 set high enough that
    // `try_reflow`'s floor rejects every target the overflow demands.
    // The engine falls through to drop; PriorityDrop fires via the
    // truncatable branch — a distinct code path from the
    // non-truncatable PriorityDrop covered above.
    struct FloorBoundTruncatable;
    impl Segment for FloorBoundTruncatable {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new("abcdefghij"))) // 10 cells
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(200)
                .with_truncatable(true)
                .with_width(WidthBounds::new(8, u16::MAX).expect("valid"))
        }
    }
    let items: Vec<LineItem> = vec![
        LineItem::Segment {
            id: Cow::Borrowed("anchor"),
            segment: Box::new(StubSegment(Ok(Some(RenderedSegment::new("a"))))),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("floor-bound"),
            segment: Box::new(FloorBoundTruncatable),
        },
    ];
    // Total: 1 + 1 + 10 = 12. Budget 6 → overflow 6 → target 4.
    // Reflow floor max(8, 2) = 8 rejects target 4 → drop via the
    // truncatable branch.
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 6, &mut observers);
    assert_eq!(decisions.len(), 1, "exactly one decision: {decisions:?}");
    match &decisions[0] {
        LayoutDecision::PriorityDrop {
            id,
            priority,
            terminal_width,
            overflow,
            dropped_width,
            ..
        } => {
            assert_eq!(id.as_ref(), "floor-bound");
            assert_eq!(*priority, 200);
            assert_eq!(*terminal_width, 6);
            assert!(*overflow >= 1);
            assert_eq!(*dropped_width, 10);
        }
        other => panic!("expected PriorityDrop, got {other:?}"),
    }
}

#[test]
fn emit_multiple_decisions_in_iteration_order_under_compound_pressure() {
    // Two reflow-loop iterations under compound pressure: priority-200
    // (shrinkable) tries shrink first but the compact form still
    // exceeds the target, so the segment drops; priority-150 then
    // drops to clear remaining overflow. Pins both ordering and
    // per-iteration capture so an emit-before-mutate vs mutate-before-
    // emit swap is visible.
    struct DroppableP150(&'static str);
    impl Segment for DroppableP150 {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new(self.0)))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(150)
        }
    }
    let items: Vec<LineItem> = vec![
        LineItem::Segment {
            id: Cow::Borrowed("anchor"),
            segment: Box::new(AnchorSegment("A")),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("shrinkable"),
            segment: Box::new(ShrinkableSegment {
                full: "longbranch * ↑2 ↓1",
                compact: "longbranch",
            }),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("droppable"),
            segment: Box::new(DroppableP150("midpriority")),
        },
    ];
    // Full: 1 + 1 + 18 + 1 + 11 = 32. Budget 11.
    // Iter 1: priority 200 (shrinkable) fires. try_shrink target =
    // saturating_sub(18, 21) = 0; compact (10) > 0 → reject. Not
    // truncatable → drop "shrinkable".
    // Iter 2: total = 1 + 1 + 11 = 13, still > 11. Priority 150
    // fires; not truncatable → drop "droppable".
    // Captured: [PriorityDrop shrinkable, PriorityDrop droppable].
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 11, &mut observers);
    assert_eq!(decisions.len(), 2, "two decisions in order: {decisions:?}");
    match (&decisions[0], &decisions[1]) {
        (
            LayoutDecision::PriorityDrop {
                id: id1,
                priority: p1,
                ..
            },
            LayoutDecision::PriorityDrop {
                id: id2,
                priority: p2,
                ..
            },
        ) => {
            assert_eq!(
                id1.as_ref(),
                "shrinkable",
                "shrinkable drops first (priority 200)"
            );
            assert_eq!(*p1, 200);
            assert_eq!(
                id2.as_ref(),
                "droppable",
                "droppable drops second (priority 150)"
            );
            assert_eq!(*p2, 150);
        }
        other => panic!("expected two PriorityDrops in order, got {other:?}"),
    }
}

#[test]
fn emit_priority_drop_does_not_panic_on_zero_width_segment() {
    // Regression: `RenderedSegment::new("")` is a valid zero-cell
    // render. Under separator pressure the engine can select such a
    // segment to drop, and the PriorityDrop emit must accept
    // `dropped_width == 0` instead of panicking debug builds.
    struct EmptySegment;
    impl Segment for EmptySegment {
        fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
            Ok(Some(RenderedSegment::new("")))
        }
        fn defaults(&self) -> SegmentDefaults {
            SegmentDefaults::with_priority(200)
        }
    }
    // Two anchors flanking an empty priority-200 segment so the
    // separators on either side give the engine overflow to chase.
    let items: Vec<LineItem> = vec![
        LineItem::Segment {
            id: Cow::Borrowed("anchor-l"),
            segment: Box::new(AnchorSegment("L")),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("empty"),
            segment: Box::new(EmptySegment),
        },
        LineItem::Separator(Separator::Space),
        LineItem::Segment {
            id: Cow::Borrowed("anchor-r"),
            segment: Box::new(AnchorSegment("R")),
        },
    ];
    // Total widths: 1 + 1 + 0 + 1 + 1 = 4. Budget 2 forces drop;
    // empty (priority 200) is the only droppable target.
    let_capturing_observers!(observers, decisions);
    let _ = render_to_runs(&items, &empty_ctx(), 2, &mut observers);
    assert_eq!(decisions.len(), 1, "exactly one decision: {decisions:?}");
    match &decisions[0] {
        LayoutDecision::PriorityDrop {
            id, dropped_width, ..
        } => {
            assert_eq!(id.as_ref(), "empty");
            assert_eq!(*dropped_width, 0, "zero-width drop must round-trip cleanly");
        }
        other => panic!("expected PriorityDrop, got {other:?}"),
    }
}