linesmith-core 0.1.3

Internal core engine for linesmith. No SemVer guarantee for direct dependents — depend on the `linesmith` binary or accept breakage between minor versions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! Segment trait and layout-intent types. Full contract lives in
//! `docs/specs/segment-system.md`; this module carries the subset the
//! layout engine uses today: visibility, cell width, priority,
//! separator preference, and theme role.

use crate::data_context::{DataContext, DataDep};
use crate::theme::{Role, Style};
use std::borrow::Cow;
use unicode_width::UnicodeWidthStr;

pub mod agent;
pub mod builder;
pub mod context_bar;
pub mod context_window;
pub mod cost;
pub mod effort;
pub mod extra_usage;
pub mod extras;
pub mod git_branch;
pub mod model;
pub mod output_style;
pub mod rate_limit;
pub mod session_duration;
pub mod tokens;
pub mod version;
pub mod vim;
pub mod workspace;

/// Output of a successful segment render.
///
/// Fields are `pub(crate)` so the engine can read them directly;
/// external callers go through the constructors and accessors so the
/// `width == text_width(text)` invariant can't desync via a mutable
/// `text`. `#[non_exhaustive]` keeps future additions SemVer-safe.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RenderedSegment {
    pub(crate) text: String,
    pub(crate) width: u16,
    pub(crate) right_separator: Option<Separator>,
    pub(crate) style: Style,
}

impl RenderedSegment {
    /// Build a rendered segment from `text`, auto-computing its cell
    /// width. Use [`Self::with_separator`] when the segment wants to
    /// override its default right-separator for this boundary, and
    /// [`Self::with_role`] / [`Self::with_style`] to attach a theme
    /// role or full style.
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        let text = sanitize_control_chars(text.into());
        let width = text_width(&text);
        Self {
            text,
            width,
            right_separator: None,
            style: Style::default(),
        }
    }

    #[must_use]
    pub fn with_separator(text: impl Into<String>, separator: Separator) -> Self {
        let text = sanitize_control_chars(text.into());
        let width = text_width(&text);
        Self {
            text,
            width,
            right_separator: Some(separator),
            style: Style::default(),
        }
    }

    /// Chainable setter for the segment's theme role. The layout
    /// engine resolves the role against the active theme + terminal
    /// capability at render time; no ANSI bytes land in `text`.
    ///
    /// Preserves any decorations previously set by [`Self::with_style`].
    /// Pair with `with_style` carefully: `.with_style(s).with_role(r)`
    /// keeps `s`'s bold/fg/etc. and swaps role, whereas
    /// `.with_role(r).with_style(s)` wholesale-replaces everything.
    #[must_use]
    pub fn with_role(mut self, role: Role) -> Self {
        self.style.role = Some(role);
        self
    }

    /// Chainable setter for the full style (role + decorations).
    /// Wholesale-replaces the current style; use [`Self::with_role`]
    /// when you want to preserve decorations and swap only the role.
    #[must_use]
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Style this segment wants applied when the layout emits it.
    #[must_use]
    pub fn style(&self) -> &Style {
        &self.style
    }

    /// The rendered text.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Cell width of the rendered text.
    #[must_use]
    pub fn width(&self) -> u16 {
        self.width
    }

    /// Separator this render prefers on its right edge, if any. `None`
    /// means "fall back to the segment's default separator."
    #[must_use]
    pub fn right_separator(&self) -> Option<&Separator> {
        self.right_separator.as_ref()
    }

    /// Trusted crate-internal constructor that accepts an explicit
    /// `width` and `style`. Reserved for [`crate::layout::truncate_to`];
    /// every other caller goes through [`Self::new`] so the width stays
    /// a function of the text.
    #[must_use]
    pub(crate) fn from_parts(
        text: String,
        width: u16,
        right_separator: Option<Separator>,
        style: Style,
    ) -> Self {
        Self {
            text,
            width,
            right_separator,
            style,
        }
    }
}

/// Cell count of `s` on a standard terminal, saturating at `u16::MAX`.
#[must_use]
pub(crate) fn text_width(s: &str) -> u16 {
    u16::try_from(UnicodeWidthStr::width(s)).unwrap_or(u16::MAX)
}

/// Strip Unicode control characters from `s`.
///
/// Segment text often comes from untrusted input (a project dir
/// basename, a worktree name). `UnicodeWidthChar::width` reports
/// control chars as 0 cells, but terminals interpret them as
/// cursor-movement, screen-clear, or OSC payloads: a worktree named
/// `evil\x1b[2J` would blank the terminal on every statusline render.
/// Stripping at the `RenderedSegment` boundary protects every segment
/// that funnels user data through it.
///
/// Returns the input unchanged when it has no control chars.
pub(crate) fn sanitize_control_chars(s: String) -> String {
    if !s.chars().any(char::is_control) {
        return s;
    }
    s.chars().filter(|c| !c.is_control()).collect()
}

/// Separator between adjacent segments. Chosen by the segment to its
/// left; themes and user config can override.
///
/// `Theme` is reserved for theme-provided padding and renders as a
/// single space when no theme is configured. `Literal` carries a
/// `Cow<'static, str>` so built-ins stay zero-alloc while user config
/// allocates once. `Powerline { width }` emits the Nerd Font
/// right-arrow chevron (U+E0B0) flanked by single-space padding;
/// `width` is the chevron's own cell count (1 or 2 — see
/// `[layout_options].powerline_width`), and the reported [`width()`]
/// includes the 2 padding cells. Chevron styling lives in
/// [`crate::layout::separator_style`].
///
/// [`width()`]: Separator::width
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Separator {
    Space,
    Theme,
    Literal(Cow<'static, str>),
    Powerline { width: PowerlineWidth },
    None,
}

/// Cell-count for the Nerd Font powerline chevron (U+E0B0). Most
/// modern fonts at standard sizes render the chevron as a single cell;
/// some larger sizes / older Nerd Font builds render it as two. The
/// type makes any other value unrepresentable so layout-width math
/// can't drift into invalid territory.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PowerlineWidth {
    #[default]
    One,
    Two,
}

impl PowerlineWidth {
    /// Cell count this width represents (1 or 2).
    #[must_use]
    pub const fn cells(self) -> u16 {
        match self {
            Self::One => 1,
            Self::Two => 2,
        }
    }
}

/// Nerd Font right-arrow chevron (U+E0B0) with single-space padding
/// on each side.
const POWERLINE_CHEVRON_PADDED: &str = " \u{E0B0} ";

impl Separator {
    /// Default 1-cell powerline chevron. Use this for the common case
    /// (most modern Nerd Fonts render U+E0B0 as 1 cell at standard
    /// sizes); pass `Powerline { width: PowerlineWidth::Two }` for
    /// fonts/sizes that render 2 cells.
    #[must_use]
    pub const fn powerline() -> Self {
        Self::Powerline {
            width: PowerlineWidth::One,
        }
    }

    #[must_use]
    pub fn text(&self) -> &str {
        match self {
            Self::Space | Self::Theme => " ",
            Self::Literal(s) => s,
            Self::Powerline { .. } => POWERLINE_CHEVRON_PADDED,
            Self::None => "",
        }
    }

    #[must_use]
    pub fn width(&self) -> u16 {
        match self {
            Self::Space | Self::Theme => 1,
            Self::Literal(s) => text_width(s),
            Self::Powerline { width } => width.cells() + 2,
            Self::None => 0,
        }
    }
}

/// Width bounds in cells with `min <= max` enforced at construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WidthBounds {
    min: u16,
    max: u16,
}

impl WidthBounds {
    /// Returns `None` when `min > max`.
    #[must_use]
    pub fn new(min: u16, max: u16) -> Option<Self> {
        (min <= max).then_some(Self { min, max })
    }

    #[must_use]
    pub fn min(self) -> u16 {
        self.min
    }

    #[must_use]
    pub fn max(self) -> u16 {
        self.max
    }
}

/// Layout intent declared by a segment; user config may override each
/// field.
///
/// Under width pressure the engine drops segments in descending
/// `priority` order: `255` drops first, `0` never drops. Default `128`.
/// Ties break by position: the right-most segment drops first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct SegmentDefaults {
    pub priority: u8,
    pub width: Option<WidthBounds>,
    /// May the layout engine shrink this segment under width pressure
    /// before dropping it? Default `false` — only prose-like segments
    /// (workspace name, branch name) opt in. Numeric or structured
    /// segments leave this `false`: a half-cut percentage reads as
    /// the wrong number, which is worse than no number.
    /// See `docs/specs/segment-system.md` §Layout algorithm.
    pub truncatable: bool,
}

impl SegmentDefaults {
    /// Constructor shorthand for the common case of "default layout
    /// intent with a specific priority." Chainable with
    /// [`Self::with_width`] and [`Self::with_truncatable`].
    #[must_use]
    pub fn with_priority(priority: u8) -> Self {
        Self {
            priority,
            ..Self::default()
        }
    }

    /// Chainable setter for width bounds.
    #[must_use]
    pub fn with_width(mut self, bounds: WidthBounds) -> Self {
        self.width = Some(bounds);
        self
    }

    /// Chainable setter for the truncate-before-drop opt-in.
    #[must_use]
    pub fn with_truncatable(mut self, truncatable: bool) -> Self {
        self.truncatable = truncatable;
        self
    }
}

impl Default for SegmentDefaults {
    fn default() -> Self {
        Self {
            priority: 128,
            width: None,
            truncatable: false,
        }
    }
}

/// Shorthand for [`Segment::render`]'s return type.
///
/// Three states:
/// - `Ok(Some(r))`: the segment renders `r`.
/// - `Ok(None)`: the segment has no content this invocation and should
///   be hidden (intentional, e.g. rate-limit segment on an API-tier
///   user).
/// - `Err(e)`: the segment attempted to render but failed. The layout
///   engine logs `e` to stderr and hides the segment — same visual
///   result as `Ok(None)`, but the diagnostic distinguishes failure
///   from intentional absence.
pub type RenderResult = Result<Option<RenderedSegment>, SegmentError>;

/// Runtime failure from a segment's [`Segment::render`]. Built-in
/// segments return `Ok(...)` today; this surface is primarily for
/// plugin-authored segments (rhai script errors, unexpected input,
/// propagated I/O).
#[derive(Debug)]
#[non_exhaustive]
pub struct SegmentError {
    pub message: String,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

impl SegmentError {
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            source: None,
        }
    }

    #[must_use]
    pub fn with_source(
        message: impl Into<String>,
        source: Box<dyn std::error::Error + Send + Sync>,
    ) -> Self {
        Self {
            message: message.into(),
            source: Some(source),
        }
    }
}

impl std::fmt::Display for SegmentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)?;
        if let Some(src) = &self.source {
            write!(f, ": {src}")?;
        }
        Ok(())
    }
}

impl std::error::Error for SegmentError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_deref().map(|e| e as &dyn std::error::Error)
    }
}

/// Per-render layout state the engine builds once per call and threads
/// into every [`Segment::render`]. Distinct from [`DataContext`], which
/// is the data layer (one instance per process invocation, shared
/// across segments). `RenderContext` is the layout layer: terminal
/// width today, room for line index / capability / neighbor info as
/// dynamic-segment work lands.
///
/// `#[non_exhaustive]` keeps future additions SemVer-safe; segments
/// that don't read the field accept it as `_rc: &RenderContext` and
/// pay nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RenderContext {
    /// Total cells available to this line. Sourced from the terminal,
    /// or the schema-defined fallback (200) when stdout is detached.
    pub terminal_width: u16,
}

impl RenderContext {
    #[must_use]
    pub fn new(terminal_width: u16) -> Self {
        Self { terminal_width }
    }
}

pub trait Segment: Send {
    /// Render this segment for the given context.
    ///
    /// Returns `Ok(None)` to hide, `Ok(Some(_))` to render, or `Err` on
    /// a runtime failure that the layout engine logs and treats as
    /// hidden. See [`RenderResult`]. `ctx` owns the parsed stdin
    /// payload (`ctx.status`) plus lazy accessors for other sources
    /// (`ctx.usage()`, `ctx.git()`, etc.) declared in
    /// [`data_deps`](Self::data_deps). `rc` is per-render layout
    /// state — terminal width today — for segments that pick their
    /// own shape based on available room.
    fn render(&self, ctx: &DataContext, rc: &RenderContext) -> RenderResult;

    /// Layout-pressure-aware compaction hook. The reflow loop calls
    /// this on any segment under width pressure (truncatable or
    /// not), asking whether it can produce a render at most `target`
    /// cells wide. It runs before `truncatable` end-ellipsis
    /// truncation, so segment-side intelligence beats generic
    /// string clipping when both apply. Default returns `None` (no
    /// compact form available; engine falls through to truncatable
    /// or drop). Segments with structured tail content override to
    /// shed decoration while keeping the signal-bearing prefix.
    ///
    /// The returned render must lie in `[width.min, target]` cells:
    /// wider violates the layout-fit invariant (engine rejects and
    /// warns), narrower violates the user's `width.min` contract
    /// (engine rejects silently, same as `apply_width_bounds`).
    /// Implementations should return `None` rather than emit a
    /// render outside this range.
    ///
    /// See `docs/specs/segment-system.md` §Layout algorithm for
    /// the reflow loop's full ordering and target derivation.
    #[allow(unused_variables)]
    #[must_use]
    fn shrink_to_fit(
        &self,
        ctx: &DataContext,
        rc: &RenderContext,
        target: u16,
    ) -> Option<RenderedSegment> {
        None
    }

    /// Declare which data sources this segment reads. The runtime
    /// computes the union across all enabled segments and lazy-fetches
    /// only those sources. Defaults to the stdin payload only; segments
    /// that read other sources must override. See
    /// `docs/specs/data-fetching.md` §Segment dependency declaration.
    ///
    /// The `&'static` lifetime is deliberate: built-in segments return
    /// a `const &[DataDep]` at zero cost, and runtime-loaded plugin
    /// segments (e.g. `RhaiSegment`) promote their parsed
    /// `Vec<DataDep>` via `Vec::leak` once at plugin-load time. The
    /// plugin registry is built once per process and lives until exit,
    /// so the leak is bounded. If plugin hot-reload arrives (deferred
    /// feature), swap to an arena allocator or `Arc<[DataDep]>`.
    #[must_use]
    fn data_deps(&self) -> &'static [DataDep] {
        &[DataDep::Status]
    }

    /// Layout defaults (priority, width bounds, truncatable opt-in).
    /// User config may override each field via [`OverriddenSegment`].
    /// Implementations must be O(1), do no I/O, and avoid allocation:
    /// the layout engine snapshots this at collect time and the
    /// [`LineItem::Debug`] impl reads it for `dbg!` / panic-backtrace
    /// formatting.
    #[must_use]
    fn defaults(&self) -> SegmentDefaults {
        SegmentDefaults::default()
    }
}

// --- Built-in registry + config-driven override wrapper ----------------

/// Default segment order when no config supplies one. No rate-limit
/// segments are in the default line: a first-run user without any
/// config shouldn't trigger a macOS Keychain prompt or a network
/// request just to render the statusline. Users opt in by listing
/// the rate-limit segments explicitly in `[line.segments]`.
pub const DEFAULT_SEGMENT_IDS: &[&str] = &[
    "model",
    "context_window",
    "cost",
    "effort",
    "git_branch",
    "workspace",
];

/// Every built-in segment id. Used by [`PluginRegistry`] to reject
/// plugins whose `const ID` shadows a built-in. Add new built-ins
/// here AND to [`built_in_by_id`].
///
/// Also used by `resolve_segment_id` (O(n) per segment at build time,
/// not render time) to pin built-in ids to `Cow::Borrowed` per ADR-0026.
/// If the list grows past ~50 entries, swap to a `phf::Set`.
///
/// [`PluginRegistry`]: linesmith_plugin::PluginRegistry
pub const BUILT_IN_SEGMENT_IDS: &[&str] = &[
    "model",
    "context_window",
    "context_bar",
    "workspace",
    "cost",
    "effort",
    "output_style",
    "vim",
    "agent",
    "git_branch",
    "rate_limit_5h",
    "rate_limit_7d",
    "rate_limit_5h_reset",
    "rate_limit_7d_reset",
    "extra_usage",
    "session_duration",
    "tokens_input",
    "tokens_output",
    "tokens_cached",
    "tokens_total",
    "version",
];

/// Construct a built-in segment by its config id. Unknown ids return
/// `None` so config loaders can warn and skip. `extras` carries the
/// `[segments.<id>]` TOML bag; rate-limit segments parse their knobs
/// from it (`format`, `invert`, `compact`, `use_days`, `icon`,
/// `label`, `stale_marker`, `progress_width`). Other built-ins
/// currently ignore `extras`.
///
/// Every arm in this `match` must have a corresponding entry in
/// [`BUILT_IN_SEGMENT_IDS`] and vice versa. The forward direction is
/// covered by `built_in_by_id_resolves_every_id_in_built_in_segment_ids`;
/// a match arm missing from the const would silently let a plugin shadow
/// the built-in and degrade its `Cow::Borrowed` short-circuit to
/// `Cow::Owned`. Add new built-ins to both lists together.
#[must_use]
pub fn built_in_by_id(
    id: &str,
    extras: Option<&std::collections::BTreeMap<String, toml::Value>>,
    warn: &mut impl FnMut(&str),
) -> Option<Box<dyn Segment>> {
    let empty: std::collections::BTreeMap<String, toml::Value> = std::collections::BTreeMap::new();
    let e = extras.unwrap_or(&empty);
    match id {
        "model" => Some(Box::new(model::ModelSegment::from_extras(e, warn))),
        "context_window" => Some(Box::new(context_window::ContextWindowSegment)),
        "context_bar" => Some(Box::new(context_bar::ContextBarSegment::from_extras(
            e, warn,
        ))),
        "workspace" => Some(Box::new(workspace::WorkspaceSegment)),
        "cost" => Some(Box::new(cost::CostSegment)),
        "effort" => Some(Box::new(effort::EffortSegment)),
        "output_style" => Some(Box::new(output_style::OutputStyleSegment)),
        "vim" => Some(Box::new(vim::VimSegment)),
        "agent" => Some(Box::new(agent::AgentSegment)),
        "git_branch" => Some(Box::new(git_branch::GitBranchSegment::from_extras(e, warn))),
        "rate_limit_5h" => Some(Box::new(
            rate_limit::five_hour::RateLimit5hSegment::from_extras(e, warn),
        )),
        "rate_limit_7d" => Some(Box::new(
            rate_limit::seven_day::RateLimit7dSegment::from_extras(e, warn),
        )),
        "rate_limit_5h_reset" => Some(Box::new(
            rate_limit::five_hour::RateLimit5hResetSegment::from_extras(e, warn),
        )),
        "rate_limit_7d_reset" => Some(Box::new(
            rate_limit::seven_day::RateLimit7dResetSegment::from_extras(e, warn),
        )),
        "extra_usage" => Some(Box::new(extra_usage::ExtraUsageSegment::from_extras(
            e, warn,
        ))),
        "session_duration" => Some(Box::new(session_duration::SessionDurationSegment)),
        "tokens_input" => Some(Box::new(tokens::TokensInputSegment)),
        "tokens_output" => Some(Box::new(tokens::TokensOutputSegment)),
        "tokens_cached" => Some(Box::new(tokens::TokensCachedSegment)),
        "tokens_total" => Some(Box::new(tokens::TokensTotalSegment)),
        "version" => Some(Box::new(version::VersionSegment::from_extras(e, warn))),
        _ => None,
    }
}

/// Wraps a `Segment` to override its `defaults()` output while
/// delegating `render` unchanged. Applying `[segments.<id>]` overrides
/// without touching the inner segment.
pub struct OverriddenSegment {
    inner: Box<dyn Segment>,
    priority: Option<u8>,
    width: Option<WidthBounds>,
    user_style: Option<Style>,
}

impl OverriddenSegment {
    #[must_use]
    pub fn new(inner: Box<dyn Segment>) -> Self {
        Self {
            inner,
            priority: None,
            width: None,
            user_style: None,
        }
    }

    #[must_use]
    pub fn with_priority(mut self, priority: u8) -> Self {
        self.priority = Some(priority);
        self
    }

    #[must_use]
    pub fn with_width(mut self, bounds: WidthBounds) -> Self {
        self.width = Some(bounds);
        self
    }

    /// Wholesale-replaces the inner segment's declared style at render
    /// time. See `docs/specs/theming.md` §Resolution precedence.
    #[must_use]
    pub fn with_user_style(mut self, style: Style) -> Self {
        self.user_style = Some(style);
        self
    }
}

impl Segment for OverriddenSegment {
    fn render(&self, ctx: &DataContext, rc: &RenderContext) -> RenderResult {
        let result = self.inner.render(ctx, rc)?;
        Ok(result.map(|r| match &self.user_style {
            Some(override_style) => {
                let merged = merge_user_override(r.style(), override_style);
                r.with_style(merged)
            }
            None => r,
        }))
    }

    fn shrink_to_fit(
        &self,
        ctx: &DataContext,
        rc: &RenderContext,
        target: u16,
    ) -> Option<RenderedSegment> {
        let inner = self.inner.shrink_to_fit(ctx, rc, target)?;
        Some(match &self.user_style {
            Some(override_style) => {
                let merged = merge_user_override(inner.style(), override_style);
                inner.with_style(merged)
            }
            None => inner,
        })
    }

    fn data_deps(&self) -> &'static [DataDep] {
        self.inner.data_deps()
    }

    fn defaults(&self) -> SegmentDefaults {
        let mut d = self.inner.defaults();
        if let Some(p) = self.priority {
            d.priority = p;
        }
        if let Some(w) = self.width {
            d.width = Some(w);
        }
        d
    }
}

/// Merge a user-config style override onto the inner segment's style.
/// Visual fields (role, fg, bold, italic, underline, dim) take the
/// override's value — that's the documented "user wholesale-replaces
/// segment styling" behavior. `hyperlink` is the exception: it carries
/// segment behavior (the link target) rather than appearance, and the
/// user-style TOML syntax doesn't expose a way to set it, so the
/// override always arrives with `hyperlink: None`. Inheriting the
/// inner segment's hyperlink keeps `[segments.X] color = "red"` from
/// silently stripping links the segment emits.
fn merge_user_override(inner: &Style, override_style: &Style) -> Style {
    let mut merged = override_style.clone();
    if merged.hyperlink.is_none() {
        merged.hyperlink = inner.hyperlink.clone();
    }
    merged
}

/// One slot in a line layout: a configured segment or an inline
/// separator between segments. The builder (`build_segments` /
/// `build_lines`) interleaves separators between adjacent segments
/// from `[layout_options].separator`; the renderer walks this list
/// directly. See `docs/specs/segment-system.md` §Data model.
///
/// A plugin's per-render override ([`RenderedSegment::with_separator`])
/// beats the inline `Separator` only when an inline-separator slot
/// exists immediately to the segment's right. An override on the
/// rightmost segment, or a segment whose right-neighbor separator
/// has already been pruned, has no boundary to apply to and is
/// silently discarded.
///
/// Per-variant `#[non_exhaustive]` is omitted from `LineItem::Segment`
/// because consumers pattern-match `{ id, segment }` directly and the
/// consumer set is narrow (builder + tests + benches). Contrast
/// `LayoutDecision`'s per-variant `#[non_exhaustive]` (ADR-0026 §C):
/// those events are observability surfaces with an unknown consumer set,
/// so field-additive forward-compat justifies the `, ..` pattern cost.
#[non_exhaustive]
pub enum LineItem {
    /// A segment paired with the user-facing config id that names it
    /// (per ADR-0026). Sourced from `LineEntry::segment_id()` (the TOML key).
    ///
    /// `id` is a label, not an identity: the layout engine threads it
    /// through `LayoutDecision` events but does not verify it against the
    /// inner segment's type. External constructors must keep the two in sync.
    ///
    /// `Cow::Borrowed` vs `Cow::Owned` is a per-emit allocation trade-off,
    /// not a correctness invariant. Built-in ids land as `Cow::Borrowed`;
    /// plugin and user-config ids land as `Cow::Owned`. External
    /// constructors that don't preserve this partition are correct but pay
    /// one extra allocation per built-in emit.
    Segment {
        id: std::borrow::Cow<'static, str>,
        segment: Box<dyn Segment>,
    },
    Separator(Separator),
}

impl std::fmt::Debug for LineItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            // The trait has no `Debug` bound, so surface the id +
            // layout intent (priority, width hints) — that's what's
            // load-bearing in panic dumps and `dbg!` output anyway.
            Self::Segment { id, segment } => f
                .debug_struct("Segment")
                .field("id", id)
                .field("defaults", &segment.defaults())
                .finish(),
            Self::Separator(sep) => f.debug_tuple("Separator").field(sep).finish(),
        }
    }
}

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

    #[test]
    fn rendered_segment_computes_width() {
        let r = RenderedSegment::new("hello");
        assert_eq!(r.text(), "hello");
        assert_eq!(r.width(), 5);
        assert_eq!(r.right_separator(), None);
    }

    #[test]
    fn rendered_segment_counts_cells_not_bytes_for_middle_dot() {
        // U+00B7 MIDDLE DOT is 2 bytes but 1 cell.
        let r = RenderedSegment::new("42% · 200k");
        assert_eq!(r.width(), 10);
    }

    #[test]
    fn rendered_segment_strips_csi_clear_screen_injection() {
        // \x1b[2J clears the screen if it reaches stdout.
        let r = RenderedSegment::new("evil\x1b[2J");
        assert_eq!(r.text(), "evil[2J");
        assert_eq!(r.width(), 7);
        assert!(!r.text().contains('\x1b'));
    }

    #[test]
    fn rendered_segment_strips_osc_set_title_with_bel_terminator() {
        // OSC 0 sets the terminal title; BEL (\x07) terminates it.
        // Both entry/exit bytes are controls and must drop out.
        let r = RenderedSegment::new("\x1b]0;pwn\x07rest");
        assert_eq!(r.text(), "]0;pwnrest");
        assert!(!r.text().contains('\x1b'));
        assert!(!r.text().contains('\x07'));
    }

    #[test]
    fn rendered_segment_strips_common_c0_controls() {
        let r = RenderedSegment::new("a\x07b\x08c\td\ne\rf");
        assert_eq!(r.text(), "abcdef");
        assert_eq!(r.width(), 6);
    }

    #[test]
    fn rendered_segment_strips_c1_controls_and_del() {
        let r = RenderedSegment::new("x\u{007F}y\u{0085}z\u{009B}");
        assert_eq!(r.text(), "xyz");
        assert_eq!(r.width(), 3);
    }

    #[test]
    fn rendered_segment_preserves_unicode_without_controls() {
        let r = RenderedSegment::new("café · 日本語");
        assert_eq!(r.text(), "café · 日本語");
    }

    #[test]
    fn rendered_segment_empty_string_stays_empty() {
        let r = RenderedSegment::new("");
        assert_eq!(r.text(), "");
        assert_eq!(r.width(), 0);
    }

    #[test]
    fn rendered_segment_all_control_input_collapses_to_empty() {
        // Downstream layout math must cope with zero-width non-None
        // renders; the `width == text_width(text)` invariant still holds.
        let r = RenderedSegment::new("\x1b\x07\n\t");
        assert_eq!(r.text(), "");
        assert_eq!(r.width(), 0);
    }

    #[test]
    fn rendered_segment_with_separator_also_strips_controls() {
        let r = RenderedSegment::with_separator("hi\x1bthere", Separator::None);
        assert_eq!(r.text(), "hithere");
        assert_eq!(r.width(), 7);
    }

    #[test]
    fn rendered_segment_with_separator_exposes_override() {
        let r = RenderedSegment::with_separator("x", Separator::None);
        assert_eq!(r.right_separator(), Some(&Separator::None));
    }

    #[test]
    fn separator_widths_match_expected() {
        assert_eq!(Separator::Space.width(), 1);
        assert_eq!(Separator::Theme.width(), 1);
        assert_eq!(Separator::None.width(), 0);
        assert_eq!(Separator::Literal(Cow::Borrowed(" | ")).width(), 3);
        // Powerline is configurable: width 1 (Nerd Font default) or
        // width 2 (some fonts/sizes render the chevron as 2 cells).
        // The reported width adds 2 cells of padding (one space on
        // each side of the chevron) since `text()` emits " ▶ ".
        assert_eq!(Separator::powerline().width(), 3);
        assert_eq!(
            Separator::Powerline {
                width: PowerlineWidth::Two,
            }
            .width(),
            4
        );
    }

    #[test]
    fn width_bounds_rejects_inverted_range() {
        assert!(WidthBounds::new(20, 10).is_none());
        assert!(WidthBounds::new(10, 10).is_some());
        assert!(WidthBounds::new(0, u16::MAX).is_some());
    }

    #[test]
    fn line_item_debug_renders_each_variant() {
        // The hand-written `Debug` impl on `LineItem` exists because
        // `Box<dyn Segment>` blocks `derive(Debug)`. Pin that both
        // variants format without panicking and that the variant
        // tag + id are visible in the output so panic backtraces
        // and `dbg!` calls identify the slot.
        struct StubSeg;
        impl Segment for StubSeg {
            fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
                Ok(None)
            }
        }
        let seg = LineItem::Segment {
            id: std::borrow::Cow::Borrowed("stub"),
            segment: Box::new(StubSeg),
        };
        let sep = LineItem::Separator(Separator::powerline());
        let seg_dbg = format!("{seg:?}");
        let sep_dbg = format!("{sep:?}");
        assert!(seg_dbg.starts_with("Segment {"), "got {seg_dbg:?}");
        assert!(sep_dbg.starts_with("Separator("), "got {sep_dbg:?}");
        // The Segment-variant body surfaces id + defaults so panic
        // dumps carry the slot name + priority/width context.
        // Field-named `id:` + `defaults:` defend against a regression
        // that renames either field while preserving the body content.
        assert!(seg_dbg.contains("id:"), "got {seg_dbg:?}");
        assert!(seg_dbg.contains("defaults:"), "got {seg_dbg:?}");
        assert!(seg_dbg.contains("stub"), "got {seg_dbg:?}");
        assert!(seg_dbg.contains("priority"), "got {seg_dbg:?}");
    }

    #[test]
    fn segment_defaults_default_priority_is_128() {
        assert_eq!(SegmentDefaults::default().priority, 128);
    }

    #[test]
    fn with_priority_preserves_other_defaults() {
        let d = SegmentDefaults::with_priority(64);
        assert_eq!(d.priority, 64);
        assert_eq!(d.width, None);
        assert!(!d.truncatable);
    }

    #[test]
    fn builders_chain_on_segment_defaults() {
        let bounds = WidthBounds::new(4, 40).expect("valid bounds");
        let d = SegmentDefaults::with_priority(32)
            .with_width(bounds)
            .with_truncatable(true);
        assert_eq!(d.priority, 32);
        assert_eq!(d.width, Some(bounds));
        assert!(d.truncatable);
    }

    #[test]
    fn segment_error_display_includes_message_only_without_source() {
        let err = SegmentError::new("missing rate_limits field");
        assert_eq!(err.to_string(), "missing rate_limits field");
    }

    #[test]
    fn segment_error_display_chains_source() {
        let src = std::io::Error::new(std::io::ErrorKind::NotFound, "cache.json");
        let err = SegmentError::with_source("cache read failed", Box::new(src));
        let rendered = err.to_string();
        assert!(rendered.starts_with("cache read failed: "));
        assert!(rendered.contains("cache.json"));
    }

    #[test]
    fn segment_error_source_chain_is_walkable() {
        use std::error::Error;
        let src = std::io::Error::other("inner");
        let err = SegmentError::with_source("outer", Box::new(src));
        let source = err.source().expect("source present");
        assert_eq!(source.to_string(), "inner");
    }

    // --- registry ---

    #[test]
    fn built_in_by_id_resolves_every_default_segment() {
        for id in DEFAULT_SEGMENT_IDS {
            assert!(
                built_in_by_id(id, None, &mut |_| {}).is_some(),
                "expected built-in registry to know {id}"
            );
        }
    }

    #[test]
    fn built_in_by_id_resolves_additional_documented_ids() {
        for id in [
            "context_bar",
            "session_duration",
            "rate_limit_5h",
            "rate_limit_7d",
            "rate_limit_5h_reset",
            "rate_limit_7d_reset",
            "extra_usage",
            "tokens_input",
            "tokens_output",
            "tokens_cached",
            "tokens_total",
            "output_style",
            "vim",
            "agent",
        ] {
            assert!(
                built_in_by_id(id, None, &mut |_| {}).is_some(),
                "expected {id} to resolve"
            );
        }
    }

    #[test]
    fn built_in_by_id_resolves_every_id_in_built_in_segment_ids() {
        // Anchors the contract documented at `BUILT_IN_SEGMENT_IDS`:
        // every id in the const must round-trip through the registry.
        // Catches drift between the const and the match arms.
        for id in BUILT_IN_SEGMENT_IDS {
            assert!(
                built_in_by_id(id, None, &mut |_| {}).is_some(),
                "BUILT_IN_SEGMENT_IDS lists {id} but built_in_by_id can't construct it"
            );
        }
    }

    #[test]
    fn built_in_by_id_rejects_unknown() {
        assert!(built_in_by_id("nope", None, &mut |_| {}).is_none());
        assert!(built_in_by_id("", None, &mut |_| {}).is_none());
    }

    #[test]
    fn built_in_by_id_threads_extras_to_version_segment() {
        // Pin the registry → from_extras wiring for `version`. A
        // future refactor that drops `from_extras` and constructs
        // `VersionSegment::default()` would silently break user
        // configs that set `[segments.version].prefix = "CC "`.
        use crate::input::{ModelInfo, StatusContext, Tool, WorkspaceInfo};
        use std::collections::BTreeMap;
        use std::path::PathBuf;
        use std::sync::Arc;

        let mut extras = BTreeMap::new();
        extras.insert("prefix".to_string(), toml::Value::String("CC ".to_string()));
        let seg = built_in_by_id("version", Some(&extras), &mut |_| {})
            .expect("version segment resolves");

        let ctx = DataContext::new(StatusContext {
            tool: Tool::ClaudeCode,
            model: Some(ModelInfo {
                display_name: "X".into(),
            }),
            workspace: Some(WorkspaceInfo {
                project_dir: PathBuf::from("/r"),
                git_worktree: None,
            }),
            context_window: None,
            cost: None,
            effort: None,
            vim: None,
            output_style: None,
            agent_name: None,
            version: Some("2.1.90".into()),
            raw: Arc::new(serde_json::Value::Null),
        });
        let rc = RenderContext::new(80);
        let rendered = seg.render(&ctx, &rc).unwrap().expect("renders");
        assert_eq!(rendered.text(), "CC 2.1.90");
    }

    // --- OverriddenSegment ---

    #[test]
    fn overridden_segment_replaces_priority() {
        let base = built_in_by_id("workspace", None, &mut |_| {}).expect("known id");
        let base_priority = base.defaults().priority;
        let wrapped = OverriddenSegment::new(base).with_priority(200);
        assert_eq!(wrapped.defaults().priority, 200);
        assert_ne!(wrapped.defaults().priority, base_priority);
    }

    #[test]
    fn overridden_segment_replaces_width_bounds() {
        let base = built_in_by_id("workspace", None, &mut |_| {}).expect("known id");
        assert_eq!(base.defaults().width, None);
        let bounds = WidthBounds::new(5, 40).expect("valid");
        let wrapped = OverriddenSegment::new(base).with_width(bounds);
        assert_eq!(wrapped.defaults().width, Some(bounds));
    }

    #[test]
    fn overridden_segment_delegates_render_to_inner() {
        let wrapped =
            OverriddenSegment::new(built_in_by_id("workspace", None, &mut |_| {}).unwrap())
                .with_priority(0);
        let rendered = wrapped
            .render(&stub_ctx(), &stub_rc())
            .unwrap()
            .expect("rendered");
        assert_eq!(rendered.text(), "linesmith");
    }

    #[test]
    fn style_override_wholesale_replaces_inner_declared_style() {
        // A stub that declares Role::Accent + bold at render time. The
        // override must wipe both, not merge with them.
        struct Styled;
        impl Segment for Styled {
            fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
                Ok(Some(
                    RenderedSegment::new("x")
                        .with_role(Role::Accent)
                        .with_style(Style {
                            bold: true,
                            ..Style::default()
                        }),
                ))
            }
            fn defaults(&self) -> SegmentDefaults {
                SegmentDefaults::with_priority(0)
            }
        }
        let override_style = Style {
            role: Some(Role::Primary),
            italic: true,
            ..Style::default()
        };
        let wrapped =
            OverriddenSegment::new(Box::new(Styled)).with_user_style(override_style.clone());
        let rendered = wrapped
            .render(&stub_ctx(), &stub_rc())
            .unwrap()
            .expect("rendered");
        assert_eq!(rendered.style, override_style);
    }

    #[test]
    fn user_style_override_preserves_inner_hyperlink() {
        // Pin the merge contract: visual override fields wholesale-
        // replace, but the inner segment's hyperlink survives so a
        // user `[segments.X] color = "red"` doesn't silently strip
        // links the segment emits. The user-style TOML syntax has no
        // hyperlink slot today, so the override's hyperlink is
        // always None — inheriting from the inner is lossless.
        struct Linked;
        impl Segment for Linked {
            fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
                Ok(Some(RenderedSegment::new("x").with_style(
                    Style::default().with_hyperlink("https://example.com"),
                )))
            }
            fn defaults(&self) -> SegmentDefaults {
                SegmentDefaults::with_priority(0)
            }
        }
        let override_style = Style::role(Role::Error);
        let wrapped =
            OverriddenSegment::new(Box::new(Linked)).with_user_style(override_style.clone());
        let rendered = wrapped
            .render(&stub_ctx(), &stub_rc())
            .unwrap()
            .expect("rendered");
        assert_eq!(rendered.style.role, Some(Role::Error));
        assert_eq!(
            rendered.style.hyperlink.as_deref(),
            Some("https://example.com"),
        );
    }

    #[test]
    fn style_override_preserves_inner_none_return() {
        struct Hidden;
        impl Segment for Hidden {
            fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
                Ok(None)
            }
            fn defaults(&self) -> SegmentDefaults {
                SegmentDefaults::with_priority(0)
            }
        }
        let wrapped =
            OverriddenSegment::new(Box::new(Hidden)).with_user_style(Style::role(Role::Primary));
        assert_eq!(wrapped.render(&stub_ctx(), &stub_rc()).unwrap(), None);
    }

    #[test]
    fn shrink_to_fit_passthrough_reaches_inner_with_user_style_applied() {
        // The OverriddenSegment wrapper must forward shrink_to_fit to
        // the inner segment so user-overridden segments retain their
        // layout-pressure compaction. The wrapper also has to apply
        // user_style to the shrunk render the same way it does on
        // render — otherwise a styled override loses its theme on the
        // compact path.
        struct Shrinkable;
        impl Segment for Shrinkable {
            fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
                Ok(Some(RenderedSegment::new("full")))
            }
            fn shrink_to_fit(
                &self,
                _: &DataContext,
                _: &RenderContext,
                target: u16,
            ) -> Option<RenderedSegment> {
                let r = RenderedSegment::new("c");
                (r.width <= target).then_some(r)
            }
        }
        let override_style = Style {
            role: Some(Role::Primary),
            italic: true,
            ..Style::default()
        };
        let wrapped =
            OverriddenSegment::new(Box::new(Shrinkable)).with_user_style(override_style.clone());
        let shrunk = wrapped
            .shrink_to_fit(&stub_ctx(), &stub_rc(), 5)
            .expect("inner returned compact form");
        assert_eq!(shrunk.text, "c");
        assert_eq!(shrunk.style, override_style);
    }

    #[test]
    fn shrink_to_fit_passthrough_keeps_inner_style_when_no_user_override() {
        // The `None` arm of `match self.user_style` must pass the
        // inner shrunk render through unchanged. A regression that
        // unconditionally applies a default style would clobber the
        // inner segment's role (e.g. `git_branch`'s `Role::Accent`
        // would silently drop on the compact path for any user
        // without a configured style override).
        struct ShrinkableWithRole;
        impl Segment for ShrinkableWithRole {
            fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
                Ok(Some(RenderedSegment::new("full").with_role(Role::Accent)))
            }
            fn shrink_to_fit(
                &self,
                _: &DataContext,
                _: &RenderContext,
                _target: u16,
            ) -> Option<RenderedSegment> {
                Some(RenderedSegment::new("c").with_role(Role::Accent))
            }
        }
        // No `with_user_style` call — wrapper carries no override.
        let wrapped = OverriddenSegment::new(Box::new(ShrinkableWithRole));
        let shrunk = wrapped
            .shrink_to_fit(&stub_ctx(), &stub_rc(), 10)
            .expect("inner returned compact form");
        assert_eq!(shrunk.style.role, Some(Role::Accent));
    }

    #[test]
    fn shrink_to_fit_passthrough_returns_none_when_inner_declines() {
        // Default trait impl returns None; the wrapper must forward
        // None unchanged rather than emit a stub render of its own.
        struct Plain;
        impl Segment for Plain {
            fn render(&self, _: &DataContext, _: &RenderContext) -> RenderResult {
                Ok(Some(RenderedSegment::new("plain")))
            }
        }
        let wrapped =
            OverriddenSegment::new(Box::new(Plain)).with_user_style(Style::role(Role::Primary));
        assert!(wrapped
            .shrink_to_fit(&stub_ctx(), &stub_rc(), 100)
            .is_none());
    }

    fn stub_ctx() -> DataContext {
        use crate::input::{ModelInfo, StatusContext, Tool, WorkspaceInfo};
        use std::path::PathBuf;
        use std::sync::Arc;
        DataContext::new(StatusContext {
            tool: Tool::ClaudeCode,
            model: Some(ModelInfo {
                display_name: "Claude".into(),
            }),
            workspace: Some(WorkspaceInfo {
                project_dir: PathBuf::from("/repo/linesmith"),
                git_worktree: None,
            }),
            context_window: None,
            cost: None,
            effort: None,
            vim: None,
            output_style: None,
            agent_name: None,
            version: None,
            raw: Arc::new(serde_json::Value::Null),
        })
    }

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