inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
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
//! Plain-frame render assembly — M1-5 implementation per ADR-2.
//!
//! # Module structure
//! - `cli_boxes`  — vendored cli-boxes@4.0.1 char table (border drawing chars).
//! - `grid`       — char grid: write/clip/wide-char cleanup/get (output.ts port).
//! - `border`     — border char drawing (render-border.ts port, plain slice).
//! - `walk`       — arena tree walk → grid (render-node-to-output.ts port).
//! - `mod` (this) — `render_to_string` entry point tying layout + grid together.
//!
//! # Engine-per-call design (ADR-3, M3-A)
//! Both `render_to_string` and the `build_layout_engine` seam create a **fresh**
//! `TaffyEngine` on each call. ADR-3 (`docs/adr3-engine-lifetime.md`) chose
//! per-frame rebuild over a live incremental engine: persistence lives in the
//! `Arena` (which `InkRoot` will own across `commit()` calls, M3-D), while the
//! engine is a pure function of the arena at render time. A fresh engine
//! re-runs `set_measure` for every text node every frame, so the
//! measure-invalidation discipline (`layout/engine.rs:78-82`) is satisfied for
//! free — the rejected incremental option would have had to replicate it by
//! hand, at the risk of silent text-measure corruption. The node-creation walk
//! is NEVER re-run against an already-populated engine: `insert_child` appends,
//! so reuse would duplicate child lists. See ADR-3 for the full rationale.
//!
//! # Height for unconstrained render (render-to-string.ts:62-68 citation)
//! ink's `renderToString` calls:
//! ```ts
//! rootNode.yogaNode!.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
//! ```
//! ink passes `undefined` for both axes in yoga, but the root node has an
//! explicit `setWidth(columns)` call immediately before (render-to-string.ts:62),
//! so in practice width is definite and only height is unconstrained.
//! `render_to_string` mirrors this: width is `AvailableSpace::Definite(columns)`,
//! height is `AvailableSpace::MaxContent` (passed as `None` to `calculate`).
//! The grid is sized to the computed root height so trailing empty rows are
//! never included in the output.

pub mod background;
pub mod border;
pub mod cli_boxes;
pub mod colorize;
#[cfg(test)]
mod colorize_chalk_parity_tests;
pub mod grid;
pub mod walk;

pub use colorize::{ColorLevel, Kind as ColorKind, colorize, dim};

use crate::dom::{Arena, Kind};
use crate::layout::{LayoutEngine, Rect, TaffyEngine};
use crate::render::grid::Grid;
use crate::render::walk::{TransformAccessor, walk, walk_static};
use crate::text_measure::build_measure_fn_for;

/// Render the arena tree rooted at `root_id` to a plain-frame string.
///
/// Orchestration (mirrors `renderer.ts` + `render-to-string.ts`):
/// 1. Build a fresh `TaffyEngine` (engine-per-call; see module docs).
/// 2. Walk the arena: create taffy nodes, apply styles, set text measures.
/// 3. `calculate(root, width, MAX_HEIGHT)` — unconstrained height per ink.
/// 4. Walk arena again: render each node into a `Grid`.
/// 5. Return `grid.get().0` (the trimmed frame string).
///
/// The returned string matches ink's `renderToString` output for unstyled
/// content (no SGR transformers, no static nodes).
pub fn render_to_string(arena: &Arena, root_id: u32, width: u16) -> String {
    // render_to_string is the PLAIN slice of `render_styled`: a no-op transform
    // accessor (`&|_| None`) leaves the transformer chain empty at every node,
    // so the styled write path degenerates to the plain one and the bytes are
    // identical to the pre-seam output (the corpus, 188/5 exact, is the proof).
    // The returned height is discarded here; callers that need it use
    // `render_styled` directly.
    //
    // Color level is fixed to `Truecolor` (=3) here: this helper backs the
    // `layout_corpus` byte tests, whose border-color EXPECTED literals are
    // chalk@5 level-3 bytes. The PRODUCTION `renderToString` does NOT go through
    // this helper — it calls `render_frame` (napi) with the detected
    // `opts.color_level`, so honoring the level lives there, not here.
    render_styled(arena, root_id, width, &|_| None, ColorLevel::Truecolor).0
}

/// Render the arena tree rooted at `root_id` to a **styled** frame, returning
/// both the frame string and its height in rows (`mirrors ink's `{output,
/// height}`, output.ts:315-316). This is the entry M3-E `render_frame` calls.
///
/// `transform_of` is the per-node own-transform seam (see
/// [`walk::TransformAccessor`]): given a dom id it returns the node's own output
/// transform (ink's `internal_transform`), or `None`. `<Text color>` SGR is *not*
/// a separate path — in ink it lives **inside** `internal_transform`
/// (Text.tsx:94-130 → `colorize`), so a core caller wires `colorize` into the
/// accessor and napi (M3-E) dispatches to a JS `internal_transform`; both flow
/// through the same `[own, ...inherited]` chain (render-node-to-output.ts:136).
///
/// Reuses [`build_layout_engine`] (the M3-A seam) verbatim — the layout build is
/// never duplicated. An empty/zero-sized frame returns `(String::new(), 0)`,
/// matching the prior `render_to_string` error/empty path.
pub fn render_styled<'a>(
    arena: &'a Arena,
    root_id: u32,
    width: u16,
    transform_of: &'a TransformAccessor<'a>,
    color_level: ColorLevel,
) -> (String, u16) {
    // ── 1. Layout pass (ADR-3 seam) ───────────────────────────────────────────
    // Build a fresh engine + compute layout via the shared seam. `InkRoot`
    // (M3-D) calls the same seam each frame; this entry is the styled wrapper
    // over it, so the two paths cannot drift in their layout.
    let Some((engine, root_rect)) = build_layout_engine(arena, root_id, width) else {
        return (String::new(), 0);
    };

    // ── 2. Render pass ────────────────────────────────────────────────────────
    // renderer.ts:37-39: Output is sized to the computed root dimensions.
    let grid_rows = root_rect.height as usize;
    let grid_cols = root_rect.width as usize;

    if grid_rows == 0 || grid_cols == 0 {
        return (String::new(), 0);
    }

    let mut grid = Grid::new(grid_rows, grid_cols);

    // Build a rect accessor closure from the engine.
    // The closure captures engine by reference for the walk.
    let rect_fn = |id: u32| engine.computed(id);

    walk(
        arena,
        root_id,
        &rect_fn,
        transform_of,
        &mut grid,
        color_level,
    );

    // grid.get() returns (output, height); height == grid_rows == root height.
    let (output, height) = grid.get();
    (output, height as u16)
}

/// Render the **static** subtree (ink's `<Static>`) to its standalone output
/// string — the text ink prints once, above the live region.
///
/// This is the SECOND render pass, a faithful port of `renderer.ts`'s static
/// branch (renderer.ts:46-66):
/// ```ts
/// let staticOutput;
/// if (node.staticNode?.yogaNode) {
///   staticOutput = new Output({
///     width:  node.staticNode.yogaNode.getComputedWidth(),
///     height: node.staticNode.yogaNode.getComputedHeight(),
///   });
///   renderNodeToOutput(node.staticNode, staticOutput, {skipStaticElements: false});
/// }
/// // …
/// staticOutput: staticOutput ? `${staticOutput.get().output}\n` : '',
/// ```
///
/// Semantics, point by point:
/// 1. **Find the static node.** ink tracks a single `node.staticNode` set by the
///    reconciler when `internal_static` is applied (reconciler.ts:236-244). The
///    arena instead marks the node with `is_static` (set by `Op::SetStatic`), so
///    we DFS from `root_id` for the first `is_static` node. No static node →
///    return `""` (the common case; matches `staticNode` being `undefined`).
/// 2. **Layout.** Reuse [`build_layout_engine`] at the SAME `width` ink lays the
///    root out at — the static node is part of that one tree, so its computed
///    rect (`engine.computed(static_id)`) falls out of the single root layout,
///    exactly as `node.staticNode.yogaNode` is laid out by the root's
///    `calculateLayout`. If the static id has no computed rect, return `""`
///    (matches `node.staticNode?.yogaNode` being absent).
/// 3. **Own-sized grid.** Size the static grid to the static node's OWN computed
///    width/height (renderer.ts:50-52: `new Output({width: …getComputedWidth(),
///    height: …getComputedHeight()})`), NOT the root's.
/// 4. **Walk at offset 0** via [`walk_static`] (`skipStaticElements: false`): the
///    static entry's own computed left/top become the first write position
///    (render-node-to-output.ts:129-130 with offsetX/Y defaulting to 0).
/// 5. **Trailing newline** (renderer.ts:64-66): a PRESENT static node always
///    appends `\n` ("static output doesn't have one, so interactive output will
///    override last line of static output"), even for an empty body (→ `"\n"`).
///    An ABSENT static node yields `""`. A zero-dimensioned static node skips
///    `Grid::new` and still yields `"\n"`, matching `staticOutput.get().output`
///    being `""` for an empty `Output` plus the appended newline.
///
/// `transform_of` is the same per-node own-transform seam [`render_styled`] uses;
/// the napi caller passes the SAME accessor so a `<Transform>`/`<Text color>`
/// inside `<Static>` is honored in the static pass too.
pub fn render_static<'a>(
    arena: &'a Arena,
    root_id: u32,
    width: u16,
    transform_of: &'a TransformAccessor<'a>,
    color_level: ColorLevel,
) -> String {
    // ── 1. Find the static node (DFS from root) — short-circuit BEFORE any
    //       layout build so a static-free frame (the common case) skips the
    //       layout/grid/walk work below. It still pays one O(n) pre-order DFS of
    //       the arena (`find_static_node`) per frame before it can return `""`;
    //       negligible in practice, but not free.
    let Some(static_id) = find_static_node(arena, root_id) else {
        return String::new();
    };

    // ── 2. Layout pass: the static node is part of the one root layout, so its
    //       computed rect falls out of a `build_layout_engine` build at the SAME
    //       width ink uses. NOTE: this builds a FRESH taffy tree rather than
    //       reusing the M3-A persistent engine, so a static-bearing frame computes
    //       layout twice (main pass + here). Perf-only, and only on the rare
    //       static-bearing frame; correctness is unaffected.
    let Some((engine, _root_rect)) = build_layout_engine(arena, root_id, width) else {
        return String::new();
    };
    let Some(static_rect) = engine.computed(static_id) else {
        return String::new();
    };

    // ── 3. Own-sized grid (renderer.ts:50-52). A zero-dim static node still gets
    //       the trailing newline below (a present `staticNode` always does).
    let grid_rows = static_rect.height as usize;
    let grid_cols = static_rect.width as usize;
    if grid_rows == 0 || grid_cols == 0 {
        return "\n".to_owned();
    }

    let mut grid = Grid::new(grid_rows, grid_cols);
    let rect_fn = |id: u32| engine.computed(id);

    // ── 4. Render pass with skipStaticElements=false (renderer.ts:54).
    walk_static(
        arena,
        static_id,
        &rect_fn,
        transform_of,
        &mut grid,
        color_level,
    );

    // ── 5. Trailing newline (renderer.ts:64-66): present static → body + "\n".
    let (body, _height) = grid.get();
    format!("{body}\n")
}

/// DFS the arena tree rooted at `root_id` for the first `is_static` node, in
/// pre-order. ink supports exactly ONE `<Static>` per tree (the reconciler keeps
/// a lone `rootNode.staticNode` reference, reconciler.ts:243), so in every
/// supported tree there is at most one `is_static` node and "first in pre-order"
/// is unambiguous — matching ink's single `node.staticNode`.
///
/// Multiple static nodes are undefined in ink itself. NOTE: for that
/// ink-undefined case the selection *direction* differs: we take the FIRST
/// `is_static` node in pre-order, whereas ink's reconciler reassigns
/// `rootNode.staticNode = node` on every `internal_static` apply
/// (reconciler.ts:243), so ink's effective static node is the LAST one committed.
/// Both pick deterministically; they only diverge on a tree ink does not support.
/// Returns the static entry id, or `None` when the tree carries no static node.
fn find_static_node(arena: &Arena, id: u32) -> Option<u32> {
    let node = arena.get(id)?;
    if node.is_static {
        return Some(id);
    }
    for &child_id in &node.children {
        if let Some(found) = find_static_node(arena, child_id) {
            return Some(found);
        }
    }
    None
}

/// Build a fresh layout engine for the arena tree rooted at `root_id`, compute
/// layout at the given `width`, and return the built engine plus the root rect.
///
/// This is the **M3-A engine-lifetime seam** (ADR-3,
/// `docs/adr3-engine-lifetime.md`) — the **public** entry `InkRoot`
/// (`inkferro-napi`, M3-D) calls each `render_frame`. `render_to_string` calls
/// it as step 1 of its own body, so the two paths cannot drift. It is the single
/// place the taffy tree is constructed, so callers cannot accidentally re-run
/// node creation against a populated engine (which would duplicate child lists —
/// `insert_child` appends).
///
/// It is `pub` (not `pub(crate)`) because the consumer lives in a *different*
/// crate (`inkferro-napi`). Returning the concrete `TaffyEngine` — rather than
/// `impl LayoutEngine` — lets `InkRoot` store it as a named field and read
/// `computed(id)` later (still via the `LayoutEngine` trait). This deliberately
/// names the concrete backend across the napi boundary; the ADR-1
/// `LayoutEngine`-trait seam still governs *behavior*, and a backend swap would
/// change only this return type in one place.
///
/// Returns the **built-and-computed** engine so a single per-frame build serves
/// both the render walk (M3-E reads `engine.computed(id)` as the rect accessor)
/// and `measure(id)` (M3-F reads `engine.computed(id)` from the *same* stored
/// build) — no second rebuild.
///
/// # Per-frame rebuild (ADR-3 Option A)
/// Always allocates a fresh `TaffyEngine`. Persistence is the `Arena`'s job; the
/// engine is a pure function of the arena at render time. A fresh engine
/// re-`set_measure`s every text node, satisfying the measure-invalidation
/// discipline (`layout/engine.rs:78-82`) for free.
///
/// Returns `None` if `calculate` fails (e.g. an inconsistent tree); the caller
/// renders an empty frame, matching the prior `render_to_string` error path.
pub fn build_layout_engine(arena: &Arena, root_id: u32, width: u16) -> Option<(TaffyEngine, Rect)> {
    let mut engine = TaffyEngine::new();

    // First pass: create nodes and wire the tree. Run on a FRESH engine only —
    // see ADR-3 "the trap inside A": re-running this against a populated engine
    // re-appends children and corrupts the layout.
    create_layout_nodes(arena, root_id, &mut engine);

    // Width is definite (caller-supplied columns). Height is unconstrained —
    // mirrors ink's render-to-string.ts:62-68 where yogaNode.calculateLayout
    // receives `undefined` for height (MaxContent), letting content determine
    // the frame height. None → AvailableSpace::MaxContent in TaffyEngine::calculate.
    if engine.calculate(root_id, width as f32, None).is_err() {
        return None;
    }

    // Read the computed root rect to size the grid (renderer.ts:37-39). Fall
    // back to a zero-height rect at the caller width if the root id is unknown
    // — preserves the prior `unwrap_or` behavior so empty/absent roots render
    // an empty frame rather than panicking.
    let root_rect = engine.computed(root_id).unwrap_or(Rect {
        x: 0,
        y: 0,
        width,
        height: 0,
    });

    Some((engine, root_rect))
}

/// Recursively register all arena nodes into the layout engine.
///
/// For each node: create the taffy node, apply its style, attach text measure
/// for Text/VirtualText nodes, then insert children in order.
fn create_layout_nodes(arena: &Arena, id: u32, engine: &mut TaffyEngine) {
    let Some(node) = arena.get(id) else { return };

    // Create the taffy node (idempotent).
    let _ = engine.create(id);

    let style = match node.kind {
        Kind::Root => root_style_with_ink_defaults(&node.style),
        _ => node.style.clone(),
    };
    let _ = engine.apply_style(id, &style);

    // Wire text measure for text-bearing nodes, then STOP: a Text/VirtualText node
    // is a taffy LEAF whose measure fn squashes its WHOLE subtree once
    // (`build_measure_fn_for` → `squash_text`), exactly like ink's `ink-text`
    // (dom.ts:222-246) — whose nested `ink-virtual-text` children carry NO yoga node
    // (dom.ts:102) and are never inserted as yoga children (dom.ts:125). #71: NOT
    // returning here gave every nested segment its own taffy node + measure fn, so
    // taffy (which only measures LEAF nodes) measured each inner segment ALONE in
    // its own wrap mode — truncating/wrapping per leaf instead of over the combined
    // squash. Returning makes the text-root the sole measured unit → squash-then-
    // truncate, byte-identical to ink and to the render walk (which already squashes
    // the whole Text subtree once, walk.rs Text arm). The reconciler forbids a Box
    // child of a Text node (`caseBoxInTextThrows`), so a Text node never has
    // layout-bearing children to recurse into; multi-segment text is purely nested
    // Text/VirtualText, all folded by `squash_text`. (Sibling Texts under a Box are
    // separate text-ROOTS, reached from the Box/Root branch below — unaffected; and
    // when nothing truncates, the squashed width equals the sum of segment widths,
    // so single-segment text, fitting multi-segment text, the layout corpus, and the
    // zero-flicker goldens keep identical dimensions.)
    if matches!(node.kind, Kind::Text | Kind::VirtualText) {
        engine.set_measure(id, build_measure_fn_for(arena, id));
        return;
    }

    // Clone children list to avoid borrow conflict during recursion.
    let children: Vec<u32> = node.children.clone();
    for (idx, &child_id) in children.iter().enumerate() {
        create_layout_nodes(arena, child_id, engine);
        let _ = engine.insert_child(id, child_id, idx);
    }
}

// ink's `ink-root` yoga node never receives Box styles — it
// relies on Yoga's intrinsic node defaults (flex-direction: column,
// align-items: stretch), which make every top-level child stretch to the
// full root width (dom.ts:95-105 createNode: bare Yoga.Node.create(),
// empty style). Taffy's default is flex-direction: row, so the Root
// must be column + stretch explicitly to reproduce ink-root.
// Box.tsx:85 forces flex-direction: row on every <Box>, so this is
// Root-only. The other half of ink-root identity — the root width pin
// (setWidth(columns)) — lives in TaffyEngine::calculate, which has the
// viewport_width parameter.
fn root_style_with_ink_defaults(s: &crate::dom::Style) -> crate::dom::Style {
    let mut style = s.clone();
    if style.flex_direction.is_none() {
        style.flex_direction = Some(crate::dom::FlexDir::Column);
    }
    if style.align_items.is_none() {
        style.align_items = Some(crate::dom::Align::Stretch);
    }
    style
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dom::{Arena, BorderStyle, Dim, Display, Kind, Lp, Node, Overflow, Style, TextWrap};

    // ── helpers ──────────────────────────────────────────────────────────────

    fn make_root(arena: &mut Arena, id: u32) {
        arena.insert(id, Node::new(Kind::Root));
    }

    fn make_box(arena: &mut Arena, id: u32, style: Style) {
        let mut n = Node::new(Kind::Box);
        n.style = style;
        arena.insert(id, n);
    }

    fn make_text(arena: &mut Arena, id: u32, text: &str) {
        let mut n = Node::new(Kind::Text);
        n.text = Some(text.to_owned());
        arena.insert(id, n);
    }

    fn make_text_styled(arena: &mut Arena, id: u32, text: &str, style: Style) {
        let mut n = Node::new(Kind::Text);
        n.text = Some(text.to_owned());
        n.style = style;
        arena.insert(id, n);
    }

    fn add_child(arena: &mut Arena, parent: u32, child: u32) {
        arena.get_mut(parent).unwrap().children.push(child);
    }

    // ── E1: plain text at root (ink oracle) ─────────────────────────────────
    // ink: renderToString(<Text>Hello</Text>) === "Hello"
    #[test]
    fn e1_plain_text() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, "Hello");
        add_child(&mut a, 0, 1);
        assert_eq!(render_to_string(&a, 0, 80), "Hello");
    }

    // ── E2: single border, empty box (ink oracle) ────────────────────────────
    // ink: renderToString(<Box borderStyle="single" width={10} height={3}/>) ===
    //   "┌────────┐\n│        │\n└────────┘"
    #[test]
    fn e2_single_border_empty_10x3() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(3.0)),
                ..Style::default()
            },
        );
        add_child(&mut a, 0, 1);
        assert_eq!(
            render_to_string(&a, 0, 80),
            "┌────────┐\n│        │\n└────────┘"
        );
    }

    // ── E3: border with text inside (ink oracle) ─────────────────────────────
    // ink: renderToString(<Box borderStyle="single" width={12} height={4}><Text>Hi</Text></Box>) ===
    //   "┌──────────┐\n│Hi        │\n│          │\n└──────────┘"
    #[test]
    fn e3_border_with_text() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                width: Some(Dim::Points(12.0)),
                height: Some(Dim::Points(4.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Hi");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        assert_eq!(
            render_to_string(&a, 0, 80),
            "┌──────────┐\n│Hi        │\n│          │\n└──────────┘"
        );
    }

    // ── E4: column layout, two boxes (ink oracle) ────────────────────────────
    // ink: renderToString(
    //   <Box flexDirection="column" width={10}>
    //     <Box borderStyle="single"><Text>A</Text></Box>
    //     <Box borderStyle="single"><Text>B</Text></Box>
    //   </Box>) ===
    //   "┌────────┐\n│A       │\n└────────┘\n┌────────┐\n│B       │\n└────────┘"
    #[test]
    fn e4_column_two_bordered_boxes() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                flex_direction: Some(crate::dom::FlexDir::Column),
                width: Some(Dim::Points(10.0)),
                ..Style::default()
            },
        );
        make_box(
            &mut a,
            2,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                ..Style::default()
            },
        );
        make_text(&mut a, 3, "A");
        make_box(
            &mut a,
            4,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                ..Style::default()
            },
        );
        make_text(&mut a, 5, "B");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 2, 3);
        add_child(&mut a, 1, 4);
        add_child(&mut a, 4, 5);
        assert_eq!(
            render_to_string(&a, 0, 80),
            "┌────────┐\n│A       │\n└────────┘\n┌────────┐\n│B       │\n└────────┘"
        );
    }

    // ── E5: padding (ink oracle) ─────────────────────────────────────────────
    // ink: renderToString(<Box padding={1}><Text>Hello</Text></Box>, {columns:20}) ===
    //   "\n Hello\n"
    #[test]
    fn e5_box_with_padding() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                padding: Some(Lp::Points(1.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Hello");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        assert_eq!(render_to_string(&a, 0, 20), "\n Hello\n");
    }

    // ── E6: text wrapping (ink oracle) ───────────────────────────────────────
    // ink: renderToString(<Box width={8}><Text>hello world</Text></Box>) ===
    //   "hello\nworld"
    #[test]
    fn e6_text_wrap() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(8.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "hello world");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        assert_eq!(render_to_string(&a, 0, 80), "hello\nworld");
    }

    // ── E7: overflow:hidden (ink oracle) ─────────────────────────────────────
    // ink: renderToString(
    //   <Box width={5} height={1} overflow="hidden"><Text>hello world</Text></Box>
    // ) === "hello"
    #[test]
    fn e7_overflow_hidden() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(5.0)),
                height: Some(Dim::Points(1.0)),
                overflow_x: Some(Overflow::Hidden),
                overflow_y: Some(Overflow::Hidden),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "hello world");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        assert_eq!(render_to_string(&a, 0, 80), "hello");
    }

    // ── E7b: border + overflow:hidden together (ink oracle) ──────────────────
    // The clip border-inset path in walk.rs (clip = rect inset by active border
    // edges) runs ONLY when a border and overflow:hidden coexist — every other
    // overflow test has no border and every border test has no overflow.
    // ink: renderToString(
    //   <Box borderStyle="single" width={7} height={3} overflow="hidden">
    //     <Text>hello world</Text>
    //   </Box>) === "┌─────┐\n│hello│\n└─────┘"
    #[test]
    fn e7b_border_with_overflow_hidden_insets_clip() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(7.0)),
                height: Some(Dim::Points(3.0)),
                border_style: Some(BorderStyle::Named("single".to_owned())),
                overflow_x: Some(Overflow::Hidden),
                overflow_y: Some(Overflow::Hidden),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "hello world");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        assert_eq!(render_to_string(&a, 0, 80), "┌─────┐\n│hello│\n└─────┘");
    }

    // ── E8: display:none skipped (ink oracle) ────────────────────────────────
    // ink: renderToString(
    //   <Box flexDirection="column" width={20}>
    //     <Box display="none"><Text>hidden</Text></Box>
    //     <Text>visible</Text>
    //   </Box>) === "visible"
    #[test]
    fn e8_display_none_skipped() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                flex_direction: Some(crate::dom::FlexDir::Column),
                width: Some(Dim::Points(20.0)),
                ..Style::default()
            },
        );
        make_box(
            &mut a,
            2,
            Style {
                display: Some(Display::None),
                ..Style::default()
            },
        );
        make_text(&mut a, 3, "hidden");
        make_text(&mut a, 4, "visible");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 2, 3);
        add_child(&mut a, 1, 4);
        assert_eq!(render_to_string(&a, 0, 80), "visible");
    }

    // ── E9: double border (ink oracle) ───────────────────────────────────────
    // ink: renderToString(<Box borderStyle="double" width={10} height={3}/>) ===
    //   "╔════════╗\n║        ║\n╚════════╝"
    #[test]
    fn e9_double_border() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("double".to_owned())),
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(3.0)),
                ..Style::default()
            },
        );
        add_child(&mut a, 0, 1);
        assert_eq!(
            render_to_string(&a, 0, 80),
            "╔════════╗\n║        ║\n╚════════╝"
        );
    }

    // ── E10: text truncate (ink oracle) ─────────────────────────────────────
    // ink: renderToString(<Box width={8}><Text wrap="truncate">hello world</Text></Box>) ===
    //   "hello w…"
    #[test]
    fn e10_text_truncate_end() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(8.0)),
                ..Style::default()
            },
        );
        make_text_styled(
            &mut a,
            2,
            "hello world",
            Style {
                text_wrap: Some(TextWrap::TruncateEnd),
                ..Style::default()
            },
        );
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        assert_eq!(render_to_string(&a, 0, 80), "hello w\u{2026}");
    }

    // ── E11: gap between boxes (ink oracle) ──────────────────────────────────
    // ink: renderToString(
    //   <Box flexDirection="column" gap={1} width={10}>
    //     <Text>line1</Text><Text>line2</Text>
    //   </Box>) === "line1\n\nline2"
    #[test]
    fn e11_gap_column() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                flex_direction: Some(crate::dom::FlexDir::Column),
                width: Some(Dim::Points(10.0)),
                gap: Some(1.0),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "line1");
        make_text(&mut a, 3, "line2");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 1, 3);
        assert_eq!(render_to_string(&a, 0, 80), "line1\n\nline2");
    }

    // ── E12: no-top border (ink oracle) ─────────────────────────────────────
    // ink: renderToString(<Box borderStyle="single" borderTop={false} width={10} height={3}/>) ===
    //   "│        │\n│        │\n└────────┘"
    #[test]
    fn e12_no_top_border() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                border_top: Some(false),
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(3.0)),
                ..Style::default()
            },
        );
        add_child(&mut a, 0, 1);
        assert_eq!(
            render_to_string(&a, 0, 80),
            "│        │\n│        │\n└────────┘"
        );
    }

    // ── E13: deeply nested border+padding (ink oracle) ───────────────────────
    // ink: renderToString(
    //   <Box borderStyle="single" padding={1} width={20} height={7}>
    //     <Box borderStyle="double"><Text>inner</Text></Box>
    //   </Box>) ===
    // "┌──────────────────┐\n│                  │\n│ ╔═════╗          │\n│ ║inner║          │\n│ ╚═════╝          │\n│                  │\n└──────────────────┘"
    #[test]
    fn e13_nested_border_padding() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                padding: Some(Lp::Points(1.0)),
                width: Some(Dim::Points(20.0)),
                height: Some(Dim::Points(7.0)),
                ..Style::default()
            },
        );
        make_box(
            &mut a,
            2,
            Style {
                border_style: Some(BorderStyle::Named("double".to_owned())),
                ..Style::default()
            },
        );
        make_text(&mut a, 3, "inner");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 2, 3);
        assert_eq!(
            render_to_string(&a, 0, 80),
            "┌──────────────────┐\n│                  │\n│ ╔═════╗          │\n│ ║inner║          │\n│ ╚═════╝          │\n│                  │\n└──────────────────┘"
        );
    }

    // ── E14: no-left border (ink oracle) ────────────────────────────────────
    // ink: renderToString(<Box borderStyle="single" borderLeft={false} width={10} height={3}/>) ===
    //   "─────────┐\n         │\n─────────┘"
    #[test]
    fn e14_no_left_border() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                border_left: Some(false),
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(3.0)),
                ..Style::default()
            },
        );
        add_child(&mut a, 0, 1);
        assert_eq!(
            render_to_string(&a, 0, 80),
            "─────────┐\n\n─────────┘"
        );
    }

    // ── E15: two text nodes side by side (ink oracle) ────────────────────────
    // ink: renderToString(<Box width={20}><Text>left</Text><Text>right</Text></Box>) ===
    //   "leftright"
    #[test]
    fn e15_two_text_nodes_row() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(20.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "left");
        make_text(&mut a, 3, "right");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 1, 3);
        assert_eq!(render_to_string(&a, 0, 80), "leftright");
    }

    // ── M2-D regression: colorless frame byte-equals the pre-styled output ────
    // After promoting the grid to StyledChar cells, a colorless frame must be
    // byte-IDENTICAL to the old plain path: every cell's `styles` is empty, so
    // `styled_chars_to_string` degenerates to plain `.value` concatenation and
    // `trim_end_matches(' ')` collapses trailing spaces exactly as before.
    // We assert a border-with-text frame (border draw + text write + trailing
    // pad on every interior row) equals its plain string AND carries NO ESC byte
    // — proving the styled machinery emits zero SGR for uncolored input.
    #[test]
    fn m2d_colorless_frame_byte_equals_plain() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                width: Some(Dim::Points(12.0)),
                height: Some(Dim::Points(4.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Hi");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        let out = render_to_string(&a, 0, 80);
        assert_eq!(
            out,
            "┌──────────┐\n│Hi        │\n│          │\n└──────────┘"
        );
        assert!(
            !out.contains('\u{1b}'),
            "colorless frame must contain no SGR escape bytes"
        );
    }

    // ═══ M3-A engine-lifetime seam (ADR-3) ═══════════════════════════════════
    //
    // These tests prove the persist-arena / rebuild-engine-per-frame contract
    // that `InkRoot` (M3-D) relies on: a SINGLE long-lived `Arena` is mutated
    // by ops between renders, and each render drives a FRESH engine via the
    // `build_layout_engine` seam. They are the M3-A correctness gate — the
    // thing the rejected Option B would have risked (silent measure corruption).

    use crate::dom::{Op, apply};

    /// Render the persisted arena through the seam exactly as `InkRoot` will:
    /// build a fresh engine each call, then walk into a grid. Mirrors
    /// `render_to_string`'s body so the two paths cannot drift.
    fn render_via_seam(arena: &Arena, root_id: u32, width: u16) -> String {
        let Some((engine, root_rect)) = build_layout_engine(arena, root_id, width) else {
            return String::new();
        };
        let grid_rows = root_rect.height as usize;
        let grid_cols = root_rect.width as usize;
        if grid_rows == 0 || grid_cols == 0 {
            return String::new();
        }
        let mut grid = Grid::new(grid_rows, grid_cols);
        let rect_fn = |id: u32| engine.computed(id);
        walk(
            arena,
            root_id,
            &rect_fn,
            &|_| None,
            &mut grid,
            crate::render::colorize::ColorLevel::Truecolor,
        );
        grid.get().0
    }

    // ── A1: two sequential renders, SetText between them → measure reflects the
    //        NEW text (this is the load-bearing measure-invalidation proof).
    //
    // The box is width=8. "hi" fits on one line. After `SetText` to
    // "hello world" the fresh-engine rebuild re-`set_measure`s the text node,
    // so the second frame measures the NEW string and wraps it to "hello\nworld"
    // (same oracle as E6). A stale measure closure (Option B's risk) would keep
    // measuring "hi" and produce a wrong frame. One persisted arena, two
    // fresh-engine renders.
    #[test]
    fn a1_seam_settext_between_renders_remeasures() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(8.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "hi");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);

        // Frame 1: short text fits on one line.
        let frame1 = render_via_seam(&a, 0, 80);
        assert_eq!(
            frame1, "hi",
            "frame 1 should render the original short text"
        );

        // Mutate the persisted arena: SetText to a string that wraps at width 8.
        apply(
            &mut a,
            &[Op::SetText {
                id: 2,
                text: "hello world".to_owned(),
            }],
        );

        // Frame 2: a FRESH engine must re-measure the new text and wrap it.
        let frame2 = render_via_seam(&a, 0, 80);
        assert_eq!(
            frame2, "hello\nworld",
            "frame 2 must reflect the new text's measurement (wrap at width 8) — \
             a stale measure closure would still measure \"hi\""
        );
    }

    // ── A2: SetStyle changing the box width between renders → layout reflects
    //        the NEW width. width=20 keeps "hello world" on one line; shrinking
    //        to 8 must wrap it. Proves style mutation on the persisted arena is
    //        honored by the next fresh-engine render.
    #[test]
    fn a2_seam_setstyle_width_change_between_renders() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(20.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "hello world");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);

        let frame1 = render_via_seam(&a, 0, 80);
        assert_eq!(frame1, "hello world", "width 20 keeps the text on one line");

        apply(
            &mut a,
            &[Op::SetStyle {
                id: 1,
                style: Box::new(Style {
                    width: Some(Dim::Points(8.0)),
                    ..Style::default()
                }),
            }],
        );

        let frame2 = render_via_seam(&a, 0, 80);
        assert_eq!(
            frame2, "hello\nworld",
            "shrinking the box to width 8 must wrap the text on the next render"
        );
    }

    // ── A3: node removal mid-tree between renders → removed subtree disappears.
    //        Column of three text lines; RemoveChild + Free the middle node;
    //        the next fresh-engine render shows the tree without it. Proves the
    //        rebuild reads the post-removal arena (no orphaned taffy node from a
    //        reused engine).
    #[test]
    fn a3_seam_node_removal_between_renders() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                flex_direction: Some(crate::dom::FlexDir::Column),
                width: Some(Dim::Points(10.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "alpha");
        make_text(&mut a, 3, "bravo");
        make_text(&mut a, 4, "gamma");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 1, 3);
        add_child(&mut a, 1, 4);

        let frame1 = render_via_seam(&a, 0, 80);
        assert_eq!(
            frame1, "alpha\nbravo\ngamma",
            "frame 1 renders all three column children"
        );

        // Remove the middle child from its parent, then free its slot — the
        // op pair the reconciler emits (RemoveChild on removeChild, Free on
        // detachDeletedInstance, op.rs).
        apply(
            &mut a,
            &[
                Op::RemoveChild {
                    parent: 1,
                    child: 3,
                },
                Op::Free { id: 3 },
            ],
        );

        let frame2 = render_via_seam(&a, 0, 80);
        assert_eq!(
            frame2, "alpha\ngamma",
            "frame 2 must drop the removed middle node — fresh engine reads the \
             post-removal arena with no orphan from a stale tree"
        );
    }

    // ── A4: the seam's frozen-wrapper guarantee — `render_to_string` and a
    //        direct seam render produce byte-identical output for the same
    //        arena. If `render_to_string` ever drifts from the seam, this fails.
    #[test]
    fn a4_seam_matches_render_to_string() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                width: Some(Dim::Points(12.0)),
                height: Some(Dim::Points(4.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Hi");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        assert_eq!(render_via_seam(&a, 0, 80), render_to_string(&a, 0, 80));
    }

    // ═══ M3-B styled-render entry (oracle-parity gate) ════════════════════════
    //
    // Every expected literal below was MATERIALIZED by running the live ink
    // oracle at /home/alpha/rewrite/ink with FORCE_COLOR=3 (chalk level 3) via a
    // scratch `renderToString` probe (test/helpers/render-to-string.ts +
    // force-colors.ts), then deleted. Command (all fixtures in one run):
    //   FORCE_COLOR=3 npx tsx scratch_m3b_oracle.tsx
    // where each fixture is `renderToString(<…/>)` and the bytes are dumped as a
    // JSON-escaped string. The exact oracle JSON output is pinned per test.
    //
    // These tests prove the styled entry (`render_styled`) reproduces ink for
    // `<Text color>` SGR and `<Transform>` callbacks — `<Text color>` SGR lives
    // INSIDE the per-node transform (Text.tsx:94-130 → colorize), so a core test
    // wires `colorize` into the accessor exactly as the napi layer will dispatch
    // to a JS `internal_transform`.

    use crate::render::colorize::{ColorLevel, Kind as ColorKind, colorize, dim};
    use crate::render::walk::TransformAccessor;

    /// An owned output transform — the per-line closure shape the accessor mints
    /// (matches the `Box<…>` inside [`TransformAccessor`]).
    type TextTransform = Box<dyn Fn(&str, usize) -> String>;

    /// Build a `<Text>`-style transform mirroring Text.tsx:94-130's EXACT order:
    /// dimColor → color(fg) → backgroundColor → bold → italic → underline →
    /// strikethrough → inverse. `bold`/`italic`/… resolve through `colorize`'s
    /// named-style branch (they are in STYLE_NAMES), reproducing chalk's bytes.
    /// Each flag is the chalk style name (or `None` to skip).
    fn text_transform(
        dim_color: bool,
        color: Option<&'static str>,
        bg_color: Option<&'static str>,
        bold: bool,
    ) -> TextTransform {
        Box::new(move |s: &str, _i: usize| {
            // These accessor transforms mimic ink's JS-side `<Text>` colorize,
            // which the conformance harness forces to chalk.level=3 — so they pin
            // level-3 (Truecolor) SGR bytes here too.
            let lvl = ColorLevel::Truecolor;
            // Text.tsx:95-97
            let mut out = if dim_color { dim(s, lvl) } else { s.to_owned() };
            // Text.tsx:99-101
            if let Some(c) = color {
                out = colorize(&out, Some(c), ColorKind::Fg, lvl);
            }
            // Text.tsx:103-108
            if let Some(bg) = bg_color {
                out = colorize(&out, Some(bg), ColorKind::Bg, lvl);
            }
            // Text.tsx:110-112
            if bold {
                out = colorize(&out, Some("bold"), ColorKind::Fg, lvl);
            }
            out
        })
    }

    /// Render `<Text …>Test</Text>` at root (Root→Text), with the Text node's
    /// own transform supplied by `mk` (a Text.tsx-order transform). Mirrors the
    /// oracle's `renderToString(<Text …>Test</Text>)`.
    fn render_single_text(text: &str, mk: fn() -> TextTransform) -> String {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, text);
        add_child(&mut a, 0, 1);
        // Accessor: node 1 carries the transform; all others None.
        let t = mk();
        let acc: &TransformAccessor<'_> = &|id: u32| match id {
            1 => Some(Box::new(|s: &str, i: usize| t(s, i)) as _),
            _ => None,
        };
        render_styled(&a, 0, 100, acc, ColorLevel::Truecolor).0
    }

    // ── named color (fg) ──────────────────────────────────────────────────────
    // oracle: renderToString(<Text color="green">Test</Text>)
    //   == "Test"
    #[test]
    fn m3b_named_color_fg() {
        let out = render_single_text("Test", || text_transform(false, Some("green"), None, false));
        assert_eq!(out, "\u{1b}[32mTest\u{1b}[39m");
    }

    // ── hex color (fg) ────────────────────────────────────────────────────────
    // oracle: renderToString(<Text color="#ff8800">Test</Text>)
    //   == "Test"
    #[test]
    fn m3b_hex_color_fg() {
        let out = render_single_text("Test", || {
            text_transform(false, Some("#ff8800"), None, false)
        });
        assert_eq!(out, "\u{1b}[38;2;255;136;0mTest\u{1b}[39m");
    }

    // ── background color ──────────────────────────────────────────────────────
    // oracle: renderToString(<Text backgroundColor="green">Test</Text>)
    //   == "Test"
    #[test]
    fn m3b_bg_color() {
        let out = render_single_text("Test", || text_transform(false, None, Some("green"), false));
        assert_eq!(out, "\u{1b}[42mTest\u{1b}[49m");
    }

    // ── dim ───────────────────────────────────────────────────────────────────
    // oracle: renderToString(<Text dimColor>Test</Text>)
    //   == "Test"
    #[test]
    fn m3b_dim() {
        let out = render_single_text("Test", || text_transform(true, None, None, false));
        assert_eq!(out, "\u{1b}[2mTest\u{1b}[22m");
    }

    // ── bold + color combo (order: color fg inner, bold outer per Text.tsx) ────
    // oracle: renderToString(<Text bold color="red">Test</Text>)
    //   == "Test"
    // (Text.tsx applies color BEFORE bold, so bold's 1/22 wraps the red span.)
    #[test]
    fn m3b_bold_color_combo() {
        let out = render_single_text("Test", || text_transform(false, Some("red"), None, true));
        assert_eq!(out, "\u{1b}[1m\u{1b}[31mTest\u{1b}[39m\u{1b}[22m");
    }

    // ── P6.2 CLEAR_TEXT_STYLE render-byte equivalence (op→apply→render loop) ───
    // The styled→plain transition is pinned at the op-emit (native-style-emit),
    // decode (decode_tests), and apply (op.rs) layers — but nothing renders BYTES
    // to confirm a CLEARED node renders PLAIN. This closes that loop end-to-end.
    //
    // We drive the NATIVE path: `render_styled` with an all-None accessor resolves
    // each node through `resolve_transform` (render/walk.rs), which composes SGR
    // from the node's OWN `text_styling` field — exactly the path the napi layer
    // uses for a simple styled `<Text>`. So applying SetTextStyle{red} then Clear
    // through `apply` (the real op-application code) and rendering twice exercises
    // the whole op→apply→render chain, not a hand-injected transform.
    //
    // Non-vacuity guard: the FIRST render MUST contain the red SGR (`\x1b[31m`) —
    // if it didn't, the node was never actually styled and the byte-identity check
    // below would pass vacuously. The SECOND render (after ClearTextStyle) must be
    // byte-identical to the SAME `Test` node rendered as a never-styled plain node.
    #[test]
    fn p6_2_clear_text_style_renders_plain_bytes() {
        use crate::dom::{Op, TextStyle, apply};

        // Oracle: the SAME content rendered as a never-styled plain node. Built in
        // its own arena so no styling op ever touched it.
        let mut plain = Arena::new();
        make_root(&mut plain, 0);
        make_text(&mut plain, 1, "Test");
        add_child(&mut plain, 0, 1);
        let plain_bytes = render_styled(&plain, 0, 100, &|_| None, ColorLevel::Truecolor).0;

        // The node under test: Root → Text("Test").
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, "Test");
        add_child(&mut a, 0, 1);

        // SetTextStyle{color: red} via the real apply() path, then render NATIVE
        // (all-None accessor → resolve_transform reads `text_styling`).
        apply(
            &mut a,
            &[Op::SetTextStyle {
                id: 1,
                style: TextStyle {
                    color: Some("red".into()),
                    ..Default::default()
                },
            }],
        );
        let styled_bytes = render_styled(&a, 0, 100, &|_| None, ColorLevel::Truecolor).0;

        // Non-vacuity: the styled render really carries the red SGR. Without this,
        // a no-op apply would make the byte-identity below pass for the wrong reason.
        assert!(
            styled_bytes.contains("\u{1b}[31m"),
            "precondition: the red-styled node renders the red SGR (\\x1b[31m); got {styled_bytes:?}"
        );
        // It also diverges from the plain oracle (belt-and-braces: styled ≠ plain).
        assert_ne!(
            styled_bytes, plain_bytes,
            "the red-styled render must differ from the plain render"
        );

        // ClearTextStyle via apply(), then render again — must render PLAIN.
        apply(&mut a, &[Op::ClearTextStyle { id: 1 }]);
        let cleared_bytes = render_styled(&a, 0, 100, &|_| None, ColorLevel::Truecolor).0;

        assert_eq!(
            cleared_bytes, plain_bytes,
            "after ClearTextStyle the node renders BYTE-IDENTICAL to a never-styled plain node (P6.2)"
        );
    }

    // ── transform callback (uppercase) ────────────────────────────────────────
    // oracle: renderToString(
    //   <Transform transform={s => s.toUpperCase()}><Text>hello</Text></Transform>)
    //   == "HELLO"
    // <Transform> renders an ink-text wrapping the inner <Text> ink-text; the
    // uppercase transform is applied via output.write on the OUTER text node.
    // Arena: Root→Text(outer, uppercase)→Text(inner "hello", identity).
    #[test]
    fn m3b_transform_uppercase() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, ""); // outer <Transform> ink-text: no own #text
        make_text(&mut a, 2, "hello"); // inner <Text> leaf
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        let acc: &TransformAccessor<'_> = &|id: u32| match id {
            1 => Some(Box::new(|s: &str, _i: usize| s.to_uppercase())),
            _ => None,
        };
        assert_eq!(
            render_styled(&a, 0, 100, acc, ColorLevel::Truecolor).0,
            "HELLO"
        );
    }

    // ── nested transformers (order proof) ─────────────────────────────────────
    // oracle: renderToString(
    //   <Transform transform={s => `O(${s})`}>
    //     <Transform transform={s => `I(${s})`}>
    //       <Text>x</Text>
    //   </Transform></Transform>)
    //   == "O(I(x))"
    // The inner transform is applied during squash (squash-text-nodes.ts:34-39);
    // the outer via output.write. Arena: Root→Text(outer O)→Text(inner I)→Text("x").
    // Proves innermost-first order: I wraps x, then O wraps that.
    #[test]
    fn m3b_nested_transformers_order() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, ""); // outer <Transform>
        make_text(&mut a, 2, ""); // inner <Transform>
        make_text(&mut a, 3, "x"); // <Text>x</Text>
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 2, 3);
        let acc: &TransformAccessor<'_> = &|id: u32| match id {
            1 => Some(Box::new(|s: &str, _i: usize| format!("O({s})"))),
            2 => Some(Box::new(|s: &str, _i: usize| format!("I({s})"))),
            _ => None,
        };
        assert_eq!(
            render_styled(&a, 0, 100, acc, ColorLevel::Truecolor).0,
            "O(I(x))"
        );
    }

    // ── color + transform combined (squash/write interleave proof) ────────────
    // oracle: renderToString(
    //   <Transform transform={s => s.toUpperCase()}><Text color="green">test</Text></Transform>)
    //   == "TEST"
    // The inner <Text color> colorizes "test" → "\x1b[32mtest\x1b[39m" (in squash),
    // then the outer uppercase transform (via write) uppercases the WHOLE string
    // INCLUDING the SGR letters m→M. The uppercased SGR is the proof that color
    // (inner/squash) runs strictly before the transform (outer/write).
    #[test]
    fn m3b_color_then_transform_interleave() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, ""); // outer <Transform> uppercase
        make_text(&mut a, 2, "test"); // inner <Text color="green">
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        let acc: &TransformAccessor<'_> = &|id: u32| match id {
            1 => Some(Box::new(|s: &str, _i: usize| s.to_uppercase())),
            2 => Some(Box::new(|s: &str, _i: usize| {
                colorize(s, Some("green"), ColorKind::Fg, ColorLevel::Truecolor)
            })),
            _ => None,
        };
        assert_eq!(
            render_styled(&a, 0, 100, acc, ColorLevel::Truecolor).0,
            "\u{1b}[32MTEST\u{1b}[39M"
        );
    }

    // ── height return correctness (multi-line frame) ──────────────────────────
    // oracle: renderToString(
    //   <Box flexDirection="column" width={10}>
    //     <Text>line1</Text><Text>line2</Text><Text>line3</Text></Box>)
    //   == "line1\nline2\nline3" (3 rows)
    // render_styled must return both the string AND height == 3.
    #[test]
    fn m3b_height_return_multiline() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                flex_direction: Some(crate::dom::FlexDir::Column),
                width: Some(Dim::Points(10.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "line1");
        make_text(&mut a, 3, "line2");
        make_text(&mut a, 4, "line3");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 1, 3);
        add_child(&mut a, 1, 4);
        let (out, height) = render_styled(&a, 0, 80, &|_| None, ColorLevel::Truecolor);
        assert_eq!(out, "line1\nline2\nline3");
        assert_eq!(height, 3, "3 column text lines → height 3");
    }

    // ── drift guard: no styles/no transforms == render_to_string + height ──────
    // The styled entry with an all-None accessor must byte-equal render_to_string
    // AND report the correct height. Covers a border-with-text frame (border draw
    // + text write + interior pads): the no-op accessor path is the regression
    // oracle for byte-identity (the corpus proves the same for layout fixtures).
    #[test]
    fn m3b_drift_guard_noop_equals_plain() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                border_style: Some(BorderStyle::Named("single".to_owned())),
                width: Some(Dim::Points(12.0)),
                height: Some(Dim::Points(4.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Hi");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);

        let plain = render_to_string(&a, 0, 80);
        let (styled, height) = render_styled(&a, 0, 80, &|_| None, ColorLevel::Truecolor);
        assert_eq!(
            styled, plain,
            "no-op accessor must byte-equal render_to_string"
        );
        assert_eq!(
            styled,
            "┌──────────┐\n│Hi        │\n│          │\n└──────────┘"
        );
        assert_eq!(height, 4, "4-row bordered box → height 4");
        assert!(
            !styled.contains('\u{1b}'),
            "no-op accessor frame must carry no SGR"
        );
    }

    // ── nested styled text correctness (the real-world case squash threading fixes) ──
    // <Text color="red">a<Text color="blue">b</Text></Text>: ink colors ONLY "b"
    // blue (the inner child's transform applied in squash), with "a" + the blue
    // span both wrapped red by the outer (via write). Materialized from the oracle:
    //   renderToString(<Text color="red">a<Text color="blue">b</Text></Text>)
    //   == "ab"
    // (oracle: FORCE_COLOR=3 renderToString, chalk level 3.) Without squash
    // threading "b" would be colored red, not blue — this is the correctness gate.
    // ── nested same-axis styled text: inner color applies to the CHILD span ───
    // <Text color="red">a<Text color="blue">b</Text></Text>: the inner child's
    // blue transform is applied to ONLY its own folded substring ("b") during
    // squash (squash-text-nodes.ts:34-39); the outer red wraps the whole via
    // write. This is the real-world correctness the squash threading exists for —
    // without it, "b" would be red, not blue.
    //
    // Oracle (FORCE_COLOR=3 renderToString, chalk level 3):
    //   renderToString(<Text color="red">a<Text color="blue">b</Text></Text>)
    //   == "ESC[31ma ESC[34mb ESC[39m"   (single trailing reset)
    //
    // inkferro reproduces this BYTE-FOR-BYTE: the outer red wrap nominally yields
    // a doubled `ESC[39m` close, but the styled-char grid re-tokenizes the line on
    // write and serializes minimal SGR (`styled_chars_to_string`), collapsing the
    // redundant trailing reset — the same single `ESC[39m` chalk's closeRe emits.
    // So no divergence here: the grid's SGR de-duplication absorbs what would
    // otherwise be a same-close-code mismatch. The load-bearing fact is that "b"
    // carries BLUE (the inner child's color via squash), not red.
    #[test]
    fn m3b_nested_styled_text_inner_color_applies_to_child() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, "a"); // outer <Text color="red">: own #text "a"
        make_text(&mut a, 2, "b"); // inner <Text color="blue">b</Text>
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        let acc: &TransformAccessor<'_> = &|id: u32| match id {
            1 => Some(Box::new(|s: &str, _i: usize| {
                colorize(s, Some("red"), ColorKind::Fg, ColorLevel::Truecolor)
            })),
            2 => Some(Box::new(|s: &str, _i: usize| {
                colorize(s, Some("blue"), ColorKind::Fg, ColorLevel::Truecolor)
            })),
            _ => None,
        };
        let out = render_styled(&a, 0, 100, acc, ColorLevel::Truecolor).0;
        // Byte-for-byte oracle match: red "a", blue "b" (inner color on the child
        // span via squash), single trailing reset (grid SGR de-dup == chalk closeRe).
        assert_eq!(
            out, "\u{1b}[31ma\u{1b}[34mb\u{1b}[39m",
            "inner blue must apply to the child span and match the oracle bytes"
        );
    }

    // ═══ static render pass (renderer.ts static branch) ═══════════════════════
    //
    // `render_static` is ink's SECOND render pass: the `<Static>` subtree rendered
    // into its OWN-sized output with skipStaticElements=false, plus a trailing
    // `\n` when a static node is present (renderer.ts:46-66). The main `walk`
    // SKIPS the same static subtree (skipStaticElements=true), so the static
    // content NEVER appears in `plain_output`. Each test mutation-checks BOTH
    // directions: static_output carries the content, plain_output does not.
    // (`Op`/`apply` are already imported by the M3-A seam test section above.)

    // ── static present: subtree → "<body>\n", and main walk omits it ──────────
    // Tree: Root → static Box (position:absolute, so out of flow at (0,0)) → Text.
    // ink's real `<Static>` is `position:absolute` (the JS component sets it), so
    // it occupies no flow space and the live region collapses to empty. We model
    // that layout effect here so the fixture matches ink's static semantics: the
    // live region is empty, and the static output is the box content + newline.
    #[test]
    fn static_present_renders_with_trailing_newline_and_omitted_from_main() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                position: Some(crate::dom::Position::Absolute),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Done");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        // Mark the box static via the real op handler (exercises Op::SetStatic).
        apply(&mut a, &[Op::SetStatic { id: 1, value: true }]);

        // Static pass: the static subtree renders, body + trailing "\n".
        let static_out = render_static(&a, 0, 80, &|_| None, ColorLevel::Truecolor);
        assert_eq!(
            static_out, "Done\n",
            "static output is the static subtree's content plus a trailing newline"
        );

        // Main pass MUST skip the static subtree → empty live region. This is the
        // mutation check: if the skip regressed, plain_output would be "Done".
        let (plain, _h) = render_styled(&a, 0, 80, &|_| None, ColorLevel::Truecolor);
        assert_eq!(
            plain, "",
            "the static subtree must NOT appear in the live (main) output"
        );
    }

    // ── no static node: static_output is "" (the common case, no behavior change) ─
    #[test]
    fn no_static_node_returns_empty_string() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_text(&mut a, 1, "live");
        add_child(&mut a, 0, 1);

        assert_eq!(
            render_static(&a, 0, 80, &|_| None, ColorLevel::Truecolor),
            "",
            "a tree with no static node yields an empty static output"
        );
        // And the main output is unaffected: "live" renders normally.
        assert_eq!(
            render_styled(&a, 0, 80, &|_| None, ColorLevel::Truecolor).0,
            "live"
        );
    }

    // ── reverse-pollution: a LIVE sibling must NOT leak into static_output ─────
    // Tree: Root → [ static Box(position:absolute) → "Done", live Text "live" ].
    // Unlike the other static fixtures, the static subtree is NOT the only content
    // here: a live Text sibling coexists with the static node under the same root.
    // This is the bidirectional pollution check the adversarial review demanded:
    //   • static_output == "Done\n"  catches the static walk ASCENDING to the root
    //     and sweeping in the live sibling;
    //   • render_styled == "live"    catches the converse — the static-skip eating
    //     the live sibling too (it would be "").
    //
    // Child order is load-bearing for the FIRST assertion to discriminate. Layout
    // puts BOTH the static box and the live text at (0,0) (the box is absolute, the
    // live text is the sole flow child), and the static grid is clipped to the
    // box's own 4-wide rect. So if `walk_static` ever ascended to the root, the
    // grid would receive both "Done" and "live" at (0,0) under last-writer-wins —
    // and only the LATER pre-order write survives. By appending the static box
    // FIRST and the live sibling SECOND, a root-ascending leak writes "live" LAST,
    // overwriting "Done" → "live\n" ≠ "Done\n", so the assertion catches it. (The
    // reversed order would let "Done" mask "live" and the test would pass even on
    // the leak — verified empirically.) The correct code, walking from the static
    // node, never sees the live sibling regardless of order.
    #[test]
    fn static_node_does_not_pull_live_sibling_into_static_output() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                position: Some(crate::dom::Position::Absolute),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Done");
        make_text(&mut a, 3, "live");
        add_child(&mut a, 0, 1); // static box FIRST in pre-order
        add_child(&mut a, 1, 2);
        add_child(&mut a, 0, 3); // live sibling SECOND (written last on a leak)
        apply(&mut a, &[Op::SetStatic { id: 1, value: true }]);

        // Static pass: ONLY the static subtree's content, not the live sibling.
        assert_eq!(
            render_static(&a, 0, 80, &|_| None, ColorLevel::Truecolor),
            "Done\n",
            "static_output carries ONLY the static subtree; the live sibling must \
             NOT appear (the walk starts at the static node, never ascends to root)"
        );

        // Live pass: the live sibling renders; the static subtree is skipped.
        assert_eq!(
            render_styled(&a, 0, 80, &|_| None, ColorLevel::Truecolor).0,
            "live",
            "the live (main) output carries the live sibling, with the static \
             subtree omitted"
        );
    }

    // ── multi-line static subtree → each line preserved, single trailing "\n" ──
    // A column of two static text lines: the static body is "a\nb", then the one
    // appended newline (renderer.ts:66) → "a\nb\n". Proves the trailing newline is
    // appended to the WHOLE static block once, not per line.
    #[test]
    fn static_multiline_subtree_single_trailing_newline() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                // position:absolute mirrors ink's `<Static>` (out of flow), so the
                // live region collapses to empty while the static box keeps its
                // own computed width/height for the second-pass grid.
                position: Some(crate::dom::Position::Absolute),
                flex_direction: Some(crate::dom::FlexDir::Column),
                width: Some(Dim::Points(10.0)),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "a");
        make_text(&mut a, 3, "b");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        add_child(&mut a, 1, 3);
        apply(&mut a, &[Op::SetStatic { id: 1, value: true }]);

        assert_eq!(
            render_static(&a, 0, 80, &|_| None, ColorLevel::Truecolor),
            "a\nb\n",
            "multi-line static block keeps its lines and gets one trailing newline"
        );
        assert_eq!(
            render_styled(&a, 0, 80, &|_| None, ColorLevel::Truecolor).0,
            "",
            "the static block is omitted from the live output"
        );
    }

    // ── styled/transform child INSIDE a static node → SGR carried in static_out ─
    // The static pass MUST honor `<Transform>`/`<Text color>` on a node inside the
    // `<Static>` subtree, exactly as the live pass does: `render_static` forwards
    // the SAME `transform_of` accessor to `walk_static`. Here the static text node
    // carries a `green` colorize transform; the static output must contain the SGR
    // escape "\x1b[32m…\x1b[39m". This is the mutation check the adversarial review
    // demanded: if `walk_static`'s `transform_of` were silently no-op'd (or
    // `render_static` stopped threading the accessor into the static walk), the
    // assert below would fail — the static body would be the uncolored "Done".
    #[test]
    fn static_present_honors_styled_transform_child() {
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                position: Some(crate::dom::Position::Absolute),
                ..Style::default()
            },
        );
        make_text(&mut a, 2, "Done");
        add_child(&mut a, 0, 1);
        add_child(&mut a, 1, 2);
        apply(&mut a, &[Op::SetStatic { id: 1, value: true }]);

        // Accessor: the static leaf (id 2) carries a green fg colorize transform,
        // mirroring `<Text color="green">` (Text.tsx:94-130 → colorize). All other
        // ids None — same shape the napi caller mints per id.
        let acc: &crate::render::walk::TransformAccessor<'_> = &|id: u32| match id {
            2 => Some(Box::new(|s: &str, _i: usize| {
                crate::render::colorize::colorize(
                    s,
                    Some("green"),
                    crate::render::colorize::Kind::Fg,
                    ColorLevel::Truecolor,
                )
            })),
            _ => None,
        };

        // Static pass must carry the SGR: green fg wraps "Done", then trailing "\n".
        let static_out = render_static(&a, 0, 80, acc, ColorLevel::Truecolor);
        assert_eq!(
            static_out, "\u{1b}[32mDone\u{1b}[39m\n",
            "the static pass honors a `<Text color>`/`<Transform>` child — the SGR \
             escape MUST appear in static_output (transform_of forwarded to walk_static)"
        );

        // Mutation control: with a NO-OP accessor (the stub the review feared), the
        // same tree yields the uncolored body — proving the SGR above is sourced
        // from the forwarded accessor, not some unconditional colorization.
        assert_eq!(
            render_static(&a, 0, 80, &|_| None, ColorLevel::Truecolor),
            "Done\n",
            "a no-op transform accessor yields the uncolored static body (mutation control)"
        );
    }

    // ── #71: multi-segment <Text wrap=truncate> squashes-then-truncates ──────
    //
    // ink squashes ALL descendant text of an `ink-text` into ONE string FIRST
    // (squash-text-nodes.ts), then measures THAT single fragment once — the
    // `ink-text` is the only node with a yoga measure func; its `ink-virtual-text`
    // children get NO yoga node at all (dom.ts:102/125, measureTextNode at
    // dom.ts:222-246). inkferro USED to attach a measure fn to AND insert a taffy
    // node for EVERY nested segment, so taffy measured each inner segment ALONE in
    // its own wrap mode → a segment WIDER than the box wrapped to ≥2 lines and
    // inflated the text-root's height, where ink (squash-then-truncate) yields ONE
    // line. The fix makes a `Text`/`VirtualText` node a taffy LEAF
    // (`create_layout_nodes` returns after `set_measure`), so the measured unit is
    // the whole squashed subtree — exactly like ink's `ink-text`.
    //
    // SCOPE of the core pin: the per-leaf bug is a MEASURE-time defect. At RENDER
    // time `walk_node`'s Text arm already squashes the whole subtree and truncates
    // once at `rect.width` (divergence map: render path already correct), and an
    // explicit `Box width` PINS `rect.width` regardless of the measure — so render
    // BYTES are not a measure discriminator and are NOT pinned here (the 6 npm byte
    // pins, through the real reconciler + native addon, own those). The core pin
    // routes through `build_layout_engine` (exercising `create_layout_nodes`) and
    // asserts the text-root's computed HEIGHT, which the per-leaf wrap inflates.
    //
    // FAITHFUL arena shape (mirrors the live reconciler; Text.tsx:134 sets
    // `textWrap` on EVERY ink-text/virtual-text, default `'wrap'`): a `Text` root
    // carrying the truncate `text_wrap`, own text None, whose children are
    // `VirtualText` SEGMENTS that EACH carry their OWN `text_wrap = Wrap` (the
    // component default) and the segment string. Without the own-Wrap on the
    // segments the pin would be vacuous: #70's `effective_text_wrap` would make a
    // wrap-less segment INHERIT the root's truncate (height 1) even pre-fix. The
    // own-Wrap is what makes the per-leaf path overflow-then-WRAP, reproducing the
    // inflated height the fix removes.

    /// Build `<Box width=W><Text wrap=MODE><VirtualText wrap=wrap>seg0</>…</Text></Box>`
    /// at root. ids: 0=root, 1=box, 2=text-root, 3/4=segments. Each segment carries
    /// its OWN `text_wrap = Wrap` (the `<Text>` component default — Text.tsx:134).
    fn two_segment_truncate_arena(width: f32, mode: TextWrap, seg0: &str, seg1: &str) -> Arena {
        use crate::dom::{Op, apply};
        let mut a = Arena::new();
        make_root(&mut a, 0);
        make_box(
            &mut a,
            1,
            Style {
                width: Some(Dim::Points(width)),
                ..Style::default()
            },
        );
        // text-root: carries the wrap mode, NO own text (the segments hold it).
        let mut text_root = Node::new(Kind::Text);
        text_root.style.text_wrap = Some(mode);
        a.insert(2, text_root);
        // two VirtualText segments (nested <Text> → ink-virtual-text), each with
        // its OWN default Wrap text_wrap — exactly what Text.tsx:134 emits.
        let mut s0 = Node::new(Kind::VirtualText);
        s0.text = Some(seg0.to_owned());
        s0.style.text_wrap = Some(TextWrap::Wrap);
        a.insert(3, s0);
        let mut s1 = Node::new(Kind::VirtualText);
        s1.text = Some(seg1.to_owned());
        s1.style.text_wrap = Some(TextWrap::Wrap);
        a.insert(4, s1);
        // Wire via apply so `parent` is populated on every edge (op.rs:93).
        apply(
            &mut a,
            &[
                Op::AppendChild {
                    parent: 0,
                    child: 1,
                },
                Op::AppendChild {
                    parent: 1,
                    child: 2,
                },
                Op::AppendChild {
                    parent: 2,
                    child: 3,
                },
                Op::AppendChild {
                    parent: 2,
                    child: 4,
                },
            ],
        );
        a
    }

    // MEASURE-LEVEL discriminator (routes through create_layout_nodes via
    // build_layout_engine). Box width 3 < first segment "AAAA" (4 cols). ink
    // squashes "AAAA"+"BBBB" → "AAAABBBB" and truncates the WHOLE unit at 3 → "AA…",
    // ONE line, so the text-root's computed height is 1. Pre-fix each segment is a
    // taffy leaf measured ALONE in its own Wrap mode: "AAAA"@3 wraps to "AAA\nA"
    // (2 lines), inflating the text-root to height ≥2. The HEIGHT is the
    // discriminator — the box pins the WIDTH to 3 both pre/post, so only height
    // moves (pre ≥2 → post 1).
    #[test]
    fn task71_measure_two_segment_truncate_height_is_one() {
        let a = two_segment_truncate_arena(3.0, TextWrap::TruncateEnd, "AAAA", "BBBB");
        let (engine, _root) =
            build_layout_engine(&a, 0, 80).expect("layout engine builds for the 2-segment tree");
        let text_rect = engine
            .computed(2)
            .expect("the text-root (id 2) is laid out as the measured unit");
        // The whole squash truncates to ONE line. Per-leaf Wrap measure of the
        // overflowing first segment alone inflates this to ≥2.
        assert_eq!(
            text_rect.height, 1,
            "the squashed multi-segment unit truncates to ONE line (per-leaf Wrap measure inflates the extent to >=2)"
        );
    }

    // FULL-FRAME extent pin through render_to_string (plain, #71 case 5 shape but
    // with an OVERFLOWING first segment so the extent actually moves). Box width 3,
    // segments "AAAA"/"BBBB" both Wrap. Oracle-faithful: squash "AAAABBBB" truncated
    // at 3 → "AA…", ONE row, NO trailing blank rows. Pre-fix the per-leaf Wrap of
    // "AAAA"@3 folds to 2 lines → the text-root is height ≥2 → the frame carries
    // trailing blank rows ("AA…\n…"). The full-frame equality (single row, no
    // trailing newline) is the discriminator the box-pinned width cannot mask.
    #[test]
    fn task71_render_plain_overflowing_first_segment_one_row() {
        let a = two_segment_truncate_arena(3.0, TextWrap::TruncateEnd, "AAAA", "BBBB");
        assert_eq!(
            render_to_string(&a, 0, 80),
            "AA\u{2026}",
            "plain multi-segment truncate squashes then truncates once → exactly one row, no trailing blank rows"
        );
    }
}