ftui-text 0.4.0

Text layout, wrapping, and grapheme width for FrankenTUI.
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
//! Frame-time, memory, and queue budgets per quality tier.
//!
//! This module defines measurable performance envelopes for each
//! [`LayoutTier`]. The adaptive quality controller (see the runtime control
//! layer) reads these budgets to decide when to degrade or promote tiers.
//!
//! # Budget model
//!
//! Each tier has three budget axes:
//!
//! - **Frame budget** — maximum wall-clock time (µs) for a single
//!   render frame (layout + shaping + diff + present).
//! - **Memory budget** — peak transient allocation ceiling (bytes) for
//!   per-frame working memory (caches, scratch buffers, glyph tables).
//! - **Queue budget** — maximum depth of the deferred work queue
//!   (re-shape, re-wrap, incremental reflow jobs).
//!
//! # Feature toggles
//!
//! [`TierFeatures`] defines which subsystem features are active at each
//! tier. Features are monotonically enabled as the tier increases:
//! everything active at Emergency is also active at Fast, and so on.
//!
//! # Safety constraints
//!
//! [`SafetyInvariant`] lists properties that must hold regardless of the
//! current tier. These are never disabled by the adaptive controller.

use std::fmt;
use std::time::Duration;

use crate::layout_policy::LayoutTier;

// =========================================================================
// FrameBudget
// =========================================================================

/// Wall-clock time budget for a single render frame.
///
/// All values are in microseconds for sub-millisecond precision without
/// floating point.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameBudget {
    /// Total frame budget (layout + shaping + diff + present).
    pub total_us: u64,
    /// Maximum time for the layout solver pass.
    pub layout_us: u64,
    /// Maximum time for text shaping (shaped or terminal path).
    pub shaping_us: u64,
    /// Maximum time for buffer-diff computation.
    pub diff_us: u64,
    /// Maximum time for the presenter (ANSI emit).
    pub present_us: u64,
    /// Headroom reserved for widget render + event dispatch + IO.
    pub headroom_us: u64,
}

impl FrameBudget {
    /// Budget for a target frame rate.
    ///
    /// Returns the per-frame total in microseconds.
    #[must_use]
    pub const fn from_fps(fps: u32) -> u64 {
        1_000_000 / fps as u64
    }

    /// Convert the total budget to a [`Duration`].
    #[must_use]
    pub const fn as_duration(&self) -> Duration {
        Duration::from_micros(self.total_us)
    }

    /// Sum of allocated sub-budgets (should equal total).
    #[must_use]
    pub const fn allocated(&self) -> u64 {
        self.layout_us + self.shaping_us + self.diff_us + self.present_us + self.headroom_us
    }

    /// Whether the sub-budgets are consistent with total.
    #[must_use]
    pub const fn is_consistent(&self) -> bool {
        self.allocated() == self.total_us
    }
}

impl fmt::Display for FrameBudget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}µs (layout={}µs shaping={}µs diff={}µs present={}µs headroom={}µs)",
            self.total_us,
            self.layout_us,
            self.shaping_us,
            self.diff_us,
            self.present_us,
            self.headroom_us
        )
    }
}

// =========================================================================
// MemoryBudget
// =========================================================================

/// Transient per-frame memory budget.
///
/// These are ceilings for scratch allocations that are live during a
/// single frame. Persistent caches (width cache, shaping cache) are
/// accounted separately in their own capacity configs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryBudget {
    /// Maximum bytes for shaping scratch (glyph buffers, cluster maps).
    pub shaping_bytes: usize,
    /// Maximum bytes for layout scratch (constraint vectors, flex splits).
    pub layout_bytes: usize,
    /// Maximum bytes for diff scratch (dirty bitmaps, change lists).
    pub diff_bytes: usize,
    /// Maximum entries in the width cache.
    pub width_cache_entries: usize,
    /// Maximum entries in the shaping cache.
    pub shaping_cache_entries: usize,
}

impl MemoryBudget {
    /// Total transient ceiling (shaping + layout + diff).
    #[must_use]
    pub const fn transient_total(&self) -> usize {
        self.shaping_bytes + self.layout_bytes + self.diff_bytes
    }
}

impl fmt::Display for MemoryBudget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "transient={}B (shaping={}B layout={}B diff={}B) caches: width={} shaping={}",
            self.transient_total(),
            self.shaping_bytes,
            self.layout_bytes,
            self.diff_bytes,
            self.width_cache_entries,
            self.shaping_cache_entries
        )
    }
}

// =========================================================================
// QueueBudget
// =========================================================================

/// Work-queue depth limits for deferred layout/shaping jobs.
///
/// When the queue exceeds these limits, the adaptive controller should
/// degrade to a lower tier to reduce incoming work.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueueBudget {
    /// Maximum pending re-shape jobs (text runs awaiting shaping).
    pub max_reshape_pending: usize,
    /// Maximum pending re-wrap jobs (paragraphs awaiting line-breaking).
    pub max_rewrap_pending: usize,
    /// Maximum pending incremental reflow jobs.
    pub max_reflow_pending: usize,
}

impl QueueBudget {
    /// Total maximum pending jobs across all queues.
    #[must_use]
    pub const fn total_max(&self) -> usize {
        self.max_reshape_pending + self.max_rewrap_pending + self.max_reflow_pending
    }
}

impl fmt::Display for QueueBudget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "reshape={} rewrap={} reflow={}",
            self.max_reshape_pending, self.max_rewrap_pending, self.max_reflow_pending
        )
    }
}

// =========================================================================
// TierBudget
// =========================================================================

/// Combined budget for a single quality tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TierBudget {
    /// Which tier this budget applies to.
    pub tier: LayoutTier,
    /// Frame-time budget.
    pub frame: FrameBudget,
    /// Memory budget.
    pub memory: MemoryBudget,
    /// Queue-depth budget.
    pub queue: QueueBudget,
}

impl fmt::Display for TierBudget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{}] frame: {} | mem: {} | queue: {}",
            self.tier, self.frame, self.memory, self.queue
        )
    }
}

// =========================================================================
// TierFeatures
// =========================================================================

/// Feature toggles for a quality tier.
///
/// Each flag indicates whether a subsystem feature is active at this tier.
/// Features are monotonically enabled: if a feature is on at tier T, it is
/// also on at every tier above T.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TierFeatures {
    /// Which tier these features apply to.
    pub tier: LayoutTier,

    // ── Text shaping ────────────────────────────────────────────────
    /// Use the shaped text path (HarfBuzz/rustybuzz) when available.
    pub shaped_text: bool,
    /// Use the terminal (ClusterMap) fallback path.
    pub terminal_fallback: bool,

    // ── Line breaking ───────────────────────────────────────────────
    /// Use Knuth-Plass optimal line breaking.
    pub optimal_breaking: bool,
    /// Use hyphenation for line breaking.
    pub hyphenation: bool,

    // ── Spacing / justification ─────────────────────────────────────
    /// Enable full justification (stretch/shrink word spaces).
    pub justification: bool,
    /// Enable inter-character tracking.
    pub tracking: bool,

    // ── Vertical metrics ────────────────────────────────────────────
    /// Activate baseline grid snapping.
    pub baseline_grid: bool,
    /// Apply paragraph spacing.
    pub paragraph_spacing: bool,
    /// Apply first-line indent.
    pub first_line_indent: bool,

    // ── Caching ─────────────────────────────────────────────────────
    /// Use the width cache.
    pub width_cache: bool,
    /// Use the shaping cache.
    pub shaping_cache: bool,

    // ── Rendering ───────────────────────────────────────────────────
    /// Use incremental (dirty-region) diff.
    pub incremental_diff: bool,
    /// Use sub-cell spacing (1/256 cell precision).
    pub subcell_spacing: bool,
}

impl TierFeatures {
    /// Human-readable list of active features.
    #[must_use]
    pub fn active_list(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if self.shaped_text {
            out.push("shaped-text");
        }
        if self.terminal_fallback {
            out.push("terminal-fallback");
        }
        if self.optimal_breaking {
            out.push("optimal-breaking");
        }
        if self.hyphenation {
            out.push("hyphenation");
        }
        if self.justification {
            out.push("justification");
        }
        if self.tracking {
            out.push("tracking");
        }
        if self.baseline_grid {
            out.push("baseline-grid");
        }
        if self.paragraph_spacing {
            out.push("paragraph-spacing");
        }
        if self.first_line_indent {
            out.push("first-line-indent");
        }
        if self.width_cache {
            out.push("width-cache");
        }
        if self.shaping_cache {
            out.push("shaping-cache");
        }
        if self.incremental_diff {
            out.push("incremental-diff");
        }
        if self.subcell_spacing {
            out.push("subcell-spacing");
        }
        out
    }
}

impl fmt::Display for TierFeatures {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}", self.tier, self.active_list().join(", "))
    }
}

// =========================================================================
// SafetyInvariant
// =========================================================================

/// Properties that must hold regardless of the current quality tier.
///
/// The adaptive controller must never violate these invariants, even
/// under extreme compute pressure. They define the semantic floor
/// below which output is no longer meaningful.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SafetyInvariant {
    /// Every input character must appear in the output buffer.
    /// No content may be silently dropped.
    NoContentLoss,
    /// Wide characters (CJK, emoji) must occupy 2 cells.
    /// Displaying a wide char in 1 cell corrupts layout.
    WideCharWidth,
    /// Buffer dimensions must match the terminal size.
    /// Mismatched buffers cause garbled output.
    BufferSizeMatch,
    /// Cursor position must be within buffer bounds.
    CursorInBounds,
    /// Style resets must be emitted at line boundaries.
    /// Leaking styles across lines corrupts subsequent output.
    StyleBoundary,
    /// Diff output must be idempotent: applying the same diff twice
    /// produces the same result as applying it once.
    DiffIdempotence,
    /// Greedy wrapping must always be available as a fallback.
    /// If optimal breaking fails, greedy wrapping takes over.
    GreedyWrapFallback,
    /// Width measurement must be deterministic for the same input.
    WidthDeterminism,
}

impl SafetyInvariant {
    /// All safety invariants.
    pub const ALL: &'static [Self] = &[
        Self::NoContentLoss,
        Self::WideCharWidth,
        Self::BufferSizeMatch,
        Self::CursorInBounds,
        Self::StyleBoundary,
        Self::DiffIdempotence,
        Self::GreedyWrapFallback,
        Self::WidthDeterminism,
    ];
}

impl fmt::Display for SafetyInvariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoContentLoss => write!(f, "no-content-loss"),
            Self::WideCharWidth => write!(f, "wide-char-width"),
            Self::BufferSizeMatch => write!(f, "buffer-size-match"),
            Self::CursorInBounds => write!(f, "cursor-in-bounds"),
            Self::StyleBoundary => write!(f, "style-boundary"),
            Self::DiffIdempotence => write!(f, "diff-idempotence"),
            Self::GreedyWrapFallback => write!(f, "greedy-wrap-fallback"),
            Self::WidthDeterminism => write!(f, "width-determinism"),
        }
    }
}

// =========================================================================
// TierLadder — the canonical budget/feature table
// =========================================================================

/// The canonical tier ladder: budgets, features, and safety constraints
/// for every quality tier.
///
/// This is the single source of truth that the adaptive controller reads
/// to decide degradation thresholds and feature availability.
#[derive(Debug, Clone)]
pub struct TierLadder {
    /// Budget for each tier, ordered Emergency → Fast → Balanced → Quality.
    pub budgets: [TierBudget; 4],
    /// Feature toggles for each tier, same order.
    pub features: [TierFeatures; 4],
}

impl TierLadder {
    /// Look up the budget for a specific tier.
    #[must_use]
    pub fn budget(&self, tier: LayoutTier) -> &TierBudget {
        &self.budgets[tier as usize]
    }

    /// Look up the feature toggles for a specific tier.
    #[must_use]
    pub fn features_for(&self, tier: LayoutTier) -> &TierFeatures {
        &self.features[tier as usize]
    }

    /// The default tier ladder calibrated from baseline profiles.
    ///
    /// Frame budgets target 60fps (16,667µs) with progressive headroom
    /// allocation. Memory budgets are sized for typical terminal
    /// workloads (80x24 to 200x60). Queue budgets prevent unbounded
    /// accumulation of deferred work.
    #[must_use]
    pub fn default_60fps() -> Self {
        Self {
            budgets: [
                // Emergency: 2ms total — survival mode
                TierBudget {
                    tier: LayoutTier::Emergency,
                    frame: FrameBudget {
                        total_us: 2_000,
                        layout_us: 100,
                        shaping_us: 200,
                        diff_us: 200,
                        present_us: 500,
                        headroom_us: 1_000,
                    },
                    memory: MemoryBudget {
                        shaping_bytes: 64 * 1024, // 64 KiB
                        layout_bytes: 16 * 1024,  // 16 KiB
                        diff_bytes: 32 * 1024,    // 32 KiB
                        width_cache_entries: 256,
                        shaping_cache_entries: 0, // disabled
                    },
                    queue: QueueBudget {
                        max_reshape_pending: 0, // no shaping
                        max_rewrap_pending: 4,  // minimal
                        max_reflow_pending: 1,
                    },
                },
                // Fast: 4ms total — terminal-optimized
                TierBudget {
                    tier: LayoutTier::Fast,
                    frame: FrameBudget {
                        total_us: 4_000,
                        layout_us: 200,
                        shaping_us: 800,
                        diff_us: 500,
                        present_us: 1_000,
                        headroom_us: 1_500,
                    },
                    memory: MemoryBudget {
                        shaping_bytes: 256 * 1024, // 256 KiB
                        layout_bytes: 64 * 1024,   // 64 KiB
                        diff_bytes: 128 * 1024,    // 128 KiB
                        width_cache_entries: 1_000,
                        shaping_cache_entries: 0, // no shaping at fast
                    },
                    queue: QueueBudget {
                        max_reshape_pending: 0, // no shaping
                        max_rewrap_pending: 16,
                        max_reflow_pending: 4,
                    },
                },
                // Balanced: 8ms total — good default
                TierBudget {
                    tier: LayoutTier::Balanced,
                    frame: FrameBudget {
                        total_us: 8_000,
                        layout_us: 500,
                        shaping_us: 2_500,
                        diff_us: 1_000,
                        present_us: 1_500,
                        headroom_us: 2_500,
                    },
                    memory: MemoryBudget {
                        shaping_bytes: 1024 * 1024, // 1 MiB
                        layout_bytes: 256 * 1024,   // 256 KiB
                        diff_bytes: 512 * 1024,     // 512 KiB
                        width_cache_entries: 4_000,
                        shaping_cache_entries: 512,
                    },
                    queue: QueueBudget {
                        max_reshape_pending: 32,
                        max_rewrap_pending: 64,
                        max_reflow_pending: 16,
                    },
                },
                // Quality: 16ms total — near full frame budget
                TierBudget {
                    tier: LayoutTier::Quality,
                    frame: FrameBudget {
                        total_us: 16_000,
                        layout_us: 1_000,
                        shaping_us: 5_000,
                        diff_us: 2_000,
                        present_us: 3_000,
                        headroom_us: 5_000,
                    },
                    memory: MemoryBudget {
                        shaping_bytes: 4 * 1024 * 1024, // 4 MiB
                        layout_bytes: 1024 * 1024,      // 1 MiB
                        diff_bytes: 2 * 1024 * 1024,    // 2 MiB
                        width_cache_entries: 16_000,
                        shaping_cache_entries: 2_048,
                    },
                    queue: QueueBudget {
                        max_reshape_pending: 128,
                        max_rewrap_pending: 256,
                        max_reflow_pending: 64,
                    },
                },
            ],
            features: [
                // Emergency
                TierFeatures {
                    tier: LayoutTier::Emergency,
                    shaped_text: false,
                    terminal_fallback: true,
                    optimal_breaking: false,
                    hyphenation: false,
                    justification: false,
                    tracking: false,
                    baseline_grid: false,
                    paragraph_spacing: false,
                    first_line_indent: false,
                    width_cache: true, // always on — cheap
                    shaping_cache: false,
                    incremental_diff: true, // always on — correctness aid
                    subcell_spacing: false,
                },
                // Fast
                TierFeatures {
                    tier: LayoutTier::Fast,
                    shaped_text: false,
                    terminal_fallback: true,
                    optimal_breaking: false,
                    hyphenation: false,
                    justification: false,
                    tracking: false,
                    baseline_grid: false,
                    paragraph_spacing: false,
                    first_line_indent: false,
                    width_cache: true,
                    shaping_cache: false,
                    incremental_diff: true,
                    subcell_spacing: false,
                },
                // Balanced
                TierFeatures {
                    tier: LayoutTier::Balanced,
                    shaped_text: true,
                    terminal_fallback: true,
                    optimal_breaking: true,
                    hyphenation: false,
                    justification: false,
                    tracking: false,
                    baseline_grid: false,
                    paragraph_spacing: true,
                    first_line_indent: false,
                    width_cache: true,
                    shaping_cache: true,
                    incremental_diff: true,
                    subcell_spacing: true,
                },
                // Quality
                TierFeatures {
                    tier: LayoutTier::Quality,
                    shaped_text: true,
                    terminal_fallback: true,
                    optimal_breaking: true,
                    hyphenation: true,
                    justification: true,
                    tracking: true,
                    baseline_grid: true,
                    paragraph_spacing: true,
                    first_line_indent: true,
                    width_cache: true,
                    shaping_cache: true,
                    incremental_diff: true,
                    subcell_spacing: true,
                },
            ],
        }
    }

    /// Verify that feature toggles are monotonically enabled up the ladder.
    ///
    /// Returns a list of violations where a higher tier disables a feature
    /// that a lower tier enables.
    #[must_use]
    pub fn check_monotonicity(&self) -> Vec<String> {
        let mut violations = Vec::new();

        for i in 0..self.features.len() - 1 {
            let lower = &self.features[i];
            let higher = &self.features[i + 1];

            let check = |name: &str, lo: bool, hi: bool| {
                if lo && !hi {
                    Some(format!(
                        "{name} is enabled at {} but disabled at {}",
                        lower.tier, higher.tier
                    ))
                } else {
                    None
                }
            };

            violations.extend(check(
                "terminal_fallback",
                lower.terminal_fallback,
                higher.terminal_fallback,
            ));
            violations.extend(check("width_cache", lower.width_cache, higher.width_cache));
            violations.extend(check(
                "incremental_diff",
                lower.incremental_diff,
                higher.incremental_diff,
            ));
            violations.extend(check("shaped_text", lower.shaped_text, higher.shaped_text));
            violations.extend(check(
                "optimal_breaking",
                lower.optimal_breaking,
                higher.optimal_breaking,
            ));
            violations.extend(check("hyphenation", lower.hyphenation, higher.hyphenation));
            violations.extend(check(
                "justification",
                lower.justification,
                higher.justification,
            ));
            violations.extend(check("tracking", lower.tracking, higher.tracking));
            violations.extend(check(
                "baseline_grid",
                lower.baseline_grid,
                higher.baseline_grid,
            ));
            violations.extend(check(
                "paragraph_spacing",
                lower.paragraph_spacing,
                higher.paragraph_spacing,
            ));
            violations.extend(check(
                "first_line_indent",
                lower.first_line_indent,
                higher.first_line_indent,
            ));
            violations.extend(check(
                "shaping_cache",
                lower.shaping_cache,
                higher.shaping_cache,
            ));
            violations.extend(check(
                "subcell_spacing",
                lower.subcell_spacing,
                higher.subcell_spacing,
            ));
        }
        violations
    }

    /// Verify that all budgets are consistent (sub-budgets sum to total).
    #[must_use]
    pub fn check_budget_consistency(&self) -> Vec<String> {
        let mut issues = Vec::new();
        for b in &self.budgets {
            if !b.frame.is_consistent() {
                issues.push(format!(
                    "[{}] frame sub-budgets sum to {}µs but total is {}µs",
                    b.tier,
                    b.frame.allocated(),
                    b.frame.total_us
                ));
            }
        }
        issues
    }

    /// Verify that budgets increase monotonically up the tier ladder.
    #[must_use]
    pub fn check_budget_ordering(&self) -> Vec<String> {
        let mut issues = Vec::new();
        for i in 0..self.budgets.len() - 1 {
            let lower = &self.budgets[i];
            let higher = &self.budgets[i + 1];
            if lower.frame.total_us >= higher.frame.total_us {
                issues.push(format!(
                    "frame budget {} ({}µs) >= {} ({}µs)",
                    lower.tier, lower.frame.total_us, higher.tier, higher.frame.total_us
                ));
            }
        }
        issues
    }
}

impl Default for TierLadder {
    fn default() -> Self {
        Self::default_60fps()
    }
}

impl fmt::Display for TierLadder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for b in &self.budgets {
            writeln!(f, "{b}")?;
        }
        writeln!(f)?;
        for feat in &self.features {
            writeln!(f, "{feat}")?;
        }
        Ok(())
    }
}

// =========================================================================
// Tests
// =========================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // ── FrameBudget ─────────────────────────────────────────────────

    #[test]
    fn fps_60_is_16667us() {
        assert_eq!(FrameBudget::from_fps(60), 16_666);
    }

    #[test]
    fn fps_30_is_33333us() {
        assert_eq!(FrameBudget::from_fps(30), 33_333);
    }

    #[test]
    fn frame_budget_as_duration() {
        let fb = FrameBudget {
            total_us: 16_000,
            layout_us: 1_000,
            shaping_us: 5_000,
            diff_us: 2_000,
            present_us: 3_000,
            headroom_us: 5_000,
        };
        assert_eq!(fb.as_duration(), Duration::from_micros(16_000));
    }

    #[test]
    fn frame_budget_consistency() {
        let fb = FrameBudget {
            total_us: 10_000,
            layout_us: 1_000,
            shaping_us: 2_000,
            diff_us: 2_000,
            present_us: 2_000,
            headroom_us: 3_000,
        };
        assert!(fb.is_consistent());
    }

    #[test]
    fn frame_budget_inconsistency() {
        let fb = FrameBudget {
            total_us: 10_000,
            layout_us: 1_000,
            shaping_us: 2_000,
            diff_us: 2_000,
            present_us: 2_000,
            headroom_us: 999, // wrong
        };
        assert!(!fb.is_consistent());
    }

    #[test]
    fn frame_budget_display() {
        let fb = FrameBudget {
            total_us: 4_000,
            layout_us: 200,
            shaping_us: 800,
            diff_us: 500,
            present_us: 1_000,
            headroom_us: 1_500,
        };
        let s = format!("{fb}");
        assert!(s.contains("4000µs"));
        assert!(s.contains("layout=200µs"));
    }

    // ── MemoryBudget ────────────────────────────────────────────────

    #[test]
    fn memory_transient_total() {
        let mb = MemoryBudget {
            shaping_bytes: 1024,
            layout_bytes: 512,
            diff_bytes: 256,
            width_cache_entries: 100,
            shaping_cache_entries: 50,
        };
        assert_eq!(mb.transient_total(), 1792);
    }

    #[test]
    fn memory_budget_display() {
        let mb = MemoryBudget {
            shaping_bytes: 1024,
            layout_bytes: 512,
            diff_bytes: 256,
            width_cache_entries: 100,
            shaping_cache_entries: 50,
        };
        let s = format!("{mb}");
        assert!(s.contains("transient=1792B"));
    }

    // ── QueueBudget ─────────────────────────────────────────────────

    #[test]
    fn queue_total_max() {
        let qb = QueueBudget {
            max_reshape_pending: 10,
            max_rewrap_pending: 20,
            max_reflow_pending: 5,
        };
        assert_eq!(qb.total_max(), 35);
    }

    #[test]
    fn queue_budget_display() {
        let qb = QueueBudget {
            max_reshape_pending: 10,
            max_rewrap_pending: 20,
            max_reflow_pending: 5,
        };
        let s = format!("{qb}");
        assert!(s.contains("reshape=10"));
    }

    // ── TierBudget ──────────────────────────────────────────────────

    #[test]
    fn tier_budget_display() {
        let ladder = TierLadder::default_60fps();
        let s = format!("{}", ladder.budget(LayoutTier::Fast));
        assert!(s.contains("[fast]"));
        assert!(s.contains("4000µs"));
    }

    // ── TierFeatures ────────────────────────────────────────────────

    #[test]
    fn emergency_features_minimal() {
        let ladder = TierLadder::default_60fps();
        let f = ladder.features_for(LayoutTier::Emergency);
        assert!(!f.shaped_text);
        assert!(!f.optimal_breaking);
        assert!(!f.justification);
        assert!(!f.hyphenation);
        assert!(f.terminal_fallback);
        assert!(f.width_cache);
        assert!(f.incremental_diff);
    }

    #[test]
    fn fast_features() {
        let ladder = TierLadder::default_60fps();
        let f = ladder.features_for(LayoutTier::Fast);
        assert!(!f.shaped_text);
        assert!(!f.optimal_breaking);
        assert!(f.terminal_fallback);
        assert!(f.width_cache);
    }

    #[test]
    fn balanced_features() {
        let ladder = TierLadder::default_60fps();
        let f = ladder.features_for(LayoutTier::Balanced);
        assert!(f.shaped_text);
        assert!(f.optimal_breaking);
        assert!(f.shaping_cache);
        assert!(f.subcell_spacing);
        assert!(!f.hyphenation);
        assert!(!f.justification);
    }

    #[test]
    fn quality_features_all_on() {
        let ladder = TierLadder::default_60fps();
        let f = ladder.features_for(LayoutTier::Quality);
        assert!(f.shaped_text);
        assert!(f.optimal_breaking);
        assert!(f.hyphenation);
        assert!(f.justification);
        assert!(f.tracking);
        assert!(f.baseline_grid);
        assert!(f.first_line_indent);
    }

    #[test]
    fn feature_active_list() {
        let ladder = TierLadder::default_60fps();
        let list = ladder.features_for(LayoutTier::Emergency).active_list();
        assert!(list.contains(&"terminal-fallback"));
        assert!(list.contains(&"width-cache"));
        assert!(list.contains(&"incremental-diff"));
        assert_eq!(list.len(), 3);
    }

    #[test]
    fn features_display() {
        let ladder = TierLadder::default_60fps();
        let s = format!("{}", ladder.features_for(LayoutTier::Quality));
        assert!(s.contains("[quality]"));
        assert!(s.contains("justification"));
    }

    // ── TierLadder ──────────────────────────────────────────────────

    #[test]
    fn default_ladder_budgets_are_consistent() {
        let ladder = TierLadder::default_60fps();
        let issues = ladder.check_budget_consistency();
        assert!(issues.is_empty(), "Budget inconsistencies: {issues:?}");
    }

    #[test]
    fn default_ladder_budgets_monotonically_increase() {
        let ladder = TierLadder::default_60fps();
        let issues = ladder.check_budget_ordering();
        assert!(issues.is_empty(), "Budget ordering violations: {issues:?}");
    }

    #[test]
    fn default_ladder_features_are_monotonic() {
        let ladder = TierLadder::default_60fps();
        let violations = ladder.check_monotonicity();
        assert!(
            violations.is_empty(),
            "Feature monotonicity violations: {violations:?}"
        );
    }

    #[test]
    fn ladder_budget_lookup() {
        let ladder = TierLadder::default_60fps();
        assert_eq!(ladder.budget(LayoutTier::Emergency).frame.total_us, 2_000);
        assert_eq!(ladder.budget(LayoutTier::Fast).frame.total_us, 4_000);
        assert_eq!(ladder.budget(LayoutTier::Balanced).frame.total_us, 8_000);
        assert_eq!(ladder.budget(LayoutTier::Quality).frame.total_us, 16_000);
    }

    #[test]
    fn ladder_display() {
        let ladder = TierLadder::default_60fps();
        let s = format!("{ladder}");
        assert!(s.contains("[emergency]"));
        assert!(s.contains("[fast]"));
        assert!(s.contains("[balanced]"));
        assert!(s.contains("[quality]"));
    }

    #[test]
    fn default_trait() {
        let ladder = TierLadder::default();
        assert_eq!(ladder.budget(LayoutTier::Fast).frame.total_us, 4_000);
    }

    // ── SafetyInvariant ─────────────────────────────────────────────

    #[test]
    fn all_invariants_listed() {
        assert_eq!(SafetyInvariant::ALL.len(), 8);
    }

    #[test]
    fn invariant_display() {
        assert_eq!(
            format!("{}", SafetyInvariant::NoContentLoss),
            "no-content-loss"
        );
        assert_eq!(
            format!("{}", SafetyInvariant::WideCharWidth),
            "wide-char-width"
        );
        assert_eq!(
            format!("{}", SafetyInvariant::GreedyWrapFallback),
            "greedy-wrap-fallback"
        );
    }

    #[test]
    fn invariants_cover_key_concerns() {
        let all = SafetyInvariant::ALL;
        assert!(all.contains(&SafetyInvariant::NoContentLoss));
        assert!(all.contains(&SafetyInvariant::WideCharWidth));
        assert!(all.contains(&SafetyInvariant::BufferSizeMatch));
        assert!(all.contains(&SafetyInvariant::DiffIdempotence));
        assert!(all.contains(&SafetyInvariant::WidthDeterminism));
    }

    // ── Integration: budget fits within 60fps ───────────────────────

    #[test]
    fn all_budgets_within_60fps() {
        let frame_budget_60fps = FrameBudget::from_fps(60);
        let ladder = TierLadder::default_60fps();
        for b in &ladder.budgets {
            assert!(
                b.frame.total_us <= frame_budget_60fps,
                "{} budget {}µs exceeds 60fps frame ({}µs)",
                b.tier,
                b.frame.total_us,
                frame_budget_60fps
            );
        }
    }

    #[test]
    fn emergency_queue_disables_reshape() {
        let ladder = TierLadder::default_60fps();
        assert_eq!(
            ladder
                .budget(LayoutTier::Emergency)
                .queue
                .max_reshape_pending,
            0
        );
    }

    #[test]
    fn quality_has_largest_caches() {
        let ladder = TierLadder::default_60fps();
        let e = &ladder.budget(LayoutTier::Emergency).memory;
        let q = &ladder.budget(LayoutTier::Quality).memory;
        assert!(q.width_cache_entries > e.width_cache_entries);
        assert!(q.shaping_cache_entries > e.shaping_cache_entries);
    }
}